File: ntp_promo_interactive_uitest.cc

package info (click to toggle)
chromium 142.0.7444.175-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,295,352 kB
  • sloc: cpp: 35,488,378; ansic: 7,479,680; javascript: 4,259,373; python: 1,466,843; xml: 757,444; asm: 710,716; pascal: 187,980; sh: 89,247; perl: 88,690; objc: 79,984; sql: 56,984; cs: 42,192; fortran: 24,137; makefile: 22,913; tcl: 15,277; php: 14,018; yacc: 9,005; ruby: 7,553; awk: 3,720; lisp: 3,096; lex: 1,330; ada: 727; jsp: 228; sed: 36
file content (694 lines) | stat: -rw-r--r-- 27,398 bytes parent folder | download | duplicates (4)
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
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sstream>
#include <string>
#include <string_view>

#include "base/i18n/rtl.h"
#include "base/notreached.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/browser/new_tab_page/modules/modules_constants.h"
#include "chrome/browser/new_tab_page/modules/modules_switches.h"
#include "chrome/browser/new_tab_page/modules/test_support.h"
#include "chrome/browser/ui/browser_element_identifiers.h"
#include "chrome/browser/ui/browser_window/public/browser_window_interface.h"
#include "chrome/browser/ui/interaction/browser_elements.h"
#include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
#include "chrome/browser/ui/views/user_education/impl/browser_user_education_context.h"
#include "chrome/browser/ui/webui/new_tab_page/composebox/variations/composebox_fieldtrial.h"
#include "chrome/browser/ui/webui/new_tab_page/ntp_promo/ntp_promo.mojom.h"
#include "chrome/browser/user_education/ntp_promo_identifiers.h"
#include "chrome/browser/user_education/user_education_service.h"
#include "chrome/browser/user_education/user_education_service_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/test/interaction/interactive_browser_test.h"
#include "chrome/test/interaction/tracked_element_webcontents.h"
#include "components/metrics/content/subprocess_metrics_provider.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/search/ntp_features.h"
#include "components/user_education/common/ntp_promo/ntp_promo_controller.h"
#include "components/user_education/common/ntp_promo/ntp_promo_identifier.h"
#include "components/user_education/common/ntp_promo/ntp_promo_registry.h"
#include "components/user_education/common/ntp_promo/ntp_promo_specification.h"
#include "components/user_education/common/user_education_data.h"
#include "components/user_education/common/user_education_features.h"
#include "components/user_education/common/user_education_metadata.h"
#include "components/user_education/common/user_education_storage_service.h"
#include "content/public/test/browser_test.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/typed_identifier.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/native_theme/mock_os_settings_provider.h"
#include "ui/views/interaction/polling_view_observer.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#endif  // BUILDFLAG(IS_MAC)

namespace {

using ntp_promo::mojom::ShowNtpPromosResult;
using ::testing::ValuesIn;
using user_education::features::NtpBrowserPromoType;
using Eligibility = user_education::NtpPromoSpecification::Eligibility;

inline constexpr char kTestPromoName[] = "test_promo";
const InteractiveBrowserTestApi::DeepQuery kPathToNtp = {"ntp-app"};
const InteractiveBrowserTestApi::DeepQuery kPathToIndividualPromos = {
    "ntp-app", "individual-promos", "#promos"};
const InteractiveBrowserTestApi::DeepQuery kPathToFirstIndividualPromo =
    kPathToIndividualPromos + "#promo";

const InteractiveBrowserTestApi::DeepQuery kPathToSetupList = {
    "ntp-app", "setup-list-module-wrapper", "setup-list"};
const InteractiveBrowserTestApi::DeepQuery kPathToSetupListFirstItem =
    kPathToSetupList + "setup-list-item";
constexpr char kActionIconId[] = "#actionIcon";
constexpr char kPromoTextId[] = "#bodyText";
constexpr char kPromoIconId[] = "#bodyIcon";
constexpr char kSignInIconName[] = "account_circle";
constexpr char kExtensionsIconName[] = "my_extensions";
constexpr char kCustomizationIconName[] = "palette";
const std::u16string kShortPromoText = u"Short promo text";
const std::u16string kLongPromoText =
    u"This is a long promo text string that should cause the promo to grow "
    "vertically, stretching the bounds of the promo; no text should be "
    "truncated or harmed in the adjustment of this element's sizing";
constexpr std::string_view kNtpURL = chrome::kChromeUINewTabURL;

DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNtpElementId);
DEFINE_LOCAL_CUSTOM_ELEMENT_EVENT_TYPE(kTestPromoShownEvent);
DEFINE_LOCAL_CUSTOM_ELEMENT_EVENT_TYPE(kTestPromoClickedEvent);
DEFINE_LOCAL_CUSTOM_ELEMENT_EVENT_TYPE(kMetricsRecordedEvent);

