File: first_run_service_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 (415 lines) | stat: -rw-r--r-- 17,232 bytes parent folder | download
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
// 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 "chrome/browser/ui/startup/first_run_service.h"

#include "base/files/file_path.h"
#include "base/functional/callback_forward.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/stringprintf.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/test/test_future.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/signin_features.h"
#include "chrome/browser/ui/startup/first_run_test_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/scoped_testing_local_state.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/metrics/metrics_service.h"
#include "components/metrics/metrics_service_client.h"
#include "components/metrics/metrics_state_manager.h"
#include "components/metrics/test/test_enabled_state_provider.h"
#include "components/metrics/test/test_metrics_service_client.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "components/variations/active_field_trials.h"
#include "components/variations/synthetic_trial_registry.h"
#include "components/variations/synthetic_trials.h"
#include "components/variations/synthetic_trials_active_group_id_provider.h"
#include "components/variations/variations_crash_keys.h"
#include "components/variations/variations_test_utils.h"
#include "components/version_info/channel.h"
#include "components/version_info/version_info.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"

#if !BUILDFLAG(ENABLE_DICE_SUPPORT)
#error "Unsupported platform"
#endif

namespace {

class ScopedTestingMetricsService {
 public:
  // Sets up a `metrics::MetricsService` instance and makes it available in its
  // scope via `testing_browser_process->metrics_service()`.
  //
  // This service only supports feature related to the usage of synthetic field
  // trials.
  //
  // Requires:
  // - the local state prefs to be usable from `testing_browser_process`
  // - a task runner to be available (see //docs/threading_and_tasks_testing.md)
  explicit ScopedTestingMetricsService(
      TestingBrowserProcess* testing_browser_process)
      : browser_process_(testing_browser_process) {
    CHECK(browser_process_);

    auto* local_state = browser_process_->local_state();
    CHECK(local_state)
        << "Error: local state prefs are required. In a unit test, this can be "
           "set up using base::test::ScopedFeatureList.";

    // The `SyntheticTrialsActiveGroupIdProvider` needs to be notified of
    // changes from the registry for them to be used through the variations API.
    synthetic_trial_registry_observation_.Observe(&synthetic_trial_registry_);

    metrics_service_client_.set_synthetic_trial_registry(
        &synthetic_trial_registry_);

    metrics_state_manager_ = metrics::MetricsStateManager::Create(
        local_state, &enabled_state_provider_,
        /*backup_registry_key=*/std::wstring(),
        /*user_data_dir=*/base::FilePath());

    // Needs to be set up, will be updated at each synthetic trial change.
    variations::InitCrashKeys();

    // Required by `MetricsService` to record UserActions. We don't rely on
    // these here, since we never make it start recording metrics, but the task
    // runner is still required during the shutdown sequence.
    base::SetRecordActionTaskRunner(
        base::SingleThreadTaskRunner::GetCurrentDefault());

    metrics_service_ = std::make_unique<metrics::MetricsService>(
        metrics_state_manager_.get(), &metrics_service_client_, local_state);

    browser_process_->SetMetricsService(metrics_service_.get());
  }

  ~ScopedTestingMetricsService() {
    // The scope is closing, undo the set up that was done in the constuctor:
    // `MetricsService` and other necessary parts like crash keys.
    browser_process_->SetMetricsService(nullptr);
    variations::ClearCrashKeysInstanceForTesting();

    // Note: Clears all the synthetic trials, not juste the ones registered
    // during the lifetime of this object.
    variations::SyntheticTrialsActiveGroupIdProvider::GetInstance()
        ->ResetForTesting();
  }

  metrics::MetricsService* Get() { return metrics_service_.get(); }

 private:
  raw_ptr<TestingBrowserProcess> browser_process_ = nullptr;

  metrics::TestEnabledStateProvider enabled_state_provider_{/*consent=*/true,
                                                            /*enabled=*/true};

  variations::SyntheticTrialRegistry synthetic_trial_registry_;
  base::ScopedObservation<variations::SyntheticTrialRegistry,
                          variations::SyntheticTrialObserver>
      synthetic_trial_registry_observation_{
          variations::SyntheticTrialsActiveGroupIdProvider::GetInstance()};

