File: clean_exit_beacon_unittest.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (443 lines) | stat: -rw-r--r-- 19,365 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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// 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/clean_exit_beacon.h"

#include <memory>
#include <string>

#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/metrics/field_trial.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service_factory.h"
#include "components/prefs/testing_pref_service.h"
#include "components/prefs/testing_pref_store.h"
#include "components/variations/pref_names.h"
#include "components/variations/variations_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

namespace metrics {
namespace {

const wchar_t kDummyWindowsRegistryKey[] = L"";

}  // namespace

class TestCleanExitBeacon : public CleanExitBeacon {
 public:
  explicit TestCleanExitBeacon(
      PrefService* local_state,
      const base::FilePath& user_data_dir = base::FilePath())
      : CleanExitBeacon(kDummyWindowsRegistryKey, user_data_dir, local_state) {
    Initialize();
  }

  ~TestCleanExitBeacon() override = default;
};

class CleanExitBeaconTest : public ::testing::Test {
 public:
  void SetUp() override {
    metrics::CleanExitBeacon::RegisterPrefs(prefs_.registry());
    ASSERT_TRUE(user_data_dir_.CreateUniqueTempDir());
  }

 protected:
  base::HistogramTester histogram_tester_;
  TestingPrefServiceSimple prefs_;
  base::ScopedTempDir user_data_dir_;

 private:
  base::test::TaskEnvironment task_environment_;
};

struct BadBeaconTestParams {
  const std::string test_name;
  bool beacon_file_exists;
  const std::string beacon_file_contents;
  BeaconFileState beacon_file_state;
};

// Used for testing beacon files that are not well-formed, do not exist, etc.
class BadBeaconFileTest
    : public testing::WithParamInterface<BadBeaconTestParams>,
      public CleanExitBeaconTest {};

struct BeaconConsistencyTestParams {
  // Inputs:
  const std::string test_name;
  absl::optional<bool> beacon_file_beacon_value;
  absl::optional<bool> platform_specific_beacon_value;
  absl::optional<bool> local_state_beacon_value;
  // Result:
  CleanExitBeaconConsistency expected_consistency;
};

#if BUILDFLAG(IS_IOS)
// Used for testing the logic that emits to the UMA.CleanExitBeaconConsistency3
// histogram.
class BeaconFileAndPlatformBeaconConsistencyTest
    : public testing::WithParamInterface<BeaconConsistencyTestParams>,
      public CleanExitBeaconTest {};
#endif  // BUILDFLAG(IS_IOS)

// Verify that the crash streak metric is 0 when default pref values are used.
TEST_F(CleanExitBeaconTest, CrashStreakMetricWithDefaultPrefs) {
  CleanExitBeacon::ResetStabilityExitedCleanlyForTesting(&prefs_);
  TestCleanExitBeacon clean_exit_beacon(&prefs_);
  histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 0,
                                       1);
}

// Verify that the crash streak metric is 0 when prefs are explicitly set to
// their defaults.
TEST_F(CleanExitBeaconTest, CrashStreakMetricWithNoCrashes) {
  // The default value for kStabilityExitedCleanly is true, but defaults can
  // change, so we explicitly set it to true here. Similarly, we explicitly set
  // kVariationsCrashStreak to 0.
  CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, true);
  prefs_.SetInteger(variations::prefs::kVariationsCrashStreak, 0);
  TestCleanExitBeacon clean_exit_beacon(&prefs_);
  histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 0,
                                       1);
}

// Verify that the crash streak metric is correctly recorded when there is a
// non-zero crash streak.
TEST_F(CleanExitBeaconTest, CrashStreakMetricWithSomeCrashes) {
  // The default value for kStabilityExitedCleanly is true, but defaults can
  // change, so we explicitly set it to true here.
  CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, true);
  prefs_.SetInteger(variations::prefs::kVariationsCrashStreak, 1);
  TestCleanExitBeacon clean_exit_beacon(&prefs_);
  histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 1,
                                       1);
}

// Verify that the crash streak is correctly incremented and recorded when the
// last Chrome session did not exit cleanly.
TEST_F(CleanExitBeaconTest, CrashIncrementsCrashStreak) {
  CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, false);
  prefs_.SetInteger(variations::prefs::kVariationsCrashStreak, 1);
  TestCleanExitBeacon clean_exit_beacon(&prefs_);
  EXPECT_EQ(prefs_.GetInteger(variations::prefs::kVariationsCrashStreak), 2);
  histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 2,
                                       1);
}