// Contains variables on which these tests may be parameterized. This approach
// makes it easy to build sets of relevant tests, vs. the brute-force
// testing::Combine() approach.
struct NtpPromoUiTestParams {
  NtpBrowserPromoType promo_type = NtpBrowserPromoType::kNone;
  std::optional<int> individual_promos = std::nullopt;
  bool long_text = false;
  ui::NativeTheme::PreferredColorScheme color_scheme =
      ui::NativeTheme::PreferredColorScheme::kLight;
  bool wide_screen = false;
  bool rtl = false;

  std::string ToString() const {
    std::ostringstream oss;
    oss << promo_type;
    if (individual_promos.has_value()) {
      oss << "_" << individual_promos.value();
    }
    if (long_text) {
      oss << "_long_text";
    }
    if (color_scheme == ui::NativeTheme::PreferredColorScheme::kDark) {
      oss << "_dark";
    }
    if (wide_screen) {
      oss << "_wide";
    }
    if (rtl) {
      oss << "_rtl";
    }

    return oss.str();
  }
};

using ObserverType =
    views::test::PollingViewPropertyObserver<std::u16string, OmniboxViewViews>;
DEFINE_LOCAL_TYPED_IDENTIFIER_VALUE(ObserverType, kLocationBarTextValue);
MATCHER_P(OptionalStringContains, text, "Optional string contains") {
  return arg.has_value() && arg.value().find(text) != std::u16string::npos;
}

}  // namespace

