File: reporting_service_unittest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, 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 (369 lines) | stat: -rw-r--r-- 15,013 bytes parent folder | download | duplicates (2)
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright 2014 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/reporting_service.h"

#include <stdint.h>

#include <deque>
#include <memory>
#include <string>
#include <string_view>

#include "base/functional/bind.h"
#include "base/hash/sha1.h"
#include "base/strings/string_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "components/metrics/log_store.h"
#include "components/metrics/metrics_features.h"
#include "components/metrics/metrics_log.h"
#include "components/metrics/metrics_scheduler.h"
#include "components/metrics/metrics_upload_scheduler.h"
#include "components/metrics/test/test_metrics_service_client.h"
#include "components/prefs/testing_pref_service.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/zlib/google/compression_utils.h"

namespace metrics {

namespace {

// Represent a flushed log and its metadata to be used for testing.
struct TestLog {
  explicit TestLog(const std::string& log) : log(log), user_id(std::nullopt) {}
  TestLog(const std::string& log, uint64_t user_id)
      : log(log), user_id(user_id) {}
  TestLog(const std::string& log, uint64_t user_id, LogMetadata log_metadata)
      : log(log), user_id(user_id), log_metadata(log_metadata) {}
  TestLog(const TestLog& other) = default;
  ~TestLog() = default;

  const std::string log;
  const std::optional<uint64_t> user_id;
  const LogMetadata log_metadata;
};

const char kTestUploadUrl[] = "test_url";
const char kTestMimeType[] = "test_mime_type";

class TestLogStore : public LogStore {
 public:
  TestLogStore() = default;
  ~TestLogStore() override = default;

  void AddLog(const TestLog& log) { logs_.push_back(log); }

  // LogStore:
  bool has_unsent_logs() const override { return !logs_.empty(); }
  bool has_staged_log() const override { return !staged_log_hash_.empty(); }
  const std::string& staged_log() const override { return logs_.front().log; }
  const std::string& staged_log_hash() const override {
    return staged_log_hash_;
  }
  std::optional<uint64_t> staged_log_user_id() const override {
    return logs_.front().user_id;
  }
  const LogMetadata staged_log_metadata() const override {
    return logs_.front().log_metadata;
  }
  const std::string& staged_log_signature() const override {
    return base::EmptyString();
  }
  void StageNextLog() override {
    if (has_unsent_logs()) {
      staged_log_hash_ = base::SHA1HashString(logs_.front().log);
    }
  }
  void DiscardStagedLog(std::string_view reason) override {
    if (!has_staged_log())
      return;
    logs_.pop_front();
    staged_log_hash_.clear();
  }
  void MarkStagedLogAsSent() override {}
  void TrimAndPersistUnsentLogs(bool overwrite_in_memory_store) override {}
  void LoadPersistedUnsentLogs() override {}

 private:
  std::string staged_log_hash_;
  std::deque<TestLog> logs_;
};

class TestReportingService : public ReportingService {
 public:
  TestReportingService(MetricsServiceClient* client, PrefService* local_state)
      : ReportingService(client,
                         local_state,
                         100,
                         /*logs_event_manager=*/nullptr) {
    Initialize();
  }

  TestReportingService(const TestReportingService&) = delete;
  TestReportingService& operator=(const TestReportingService&) = delete;

  ~TestReportingService() override = default;

  void AddLog(const TestLog& log) { log_store_.AddLog(log); }
  bool HasUnsentLogs() { return log_store_.has_unsent_logs(); }

 private:
  // ReportingService:
  LogStore* log_store() override { return &log_store_; }
  GURL GetUploadUrl() const override { return GURL(kTestUploadUrl); }
  GURL GetInsecureUploadUrl() const override { return GURL(kTestUploadUrl); }
  std::string_view upload_mime_type() const override { return kTestMimeType; }
  MetricsLogUploader::MetricServiceType service_type() const override {
    return MetricsLogUploader::MetricServiceType::UMA;
  }

  TestLogStore log_store_;
};

class ReportingServiceTest : public testing::Test {
 public:
  ReportingServiceTest() {
    ReportingService::RegisterPrefs(testing_local_state_.registry());
  }

  ReportingServiceTest(const ReportingServiceTest&) = delete;
  ReportingServiceTest& operator=(const ReportingServiceTest&) = delete;

  ~ReportingServiceTest() override = default;

  PrefService* GetLocalState() { return &testing_local_state_; }

 protected:
  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  TestMetricsServiceClient client_;

