File: hats_service_browsertest.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 (866 lines) | stat: -rw-r--r-- 35,953 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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <map>
#include <optional>

#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/user_metrics.h"
#include "base/run_loop.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "base/version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
#include "chrome/browser/metrics/variations/google_groups_manager_factory.h"
#include "chrome/browser/policy/policy_test_utils.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/hats/hats_service_desktop.h"
#include "chrome/browser/ui/hats/hats_service_factory.h"
#include "chrome/browser/ui/hats/survey_config.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_features.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/metrics_services_manager/metrics_services_manager.h"
#include "components/plus_addresses/features.h"
#include "components/plus_addresses/plus_address_hats_utils.h"
#include "components/policy/core/common/policy_pref_names.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
#include "components/variations/service/google_groups_manager.h"
#include "components/variations/service/google_groups_manager_prefs.h"
#include "components/variations/variations_seed_processor.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/isolated_world_ids.h"
#include "content/public/test/browser_test.h"
#include "net/dns/mock_host_resolver.h"

namespace {

constexpr char kRelevantGroupId[] = "1234";
constexpr base::TimeDelta kCooldownOverride = base::Days(14);

base::test::FeatureRefAndParams probability_zero{
    features::kHappinessTrackingSurveysForDesktopSettings,
    {{"probability", "0.000"}}};
base::test::FeatureRefAndParams probability_one{
    features::kHappinessTrackingSurveysForDesktopSettings,
    {{"probability", "1.000"},
     {"survey", kHatsSurveyTriggerSettings},
     {"en_site_id", "test_site_id"}}};
base::test::FeatureRefAndParams cool_down_period_overriden{
    autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey,
    {{"probability", "1.000"},
     {"survey", kHatsSurveyTriggerPlusAddressAcceptedFirstTimeCreate},
     {"cooldown-override-days", /*days=*/"14"}}};
base::test::FeatureRefAndParams cool_down_period_overriden_and_group_controlled{
    autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey,
    {{variations::internal::kGoogleGroupFeatureParamName, kRelevantGroupId},
     {"probability", "1.000"},
     {"survey", kHatsSurveyTriggerPlusAddressAcceptedFirstTimeCreate},
     {"cooldown-override-days", /*days=*/"14"}}};

class ScopedSetMetricsConsent {
 public:
  // Enables or disables metrics consent based off of |consent|.
  explicit ScopedSetMetricsConsent(bool consent) : consent_(consent) {
    ChromeMetricsServiceAccessor::SetMetricsAndCrashReportingForTesting(
        &consent_);
  }

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

  ~ScopedSetMetricsConsent() {
    ChromeMetricsServiceAccessor::SetMetricsAndCrashReportingForTesting(
        nullptr);
  }

 private:
  const bool consent_;
};

class HatsServiceBrowserTestBase : public policy::PolicyTest {
 public:
  HatsServiceBrowserTestBase(const HatsServiceBrowserTestBase&) = delete;
  HatsServiceBrowserTestBase& operator=(const HatsServiceBrowserTestBase&) =
      delete;

 protected:
  explicit HatsServiceBrowserTestBase(
      std::vector<base::test::FeatureRefAndParams> enabled_features)
      : enabled_features_(enabled_features) {
    scoped_feature_list_.InitWithFeaturesAndParameters(enabled_features_, {});
  }

  HatsServiceBrowserTestBase() = default;
  ~HatsServiceBrowserTestBase() override = default;

  Profile* profile() { return chrome_test_utils::GetProfile(this); }

  HatsServiceDesktop* GetHatsService(Browser* browser = nullptr) {
    Profile* profile =
        browser ? browser->profile() : this->browser()->profile();
    HatsServiceDesktop* service = static_cast<HatsServiceDesktop*>(
        HatsServiceFactory::GetForProfile(profile, true));
    return service;
  }

  void SetMetricsConsent(bool consent) {
    scoped_metrics_consent_.emplace(consent);
  }

  bool HatsNextDialogCreated(Browser* browser = nullptr) {
    return GetHatsService(browser)->hats_next_dialog_exists_for_testing();
  }