class NtpPromoUiTest
    : public InteractiveBrowserTest,
      public testing::WithParamInterface<NtpPromoUiTestParams> {
 public:
  NtpPromoUiTest() = default;
  ~NtpPromoUiTest() override = default;

  void SetUp() override {
    feature_list_.InitWithFeaturesAndParameters(GetEnabledFeatures(),
                                                GetDisabledFeatures());
    InteractiveBrowserTest::SetUp();
  }

  virtual std::vector<base::test::FeatureRefAndParams> GetEnabledFeatures() {
    base::FieldTrialParams params;
    params[user_education::features::kNtpBrowserPromoType.name] = [=]() {
      switch (GetParam().promo_type) {
        case NtpBrowserPromoType::kSimple:
          return "simple";
        case NtpBrowserPromoType::kSetupList:
          return "setuplist";
        default:
          NOTREACHED();
      }
    }();
    if (GetParam().individual_promos.has_value()) {
      params[user_education::features::kNtpBrowserPromoIndividualPromoLimit
                 .name] =
          base::NumberToString(GetParam().individual_promos.value());
    }
    return {{user_education::features::kEnableNtpBrowserPromos, params}};
  }

  virtual std::vector<base::test::FeatureRef> GetDisabledFeatures() {
    return {};
  }

  void SetUpOnMainThread() override {
    InteractiveBrowserTest::SetUpOnMainThread();
    // Sanity check that the flag setup actually took; if it didn't, then we
    // can't accurately perform the test.
    ASSERT_EQ(user_education::features::GetNtpBrowserPromoType(),
              GetParam().promo_type);
  }

  void ClearRegisteredPromos() {
    UserEducationService* const service =
        UserEducationServiceFactory::GetForBrowserContext(browser()->profile());
    service->ntp_promo_registry()->ClearPromosForTesting();
  }

  // Removes all promos except the specified ID. This is an easy way to test
  // individual promo functionality, as opposed to trying to target a specific
  // promo on-screen (which may not even be shown due to promo-count limits).
  void ClearRegisteredPromosExcept(
      const user_education::NtpPromoIdentifier& keep_id) {
    UserEducationService* const service =
        UserEducationServiceFactory::GetForBrowserContext(browser()->profile());
    auto ids = service->ntp_promo_registry()->GetNtpPromoIdentifiers();
    for (const auto& id : ids) {
      if (id != keep_id) {
        service->ntp_promo_registry()->ClearPromoForTesting(id);
      }
    }
  }

  void RegisterTestPromo(const user_education::NtpPromoIdentifier& id,
                         Eligibility eligibility,
                         int text_id) {
    UserEducationService* const service =
        UserEducationServiceFactory::GetForBrowserContext(browser()->profile());
    user_education::NtpPromoRegistry* registry = service->ntp_promo_registry();
    user_education::NtpPromoSpecification spec(
        id, user_education::NtpPromoContent(kSignInIconName, text_id, text_id),
        base::BindLambdaForTesting(
            [=](const user_education::UserEducationContextPtr& context) {
              return eligibility;
            }),
        base::BindRepeating(&NtpPromoUiTest::OnTestPromoShown,
                            base::Unretained(this)),
        base::BindRepeating(&NtpPromoUiTest::OnTestPromoClicked,
                            base::Unretained(this)),
        {}, user_education::Metadata());
    registry->AddPromo(std::move(spec));

    if (eligibility == Eligibility::kCompleted) {
      // Need to configure the data so that the completed promo can show.
      user_education::UserEducationStorageService& storage_service =
          service->user_education_storage_service();
      user_education::NtpPromoData data =
          storage_service.ReadNtpPromoData(id).value_or(
              user_education::NtpPromoData());
      data.last_clicked = storage_service.GetCurrentTime();
      data.completed = storage_service.GetCurrentTime();
      storage_service.SaveNtpPromoData(id, data);
    }
  }

  void InstallTestPromo(Eligibility eligibility) {
    ClearRegisteredPromos();
    RegisterTestPromo(kTestPromoName, eligibility,
                      IDS_NTP_SIGN_IN_PROMO_WITH_BOOKMARKS);
  }

  auto GetFirstPromoPath() const {
    switch (GetParam().promo_type) {
      case NtpBrowserPromoType::kSimple:
        return kPathToFirstIndividualPromo;
      case NtpBrowserPromoType::kSetupList:
        return kPathToSetupListFirstItem;
      default:
        NOTREACHED();
    }
  }

  // Returns the element containing either the individual promos, or the
  // setup list.
  auto GetPromosPath() const {
    switch (GetParam().promo_type) {
      case NtpBrowserPromoType::kSimple:
        return kPathToIndividualPromos;
      case NtpBrowserPromoType::kSetupList:
        return kPathToSetupList;
      default:
        NOTREACHED();
    }
  }

  auto GetActionButtonPath() const {
    return GetFirstPromoPath() + kActionIconId;
  }

  auto GetPromoIconPath() const { return GetFirstPromoPath() + kPromoIconId; }

  auto WaitForPromoIcon(std::string_view expected_icon) {
    const auto path = GetPromoIconPath();
    auto steps = Steps(
        WaitForElementVisible(kNtpElementId, path),
        // Verify the icon shows the correct image.
        CheckJsResultAt(kNtpElementId, path, "el => el.icon", expected_icon));
    AddDescriptionPrefix(steps, __func__);
    return steps;
  }

  auto WaitForPromoVisible(Eligibility eligibility,
                           std::string_view expected_icon) {
    MultiStep steps;
    switch (eligibility) {
      case Eligibility::kEligible:
        steps += WaitForPromoIcon(std::string("ntp-promo:") +
                                  std::string(expected_icon));
        steps += WaitForElementVisible(kNtpElementId, GetActionButtonPath());
        break;
      case Eligibility::kCompleted:
        steps += WaitForPromoIcon("cr:check");
        if (GetParam().promo_type == NtpBrowserPromoType::kSimple) {
          steps += EnsureNotVisible(kNtpElementId, GetActionButtonPath());
        } else {
          steps += WaitForElementVisible(kNtpElementId, GetActionButtonPath());
        }
        break;
      case Eligibility::kIneligible:
        NOTREACHED();
    }
    AddDescriptionPrefix(steps, __func__);
    return steps;
  }

  auto VerifyTestPromoText() {
    return CheckJsResultAt(
               kNtpElementId, GetFirstPromoPath() + kPromoTextId,
               "el => el.innerText",
               l10n_util::GetStringUTF8(IDS_NTP_SIGN_IN_PROMO_WITH_BOOKMARKS))
        .AddDescriptionPrefix(__func__);
  }

  auto PressActionButton() {
    return ClickElement(kNtpElementId, GetActionButtonPath())
        .AddDescriptionPrefix(__func__);
  }

  static constexpr std::string_view kShowResultHistogramName =
      "UserEducation.NtpPromos.ShowResult";

  auto CheckShowMetrics(ShowNtpPromosResult expected_result) {
    StateChange state_change;
    state_change.type = StateChange::Type::kExistsAndConditionTrue;
    state_change.where = kPathToNtp;
    state_change.test_function =
        "el => {"
        "return el.getAttribute('modules-loaded-status_') !== '0' || "
        "!el.querySelector('ntp-modules');"
        "}";
    state_change.event = kMetricsRecordedEvent;
    auto steps = Steps(
        WaitForStateChange(kNtpElementId, std::move(state_change)), Do([]() {
          metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
        }),
        Do([this, expected_result]() {
          histogram_tester_.ExpectBucketCount(kShowResultHistogramName,
                                              expected_result, 1);
          histogram_tester_.ExpectTotalCount(kShowResultHistogramName, 1);
        }));
    AddDescriptionPrefix(steps, __func__);
    return steps;
  }

  // Ensures that a single tab is open, ie. no second tab has spawned.
  auto CheckOneTabOpen() {
    return Check([this]() -> bool {
      return browser()->tab_strip_model()->count() == 1;
    });
  }

 private:
  void OnTestPromoShown() {
    BrowserElements::From(browser())->NotifyEvent(kBrowserViewElementId,
                                                  kTestPromoShownEvent);
  }

  void OnTestPromoClicked(
      const user_education::UserEducationContextPtr& context) {
    auto* browser_context = context->AsA<BrowserUserEducationContext>();
    BrowserWindowInterface* window =
        browser_context->GetBrowserView().browser();
    EXPECT_EQ(browser(), window);
    BrowserElements::From(window)->NotifyEvent(kBrowserViewElementId,
                                               kTestPromoClickedEvent);
  }

  base::test::ScopedFeatureList feature_list_;
  base::HistogramTester histogram_tester_;
};