  metrics::TestMetricsServiceClient metrics_service_client_;
  std::unique_ptr<metrics::MetricsStateManager> metrics_state_manager_;

  std::unique_ptr<metrics::MetricsService> metrics_service_;
};

struct FirstRunFieldTrialTestParams {
  double entropy_value;
  version_info::Channel channel;

  bool expect_study_enabled;
  bool expect_feature_enabled;
};

class ProfileNameChangeFuture : public base::test::TestFuture<std::u16string>,
                                public ProfileAttributesStorage::Observer {
 public:
  // Creates a future that will be resolved with the profile name the next time
  // it's updated. If `observed_profile_path` is empty, any profile name update
  // will result in the future resolving.
  explicit ProfileNameChangeFuture(
      ProfileAttributesStorage& profile_attributes_storage,
      const base::FilePath& observed_profile_path = base::FilePath())
      : profile_attributes_storage_(profile_attributes_storage),
        observed_profile_path_(observed_profile_path) {
    scoped_observation_.Observe(&profile_attributes_storage_.get());
  }

  // ProfileAttributesStorage::Observer:
  void OnProfileNameChanged(const base::FilePath& profile_path,
                            const std::u16string& old_profile_name) override {
    if (!observed_profile_path_.empty() &&
        observed_profile_path_ != profile_path) {
      return;
    }

    scoped_observation_.Reset();
    std::move(GetCallback())
        .Run(profile_attributes_storage_
                 ->GetProfileAttributesWithPath(profile_path)
                 ->GetLocalProfileName());
  }

 private:
  const raw_ref<ProfileAttributesStorage> profile_attributes_storage_;
  const base::FilePath observed_profile_path_;

  base::ScopedObservation<ProfileAttributesStorage,
                          ProfileAttributesStorage::Observer>
      scoped_observation_{this};
};

}  // namespace

class FirstRunServiceTest : public testing::Test {
 private:
  content::BrowserTaskEnvironment task_environment_;
};

TEST_F(FirstRunServiceTest, ShouldOpenFirstRun) {
  TestingProfileManager profile_manager{TestingBrowserProcess::GetGlobal()};
  ASSERT_TRUE(profile_manager.SetUp());

  auto* profile = profile_manager.CreateTestingProfile("Test Profile");
  EXPECT_TRUE(ShouldOpenFirstRun(profile));

  SetIsFirstRun(false);
  EXPECT_FALSE(ShouldOpenFirstRun(profile));

  SetIsFirstRun(true);
  EXPECT_TRUE(ShouldOpenFirstRun(profile));

  g_browser_process->local_state()->SetBoolean(prefs::kFirstRunFinished, true);
  EXPECT_FALSE(ShouldOpenFirstRun(profile));
}

// Regression test for crbug.com/1450709.
TEST_F(FirstRunServiceTest, ShouldPopulateProfileNameFromPrimaryAccount) {
  base::test::ScopedFeatureList feature_list{kForYouFre};

  signin::IdentityTestEnvironment identity_test_env;
  TestingProfileManager testing_profile_manager{
      TestingBrowserProcess::GetGlobal()};
  ASSERT_TRUE(testing_profile_manager.SetUp());

  Profile* profile =
      testing_profile_manager.CreateTestingProfile("Test Profile");

  AccountInfo primary_account_info = identity_test_env.MakeAccountAvailable(
      "primary@gmail.com",
      {.primary_account_consent_level = signin::ConsentLevel::kSync});
  AccountInfo secondary_account_info =
      identity_test_env.MakeAccountAvailable("secondary@gmail.com");

  ProfileNameChangeFuture profile_name_future(
      testing_profile_manager.profile_manager()->GetProfileAttributesStorage(),
      profile->GetPath());

  // Note: the identity manager is not connected to the profile, but for this
  // test, it's not necessary.
  auto first_run_service =
      FirstRunService(*profile, *identity_test_env.identity_manager());

  // Run and complete the first run.
  base::RunLoop fre_completion_loop;
  first_run_service.TryMarkFirstRunAlreadyFinished(
      fre_completion_loop.QuitClosure());
  fre_completion_loop.Run();
  EXPECT_FALSE(ShouldOpenFirstRun(profile));

  // The profile name is still unchanged.
  EXPECT_FALSE(profile_name_future.IsReady());

  // Send extended account info, starting with the secondary account.
  identity_test_env.UpdateAccountInfoForAccount(
      signin::WithGeneratedUserInfo(secondary_account_info, "Secondary"));
  identity_test_env.UpdateAccountInfoForAccount(
      signin::WithGeneratedUserInfo(primary_account_info, "Primary"));

  // The profile name should now be resolved.
  EXPECT_TRUE(profile_name_future.IsReady());
  EXPECT_EQ(u"Primary", profile_name_future.Get());
}

