File: structured_metrics_service_unittest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (330 lines) | stat: -rw-r--r-- 10,437 bytes parent folder | download | duplicates (3)
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// Copyright 2023 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/structured_metrics_service.h"

#include <memory>
#include <utility>

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_refptr.h"
#include "base/test/task_environment.h"
#include "base/test/test_simple_task_runner.h"
#include "components/metrics/log_decoder.h"
#include "components/metrics/metrics_provider.h"
#include "components/metrics/structured/recorder.h"
#include "components/metrics/structured/reporting/structured_metrics_reporting_service.h"
#include "components/metrics/structured/structured_events.h"
#include "components/metrics/structured/structured_metrics_client.h"
#include "components/metrics/structured/structured_metrics_prefs.h"
#include "components/metrics/structured/structured_metrics_recorder.h"
#include "components/metrics/structured/test/test_event_storage.h"
#include "components/metrics/structured/test/test_key_data_provider.h"
#include "components/metrics/test/test_metrics_service_client.h"
#include "components/metrics/unsent_log_store.h"
#include "components/metrics/unsent_log_store_metrics_impl.h"
#include "components/prefs/testing_pref_service.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace metrics::structured {
namespace {

using events::v2::test_project_one::TestEventOne;
using events::v2::test_project_six::TestEventSeven;

// The name hash of "TestProjectOne".
constexpr uint64_t kProjectOneHash = UINT64_C(16881314472396226433);
// The name hash of "TestProjectThree".
constexpr uint64_t kProjectThreeHash = UINT64_C(10860358748803291132);

class TestRecorder : public StructuredMetricsClient::RecordingDelegate {
 public:
  TestRecorder() = default;
  TestRecorder(const TestRecorder& recorder) = delete;
  TestRecorder& operator=(const TestRecorder& recorder) = delete;
  ~TestRecorder() override = default;

  void RecordEvent(Event&& event) override {
    Recorder::GetInstance()->RecordEvent(std::move(event));
  }

  bool IsReadyToRecord() const override { return true; }
};

}  // namespace

class StructuredMetricsServiceTest : public testing::Test {
 public:
  StructuredMetricsServiceTest() {
    reporting::StructuredMetricsReportingService::RegisterPrefs(
        prefs_.registry());
  }

  ~StructuredMetricsServiceTest() override = default;

  void SetUp() override {
    Recorder::GetInstance()->SetUiTaskRunner(
        task_environment_.GetMainThreadTaskRunner());
    StructuredMetricsClient::Get()->SetDelegate(&test_recorder_);

    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

    WriteTestingDeviceKeys();

    WriteTestingProfileKeys();
  }

  void TearDown() override {
    StructuredMetricsClient::Get()->UnsetDelegate();
    service_.reset();
    Wait();
  }

  void Init() {
    auto key_data_provider =
        std::make_unique<TestKeyDataProvider>(DeviceKeyFilePath());
    TestKeyDataProvider* test_key_data_provider = key_data_provider.get();
    auto recorder = base::MakeRefCounted<StructuredMetricsRecorder>(
        std::move(key_data_provider), std::make_unique<TestEventStorage>());

    service_ = std::make_unique<StructuredMetricsService>(&client_, &prefs_,
                                                          std::move(recorder));
    // Register the profile with the key data provider.
    test_key_data_provider->OnProfileAdded(temp_dir_.GetPath());
    Wait();
  }

  void EnableRecording() { service_->EnableRecording(); }
  void EnableReporting() { service_->EnableReporting(); }

  void DisableRecording() { service_->DisableRecording(); }
  void DisableReporting() { service_->DisableReporting(); }

  base::FilePath ProfileKeyFilePath() {
    return temp_dir_.GetPath()
        .Append(FILE_PATH_LITERAL("structured_metrics"))
        .Append(FILE_PATH_LITERAL("keys"));
  }

  base::FilePath DeviceKeyFilePath() {
    return temp_dir_.GetPath()
        .Append(FILE_PATH_LITERAL("structured_metrics"))
        .Append(FILE_PATH_LITERAL("device_keys"));
  }

  base::FilePath DeviceEventsFilePath() {
    return temp_dir_.GetPath()
        .Append(FILE_PATH_LITERAL("structured_metrics"))
        .Append(FILE_PATH_LITERAL("events"));
  }