 private:
  TestingPrefServiceSimple testing_local_state_;
};

}  // namespace

TEST_F(ReportingServiceTest, BasicTest) {
  TestReportingService service(&client_, GetLocalState());
  service.AddLog(TestLog("log1"));
  service.AddLog(TestLog("log2"));

  service.EnableReporting();
  task_environment_.FastForwardBy(
      base::Seconds(MetricsScheduler::GetInitialIntervalSeconds()));
  EXPECT_TRUE(client_.uploader()->is_uploading());
  EXPECT_EQ(1, client_.uploader()->reporting_info().attempt_count());
  EXPECT_FALSE(client_.uploader()->reporting_info().has_last_response_code());

  client_.uploader()->CompleteUpload(404);
  task_environment_.FastForwardBy(
      MetricsUploadScheduler::GetInitialBackoffInterval());
  EXPECT_TRUE(client_.uploader()->is_uploading());
  EXPECT_EQ(2, client_.uploader()->reporting_info().attempt_count());
  EXPECT_EQ(404, client_.uploader()->reporting_info().last_response_code());

  client_.uploader()->CompleteUpload(200);
  task_environment_.FastForwardBy(
      MetricsUploadScheduler::GetUnsentLogsInterval());
  EXPECT_TRUE(client_.uploader()->is_uploading());
  EXPECT_EQ(1, client_.uploader()->reporting_info().attempt_count());
  EXPECT_EQ(200, client_.uploader()->reporting_info().last_response_code());

  client_.uploader()->CompleteUpload(200);
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0U);
  EXPECT_FALSE(client_.uploader()->is_uploading());
}

TEST_F(ReportingServiceTest, UserIdLogsUploadedIfUserConsented) {
  uint64_t user_id = 12345;

  TestReportingService service(&client_, GetLocalState());
  service.AddLog(TestLog("log1", user_id));
  service.AddLog(TestLog("log2", user_id));
  service.EnableReporting();
  client_.AllowMetricUploadForUserId(user_id);

  task_environment_.FastForwardBy(
      base::Seconds(MetricsScheduler::GetInitialIntervalSeconds()));
  EXPECT_TRUE(client_.uploader()->is_uploading());
  EXPECT_EQ(1, client_.uploader()->reporting_info().attempt_count());
  EXPECT_FALSE(client_.uploader()->reporting_info().has_last_response_code());
  client_.uploader()->CompleteUpload(200);

  // Upload 2nd log and last response code logged.
  task_environment_.FastForwardBy(
      MetricsUploadScheduler::GetUnsentLogsInterval());
  EXPECT_EQ(200, client_.uploader()->reporting_info().last_response_code());
  EXPECT_TRUE(client_.uploader()->is_uploading());

  client_.uploader()->CompleteUpload(200);
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0U);
  EXPECT_FALSE(client_.uploader()->is_uploading());
}

TEST_F(ReportingServiceTest, UserIdLogsNotUploadedIfUserNotConsented) {
  TestReportingService service(&client_, GetLocalState());
  service.AddLog(TestLog("log1", 12345));
  service.AddLog(TestLog("log2", 12345));
  service.EnableReporting();

  // Log with user id should never be in uploading state if user upload
  // disabled. |client_.uploader()| should be nullptr since it is lazily
  // created when a log is to be uploaded for the first time.
  task_environment_.FastForwardBy(
      base::Seconds(MetricsScheduler::GetInitialIntervalSeconds()));
  EXPECT_EQ(client_.uploader(), nullptr);
}

TEST_F(ReportingServiceTest, ForceDiscard) {
  TestReportingService service(&client_, GetLocalState());
  service.AddLog(TestLog("log1"));

  service.EnableReporting();

  // Simulate the server returning a 500 error, which indicates that the server
  // is unhealthy.
  task_environment_.FastForwardBy(
      base::Seconds(MetricsScheduler::GetInitialIntervalSeconds()));
  EXPECT_TRUE(client_.uploader()->is_uploading());
  client_.uploader()->CompleteUpload(500);
  task_environment_.FastForwardBy(
      MetricsUploadScheduler::GetInitialBackoffInterval());
  // Verify that the log is not discarded so that it can be re-sent later.
  EXPECT_TRUE(service.HasUnsentLogs());
  EXPECT_TRUE(client_.uploader()->is_uploading());

  // Simulate the server returning a 500 error again, but this time, with
  // |force_discard| set to true.
  client_.uploader()->CompleteUpload(500, /*force_discard=*/true);
  // Verify that the log was discarded, and that |service| is not uploading
  // anymore since there are no more logs.
  EXPECT_FALSE(service.HasUnsentLogs());
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0U);
  EXPECT_FALSE(client_.uploader()->is_uploading());
}