  // Mock a survey with a custom requested browser type. The `other_browser`
  // param may be used to mock the survey in another browser too. Returns the
  // trigger to use when launching the survey.
  std::string MockSurveyWithRequestedBrowserType(
      Browser* other_browser,
      hats::SurveyConfig::RequestedBrowserType requested_browser_type) {
    for (HatsServiceDesktop* service :
         {GetHatsService(), GetHatsService(other_browser)}) {
      service
          ->GetSurveyConfigsByTriggersForTesting()[kHatsSurveyTriggerSettings]
          .requested_browser_type = requested_browser_type;
    }
    return kHatsSurveyTriggerSettings;
  }

 private:
  std::optional<ScopedSetMetricsConsent> scoped_metrics_consent_;

  base::test::ScopedFeatureList scoped_feature_list_;

  std::vector<base::test::FeatureRefAndParams> enabled_features_;
};

class HatsServiceProbabilityZero : public HatsServiceBrowserTestBase {
 public:
  HatsServiceProbabilityZero(const HatsServiceProbabilityZero&) = delete;
  HatsServiceProbabilityZero& operator=(const HatsServiceProbabilityZero&) =
      delete;

 protected:
  HatsServiceProbabilityZero()
      : HatsServiceBrowserTestBase({probability_zero}) {}

  ~HatsServiceProbabilityZero() override = default;
};

class HatsServiceProbabilityOne : public HatsServiceBrowserTestBase {
 public:
  HatsServiceProbabilityOne(const HatsServiceProbabilityOne&) = delete;
  HatsServiceProbabilityOne& operator=(const HatsServiceProbabilityOne&) =
      delete;

 protected:
  HatsServiceProbabilityOne() : HatsServiceBrowserTestBase({probability_one}) {}

  ~HatsServiceProbabilityOne() override = default;

 private:
  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    // Set the profile creation time to be old enough to ensure triggering.
    browser()->profile()->SetCreationTimeForTesting(base::Time::Now() -
                                                    base::Days(45));
  }

  void TearDownOnMainThread() override {
    GetHatsService()->SetSurveyMetadataForTesting({});
  }
};

class HatsServiceConfigCoolDownPeriodOverriden
    : public HatsServiceBrowserTestBase {
 public:
  HatsServiceConfigCoolDownPeriodOverriden(
      const HatsServiceConfigCoolDownPeriodOverriden&) = delete;
  HatsServiceConfigCoolDownPeriodOverriden& operator=(
      const HatsServiceConfigCoolDownPeriodOverriden&) = delete;

 protected:
  HatsServiceConfigCoolDownPeriodOverriden()
      : HatsServiceBrowserTestBase({cool_down_period_overriden}) {}

  ~HatsServiceConfigCoolDownPeriodOverriden() override = default;
};

class HatsServiceSurveyFeatureControlledByGroup
    : public HatsServiceBrowserTestBase {
 public:
  HatsServiceSurveyFeatureControlledByGroup(
      const HatsServiceSurveyFeatureControlledByGroup&) = delete;
  HatsServiceSurveyFeatureControlledByGroup& operator=(
      const HatsServiceSurveyFeatureControlledByGroup&) = delete;

 protected:
  HatsServiceSurveyFeatureControlledByGroup()
      : HatsServiceBrowserTestBase(
            {cool_down_period_overriden_and_group_controlled}) {}

  ~HatsServiceSurveyFeatureControlledByGroup() override = default;

  void AddProfileToGroup(const std::string& group) {
    base::Value::List pref_groups_list;
    base::Value::Dict group_dict;
    group_dict.Set(variations::kDogfoodGroupsSyncPrefGaiaIdKey, group);
    pref_groups_list.Append(std::move(group_dict));
    profile()->GetPrefs()->SetList(
#if BUILDFLAG(IS_CHROMEOS)
        variations::kOsDogfoodGroupsSyncPrefName,
#else
        variations::kDogfoodGroupsSyncPrefName,
#endif
        std::move(pref_groups_list));
  }
};

}  // namespace

