File: parent_permission_dialog_view_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (631 lines) | stat: -rw-r--r-- 27,455 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
// Copyright 2020 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/views/supervised_user/parent_permission_dialog_view.h"

#include <memory>
#include <optional>
#include <ostream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/functional/callback_forward.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/memory/scoped_refptr.h"
#include "base/notreached.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/metrics/user_action_tester.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/supervised_user/supervised_user_extensions_delegate_impl.h"
#include "chrome/browser/supervised_user/supervised_user_extensions_metrics_recorder.h"
#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_test_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_element_identifiers.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/supervised_user/parent_permission_dialog.h"
#include "chrome/browser/ui/test/test_browser_dialog.h"
#include "chrome/test/base/mixin_based_in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/interaction/interactive_browser_test.h"
#include "chrome/test/supervised_user/supervision_mixin.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "components/supervised_user/core/browser/supervised_user_service.h"
#include "components/supervised_user/core/common/supervised_user_constants.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_launcher.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/extension_dialog_auto_confirm.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_util.h"
#include "extensions/common/extension_builder.h"
#include "extensions/test/result_catcher.h"
#include "google_apis/gaia/gaia_auth_consumer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/window/dialog_client_view.h"

// Must be in the same namespace as the target type (the global namespace).
// Makes test output more readable.
// http://google.github.io/googletest/advanced.html#teaching-googletest-how-to-print-your-values
std::ostream& operator<<(std::ostream& os,
                         ParentPermissionDialog::Result result) {
  switch (result) {
    case ParentPermissionDialog::Result::kParentPermissionReceived:
      os << "kParentPermissionReceived";
      return os;
    case ParentPermissionDialog::Result::kParentPermissionCanceled:
      os << "kParentPermissionCanceled";
      return os;
    case ParentPermissionDialog::Result::kParentPermissionFailed:
      os << "kParentPermissionFailed";
      return os;
    default:
      NOTREACHED();
  }
}