#if BUILDFLAG(IS_ANDROID)
TEST_F(ReportingServiceTest, ResetMetricsUploadBackoffOnForeground) {
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeature(
      features::kResetMetricsUploadBackoffOnForeground);

  TestReportingService service(&client_, GetLocalState());
  service.AddLog(TestLog("log1"));
  service.AddLog(TestLog("log2"));
  service.AddLog(TestLog("log3"));

  service.EnableReporting();

  // Simulate the app being backgrounded.
  service.OnAppEnterBackground();

  // Simulate receiving a 105 (NAME_NOT_RESOLVED) error, which is one of the
  // many errors returned when trying to do a network request while in the
  // background on Android 15 and above.
  task_environment_.FastForwardBy(
      base::Seconds(MetricsScheduler::GetInitialIntervalSeconds()));
  EXPECT_TRUE(client_.uploader()->is_uploading());
  client_.uploader()->CompleteUpload(105);
  // Verify that the upload has been re-scheduled with the the backoff interval.
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1U);
  EXPECT_EQ(task_environment_.NextMainThreadPendingTaskDelay(),
            MetricsUploadScheduler::GetInitialBackoffInterval());
  // Simulate the app being foregrounded. The backoff should be reset, and the
  // upload should have be re-scheduled with the normal interval.
  service.OnAppEnterForeground();
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1U);
  EXPECT_EQ(task_environment_.NextMainThreadPendingTaskDelay(),
            MetricsUploadScheduler::GetUnsentLogsInterval());
  // Simulate the successful upload of log1.
  task_environment_.FastForwardBy(
      MetricsUploadScheduler::GetUnsentLogsInterval());
  EXPECT_TRUE(client_.uploader()->is_uploading());
  client_.uploader()->CompleteUpload(200);

  // The uploading of log2 should be scheduled with the normal interval as
  // usual.
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1U);
  EXPECT_EQ(task_environment_.NextMainThreadPendingTaskDelay(),
            MetricsUploadScheduler::GetUnsentLogsInterval());
  // Simulate the app being backgrounded and the upload being initiated.
  service.OnAppEnterBackground();
  task_environment_.FastForwardBy(
      MetricsUploadScheduler::GetUnsentLogsInterval());
  EXPECT_TRUE(client_.uploader()->is_uploading());
  // Simulate the app being foregrounded while the upload is ongoing.
  service.OnAppEnterForeground();
  // Simulate the upload eventually completing with a 105 failure. The upload
  // should have be re-scheduled, but *not* with the backoff interval.
  client_.uploader()->CompleteUpload(105);
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1U);
  EXPECT_EQ(task_environment_.NextMainThreadPendingTaskDelay(),
            MetricsUploadScheduler::GetUnsentLogsInterval());
  // Simulate the successful upload of log2.
  task_environment_.FastForwardBy(
      MetricsUploadScheduler::GetUnsentLogsInterval());
  EXPECT_TRUE(client_.uploader()->is_uploading());
  client_.uploader()->CompleteUpload(200);

  // The uploading of log3 should be scheduled with the normal interval as
  // usual.
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1U);
  EXPECT_EQ(task_environment_.NextMainThreadPendingTaskDelay(),
            MetricsUploadScheduler::GetUnsentLogsInterval());
  // Simulate the upload failing (while still in the foreground).
  task_environment_.FastForwardBy(
      MetricsUploadScheduler::GetUnsentLogsInterval());
  EXPECT_TRUE(client_.uploader()->is_uploading());
  client_.uploader()->CompleteUpload(500);
  // The upload should be re-scheduled with the backoff interval.
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1U);
  EXPECT_EQ(task_environment_.NextMainThreadPendingTaskDelay(),
            MetricsUploadScheduler::GetInitialBackoffInterval());
  // Simulate the app being backgrounded, and the re-scheduled upload failing
  // with yet another failure.
  service.OnAppEnterBackground();
  task_environment_.FastForwardBy(
      MetricsUploadScheduler::GetInitialBackoffInterval());
  EXPECT_TRUE(client_.uploader()->is_uploading());
  client_.uploader()->CompleteUpload(105);
  // The upload should be re-scheduled with an even longer backoff interval.
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1U);
  base::TimeDelta current_backoff_interval =
      task_environment_.NextMainThreadPendingTaskDelay();
  EXPECT_GT(current_backoff_interval,
            MetricsUploadScheduler::GetInitialBackoffInterval());
  // Simulate the app being foregrounded. The backoff interval should *not* have
  // been reset because the failures started while in the foreground.
  service.OnAppEnterForeground();
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1U);
  EXPECT_EQ(current_backoff_interval,
            task_environment_.NextMainThreadPendingTaskDelay());
  // Ditto when foregrounding during an upload.
  service.OnAppEnterBackground();
  task_environment_.FastForwardBy(current_backoff_interval);
  EXPECT_TRUE(client_.uploader()->is_uploading());
  service.OnAppEnterForeground();
  client_.uploader()->CompleteUpload(105);
  // The upload should have be re-scheduled, with an even longer backoff
  // interval (i.e. it should not be reset) since, again, failures started from
  // the foreground.
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1U);
  base::TimeDelta current_backoff_interval2 =
      task_environment_.NextMainThreadPendingTaskDelay();
  EXPECT_GT(current_backoff_interval2, current_backoff_interval);
  // Finally, simulate the successful upload of log3. There should be no more
  // logs after that.
  task_environment_.FastForwardBy(current_backoff_interval2);
  EXPECT_TRUE(client_.uploader()->is_uploading());
  client_.uploader()->CompleteUpload(200);
  EXPECT_FALSE(service.HasUnsentLogs());
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0U);
  EXPECT_FALSE(client_.uploader()->is_uploading());
}
#endif  // BUILDFLAG(IS_ANDROID)

}  // namespace metrics