INSTANTIATE_TEST_SUITE_P(
    ,
    NtpPromoUiTest,
    ValuesIn(std::vector<NtpPromoUiTestParams>{
        {.promo_type = NtpBrowserPromoType::kSimple},
        {.promo_type = NtpBrowserPromoType::kSetupList}}),
    [](const testing::TestParamInfo<NtpPromoUiTestParams>& info) {
      return info.param.ToString();
    });

IN_PROC_BROWSER_TEST_P(NtpPromoUiTest, TestPromoEligible) {
  // TODO(crbug.com/445214951): Flaky on mac-vm builder for macOS 15.
#if BUILDFLAG(IS_MAC)
  if (base::mac::MacOSMajorVersion() == 15 && base::mac::IsVirtualMachine()) {
    GTEST_SKIP() << "Disabled on macOS Sequoia for virtual machines.";
  }
#endif  // BUILDFLAG(IS_MAC)

  InstallTestPromo(Eligibility::kEligible);
  RunTestSequence(
      InstrumentTab(kNtpElementId),
      // Because the "promo was shown" event is fired asynchronously as the page
      // is loading, watch for it in parallel with navigating to the NTP.
      InParallel(
          RunSubsequence(NavigateWebContents(kNtpElementId, GURL(kNtpURL))),
          RunSubsequence(
              WaitForEvent(kBrowserViewElementId, kTestPromoShownEvent))),
      // Should already be visible at this point, but confirm it is and that it
      // is in the correct state.
      WaitForPromoVisible(Eligibility::kEligible, kSignInIconName),
      VerifyTestPromoText(),
      // As before, because the click and the event are sent asynchronously,
      // run these in parallel.
      InParallel(RunSubsequence(PressActionButton()),
                 RunSubsequence(WaitForEvent(kBrowserViewElementId,
                                             kTestPromoClickedEvent))),
      // Verify that the correct histogram was recorded.
      CheckShowMetrics(ShowNtpPromosResult::kShown));
}