class FirstRunFieldTrialCreatorTest
    : public testing::Test,
      public testing::WithParamInterface<FirstRunFieldTrialTestParams> {
 public:
  base::test::ScopedFeatureList& scoped_feature_list() {
    return scoped_feature_list_;
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_P(FirstRunFieldTrialCreatorTest, SetUpFromClientSide) {
  {
    base::MockEntropyProvider low_entropy_provider{GetParam().entropy_value};
    auto feature_list = std::make_unique<base::FeatureList>();

    FirstRunService::SetUpClientSideFieldTrial(
        low_entropy_provider, feature_list.get(), GetParam().channel);

    // Substitute the existing feature list with the one with field trial
    // configurations we are testing, so we can check the assertions.
    scoped_feature_list().InitWithFeatureList(std::move(feature_list));
  }

  EXPECT_TRUE(base::FieldTrialList::IsTrialActive("ForYouFreStudy"));

  EXPECT_EQ(GetParam().expect_study_enabled,
            base::FeatureList::IsEnabled(kForYouFreSyntheticTrialRegistration));
  EXPECT_EQ(GetParam().expect_feature_enabled,
            base::FeatureList::IsEnabled(kForYouFre));

  EXPECT_EQ(true, kForYouFreCloseShouldProceed.Get());
  EXPECT_EQ(SigninPromoVariant::kSignIn, kForYouFreSignInPromoVariant.Get());
  EXPECT_EQ(GetParam().expect_study_enabled
                ? (GetParam().expect_feature_enabled ? "ClientSideEnabled-2"
                                                     : "ClientSideDisabled-2")
                : "",
            kForYouFreStudyGroup.Get());
}

INSTANTIATE_TEST_SUITE_P(
    ,
    FirstRunFieldTrialCreatorTest,
    testing::Values(
        FirstRunFieldTrialTestParams{.entropy_value = 0.6,
                                     .channel = version_info::Channel::BETA,
                                     .expect_study_enabled = true,
                                     .expect_feature_enabled = false},
        FirstRunFieldTrialTestParams{.entropy_value = 0.01,
                                     .channel = version_info::Channel::BETA,
                                     .expect_study_enabled = true,
                                     .expect_feature_enabled = true},
        FirstRunFieldTrialTestParams{.entropy_value = 0.99,
                                     .channel = version_info::Channel::STABLE,
                                     .expect_study_enabled = false,
                                     .expect_feature_enabled = false},
        FirstRunFieldTrialTestParams{.entropy_value = 0.016,
                                     .channel = version_info::Channel::STABLE,
                                     .expect_study_enabled = true,
                                     .expect_feature_enabled = false},
        FirstRunFieldTrialTestParams{.entropy_value = 0.009,
                                     .channel = version_info::Channel::STABLE,
                                     .expect_study_enabled = true,
                                     .expect_feature_enabled = true}),

    [](const ::testing::TestParamInfo<FirstRunFieldTrialTestParams>& params) {
      return base::StringPrintf(
          "%02.0fpctEntropy%s", params.param.entropy_value * 100,
          version_info::GetChannelString(params.param.channel).data());
    });

// Tests to verify the logic for synthetic trial registration that we use to
// assign a given client in a cohort for our long term tracking metrics.
class FirstRunCohortSetupTest : public testing::Test {
 public:
  static constexpr char kStudyTestGroupName1[] = "test_group_1";
  static constexpr char kStudyTestGroupName2[] = "test_group_2";

 private:
  base::test::TaskEnvironment task_environment_;
  ScopedTestingLocalState testing_local_state_{
      TestingBrowserProcess::GetGlobal()};
  ScopedTestingMetricsService testing_metrics_service_{
      TestingBrowserProcess::GetGlobal()};
};

// `JoinFirstRunCohort` is run when the FRE is finished, if a group name is
// provided through the feature flags, should result in registering the
// synthetic trial with that group name and store it for subsequent startups.
TEST_F(FirstRunCohortSetupTest, JoinFirstRunCohort) {
  PrefService* local_state = g_browser_process->local_state();
  EXPECT_FALSE(local_state->HasPrefPath(prefs::kFirstRunStudyGroup));
  EXPECT_FALSE(
      variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName));

  // No group name available through the features, should no-op.
  FirstRunService::JoinFirstRunCohort();
  EXPECT_FALSE(local_state->HasPrefPath(prefs::kFirstRunStudyGroup));
  EXPECT_FALSE(
      variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName));

  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitWithFeaturesAndParameters(
      /*enabled_features=*/
      {
          {kForYouFreSyntheticTrialRegistration,
           {{"group_name", kStudyTestGroupName1}}},
          {kForYouFre, {}},
      },
      /*disabled_features=*/{});

  // A group name is available, the trial should get registered.
  FirstRunService::JoinFirstRunCohort();
  EXPECT_EQ(kStudyTestGroupName1,
            local_state->GetString(prefs::kFirstRunStudyGroup));
  EXPECT_TRUE(
      variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName));
  EXPECT_TRUE(variations::IsInSyntheticTrialGroup(
      FirstRunService::kSyntheticTrialName, kStudyTestGroupName1));
}