// Verify that the crash streak is correctly incremented and recorded when the
// last Chrome session did not exit cleanly and the default crash streak value
// is used.
TEST_F(CleanExitBeaconTest,
       CrashIncrementsCrashStreakWithDefaultCrashStreakPref) {
  CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, false);
  TestCleanExitBeacon clean_exit_beacon(&prefs_);
  EXPECT_EQ(prefs_.GetInteger(variations::prefs::kVariationsCrashStreak), 1);
  histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 1,
                                       1);
}

// Verify that no attempt is made to read the beacon file when no user
// data dir is provided.
TEST_F(CleanExitBeaconTest, InitWithoutUserDataDir) {
  TestCleanExitBeacon beacon(&prefs_, base::FilePath());
  EXPECT_TRUE(beacon.GetUserDataDirForTesting().empty());
  EXPECT_TRUE(beacon.GetBeaconFilePathForTesting().empty());
  histogram_tester_.ExpectTotalCount(
      "Variations.ExtendedSafeMode.BeaconFileStateAtStartup", 0);
}

INSTANTIATE_TEST_SUITE_P(
    All,
    BadBeaconFileTest,
    ::testing::Values(
        BadBeaconTestParams{
            .test_name = "NoVariationsFile",
            .beacon_file_exists = false,
            .beacon_file_contents = "",
            .beacon_file_state = BeaconFileState::kNotDeserializable},
        BadBeaconTestParams{
            .test_name = "EmptyVariationsFile",
            .beacon_file_exists = true,
            .beacon_file_contents = "",
            .beacon_file_state = BeaconFileState::kNotDeserializable},
        BadBeaconTestParams{
            .test_name = "NotDictionary",
            .beacon_file_exists = true,
            .beacon_file_contents = "{abc123",
            .beacon_file_state = BeaconFileState::kNotDeserializable},
        BadBeaconTestParams{
            .test_name = "EmptyDictionary",
            .beacon_file_exists = true,
            .beacon_file_contents = "{}",
            .beacon_file_state = BeaconFileState::kMissingDictionary},
        BadBeaconTestParams{
            .test_name = "MissingCrashStreak",
            .beacon_file_exists = true,
            .beacon_file_contents =
                "{\"user_experience_metrics.stability.exited_cleanly\":true}",
            .beacon_file_state = BeaconFileState::kMissingCrashStreak},
        BadBeaconTestParams{
            .test_name = "MissingBeacon",
            .beacon_file_exists = true,
            .beacon_file_contents = "{\"variations_crash_streak\":1}",
            .beacon_file_state = BeaconFileState::kMissingBeacon}),
    [](const ::testing::TestParamInfo<BadBeaconTestParams>& params) {
      return params.param.test_name;
    });

// Verify that the inability to get the beacon file's contents for a plethora of
// reasons (a) doesn't crash and (b) correctly records the  BeaconFileState
// metric.
TEST_P(BadBeaconFileTest, InitWithUnusableBeaconFile) {
  BadBeaconTestParams params = GetParam();

  const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
  if (params.beacon_file_exists) {
    const base::FilePath temp_beacon_file_path =
        user_data_dir_path.Append(kCleanExitBeaconFilename);
    ASSERT_TRUE(
        base::WriteFile(temp_beacon_file_path, params.beacon_file_contents));
  }

  TestCleanExitBeacon beacon(&prefs_, user_data_dir_path);
  histogram_tester_.ExpectUniqueSample(
      "Variations.ExtendedSafeMode.BeaconFileStateAtStartup",
      params.beacon_file_state, 1);
}

// Verify that successfully reading the beacon file's contents results in
// correctly (a) setting the |did_previous_session_exit_cleanly_| field and (b)
// recording metrics when the last session exited cleanly.
TEST_F(CleanExitBeaconTest, InitWithBeaconFile) {
  const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
  const base::FilePath temp_beacon_file_path =
      user_data_dir_path.Append(kCleanExitBeaconFilename);
  const int num_crashes = 2;
  ASSERT_TRUE(base::WriteFile(
      temp_beacon_file_path,
      CleanExitBeacon::CreateBeaconFileContentsForTesting(
          /*exited_cleanly=*/true, /*crash_streak=*/num_crashes)));

  TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_path);
  histogram_tester_.ExpectUniqueSample(
      "Variations.ExtendedSafeMode.BeaconFileStateAtStartup",
      BeaconFileState::kReadable, 1);
  EXPECT_TRUE(clean_exit_beacon.exited_cleanly());
  histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes",
                                       num_crashes, 1);
}