// TODO(crbug.com/448993914): Re-enable this test
#if BUILDFLAG(IS_MAC)
#define MAYBE_TestPromoCompleted DISABLED_TestPromoCompleted
#else
#define MAYBE_TestPromoCompleted TestPromoCompleted
#endif
IN_PROC_BROWSER_TEST_P(NtpPromoUiTest, MAYBE_TestPromoCompleted) {
  InstallTestPromo(Eligibility::kCompleted);
  RunTestSequence(
      InstrumentTab(kNtpElementId),
      NavigateWebContents(kNtpElementId, GURL(kNtpURL)),
      If(
          []() {
            return GetParam().promo_type == NtpBrowserPromoType::kSetupList;
          },
          Then(WaitForPromoVisible(Eligibility::kCompleted, kSignInIconName),
               VerifyTestPromoText(),
               CheckShowMetrics(ShowNtpPromosResult::kShown)),
          Else(EnsureNotVisible(kNtpElementId, GetFirstPromoPath()),
               CheckShowMetrics(ShowNtpPromosResult::kNotShownNoPromos))));
}

namespace {
const InteractiveBrowserTestApi::DeepQuery kPathToModules = {"ntp-app",
                                                             "ntp-modules"};
}  // namespace

class NtpPromoWithModuleUiTest : public NtpPromoUiTest {
 protected:
  std::vector<base::test::FeatureRefAndParams> GetEnabledFeatures() override {
    auto result = NtpPromoUiTest::GetEnabledFeatures();
    result.push_back(
        {ntp_features::kNtpTabGroupsModule,
         {{ntp_features::kNtpTabGroupsModuleDataParam, "Fake Data"}}});
    return result;
  }
};

INSTANTIATE_TEST_SUITE_P(
    ,
    NtpPromoWithModuleUiTest,
    ValuesIn(std::vector<NtpPromoUiTestParams>{
        {.promo_type = NtpBrowserPromoType::kSimple},
        {.promo_type = NtpBrowserPromoType::kSetupList}}),
    [](const testing::TestParamInfo<NtpPromoUiTestParams>& info) {
      return info.param.ToString();
    });

IN_PROC_BROWSER_TEST_P(NtpPromoWithModuleUiTest, ModuleEnabled) {
  InstallTestPromo(Eligibility::kEligible);
  RunTestSequence(InstrumentTab(kNtpElementId),
                  NavigateWebContents(kNtpElementId, GURL(kNtpURL)),
                  WaitForElementVisible(kNtpElementId, kPathToModules),
                  EnsureNotVisible(kNtpElementId, GetFirstPromoPath()),
                  CheckShowMetrics(ShowNtpPromosResult::kNotShownDueToPolicy));
}

// Broken on M142 branch on Mac. crbug.com/454672587
#if BUILDFLAG(IS_MAC)
#define MAYBE_ModuleDisabled DISABLED_ModuleDisabled
#else
#define MAYBE_ModuleDisabled ModuleDisabled
#endif
IN_PROC_BROWSER_TEST_P(NtpPromoWithModuleUiTest, MAYBE_ModuleDisabled) {
  // Disable the Tab Groups module in prefs.
  {
    ScopedListPrefUpdate update(browser()->profile()->GetPrefs(),
                                prefs::kNtpDisabledModules);
    base::Value::List& list = update.Get();
    base::Value module_id_value(ntp_modules::kTabGroupsModuleId);
    list.Append(std::move(module_id_value));
  }
  InstallTestPromo(Eligibility::kEligible);
  RunTestSequence(InstrumentTab(kNtpElementId),
                  NavigateWebContents(kNtpElementId, GURL(kNtpURL)),
                  WaitForElementVisible(kNtpElementId, GetFirstPromoPath()),
                  EnsureNotVisible(kNtpElementId, kPathToModules),
                  CheckShowMetrics(ShowNtpPromosResult::kShown));
}

// Tests in this block rely on the fact that the top priority promotion is
// signin - except on ChromeOS, where there is no signin flow. So do not build
// or run these tests on ChromeOS.
#if !BUILDFLAG(IS_CHROMEOS)

// TODO(crbug.com/448993914): Re-enable this test
#if BUILDFLAG(IS_MAC)
#define MAYBE_SigninPromoAppearsAndIsClickable \
  DISABLED_SigninPromoAppearsAndIsClickable