namespace {

enum class ActionStatus { kWasPerformed, kWasNotPerformed };

// Extracts the `name` argument for ShowUi() from the current test case name.
// E.g. for InvokeUi_name (or DISABLED_InvokeUi_name) returns "name".
std::string NameFromTestCase() {
  const std::string name = base::TestNameWithoutDisabledPrefix(
      testing::UnitTest::GetInstance()->current_test_info()->name());
  size_t underscore = name.find('_');
  return underscore == std::string::npos ? std::string()
                                         : name.substr(underscore + 1);
}

// Brings in the view under test and captures it. Does not implement any test
// logic.
class ParentPermissionDialogViewHarness
    : public TestParentPermissionDialogViewObserver {
 public:
  explicit ParentPermissionDialogViewHarness(
      supervised_user::SupervisionMixin& supervision_mixin)
      : TestParentPermissionDialogViewObserver(this),
        supervision_mixin_(supervision_mixin) {}
  ~ParentPermissionDialogViewHarness() = default;

  ParentPermissionDialog::Result GetResult() {
    CHECK(result_.has_value())
        << "Use only after the dialog was set to be interacted with.";
    return *result_;
  }

  // T is either std::u16string for regular dialogs, or const
  // extensions::Extension*  for extension dialogs.
  template <typename T>
  void ShowUi(T dialog_input, Browser* browser) {
    gfx::ImageSkia icon = gfx::ImageSkia::CreateFrom1xBitmap(
        *gfx::Image(extensions::util::GetDefaultExtensionIcon()).ToSkBitmap());
    content::WebContents* contents =
        browser->tab_strip_model()->GetActiveWebContents();

    dialog_ = CreatePermissionDialog(
        dialog_input, browser, contents, icon, extension_approval_entry_point_,
        base::BindOnce(
            &ParentPermissionDialogViewHarness::OnParentPermissionDialogDone,
            base::Unretained(this)));
    dialog_->ShowDialog();
  }

  bool InvalidCredentialWasReceived() {
    CHECK(under_test_) << "No permission view intercepted.";
    return under_test_->GetInvalidCredentialReceived();
  }

  void SetRepromptAfterIncorrectCredential(
      bool reprompt_on_incorrect_password) {
    reprompt_on_incorrect_password_ = reprompt_on_incorrect_password;
  }

  void SetExtensionApprovalEntryPoint(
      SupervisedUserExtensionParentApprovalEntryPoint
          extension_approval_entry_point) {
    extension_approval_entry_point_ = extension_approval_entry_point;
  }

 protected:
  template <typename T>
  std::unique_ptr<ParentPermissionDialog> CreatePermissionDialog(
      T dialog_input,
      Browser* browser,
      content::WebContents* contents,
      gfx::ImageSkia icon,
      std::optional<SupervisedUserExtensionParentApprovalEntryPoint>
          extension_approval_entry_point,
      ParentPermissionDialog::DoneCallback done_callback);

  template <>
  std::unique_ptr<ParentPermissionDialog> CreatePermissionDialog(
      std::u16string dialog_input,
      Browser* browser,
      content::WebContents* contents,
      gfx::ImageSkia icon,
      std::optional<SupervisedUserExtensionParentApprovalEntryPoint>
          extension_approval_entry_point,
      ParentPermissionDialog::DoneCallback done_callback) {
    return ParentPermissionDialog::CreateParentPermissionDialog(
        browser->profile(), contents->GetTopLevelNativeWindow(), icon,
        dialog_input, std::move(done_callback));
  }

  template <>
  std::unique_ptr<ParentPermissionDialog> CreatePermissionDialog(
      const extensions::Extension* dialog_input,
      Browser* browser,
      content::WebContents* contents,
      gfx::ImageSkia icon,
      std::optional<SupervisedUserExtensionParentApprovalEntryPoint>
          extension_approval_entry_point,
      ParentPermissionDialog::DoneCallback done_callback) {
    return ParentPermissionDialog::CreateParentPermissionDialogForExtension(
        browser->profile(), contents->GetTopLevelNativeWindow(), icon,
        dialog_input, extension_approval_entry_point.value(),
        std::move(done_callback));
  }

 private:
  void OnParentPermissionDialogDone(ParentPermissionDialog::Result result) {
    result_ = result;
  }

  // TestParentPermissionDialogViewObserver implementation.
  // Configures the identity manager of the view and stores
  // reference to the view under test.
  void OnTestParentPermissionDialogViewCreated(
      ParentPermissionDialogView* view) override {
    under_test_ = view;
    under_test_->SetIdentityManagerForTesting(
        supervision_mixin_->GetIdentityTestEnvironment()->identity_manager());
    under_test_->SetRepromptAfterIncorrectCredential(
        reprompt_on_incorrect_password_);
  }

  bool reprompt_on_incorrect_password_ = false;

  // Provides identity manager to the view.
  raw_ref<supervised_user::SupervisionMixin> supervision_mixin_;

  // `under_test_` is intercepted by OnTestParentPermissionDialogViewCreated.
  raw_ptr<ParentPermissionDialogView, DisableDanglingPtrDetection> under_test_;

  // The Dialog widget containing the view under test.
  // The test does not interact directly with this object
  // but it needs to be alive for the duration of the test.
  std::unique_ptr<ParentPermissionDialog> dialog_;

  // Optional result, if dialog was interacted.
  std::optional<ParentPermissionDialog::Result> result_;

  SupervisedUserExtensionParentApprovalEntryPoint
      extension_approval_entry_point_ =
          SupervisedUserExtensionParentApprovalEntryPoint::kMaxValue;
};

// End to end test of ParentPermissionDialog that exercises the dialog's
// internal logic that orchestrates the parental permission process.
class ParentPermissionDialogViewTest
    : public SupportsTestDialog<
          InteractiveBrowserTestT<MixinBasedInProcessBrowserTest>> {
 protected:
  void ShowUi(const std::string& name) override {
    if (name == "LongNameExtension") {
      const std::string long_name =
          "This extension name should be longer than our truncation threshold "
          "to test that the bubble can handle long names";
      scoped_refptr<const extensions::Extension> extension =
          AddAndDisableExtensionWithName(long_name);
      harness_.ShowUi(extension.get(), browser());
    } else if (name.find("default") != std::string::npos) {
      harness_.ShowUi(std::u16string(u"Test prompt message"), browser());
      return;
    } else if (name.find("extension") != std::string::npos) {
      harness_.ShowUi(test_extension_.get(), browser());
      return;
    } else {
      NOTREACHED() << "Check the suffix of the test name.";
    }
  }

  void SetUpOnMainThread() override {
    // Default ::SetUpOnMainThread() of all dependent mixins are invoked here.
    InteractiveBrowserTestT::SetUpOnMainThread();

    supervised_user_test_util::
        SetSupervisedUserExtensionsMayRequestPermissionsPref(
            browser()->profile(), /*enabled=*/true);

    supervised_user_extensions_delegate_ =
        std::make_unique<extensions::SupervisedUserExtensionsDelegateImpl>(
            browser()->profile());

    test_extension_ = AddAndDisableExtensionWithName("test extension");
  }

  void TearDownOnMainThread() override {
    supervised_user_extensions_delegate_.reset();
    InteractiveBrowserTestT::TearDownOnMainThread();
  }

  const extensions::Extension* test_extension() {
    return test_extension_.get();
  }

  extensions::ExtensionRegistrar* extension_registrar() {
    return extensions::ExtensionRegistrar::Get(browser()->profile());
  }

  extensions::ExtensionService* extension_service() {
    return extensions::ExtensionSystem::Get(browser()->profile())
        ->extension_service();
  }

  InteractiveTestApi::StepBuilder ShowDialog() {
    return Do([this]() -> void { ShowUi(NameFromTestCase()); });
  }

  auto CheckHistogramBucketCount(
      std::string_view histogram_name,
      SupervisedUserExtensionsMetricsRecorder::ParentPermissionDialogState
          state_bucket,
      int expected_count) {
    return Do([this, histogram_name, state_bucket, expected_count]() -> void {
      histogram_tester_.ExpectBucketCount(histogram_name, state_bucket,
                                          expected_count);
    });
  }

  auto CheckHistogramBucketCount(
      std::string_view histogram_name,
      SupervisedUserExtensionParentApprovalEntryPoint entry_point_bucket,
      int expected_count) {
    return Do(
        [this, histogram_name, entry_point_bucket, expected_count]() -> void {
          histogram_tester_.ExpectBucketCount(
              histogram_name, entry_point_bucket, expected_count);
        });
  }

  auto CheckHistogramTotalCount(std::string_view histogram_name,
                                int expected_count) {
    return Do([this, histogram_name, expected_count]() -> void {
      histogram_tester_.ExpectTotalCount(histogram_name, expected_count);
    });
  }

  auto GetActionStatus(std::string_view action_name) {
    return [this, action_name]() -> ActionStatus {
      return (user_action_tester_.GetActionCount(action_name) == 1)
                 ? ActionStatus::kWasPerformed
                 : ActionStatus::kWasNotPerformed;
    };
  }

  std::unique_ptr<extensions::SupervisedUserExtensionsDelegate>
      supervised_user_extensions_delegate_;

  supervised_user::SupervisionMixin supervision_mixin_{
      mixin_host_,
      this,
      embedded_test_server(),
      {.consent_level = signin::ConsentLevel::kSync,
       .sign_in_mode =
           content::IsPreTest()
               ? supervised_user::SupervisionMixin::SignInMode::kRegular
               : supervised_user::SupervisionMixin::SignInMode::kSupervised}};

  ParentPermissionDialogViewHarness harness_{supervision_mixin_};

 private:
  scoped_refptr<const extensions::Extension> AddAndDisableExtensionWithName(
      const std::string& extension_name) {
    scoped_refptr<const extensions::Extension> extension =
        extensions::ExtensionBuilder(extension_name).Build();
    extension_registrar()->AddExtension(extension);
    extension_registrar()->DisableExtension(
        extension->id(),
        {extensions::disable_reason::DISABLE_CUSTODIAN_APPROVAL_REQUIRED});
    return extension;
  }

  base::HistogramTester histogram_tester_;
  base::UserActionTester user_action_tester_;
  scoped_refptr<const extensions::Extension> test_extension_;
};

// Tests that a plain dialog widget is shown using the TestBrowserUi
// infrastructure.
IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest, InvokeUi_default) {
  ShowAndVerifyUi();
}