IN_PROC_BROWSER_TEST_F(HatsServiceBrowserTestBase, BubbleNotShownOnDefault) {
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityZero, NoShow) {
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, NoShowConsentNotGiven) {
  SetMetricsConsent(false);
  ASSERT_FALSE(
      g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_FALSE(HatsNextDialogCreated());

  Browser* incognito_browser = CreateIncognitoBrowser();
  GetHatsService(incognito_browser)->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_FALSE(HatsNextDialogCreated(incognito_browser));
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, TriggerMismatchNoShow) {
  SetMetricsConsent(true);
  ASSERT_TRUE(
      g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
  GetHatsService()->LaunchSurvey("nonexistent-trigger");
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, AlwaysShow) {
  SetMetricsConsent(true);
  ASSERT_TRUE(
      g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       ShowWhenFeedbackSurveyPolicyEnabled) {
  SetMetricsConsent(true);
  policy::PolicyMap policies;
  SetPolicy(&policies, policy::key::kFeedbackSurveysEnabled, base::Value(true));
  UpdateProviderPolicy(policies);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       NoShowWhenFeedbackSurveyPolicyDisabled) {
  SetMetricsConsent(true);
  policy::PolicyMap policies;
  SetPolicy(&policies, policy::key::kFeedbackSurveysEnabled,
            base::Value(false));
  UpdateProviderPolicy(policies);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_FALSE(HatsNextDialogCreated());

  Browser* incognito_browser = CreateIncognitoBrowser();
  auto trigger = MockSurveyWithRequestedBrowserType(
      incognito_browser, hats::SurveyConfig::RequestedBrowserType::kIncognito);
  GetHatsService(incognito_browser)->LaunchSurvey(trigger);
  EXPECT_FALSE(HatsNextDialogCreated(incognito_browser));
}

IN_PROC_BROWSER_TEST_F(
    HatsServiceProbabilityOne,
    NeverShowWhenFeedbackSurveyPolicyEnabledWithoutMetricsConsent) {
  SetMetricsConsent(false);
  policy::PolicyMap policies;
  SetPolicy(&policies, policy::key::kFeedbackSurveysEnabled, base::Value(true));
  UpdateProviderPolicy(policies);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, AlsoShowsSettingsSurvey) {
  SetMetricsConsent(true);
  ASSERT_TRUE(
      g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, SameMajorVersionNoShow) {
  SetMetricsConsent(true);
  base::HistogramTester histogram_tester;
  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.last_major_version = version_info::GetVersion().components()[0];
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  histogram_tester.ExpectUniqueSample(
      kHatsShouldShowSurveyReasonHistogram,
      HatsServiceDesktop::ShouldShowSurveyReasons::
          kNoReceivedSurveyInCurrentMilestone,
      1);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, DifferentMajorVersionShow) {
  SetMetricsConsent(true);
  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.last_major_version = 42;
  ASSERT_NE(42u, version_info::GetVersion().components()[0]);
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       SurveyStartedBeforeRequiredElapsedTimeNoShow) {
  SetMetricsConsent(true);
  base::HistogramTester histogram_tester;
  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.last_survey_started_time = base::Time::Now();
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  histogram_tester.ExpectUniqueSample(
      kHatsShouldShowSurveyReasonHistogram,
      HatsServiceDesktop::ShouldShowSurveyReasons::kNoLastSurveyTooRecent, 1);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       SurveyStartedBeforeElapsedTimeBetweenAnySurveys) {
  SetMetricsConsent(true);
  base::HistogramTester histogram_tester;
  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.any_last_survey_started_time = base::Time::Now();
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_FALSE(HatsNextDialogCreated());
  histogram_tester.ExpectUniqueSample(
      kHatsShouldShowSurveyReasonHistogram,
      HatsServiceDesktop::ShouldShowSurveyReasons::kNoAnyLastSurveyTooRecent,
      1);
}

IN_PROC_BROWSER_TEST_F(
    HatsServiceConfigCoolDownPeriodOverriden,
    SurveyWithCoolddownOverride_FeatureNotGroupControlled_NoSurvey) {
  base::HistogramTester histogram_tester;
  SetMetricsConsent(true);
  browser()->profile()->SetCreationTimeForTesting(base::Time::Now() -
                                                  base::Days(31));

  GoogleGroupsManager* groups_manager =
      GoogleGroupsManagerFactory::GetForBrowserContext(profile());
  EXPECT_FALSE(groups_manager->IsFeatureGroupControlled(
      autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey));
  EXPECT_TRUE(groups_manager->IsFeatureEnabledForProfile(
      autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey));
  // The cooldown override for the feature should be set to 14 days.
  EXPECT_EQ(base::FeatureParam<int>(
                &autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey,
                plus_addresses::hats::kCooldownOverrideDays, 0)
                .Get(),
            14);

  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.any_last_survey_started_time = base::Time::Now();
  metadata.any_last_survey_with_cooldown_override_started_time =
      base::Time::Now() - (kCooldownOverride + base::Days(1));
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  // kHatsSurveyTriggerPlusAddressAcceptedFirstTimeCreate overrides the cool
  // down period.
  GetHatsService()->LaunchSurvey(
      kHatsSurveyTriggerPlusAddressAcceptedFirstTimeCreate,
      /*success_callback=*/base::DoNothing(),
      /*failure_callback=*/base::DoNothing(), /*product_specific_bits_data=*/{},
      /*product_specific_string_data=*/
      std::map<std::string, std::string>{
          {plus_addresses::hats::kPlusAddressesCount, "0"},
          {plus_addresses::hats::kFirstPlusAddressCreationTime, "0"},
          {plus_addresses::hats::kLastPlusAddressFillingTime, "0"}});
  EXPECT_FALSE(GetHatsService()->hats_next_dialog_exists_for_testing());
  // Since the feature is not group controlled, the cooldown override has no
  // effect. The default cooldown of 180 days is used, so the survey is on
  // cooldown.
  histogram_tester.ExpectUniqueSample(
      kHatsShouldShowSurveyReasonHistogram,
      HatsServiceDesktop::ShouldShowSurveyReasons::kNoAnyLastSurveyTooRecent,
      1);
}

IN_PROC_BROWSER_TEST_F(
    HatsServiceSurveyFeatureControlledByGroup,
    SurveyWithCoolddownOverride_FeatureIsOnCooldown_NoSurvey) {
  base::HistogramTester histogram_tester;
  // Add the profile to the group assigned in the field trial config.
  // `GoogleGroupsManager::IsFeatureGroupControlled()` returns `false` without
  // this call.
  AddProfileToGroup(kRelevantGroupId);
  SetMetricsConsent(true);
  browser()->profile()->SetCreationTimeForTesting(base::Time::Now() -
                                                  base::Days(31));

  GoogleGroupsManager* groups_manager =
      GoogleGroupsManagerFactory::GetForBrowserContext(profile());
  EXPECT_TRUE(groups_manager->IsFeatureGroupControlled(
      autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey));
  EXPECT_TRUE(groups_manager->IsFeatureEnabledForProfile(
      autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey));
  // The cooldown override for the feature should be set to 14 days.
  EXPECT_EQ(base::FeatureParam<int>(
                &autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey,
                plus_addresses::hats::kCooldownOverrideDays, 0)
                .Get(),
            14);

  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.any_last_survey_started_time = base::Time::Now() - base::Days(365);
  metadata.any_last_survey_with_cooldown_override_started_time =
      base::Time::Now() - (kCooldownOverride - base::Days(1));
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  // kHatsSurveyTriggerPlusAddressAcceptedFirstTimeCreate overrides the cool
  // down period.
  GetHatsService()->LaunchSurvey(
      kHatsSurveyTriggerPlusAddressAcceptedFirstTimeCreate,
      /*success_callback=*/base::DoNothing(),
      /*failure_callback=*/base::DoNothing(), /*product_specific_bits_data=*/{},
      /*product_specific_string_data=*/
      std::map<std::string, std::string>{
          {plus_addresses::hats::kPlusAddressesCount, "0"},
          {plus_addresses::hats::kFirstPlusAddressCreationTime, "0"},
          {plus_addresses::hats::kLastPlusAddressFillingTime, "0"}});
  EXPECT_FALSE(GetHatsService()->hats_next_dialog_exists_for_testing());
  // Cooldown period is set, the feature is enabled for profile and group
  // controlled. However, the last survey with cooldown override was shown just
  // 2 days ago, so the survey is on cooldown.
  histogram_tester.ExpectUniqueSample(
      kHatsShouldShowSurveyReasonHistogram,
      HatsServiceDesktop::ShouldShowSurveyReasons::kNoAnyLastSurveyTooRecent,
      1);
}

IN_PROC_BROWSER_TEST_F(
    HatsServiceSurveyFeatureControlledByGroup,
    SurveyWithCoolddownOverride_FeatureIsGroupControlled_StartsSurvey) {
  // Add the profile to the group assigned in the field trial config.
  // `GoogleGroupsManager::IsFeatureGroupControlled()` returns `false` without
  // this call.
  AddProfileToGroup(kRelevantGroupId);
  SetMetricsConsent(true);
  browser()->profile()->SetCreationTimeForTesting(base::Time::Now() -
                                                  base::Days(31));

  GoogleGroupsManager* groups_manager =
      GoogleGroupsManagerFactory::GetForBrowserContext(profile());
  EXPECT_TRUE(groups_manager->IsFeatureGroupControlled(
      autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey));
  EXPECT_TRUE(groups_manager->IsFeatureEnabledForProfile(
      autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey));
  // The cooldown override for the feature should be set to 14 days.
  EXPECT_EQ(base::FeatureParam<int>(
                &autofill::features::kPlusAddressAcceptedFirstTimeCreateSurvey,
                plus_addresses::hats::kCooldownOverrideDays, 0)
                .Get(),
            14);

  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.any_last_survey_started_time = base::Time::Now();
  metadata.any_last_survey_with_cooldown_override_started_time =
      base::Time::Now() - (kCooldownOverride + base::Days(1));
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  // kHatsSurveyTriggerPlusAddressAcceptedFirstTimeCreate overrides the cool
  // down period.
  GetHatsService()->LaunchSurvey(
      kHatsSurveyTriggerPlusAddressAcceptedFirstTimeCreate,
      /*success_callback=*/base::DoNothing(),
      /*failure_callback=*/base::DoNothing(), /*product_specific_bits_data=*/{},
      /*product_specific_string_data=*/
      std::map<std::string, std::string>{
          {plus_addresses::hats::kPlusAddressesCount, "0"},
          {plus_addresses::hats::kFirstPlusAddressCreationTime, "0"},
          {plus_addresses::hats::kLastPlusAddressFillingTime, "0"}});
  EXPECT_TRUE(GetHatsService()->hats_next_dialog_exists_for_testing());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, ProfileTooYoungToShow) {
  SetMetricsConsent(true);
  base::HistogramTester histogram_tester;
  // Set creation time to only 15 days.
  browser()->profile()->SetCreationTimeForTesting(base::Time::Now() -
                                                  base::Days(15));
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  histogram_tester.ExpectUniqueSample(
      kHatsShouldShowSurveyReasonHistogram,
      HatsServiceDesktop::ShouldShowSurveyReasons::kNoProfileTooNew, 1);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, ProfileOldEnoughToShow) {
  SetMetricsConsent(true);
  // Set creation time to 31 days. This is just past the threshold.
  browser()->profile()->SetCreationTimeForTesting(base::Time::Now() -
                                                  base::Days(31));
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       RegularSurveyInIncognitoNoShow) {
  SetMetricsConsent(true);
  base::HistogramTester histogram_tester;

  // A regular survey should not be shown in incognito
  Browser* incognito_browser = CreateIncognitoBrowser();
  GetHatsService(incognito_browser)->LaunchSurvey(kHatsSurveyTriggerSettings);
  histogram_tester.ExpectUniqueSample(
      kHatsShouldShowSurveyReasonHistogram,
      HatsServiceDesktop::ShouldShowSurveyReasons::kNoWrongBrowserType, 1);
  EXPECT_FALSE(HatsNextDialogCreated(incognito_browser));
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       IncognitoSurveyShownOnlyInIncognito) {
  SetMetricsConsent(true);
  base::HistogramTester histogram_tester;

  Browser* incognito_browser = CreateIncognitoBrowser();
  auto trigger = MockSurveyWithRequestedBrowserType(
      incognito_browser, hats::SurveyConfig::RequestedBrowserType::kIncognito);

  // An incognito survey should not be shown in regular
  GetHatsService()->LaunchSurvey(trigger);
  histogram_tester.ExpectUniqueSample(
      kHatsShouldShowSurveyReasonHistogram,
      HatsServiceDesktop::ShouldShowSurveyReasons::kNoWrongBrowserType, 1);
  EXPECT_FALSE(HatsNextDialogCreated());

  // An incognito survey should be shown in incognito
  GetHatsService(incognito_browser)->LaunchSurvey(trigger);
  EXPECT_TRUE(HatsNextDialogCreated(incognito_browser));
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, IncognitoModeDisabledNoShow) {
  SetMetricsConsent(true);
  // Disable incognito mode for this profile.
  PrefService* pref_service = browser()->profile()->GetPrefs();
  pref_service->SetInteger(
      policy::policy_prefs::kIncognitoModeAvailability,
      static_cast<int>(policy::IncognitoModeAvailability::kDisabled));
  EXPECT_EQ(policy::IncognitoModeAvailability::kDisabled,
            IncognitoModePrefs::GetAvailability(pref_service));

  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, CheckedWithinADayNoShow) {
  SetMetricsConsent(true);
  base::HistogramTester histogram_tester;
  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.last_survey_check_time = base::Time::Now() - base::Hours(23);
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  histogram_tester.ExpectUniqueSample(
      kHatsShouldShowSurveyReasonHistogram,
      HatsServiceDesktop::ShouldShowSurveyReasons::kNoLastSurveyCheckTooRecent,
      1);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, CheckedAfterADayToShow) {
  SetMetricsConsent(true);
  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.last_survey_check_time = base::Time::Now() - base::Days(1);
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, SurveyAlreadyFullNoShow) {
  SetMetricsConsent(true);
  HatsServiceDesktop::SurveyMetadata metadata;
  metadata.is_survey_full = true;
  GetHatsService()->SetSurveyMetadataForTesting(metadata);
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, LaunchDelayedSurvey) {
  SetMetricsConsent(true);
  EXPECT_TRUE(
      GetHatsService()->LaunchDelayedSurvey(kHatsSurveyTriggerSettings, 0));
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       LaunchDelayedSurveyForWebContents) {
  SetMetricsConsent(true);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 0));
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, DisallowsEmptyWebContents) {
  SetMetricsConsent(true);
  EXPECT_FALSE(GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, nullptr, 0));
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(
    HatsServiceProbabilityOne,
    AllowsMultipleDelayedSurveyRequestsDifferentWebContents) {
  SetMetricsConsent(true);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 0));
  base::RunLoop().RunUntilIdle();
  chrome::AddTabAt(browser(), GURL(), -1, true);
  EXPECT_TRUE(GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings,
      browser()->tab_strip_model()->GetActiveWebContents(), 0));
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       DisallowsSameDelayedSurveyForWebContentsRequests) {
  SetMetricsConsent(true);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 0));
  EXPECT_FALSE(GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 0));
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       ReleasesPendingTaskAfterFulfilling) {
  SetMetricsConsent(true);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 0));
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(GetHatsService()->HasPendingTasks());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, VisibleWebContentsShow) {
  SetMetricsConsent(true);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 0);
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, InvisibleWebContentsNoShow) {
  SetMetricsConsent(true);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 0);
  chrome::AddTabAt(browser(), GURL(), -1, true);
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       NavigatedWebContents_RequireSameOrigin) {
  SetMetricsConsent(true);
  ASSERT_TRUE(embedded_test_server()->Start());

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("a.test", "/empty.html")));

  // As navigating also occurs asynchronously, a long survey delay is use to
  // ensure it completes before the survey tries to run.
  GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 10000, {}, {},
      /*navigation_behavior=*/
      HatsService::NavigationBehavior::REQUIRE_SAME_ORIGIN);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("b.test", "/empty.html")));
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(GetHatsService()->HasPendingTasks());
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       NavigatedWebContents_NoRequireSameOrigin) {
  SetMetricsConsent(true);
  ASSERT_TRUE(embedded_test_server()->Start());

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("a.test", "/empty.html")));

  EXPECT_FALSE(GetHatsService()->HasPendingTasks());
  GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 10000, {}, {},
      /*navigation_behavior=*/
      HatsService::NavigationBehavior::ALLOW_ANY);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("b.test", "/empty.html")));
  base::RunLoop().RunUntilIdle();

  // The survey task should still be in the pending task queue.
  EXPECT_TRUE(GetHatsService()->HasPendingTasks());
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       NavigatedWebContents_RequireSameDocument) {
  SetMetricsConsent(true);
  ASSERT_TRUE(embedded_test_server()->Start());

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  const GURL kTestUrl = embedded_test_server()->GetURL("a.test", "/empty.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), kTestUrl));

  // As navigating also occurs asynchronously, a long survey delay is use to
  // ensure it completes before the survey tries to run.
  GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 10000, {}, {},
      /*navigation_behavior=*/
      HatsService::NavigationBehavior::REQUIRE_SAME_DOCUMENT);

  // Same-document navigation
  web_contents->GetPrimaryMainFrame()->ExecuteJavaScriptForTests(
      u"document.location='#';", base::NullCallback(),
      content::ISOLATED_WORLD_ID_GLOBAL);
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(GetHatsService()->HasPendingTasks());
  EXPECT_FALSE(HatsNextDialogCreated());

  // Same-origin navigation
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(),
      embedded_test_server()->GetURL("a.test", "/empty_script.html")));

  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(GetHatsService()->HasPendingTasks());
  EXPECT_FALSE(HatsNextDialogCreated());
}

IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, SameOriginNavigation) {
  SetMetricsConsent(true);
  ASSERT_TRUE(embedded_test_server()->Start());

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("a.test", "/empty.html")));

  EXPECT_FALSE(GetHatsService()->HasPendingTasks());
  GetHatsService()->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerSettings, web_contents, 10000, {}, {},
      /*navigation_behavior=*/
      HatsService::NavigationBehavior::REQUIRE_SAME_ORIGIN);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("a.test", "/form.html")));
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(GetHatsService()->HasPendingTasks());
  EXPECT_FALSE(HatsNextDialogCreated());
}

// Check that once a HaTS Next dialog has been created, ShouldShowSurvey
// returns false until the service has been informed the dialog was closed.
IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, SingleHatsNextDialog) {
  SetMetricsConsent(true);
  EXPECT_TRUE(GetHatsService()->ShouldShowSurvey(kHatsSurveyTriggerSettings));
  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);

  // Clear any metadata that would prevent another survey from being displayed.
  GetHatsService()->SetSurveyMetadataForTesting({});

  // At this point a HaTS Next dialog is created and is attempting to contact
  // the wrapper website (which will fail as requests to non-localhost addresses
  // are disallowed in browser tests). Regardless of the outcome of the network
  // request, the dialog waits for a timeout posted to the UI thread before
  // closing itself. Since this test is also on the UI thread, these checks,
  // which rely on the dialog still being open, will not race.
  EXPECT_FALSE(GetHatsService()->ShouldShowSurvey(kHatsSurveyTriggerSettings));

  // Inform the service directly that the dialog has been closed.
  GetHatsService()->HatsNextDialogClosed();
  EXPECT_TRUE(GetHatsService()->ShouldShowSurvey(kHatsSurveyTriggerSettings));
}