// Verify that successfully reading the beacon file's contents results in
// correctly (a) setting the |did_previous_session_exit_cleanly_| field and (b)
// recording metrics when the last session did not exit cleanly.
TEST_F(CleanExitBeaconTest, InitWithCrashAndBeaconFile) {
  const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
  const base::FilePath temp_beacon_file_path =
      user_data_dir_path.Append(kCleanExitBeaconFilename);
  const int last_session_num_crashes = 2;
  ASSERT_TRUE(
      base::WriteFile(temp_beacon_file_path,
                      CleanExitBeacon::CreateBeaconFileContentsForTesting(
                          /*exited_cleanly=*/false,
                          /*crash_streak=*/last_session_num_crashes)));

  const int updated_num_crashes = last_session_num_crashes + 1;
  TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_path);
  histogram_tester_.ExpectUniqueSample(
      "Variations.ExtendedSafeMode.BeaconFileStateAtStartup",
      BeaconFileState::kReadable, 1);
  EXPECT_FALSE(clean_exit_beacon.exited_cleanly());
  histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes",
                                       updated_num_crashes, 1);
}

TEST_F(CleanExitBeaconTest, WriteBeaconValueWhenNotExitingCleanly) {
  const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
  const base::FilePath beacon_file_path =
      user_data_dir_path.Append(kCleanExitBeaconFilename);
  ASSERT_FALSE(base::PathExists(beacon_file_path));

  TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_path);
  clean_exit_beacon.WriteBeaconValue(/*exited_cleanly=*/false,
                                     /*is_extended_safe_mode=*/true);

  // Verify that the beacon file exists and has well-formed contents after
  // updating the beacon value.
  EXPECT_TRUE(base::PathExists(beacon_file_path));
  std::string beacon_file_contents1;
  ASSERT_TRUE(base::ReadFileToString(beacon_file_path, &beacon_file_contents1));
  EXPECT_EQ(beacon_file_contents1,
            "{\"user_experience_metrics.stability.exited_cleanly\":false,"
            "\"variations_crash_streak\":0}");
  // Verify that the BeaconFileWrite metric was emitted.
  histogram_tester_.ExpectUniqueSample(
      "Variations.ExtendedSafeMode.BeaconFileWrite", 1, 1);

  // Write the beacon value again. This is done because it is possible for
  // WriteBeaconValue() to be called twice during startup or shutdown with the
  // same value for |exited_cleanly|.
  clean_exit_beacon.WriteBeaconValue(/*exited_cleanly*/ false,
                                     /*is_extended_safe_mode=*/false);

  // Verify that the beacon file exists and has well-formed contents after
  // updating the beacon value.
  EXPECT_TRUE(base::PathExists(beacon_file_path));
  std::string beacon_file_contents2;
  ASSERT_TRUE(base::ReadFileToString(beacon_file_path, &beacon_file_contents2));
  EXPECT_EQ(beacon_file_contents2,
            "{\"user_experience_metrics.stability.exited_cleanly\":false,"
            "\"variations_crash_streak\":0}");
  // Verify that the BeaconFileWrite metric was not emitted a second time. The
  // beacon file should not have been written again since the beacon value did
  // not change.
  histogram_tester_.ExpectUniqueSample(
      "Variations.ExtendedSafeMode.BeaconFileWrite", 1, 1);
}

TEST_F(CleanExitBeaconTest, WriteBeaconValueWhenExitingCleanly) {
  const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
  const base::FilePath beacon_file_path =
      user_data_dir_path.Append(kCleanExitBeaconFilename);
  ASSERT_FALSE(base::PathExists(beacon_file_path));

  TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_path);
  clean_exit_beacon.WriteBeaconValue(/*exited_cleanly=*/true,
                                     /*is_extended_safe_mode=*/false);

  // Verify that the beacon file exists and has well-formed contents after
  // updating the beacon value.
  EXPECT_TRUE(base::PathExists(beacon_file_path));
  std::string beacon_file_contents1;
  ASSERT_TRUE(base::ReadFileToString(beacon_file_path, &beacon_file_contents1));
  EXPECT_EQ(beacon_file_contents1,
            "{\"user_experience_metrics.stability.exited_cleanly\":true,"
            "\"variations_crash_streak\":0}");
  // Verify that the BeaconFileWrite metric was emitted.
  histogram_tester_.ExpectUniqueSample(
      "Variations.ExtendedSafeMode.BeaconFileWrite", 1, 1);

  // Write the beacon value again. This is done because it is possible for
  // WriteBeaconValue() to be called twice during startup or shutdown with the
  // same value for |exited_cleanly|.
  clean_exit_beacon.WriteBeaconValue(/*exited_cleanly*/ true,
                                     /*is_extended_safe_mode=*/false);

  // Verify that the beacon file exists and has well-formed contents after
  // updating the beacon value.
  EXPECT_TRUE(base::PathExists(beacon_file_path));
  std::string beacon_file_contents2;
  ASSERT_TRUE(base::ReadFileToString(beacon_file_path, &beacon_file_contents2));
  EXPECT_EQ(beacon_file_contents2,
            "{\"user_experience_metrics.stability.exited_cleanly\":true,"
            "\"variations_crash_streak\":0}");
  // Verify that the BeaconFileWrite metric was not emitted a second time. The
  // beacon file should not have been written again since the beacon value did
  // not change.
  histogram_tester_.ExpectUniqueSample(
      "Variations.ExtendedSafeMode.BeaconFileWrite", 1, 1);
}

