File: external_metrics_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (293 lines) | stat: -rw-r--r-- 9,900 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/metrics/structured/external_metrics.h"

#include <memory>
#include <numeric>
#include <string>

#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "components/metrics/structured/histogram_util.h"
#include "components/metrics/structured/proto/event_storage.pb.h"
#include "components/metrics/structured/structured_metrics_features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace metrics::structured {
namespace {

using testing::UnorderedElementsAre;

// Make a simple testing proto with one |uma_events| message for each id in
// |ids|.
EventsProto MakeTestingProto(const std::vector<uint64_t>& ids,
                             uint64_t project_name_hash = 0) {
  EventsProto proto;

  for (const auto id : ids) {
    auto* event = proto.add_uma_events();
    event->set_project_name_hash(project_name_hash);
    event->set_profile_event_id(id);
  }

  return proto;
}

// Check that |proto| is consistent with the proto that would be generated by
// MakeTestingProto(ids).
void AssertEqualsTestingProto(const EventsProto& proto,
                              const std::vector<uint64_t>& ids) {
  ASSERT_EQ(proto.uma_events().size(), static_cast<int>(ids.size()));
  ASSERT_TRUE(proto.events().empty());

  for (size_t i = 0; i < ids.size(); ++i) {
    const auto& event = proto.uma_events(i);
    ASSERT_EQ(event.profile_event_id(), ids[i]);
    ASSERT_FALSE(event.has_event_name_hash());
    ASSERT_TRUE(event.metrics().empty());
  }
}

}  // namespace

class ExternalMetricsTest : public testing::Test {
 public:
  void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); }

  void Init() {
    // We don't use the scheduling feature when testing ExternalMetrics, instead
    // we just call CollectMetrics directly. So make up a time interval here
    // that we'll never reach in a test.
    const auto one_hour = base::Hours(1);
    external_metrics_ = std::make_unique<ExternalMetrics>(
        temp_dir_.GetPath(), one_hour,
        base::BindRepeating(&ExternalMetricsTest::OnEventsCollected,
                            base::Unretained(this)));

    // For most tests the recording needs to be enabled.
    EnableRecording();
  }

  void EnableRecording() { external_metrics_->EnableRecording(); }

  void DisableRecording() { external_metrics_->DisableRecording(); }

  void CollectEvents() {
    external_metrics_->CollectEvents();
    Wait();
    CHECK(proto_.has_value());
  }

  void OnEventsCollected(const EventsProto& proto) {
    proto_ = std::move(proto);
  }

  void WriteToDisk(const std::string& name, const EventsProto& proto) {
    CHECK(base::WriteFile(temp_dir_.GetPath().Append(name),
                          proto.SerializeAsString()));
  }

  void WriteToDisk(const std::string& name, const std::string& str) {
    CHECK(base::WriteFile(temp_dir_.GetPath().Append(name), str));
  }

  void Wait() { task_environment_.RunUntilIdle(); }

  base::ScopedTempDir temp_dir_;
  std::unique_ptr<ExternalMetrics> external_metrics_;
  std::optional<EventsProto> proto_;

  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::MainThreadType::UI,
      base::test::TaskEnvironment::ThreadPoolExecutionMode::QUEUED};
  base::HistogramTester histogram_tester_;
};

TEST_F(ExternalMetricsTest, ReadOneFile) {
  // Make one proto with three events.
  WriteToDisk("myproto", MakeTestingProto({111, 222, 333}));
  Init();

  CollectEvents();

  // We should have correctly picked up the three events.
  AssertEqualsTestingProto(proto_.value(), {111, 222, 333});
  // And the directory should now be empty.
  ASSERT_TRUE(base::IsDirectoryEmpty(temp_dir_.GetPath()));
}

TEST_F(ExternalMetricsTest, ReadManyFiles) {
  // Make three protos with three events each.
  WriteToDisk("first", MakeTestingProto({111, 222, 333}));
  WriteToDisk("second", MakeTestingProto({444, 555, 666}));
  WriteToDisk("third", MakeTestingProto({777, 888, 999}));
  Init();

  CollectEvents();

  // We should have correctly picked up the nine events. Don't check for order,
  // because we can't guarantee the files will be read from disk in any
  // particular order.
  std::vector<int64_t> ids;
  for (const auto& event : proto_.value().uma_events()) {
    ids.push_back(event.profile_event_id());
  }
  ASSERT_THAT(
      ids, UnorderedElementsAre(111, 222, 333, 444, 555, 666, 777, 888, 999));

  // The directory should be empty after reading.
  ASSERT_TRUE(base::IsDirectoryEmpty(temp_dir_.GetPath()));
}

TEST_F(ExternalMetricsTest, ReadZeroFiles) {
  Init();
  CollectEvents();
  // We should have an empty proto.
  AssertEqualsTestingProto(proto_.value(), {});
  // And the directory should be empty too.
  ASSERT_TRUE(base::IsDirectoryEmpty(temp_dir_.GetPath()));
}

TEST_F(ExternalMetricsTest, CollectTwice) {
  Init();
  WriteToDisk("first", MakeTestingProto({111, 222, 333}));
  CollectEvents();
  AssertEqualsTestingProto(proto_.value(), {111, 222, 333});

  WriteToDisk("first", MakeTestingProto({444}));
  CollectEvents();
  AssertEqualsTestingProto(proto_.value(), {444});
}