// Tests that a plain dialog widget is shown using the TestBrowserUi
// infrastructure.
IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest, InvokeUi_extension) {
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest,
                       InvokeUi_LongNameExtension) {
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest,
                       PermissionReceived_default) {
  RunTestSequence(InAnyContext(
      ShowDialog(),
      WaitForShow(ParentPermissionDialog::kDialogViewIdForTesting),
      PressButton(views::DialogClientView::kOkButtonElementId),
      WaitForHide(ParentPermissionDialog::kDialogViewIdForTesting),
      CheckResult([this]() { return harness_.GetResult(); },
                  ParentPermissionDialog::Result::kParentPermissionReceived)));
}

IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest,
                       PermissionFailedInvalidPassword_default) {
  supervision_mixin_.SetNextReAuthStatus(
      GaiaAuthConsumer::ReAuthProofTokenStatus::kInvalidGrant);

  RunTestSequence(InAnyContext(
      ShowDialog(),
      WaitForShow(ParentPermissionDialog::kDialogViewIdForTesting),
      PressButton(views::DialogClientView::kOkButtonElementId),
      // Closing the dialog results in the freeing of resources, so checks must
      // be done together without waiting for a fresh call stack.
      WithoutDelay(
          WaitForHide(ParentPermissionDialog::kDialogViewIdForTesting),
          CheckResult(
              [this]() { return harness_.InvalidCredentialWasReceived(); },
              true),
          CheckResult(
              [this]() { return harness_.GetResult(); },
              ParentPermissionDialog::Result::kParentPermissionFailed))));
}

IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest,
                       PermissionDialogCanceled_default) {
  RunTestSequence(InAnyContext(
      ShowDialog(),
      WaitForShow(ParentPermissionDialog::kDialogViewIdForTesting),
      PressButton(views::DialogClientView::kCancelButtonElementId),
      WaitForHide(ParentPermissionDialog::kDialogViewIdForTesting),
      CheckResult([this]() { return harness_.GetResult(); },
                  ParentPermissionDialog::Result::kParentPermissionCanceled)));
}

IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest,
                       PermissionReceived_extension) {
  // Provide an extension dialog entry point to test the recorded histograms.
  harness_.SetExtensionApprovalEntryPoint(
      SupervisedUserExtensionParentApprovalEntryPoint::kOnWebstoreInstallation);
  supervision_mixin_.SetNextReAuthStatus(
      GaiaAuthConsumer::ReAuthProofTokenStatus::kSuccess);

  RunTestSequence(InAnyContext(
      ShowDialog(),
      WaitForShow(ParentPermissionDialog::kDialogViewIdForTesting),
      PressButton(views::DialogClientView::kOkButtonElementId),
      WaitForHide(ParentPermissionDialog::kDialogViewIdForTesting),
      CheckResult([this]() { return harness_.GetResult(); },
                  ParentPermissionDialog::Result::kParentPermissionReceived),
      CheckHistogramBucketCount(SupervisedUserExtensionsMetricsRecorder::
                                    kParentPermissionDialogHistogramName,
                                SupervisedUserExtensionsMetricsRecorder::
                                    ParentPermissionDialogState::kOpened,
                                1),
      CheckHistogramBucketCount(
          SupervisedUserExtensionsMetricsRecorder::
              kParentPermissionDialogHistogramName,
          SupervisedUserExtensionsMetricsRecorder::ParentPermissionDialogState::
              kParentApproved,
          1),
      // The total histogram count is 2 (one for kOpened and one for
      // kParentApproved).
      CheckHistogramTotalCount(SupervisedUserExtensionsMetricsRecorder::
                                   kParentPermissionDialogHistogramName,
                               2),
      CheckResult(GetActionStatus(SupervisedUserExtensionsMetricsRecorder::
                                      kParentPermissionDialogOpenedActionName),
                  ActionStatus::kWasPerformed),
      // The provided entry point for the parent approval dialog has been
      // recorded.
      CheckHistogramBucketCount(
          SupervisedUserExtensionsMetricsRecorder::
              kExtensionParentApprovalEntryPointHistogramName,
          SupervisedUserExtensionParentApprovalEntryPoint::
              kOnWebstoreInstallation,
          1),
      CheckResult(
          GetActionStatus(SupervisedUserExtensionsMetricsRecorder::
                              kParentPermissionDialogParentApprovedActionName),
          ActionStatus::kWasPerformed)));
}

IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest,
                       PermissionFailedInvalidPassword_extension) {
  // Provide an extension dialog entry point to test the recorded histograms.
  harness_.SetExtensionApprovalEntryPoint(
      SupervisedUserExtensionParentApprovalEntryPoint::
          kOnExtensionManagementSetEnabledOperation);
  supervision_mixin_.SetNextReAuthStatus(
      GaiaAuthConsumer::ReAuthProofTokenStatus::kInvalidGrant);

  RunTestSequence(InAnyContext(
      ShowDialog(),
      WaitForShow(ParentPermissionDialog::kDialogViewIdForTesting),
      PressButton(views::DialogClientView::kOkButtonElementId),
      // Closing the dialog results in the freeing of resources, so checks must
      // be done together without waiting for a fresh call stack.
      WithoutDelay(
          WaitForHide(ParentPermissionDialog::kDialogViewIdForTesting),
          CheckResult(
              [this]() { return harness_.InvalidCredentialWasReceived(); },
              true),
          CheckResult([this]() { return harness_.GetResult(); },
                      ParentPermissionDialog::Result::kParentPermissionFailed),
          CheckHistogramBucketCount(SupervisedUserExtensionsMetricsRecorder::
                                        kParentPermissionDialogHistogramName,
                                    SupervisedUserExtensionsMetricsRecorder::
                                        ParentPermissionDialogState::kOpened,
                                    1),
          CheckHistogramBucketCount(
              SupervisedUserExtensionsMetricsRecorder::
                  kParentPermissionDialogHistogramName,
              SupervisedUserExtensionsMetricsRecorder::
                  ParentPermissionDialogState::kIncorrectParentPasswordProvided,
              1),
          CheckHistogramBucketCount(SupervisedUserExtensionsMetricsRecorder::
                                        kParentPermissionDialogHistogramName,
                                    SupervisedUserExtensionsMetricsRecorder::
                                        ParentPermissionDialogState::kFailed,
                                    1),
          // The total histogram count is 3 (one for kOpened, one for
          // kIncorrectPassword and one for kFailed).
          CheckHistogramTotalCount(SupervisedUserExtensionsMetricsRecorder::
                                       kParentPermissionDialogHistogramName,
                                   3),
          // The provided entry point for the parent approval dialog has been
          // recorded.
          CheckHistogramBucketCount(
              SupervisedUserExtensionsMetricsRecorder::
                  kExtensionParentApprovalEntryPointHistogramName,
              SupervisedUserExtensionParentApprovalEntryPoint::
                  kOnExtensionManagementSetEnabledOperation,
              1),
          CheckResult(
              GetActionStatus(SupervisedUserExtensionsMetricsRecorder::
                                  kParentPermissionDialogOpenedActionName),
              ActionStatus::kWasPerformed))));
}

IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest,
                       PermissionFailedInvalidPasswordWithRepromt_extension) {
  harness_.SetRepromptAfterIncorrectCredential(true);
  supervision_mixin_.SetNextReAuthStatus(
      GaiaAuthConsumer::ReAuthProofTokenStatus::kInvalidGrant);

  RunTestSequence(InAnyContext(
      ShowDialog(),
      WaitForShow(ParentPermissionDialog::kDialogViewIdForTesting),
      PressButton(views::DialogClientView::kOkButtonElementId),
      WaitForShow(ParentPermissionDialog::kIncorrectParentPasswordIdForTesting),
      CheckResult([this]() { return harness_.InvalidCredentialWasReceived(); },
                  true),
      CheckHistogramBucketCount(SupervisedUserExtensionsMetricsRecorder::
                                    kParentPermissionDialogHistogramName,
                                SupervisedUserExtensionsMetricsRecorder::
                                    ParentPermissionDialogState::kOpened,
                                1),
      CheckHistogramBucketCount(
          SupervisedUserExtensionsMetricsRecorder::
              kParentPermissionDialogHistogramName,
          SupervisedUserExtensionsMetricsRecorder::ParentPermissionDialogState::
              kIncorrectParentPasswordProvided,
          1),
      // The dialog remains open waiting for the correct password and has not
      // failed.
      EnsurePresent(ParentPermissionDialog::kDialogViewIdForTesting),
      CheckHistogramBucketCount(SupervisedUserExtensionsMetricsRecorder::
                                    kParentPermissionDialogHistogramName,
                                SupervisedUserExtensionsMetricsRecorder::
                                    ParentPermissionDialogState::kFailed,
                                0)));
}