#else
#define MAYBE_SigninPromoAppearsAndIsClickable SigninPromoAppearsAndIsClickable
#endif
IN_PROC_BROWSER_TEST_P(NtpPromoUiTest, MAYBE_SigninPromoAppearsAndIsClickable) {
  ClearRegisteredPromosExcept(kNtpSignInPromoId);
  RunTestSequence(
      InstrumentTab(kNtpElementId),
      NavigateWebContents(kNtpElementId, GURL(kNtpURL)),
      WaitForPromoVisible(Eligibility::kEligible, kSignInIconName),

      // Since bots cannot navigate to actual pages, we can't use
      // WaitForWebContentsNavigation() or the like. Instead, verify that the
      // browser *tries* to navigate to the account login page.
      PollViewProperty(kLocationBarTextValue, kOmniboxElementId,
                       &OmniboxViewViews::GetText),
      // Click the promo button; this should navigate the current page.
      PressActionButton(),
      WaitForState(kLocationBarTextValue,
                   OptionalStringContains(u"accounts.google.com")),
      // The NTP tab should navigate, rather than opening a new tab.
      CheckOneTabOpen());

  // TODD(https://crbug.com/433607240): Check model, histograms.
}

#endif  // !BUILDFLAG(IS_CHROMEOS)

// TODO(crbug.com/448993914): Re-enable this test
#if BUILDFLAG(IS_MAC)
#define MAYBE_ExtensionsPromoAppearsAndIsClickable \
  DISABLED_ExtensionsPromoAppearsAndIsClickable
#else
#define MAYBE_ExtensionsPromoAppearsAndIsClickable \
  ExtensionsPromoAppearsAndIsClickable
#endif
IN_PROC_BROWSER_TEST_P(NtpPromoUiTest,
                       MAYBE_ExtensionsPromoAppearsAndIsClickable) {
  ClearRegisteredPromosExcept(kNtpExtensionsPromoId);
  RunTestSequence(
      InstrumentTab(kNtpElementId),
      NavigateWebContents(kNtpElementId, GURL(kNtpURL)),
      WaitForPromoVisible(Eligibility::kEligible, kExtensionsIconName),

      // Since bots cannot navigate to actual pages, we can't use
      // WaitForWebContentsNavigation() or the like. Instead, verify that the
      // browser *tries* to navigate to the account login page.
      PollViewProperty(kLocationBarTextValue, kOmniboxElementId,
                       &OmniboxViewViews::GetText),
      // Click the promo button; this should navigate the current page.
      PressActionButton(),
      // Note that the URL here may not match what users see, due to redirects.
      WaitForState(kLocationBarTextValue, OptionalStringContains(u"webstore")),
      // The NTP tab should navigate, rather than opening a new tab.
      CheckOneTabOpen());

  // TODD(https://crbug.com/433607240): Check model, histograms.
}

// TODO(crbug.com/448993914): Re-enable this test
#if BUILDFLAG(IS_MAC)
#define MAYBE_CustomizationPromoAppearsAndIsClickable \
  DISABLED_CustomizationPromoAppearsAndIsClickable
#else
#define MAYBE_CustomizationPromoAppearsAndIsClickable \
  CustomizationPromoAppearsAndIsClickable
#endif
IN_PROC_BROWSER_TEST_P(NtpPromoUiTest,
                       MAYBE_CustomizationPromoAppearsAndIsClickable) {
  ClearRegisteredPromosExcept(kNtpCustomizationPromoId);
  RunTestSequence(
      InstrumentTab(kNtpElementId),
      NavigateWebContents(kNtpElementId, GURL(kNtpURL)),
      WaitForPromoVisible(Eligibility::kEligible, kCustomizationIconName),
      PressActionButton(), WaitForShow(kSidePanelElementId));

  // TODD(https://crbug.com/433607240): Check model, histograms.
}

class NtpPromoVisualUiTest : public NtpPromoUiTest {
 protected:
  ui::MockOsSettingsProvider& os_settings_provider() {
    return os_settings_provider_;
  }