TEST_F(ExternalMetricsTest, HandleCorruptFile) {
  Init();

  WriteToDisk("invalid", "surprise i'm not a proto");
  WriteToDisk("valid", MakeTestingProto({111, 222, 333}));

  CollectEvents();
  AssertEqualsTestingProto(proto_.value(), {111, 222, 333});
  // Should have deleted the invalid file too.
  ASSERT_TRUE(base::IsDirectoryEmpty(temp_dir_.GetPath()));
}

TEST_F(ExternalMetricsTest, FileNumberReadCappedAndDiscarded) {
  // Setup feature.
  base::test::ScopedFeatureList feature_list;
  const int file_limit = 2;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kStructuredMetrics,
      {{"file_limit", base::NumberToString(file_limit)}});

  Init();

  // File limit is set to 2. Include third file to test that it is omitted and
  // deleted.
  WriteToDisk("first", MakeTestingProto({111}));
  WriteToDisk("second", MakeTestingProto({222}));
  WriteToDisk("third", MakeTestingProto({333}));

  CollectEvents();

  // Number of events should be capped to the file limit since above records one
  // event per file.
  ASSERT_EQ(proto_.value().uma_events().size(), file_limit);

  // And the directory should be empty too.
  ASSERT_TRUE(base::IsDirectoryEmpty(temp_dir_.GetPath()));
}

TEST_F(ExternalMetricsTest, FilterDisallowedProjects) {
  Init();
  external_metrics_->AddDisallowedProjectForTest(2);

  // Add 3 events with a project of 1 and 2.
  WriteToDisk("first", MakeTestingProto({111}, 1));
  WriteToDisk("second", MakeTestingProto({222}, 2));
  WriteToDisk("third", MakeTestingProto({333}, 1));

  CollectEvents();

  // The events at second should be filtered.
  ASSERT_EQ(proto_.value().uma_events().size(), 2);

  std::vector<int64_t> ids;
  for (const auto& event : proto_.value().uma_events()) {
    ids.push_back(event.profile_event_id());
  }

  // Validate that only project 1 remains.
  ASSERT_THAT(ids, UnorderedElementsAre(111, 333));

  // And the directory should be empty too.
  ASSERT_TRUE(base::IsDirectoryEmpty(temp_dir_.GetPath()));
}

TEST_F(ExternalMetricsTest, DroppedEventsWhenDisabled) {
  Init();
  DisableRecording();

  // Add 3 events with a project of 1 and 2.
  WriteToDisk("first", MakeTestingProto({111}, 1));
  WriteToDisk("second", MakeTestingProto({222}, 2));
  WriteToDisk("third", MakeTestingProto({333}, 1));

  CollectEvents();

  // No events should have been collected.
  ASSERT_EQ(proto_.value().uma_events().size(), 0);

  // And the directory should be empty too.
  ASSERT_TRUE(base::IsDirectoryEmpty(temp_dir_.GetPath()));
}

TEST_F(ExternalMetricsTest, ProducedAndDroppedEventMetricCollected) {
  base::test::ScopedFeatureList feature_list;
  const int file_limit = 5;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kStructuredMetrics,
      {{"file_limit", base::NumberToString(file_limit)}});

  Init();

  // Generate 9 events.
  WriteToDisk("event0", MakeTestingProto({0}, UINT64_C(4320592646346933548)));
  WriteToDisk("event1", MakeTestingProto({1}, UINT64_C(4320592646346933548)));
  WriteToDisk("event2", MakeTestingProto({2}, UINT64_C(4320592646346933548)));
  WriteToDisk("event3", MakeTestingProto({3}, UINT64_C(4320592646346933548)));
  WriteToDisk("event4", MakeTestingProto({4}, UINT64_C(4320592646346933548)));
  WriteToDisk("event5", MakeTestingProto({5}, UINT64_C(4320592646346933548)));
  WriteToDisk("event6", MakeTestingProto({6}, UINT64_C(4320592646346933548)));
  WriteToDisk("event7", MakeTestingProto({7}, UINT64_C(4320592646346933548)));
  WriteToDisk("event8", MakeTestingProto({8}, UINT64_C(4320592646346933548)));

  CollectEvents();

  // There should be 9 files processed and 4 events dropped. We analyze the
  // histograms to verify this.
  EXPECT_EQ(histogram_tester_.GetTotalSum(
                std::string(kExternalMetricsProducedHistogramPrefix) + "WiFi"),
            9);
  EXPECT_EQ(histogram_tester_.GetTotalSum(
                std::string(kExternalMetricsDroppedHistogramPrefix) + "WiFi"),
            4);

  // There should |file_limit| events. The rest should have been dropped.
  ASSERT_EQ(proto_.value().uma_events().size(), file_limit);

  // The directory should be empty.
  ASSERT_TRUE(base::IsDirectoryEmpty(temp_dir_.GetPath()));
}

// TODO(crbug.com/40156926): Add a test for concurrent reading and writing here
// once we know the specifics of how the lock in cros is performed.

}  // namespace metrics::structured