IN_PROC_BROWSER_TEST_F(ParentPermissionDialogViewTest,
                       PermissionDialogCanceled_extension) {
  RunTestSequence(InAnyContext(
      ShowDialog(),
      WaitForShow(ParentPermissionDialog::kDialogViewIdForTesting),
      PressButton(views::DialogClientView::kCancelButtonElementId),
      WaitForHide(ParentPermissionDialog::kDialogViewIdForTesting),
      CheckResult([this]() { return harness_.GetResult(); },
                  ParentPermissionDialog::Result::kParentPermissionCanceled),
      CheckHistogramBucketCount(SupervisedUserExtensionsMetricsRecorder::
                                    kParentPermissionDialogHistogramName,
                                SupervisedUserExtensionsMetricsRecorder::
                                    ParentPermissionDialogState::kOpened,
                                1),
      CheckHistogramBucketCount(
          SupervisedUserExtensionsMetricsRecorder::
              kParentPermissionDialogHistogramName,
          SupervisedUserExtensionsMetricsRecorder::ParentPermissionDialogState::
              kParentCanceled,
          1),
      // The total histogram count is 2 (one for kOpened and one for
      // kParentCanceled).
      CheckHistogramTotalCount(SupervisedUserExtensionsMetricsRecorder::
                                   kParentPermissionDialogHistogramName,
                               2),
      CheckResult(GetActionStatus(SupervisedUserExtensionsMetricsRecorder::
                                      kParentPermissionDialogOpenedActionName),
                  ActionStatus::kWasPerformed),
      CheckResult(
          GetActionStatus(SupervisedUserExtensionsMetricsRecorder::
                              kParentPermissionDialogParentCanceledActionName),
          ActionStatus::kWasPerformed)));
}

// Test which labels are used in the Parent Permission Input Section
// of the permission dialog based on the usage of the dialog
// (extension approval, other approval).
class ParentPermissionInputSectionLabelTest
    : public ParentPermissionDialogViewTest {};

IN_PROC_BROWSER_TEST_F(ParentPermissionInputSectionLabelTest,
                       PermissionReceived_extension) {
  supervision_mixin_.SetNextReAuthStatus(
      GaiaAuthConsumer::ReAuthProofTokenStatus::kSuccess);

  // When the parent approval dialog is shown for an extension
  // approval, extension-specific labels are shown to the Permission Input
  // section of the dialog. Otherwise, general purpose labels are used.
  auto present_parent_label_id = ParentPermissionDialog::
      kExtensionsParentApprovalVerificationTextIdForTesting;
  auto non_present_parent_label_id =
      ParentPermissionDialog::kParentAccountTextIdForTesting;

  RunTestSequence(
      InAnyContext(ShowDialog(),
                   WaitForShow(ParentPermissionDialog::kDialogViewIdForTesting),
                   WaitForShow(present_parent_label_id),
                   EnsureNotPresent(non_present_parent_label_id)));
}

IN_PROC_BROWSER_TEST_F(ParentPermissionInputSectionLabelTest,
                       PermissionReceived_default) {
  supervision_mixin_.SetNextReAuthStatus(
      GaiaAuthConsumer::ReAuthProofTokenStatus::kSuccess);

  // Check that only the general purpose labels are shown when the parent
  // approval dialog is used for a purpose other than extension approval. Labels
  // related to extension approval are not shown.
  RunTestSequence(InAnyContext(
      ShowDialog(),
      WaitForShow(ParentPermissionDialog::kDialogViewIdForTesting),
      WaitForShow(ParentPermissionDialog::kParentAccountTextIdForTesting),
      EnsureNotPresent(
          ParentPermissionDialog::
              kExtensionsParentApprovalVerificationTextIdForTesting)));
}
}  // namespace