  // TODO(453086432): Remove this override and fix the test to work with
  // Compose enabled.
  std::vector<base::test::FeatureRef> GetDisabledFeatures() override {
    auto result = NtpPromoUiTest::GetDisabledFeatures();
    result.push_back(ntp_composebox::kNtpComposebox);
    return result;
  }

 private:
  ui::MockOsSettingsProvider os_settings_provider_;
};

// Screenshot the promo UI across the available presentation styles, along
// with other variables that warrant pixel-style validation.
INSTANTIATE_TEST_SUITE_P(
    ,
    NtpPromoVisualUiTest,
    ValuesIn(std::vector<NtpPromoUiTestParams>{
        {
            .promo_type = NtpBrowserPromoType::kSimple,
        },
        {
            .promo_type = NtpBrowserPromoType::kSimple,
            .color_scheme = ui::NativeTheme::PreferredColorScheme::kDark,
        },
        {
            .promo_type = NtpBrowserPromoType::kSimple,
            .rtl = true,
        },
        {
            .promo_type = NtpBrowserPromoType::kSimple,
            .individual_promos = 2,
        },
        {
            // Tests that the individual promos match in height, despite
            // lengthy text in one of the promos.
            .promo_type = NtpBrowserPromoType::kSimple,
            .individual_promos = 2,
            .long_text = true,
        },
        {
            // Tests that the promos sit side-by-side.
            .promo_type = NtpBrowserPromoType::kSimple,
            .individual_promos = 2,
            .wide_screen = true,
        },
        {
            .promo_type = NtpBrowserPromoType::kSetupList,
        },
        {
            .promo_type = NtpBrowserPromoType::kSetupList,
            .long_text = true,
        },
        {
            .promo_type = NtpBrowserPromoType::kSetupList,
            .color_scheme = ui::NativeTheme::PreferredColorScheme::kDark,
        },
        {
            .promo_type = NtpBrowserPromoType::kSetupList,
            .rtl = true,
        }}),
    [](const testing::TestParamInfo<NtpPromoUiTestParams>& info) {
      return info.param.ToString();
    });

IN_PROC_BROWSER_TEST_P(NtpPromoVisualUiTest, Screenshots) {
  // Force a consistent window size to exercise promo layout within New Tab
  // Page bounds.
  auto screen_size = gfx::Size(1000, 1200);
  if (GetParam().wide_screen) {
    // Grow the screen wide enough that individual promos can sit side-by-side.
    screen_size = gfx::Size(1500, 1200);
  }
  BrowserView::GetBrowserViewForBrowser(browser())->GetWidget()->SetSize(
      screen_size);

  os_settings_provider().SetPreferredColorScheme(GetParam().color_scheme);

  if (GetParam().rtl) {
    base::i18n::SetRTLForTesting(true);
  }

  if (GetParam().long_text) {
    // Override promo text to very long (and short) strings, to exercise the
    // promos growing to fit (nor not shrinking unexpectedly).
    auto& bundle = ui::ResourceBundle::GetSharedInstance();
    bundle.OverrideLocaleStringResource(IDS_NTP_CUSTOMIZATION_PROMO,
                                        kLongPromoText);
    bundle.OverrideLocaleStringResource(IDS_NTP_EXTENSIONS_PROMO,
                                        kShortPromoText);
  }

  // Use fake promos to exercise pending/completed state and short/long text.
  ClearRegisteredPromos();
  RegisterTestPromo("1", Eligibility::kEligible,
                    IDS_NTP_SIGN_IN_PROMO_WITH_BOOKMARKS);
  RegisterTestPromo("2", Eligibility::kEligible, IDS_NTP_CUSTOMIZATION_PROMO);
  RegisterTestPromo("3", Eligibility::kCompleted, IDS_NTP_EXTENSIONS_PROMO);

  RunTestSequence(
      InstrumentTab(kNtpElementId),
      NavigateWebContents(kNtpElementId, GURL(kNtpURL)),
      WaitForElementVisible(kNtpElementId, GetFirstPromoPath()),
      ScrollIntoView(kNtpElementId, GetPromosPath()),
      SetOnIncompatibleAction(OnIncompatibleAction::kSkipTest,
                              "Screenshots not captured on this platform."),
      ScreenshotWebUi(kNtpElementId, GetPromosPath(),
                      /*screenshot_name=*/std::string(),
                      /*baseline_cl=*/"6998053"));
}