// Verify that there's a DCHECK when attempting to write a clean beacon with
// |is_extended_safe_mode| set to true. When |is_extended_safe_mode| is true,
// the only valid value for |exited_cleanly| is false.
TEST_F(CleanExitBeaconTest, InvalidWriteBeaconValueArgsTriggerDcheck) {
  TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_.GetPath());
  EXPECT_DCHECK_DEATH(
      clean_exit_beacon.WriteBeaconValue(/*exited_cleanly=*/true,
                                         /*is_extended_safe_mode=*/true));
}

#if BUILDFLAG(IS_IOS)
// Verify the logic for recording UMA.CleanExitBeaconConsistency3.
INSTANTIATE_TEST_SUITE_P(
    All,
    BeaconFileAndPlatformBeaconConsistencyTest,
    ::testing::Values(
        BeaconConsistencyTestParams{
            .test_name = "MissingMissing",
            .expected_consistency =
                CleanExitBeaconConsistency::kMissingMissing},
        BeaconConsistencyTestParams{
            .test_name = "MissingClean",
            .platform_specific_beacon_value = true,
            .expected_consistency = CleanExitBeaconConsistency::kMissingClean},
        BeaconConsistencyTestParams{
            .test_name = "MissingDirty",
            .platform_specific_beacon_value = false,
            .expected_consistency = CleanExitBeaconConsistency::kMissingDirty},
        BeaconConsistencyTestParams{
            .test_name = "CleanMissing",
            .beacon_file_beacon_value = true,
            .expected_consistency = CleanExitBeaconConsistency::kCleanMissing},
        BeaconConsistencyTestParams{
            .test_name = "DirtyMissing",
            .beacon_file_beacon_value = false,
            .expected_consistency = CleanExitBeaconConsistency::kDirtyMissing},
        BeaconConsistencyTestParams{
            .test_name = "CleanClean",
            .beacon_file_beacon_value = true,
            .platform_specific_beacon_value = true,
            .expected_consistency = CleanExitBeaconConsistency::kCleanClean},
        BeaconConsistencyTestParams{
            .test_name = "CleanDirty",
            .beacon_file_beacon_value = true,
            .platform_specific_beacon_value = false,
            .expected_consistency = CleanExitBeaconConsistency::kCleanDirty},
        BeaconConsistencyTestParams{
            .test_name = "DirtyClean",
            .beacon_file_beacon_value = false,
            .platform_specific_beacon_value = true,
            .expected_consistency = CleanExitBeaconConsistency::kDirtyClean},
        BeaconConsistencyTestParams{
            .test_name = "DirtyDirty",
            .beacon_file_beacon_value = false,
            .platform_specific_beacon_value = false,
            .expected_consistency = CleanExitBeaconConsistency::kDirtyDirty}),
    [](const ::testing::TestParamInfo<BeaconConsistencyTestParams>& params) {
      return params.param.test_name;
    });

TEST_P(BeaconFileAndPlatformBeaconConsistencyTest, BeaconConsistency) {
  // Verify that the beacon file is not present. Unless set below, this beacon
  // is considered missing.
  const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
  const base::FilePath temp_beacon_file_path =
      user_data_dir_path.Append(kCleanExitBeaconFilename);
  ASSERT_FALSE(base::PathExists(temp_beacon_file_path));
  // Clear the platform-specific beacon. Unless set below, this beacon is also
  // considered missing.
  CleanExitBeacon::ResetStabilityExitedCleanlyForTesting(&prefs_);

  BeaconConsistencyTestParams params = GetParam();
  if (params.beacon_file_beacon_value) {
    ASSERT_TRUE(base::WriteFile(
        temp_beacon_file_path,
        CleanExitBeacon::CreateBeaconFileContentsForTesting(
            /*exited_cleanly=*/params.beacon_file_beacon_value.value(),
            /*crash_streak=*/0)));
  }
  if (params.platform_specific_beacon_value) {
    CleanExitBeacon::SetUserDefaultsBeacon(
        /*exited_cleanly=*/params.platform_specific_beacon_value.value());
  }

  TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_path);
  histogram_tester_.ExpectUniqueSample("UMA.CleanExitBeaconConsistency3",
                                       params.expected_consistency, 1);
}
#endif  // BUILDFLAG(IS_IOS)

}  // namespace metrics