  void WriteTestingProfileKeys() {
    const int today = (base::Time::Now() - base::Time::UnixEpoch()).InDays();

    KeyDataProto proto;
    KeyProto& key_one = (*proto.mutable_keys())[kProjectOneHash];
    key_one.set_key("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
    key_one.set_last_rotation(today);
    key_one.set_rotation_period(90);

    KeyProto& key_three = (*proto.mutable_keys())[kProjectThreeHash];
    key_three.set_key("cccccccccccccccccccccccccccccccc");
    key_three.set_last_rotation(today);
    key_three.set_rotation_period(90);

    base::CreateDirectory(ProfileKeyFilePath().DirName());
    ASSERT_TRUE(
        base::WriteFile(ProfileKeyFilePath(), proto.SerializeAsString()));
    Wait();
  }

  void WriteTestingDeviceKeys() {
    base::CreateDirectory(DeviceKeyFilePath().DirName());
    ASSERT_TRUE(base::WriteFile(DeviceKeyFilePath(),
                                KeyDataProto().SerializeAsString()));
    Wait();
  }

  int GetPersistedLogCount() {
    return prefs_.GetList(prefs::kLogStoreName).size();
  }

  ChromeUserMetricsExtension GetPersistedLog() {
    EXPECT_THAT(GetPersistedLogCount(), 1);
    metrics::UnsentLogStore result_unsent_log_store(
        std::make_unique<UnsentLogStoreMetricsImpl>(), &prefs_,
        prefs::kLogStoreName, /*metadata_pref_name=*/nullptr,
        // Set to 3 so logs are not dropped in the test.
        UnsentLogStore::UnsentLogStoreLimits{
            .min_log_count = 3,
        },
        /*signing_key=*/std::string(),
        /*logs_event_manager=*/nullptr);

    result_unsent_log_store.LoadPersistedUnsentLogs();
    result_unsent_log_store.StageNextLog();

    ChromeUserMetricsExtension uma_proto;
    EXPECT_TRUE(metrics::DecodeLogDataToProto(
        result_unsent_log_store.staged_log(), &uma_proto));
    return uma_proto;
  }

  StructuredMetricsService& service() { return *service_.get(); }

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

  void AdvanceClock(int hours) {
    task_environment_.AdvanceClock(base::Hours(hours));
  }

 protected:
  std::unique_ptr<StructuredMetricsService> service_;
  metrics::TestMetricsServiceClient client_;

 private:
  TestingPrefServiceSimple prefs_;

  TestRecorder test_recorder_;
  base::ScopedTempDir temp_dir_;

  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::MainThreadType::UI,
      base::test::TaskEnvironment::ThreadPoolExecutionMode::QUEUED,
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
};

TEST_F(StructuredMetricsServiceTest, PurgeInMemory) {
  Init();

  EnableRecording();
  EnableReporting();

  StructuredMetricsClient::Record(
      std::move(TestEventOne().SetTestMetricTwo(1)));
  StructuredMetricsClient::Record(
      std::move(TestEventSeven().SetTestMetricSeven(1.0)));
  Wait();

  service_->Purge();
  service_->Flush(metrics::MetricsLogsEventManager::CreateReason::kUnknown);

  // Nothing should be stored.
  EXPECT_THAT(GetPersistedLogCount(), 0);
}

TEST_F(StructuredMetricsServiceTest, PurgePersisted) {
  Init();

  EnableRecording();
  EnableReporting();

  StructuredMetricsClient::Record(
      std::move(TestEventOne().SetTestMetricTwo(1)));
  StructuredMetricsClient::Record(
      std::move(TestEventSeven().SetTestMetricSeven(1.0)));
  Wait();

  service_->Flush(metrics::MetricsLogsEventManager::CreateReason::kUnknown);

  service_->Purge();

  // Need to make sure there is a log to read.
  service_->Flush(metrics::MetricsLogsEventManager::CreateReason::kUnknown);

  // Nothing should be stored.
  EXPECT_THAT(GetPersistedLogCount(), 0);
}

TEST_F(StructuredMetricsServiceTest, RotateLogs) {
  Init();

  EnableRecording();
  EnableReporting();

  StructuredMetricsClient::Record(
      std::move(TestEventOne().SetTestMetricTwo(1)));
  StructuredMetricsClient::Record(
      std::move(TestEventSeven().SetTestMetricSeven(1)));
  Wait();

  service_->Flush(metrics::MetricsLogsEventManager::CreateReason::kUnknown);

  const auto uma_proto = GetPersistedLog();
  EXPECT_THAT(uma_proto.structured_data().events().size(), 2);
  service_.reset();
}

TEST_F(StructuredMetricsServiceTest, SystemProfileFilled) {
  Init();

  EnableRecording();
  EnableReporting();

  StructuredMetricsClient::Record(
      std::move(TestEventOne().SetTestMetricTwo(1)));
  StructuredMetricsClient::Record(
      std::move(TestEventSeven().SetTestMetricSeven(1)));
  Wait();

  service_->Flush(metrics::MetricsLogsEventManager::CreateReason::kUnknown);

  const auto uma_proto = GetPersistedLog();
  EXPECT_THAT(uma_proto.structured_data().events().size(), 2);
  EXPECT_TRUE(uma_proto.has_system_profile());

  const SystemProfileProto& system_profile = uma_proto.system_profile();
  EXPECT_EQ(system_profile.channel(), client_.GetChannel());
  EXPECT_EQ(system_profile.app_version(), client_.GetVersionString());
}

TEST_F(StructuredMetricsServiceTest, DoesNotRecordWhenRecordingDisabled) {
  Init();
  EnableRecording();
  EnableReporting();

  StructuredMetricsClient::Record(
      std::move(TestEventOne().SetTestMetricTwo(1)));
  StructuredMetricsClient::Record(
      std::move(TestEventSeven().SetTestMetricSeven(1)));
  Wait();

  DisableRecording();

  StructuredMetricsClient::Record(
      std::move(TestEventOne().SetTestMetricTwo(1)));
  StructuredMetricsClient::Record(
      std::move(TestEventSeven().SetTestMetricSeven(1)));
  Wait();

  EnableRecording();

  service_->Flush(metrics::MetricsLogsEventManager::CreateReason::kUnknown);

  const auto uma_proto = GetPersistedLog();
  EXPECT_THAT(uma_proto.structured_data().events().size(), 2);
}

TEST_F(StructuredMetricsServiceTest, FlushOnShutdown) {
  Init();
  EnableRecording();
  EnableReporting();

  StructuredMetricsClient::Record(
      std::move(TestEventOne().SetTestMetricTwo(1)));
  StructuredMetricsClient::Record(
      std::move(TestEventSeven().SetTestMetricSeven(1)));
  Wait();

  // Will flush the log.
  service_.reset();

  const auto uma_proto = GetPersistedLog();
  EXPECT_THAT(uma_proto.structured_data().events().size(), 2);
}

}  // namespace metrics::structured