// `EnsureStickToFirstRunCohort` is run on startup, and should result in
// registering the synthetic trial if the client saw the FRE and we recorded a
// group name to assign to it.
TEST_F(FirstRunCohortSetupTest, EnsureStickToFirstRunCohort) {
  PrefService* local_state = g_browser_process->local_state();
  EXPECT_FALSE(local_state->HasPrefPath(prefs::kFirstRunStudyGroup));
  EXPECT_FALSE(
      variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName));

  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitWithFeaturesAndParameters(
      /*enabled_features=*/
      {
          {kForYouFreSyntheticTrialRegistration,
           {{"group_name", kStudyTestGroupName1}}},
          {kForYouFre, {}},
      },
      /*disabled_features=*/{});

  // `EnsureStickToFirstRunCohort()` no-ops without some specific prefs.
  FirstRunService::EnsureStickToFirstRunCohort();
  EXPECT_FALSE(local_state->HasPrefPath(prefs::kFirstRunStudyGroup));
  EXPECT_FALSE(
      variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName));

  // Setting the group name pref: the first, but not sufficient requirement.
  // We also set it to a different name from the feature flag to verify which
  // one is used.
  local_state->SetString(prefs::kFirstRunStudyGroup, kStudyTestGroupName2);
  FirstRunService::EnsureStickToFirstRunCohort();
  EXPECT_FALSE(
      variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName));

  // Marking the FRE finished: the second and final requirement.
  local_state->SetBoolean(prefs::kFirstRunFinished, true);
  FirstRunService::EnsureStickToFirstRunCohort();
  EXPECT_TRUE(
      variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName));

  // The registered group is read from the prefs, not from the feature param.
  EXPECT_TRUE(variations::IsInSyntheticTrialGroup(
      FirstRunService::kSyntheticTrialName, kStudyTestGroupName2));
  EXPECT_FALSE(variations::IsInSyntheticTrialGroup(
      FirstRunService::kSyntheticTrialName, kStudyTestGroupName1));
}