blob: f585d350734b10c13e49dd2818059d9d54bf6051 [file] [log] [blame]
Darin Petkov11b8eb32010-05-18 11:00:59 -07001// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "metrics_library.h"
6
7#include <cstring>
8
9#include <base/file_util.h>
10#include <gtest/gtest.h>
11
12static const FilePath kTestUMAEventsFile("test-uma-events");
13
14class MetricsLibraryTest : public testing::Test {
15 protected:
16 virtual void SetUp() {
17 EXPECT_EQ(NULL, lib_.uma_events_file_);
18 lib_.Init();
19 EXPECT_TRUE(NULL != lib_.uma_events_file_);
20 lib_.uma_events_file_ = kTestUMAEventsFile.value().c_str();
21 }
22
23 virtual void TearDown() {
24 file_util::Delete(kTestUMAEventsFile, false);
25 }
26
27 MetricsLibrary lib_;
28};
29
30TEST_F(MetricsLibraryTest, FormatChromeMessage) {
31 char buf[7];
32 const int kLen = 6;
33 EXPECT_EQ(kLen, lib_.FormatChromeMessage(7, buf, "%d", 1));
34
35 char exp[kLen];
36 sprintf(exp, "%c%c%c%c1", kLen, 0, 0, 0);
37 EXPECT_EQ(0, memcmp(exp, buf, kLen));
38}
39
40TEST_F(MetricsLibraryTest, FormatChromeMessageTooLong) {
41 char buf[7];
42 EXPECT_EQ(-1, lib_.FormatChromeMessage(7, buf, "test"));
43}
44
45TEST_F(MetricsLibraryTest, SendEnumToUMA) {
46 char buf[100];
47 const int kLen = 40;
48 EXPECT_TRUE(lib_.SendEnumToUMA("Test.EnumMetric", 1, 3));
49 EXPECT_EQ(kLen, file_util::ReadFile(kTestUMAEventsFile, buf, 100));
50
51 char exp[kLen];
52 sprintf(exp, "%c%c%c%clinearhistogram%cTest.EnumMetric 1 3",
53 kLen, 0, 0, 0, 0);
54 EXPECT_EQ(0, memcmp(exp, buf, kLen));
55}
56
57TEST_F(MetricsLibraryTest, SendMessageToChrome) {
58 EXPECT_TRUE(lib_.SendMessageToChrome(4, "test"));
59 EXPECT_TRUE(lib_.SendMessageToChrome(7, "content"));
60 std::string uma_events;
61 EXPECT_TRUE(file_util::ReadFileToString(kTestUMAEventsFile, &uma_events));
62 EXPECT_EQ("testcontent", uma_events);
63}
64
65TEST_F(MetricsLibraryTest, SendMessageToChromeUMAEventsBadFileLocation) {
66 // Checks that the library doesn't die badly if the file can't be
67 // created.
68 static const char kDoesNotExistFile[] = "/does/not/exist";
69 lib_.uma_events_file_ = kDoesNotExistFile;
70 static const char kDummyMessage[] = "Dummy Message";
71 EXPECT_FALSE(lib_.SendMessageToChrome(strlen(kDummyMessage), kDummyMessage));
72 file_util::Delete(FilePath(kDoesNotExistFile), false);
73}
74
75TEST_F(MetricsLibraryTest, SendToUMA) {
76 char buf[100];
77 const int kLen = 37;
78 EXPECT_TRUE(lib_.SendToUMA("Test.Metric", 2, 1, 100, 50));
79 EXPECT_EQ(kLen, file_util::ReadFile(kTestUMAEventsFile, buf, 100));
80
81 char exp[kLen];
82 sprintf(exp, "%c%c%c%chistogram%cTest.Metric 2 1 100 50", kLen, 0, 0, 0, 0);
83 EXPECT_EQ(0, memcmp(exp, buf, kLen));
84}
85
86int main(int argc, char** argv) {
87 testing::InitGoogleTest(&argc, argv);
88 return RUN_ALL_TESTS();
89}