// Check that launching a HaTS Next survey records a survey check time
IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne, SurveyCheckTimeRecorded) {
  SetMetricsConsent(true);

  // Clear any existing survey metadata.
  GetHatsService()->SetSurveyMetadataForTesting({});

  GetHatsService()->LaunchSurvey(kHatsSurveyTriggerSettings);

  HatsServiceDesktop::SurveyMetadata metadata;
  GetHatsService()->GetSurveyMetadataForTesting(&metadata);
  EXPECT_TRUE(metadata.last_survey_check_time.has_value());
}

// Check that launching a HaTS Next survey records a survey check time even if
// triggered in incognito
IN_PROC_BROWSER_TEST_F(HatsServiceProbabilityOne,
                       SurveyCheckTimeRecordedIncognito) {
  SetMetricsConsent(true);

  // Clear any existing survey metadata.
  GetHatsService()->SetSurveyMetadataForTesting({});

  Browser* incognito_browser = CreateIncognitoBrowser();
  auto trigger = MockSurveyWithRequestedBrowserType(
      incognito_browser, hats::SurveyConfig::RequestedBrowserType::kIncognito);

  GetHatsService(incognito_browser)->LaunchSurvey(trigger);

  HatsServiceDesktop::SurveyMetadata metadata;
  GetHatsService()->GetSurveyMetadataForTesting(&metadata);
  EXPECT_TRUE(metadata.last_survey_check_time.has_value());
}