File: page_info_bubble_view_unittest.cc

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; 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 (1315 lines) | stat: -rw-r--r-- 53,620 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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
// Copyright 2015 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/page_info/page_info_bubble_view.h"

#include <string_view>

#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/values_test_util.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/content_settings/page_specific_content_settings_delegate.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/permissions/system/system_permission_settings.h"
#include "chrome/browser/privacy_sandbox/mock_privacy_sandbox_service.h"
#include "chrome/browser/privacy_sandbox/privacy_sandbox_service_factory.h"
#include "chrome/browser/ssl/chrome_security_state_tab_helper.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/hats/mock_trust_safety_sentiment_service.h"
#include "chrome/browser/ui/hats/trust_safety_sentiment_service_factory.h"
#include "chrome/browser/ui/views/controls/hover_button.h"
#include "chrome/browser/ui/views/controls/page_switcher_view.h"
#include "chrome/browser/ui/views/controls/rich_controls_container_view.h"
#include "chrome/browser/ui/views/controls/rich_hover_button.h"
#include "chrome/browser/ui/views/page_info/chosen_object_view.h"
#include "chrome/browser/ui/views/page_info/page_info_main_view.h"
#include "chrome/browser/ui/views/page_info/page_info_permission_content_view.h"
#include "chrome/browser/ui/views/page_info/page_info_security_content_view.h"
#include "chrome/browser/ui/views/page_info/page_info_view_factory.h"
#include "chrome/browser/ui/views/page_info/permission_toggle_row_view.h"
#include "chrome/browser/usb/usb_chooser_context.h"
#include "chrome/browser/usb/usb_chooser_context_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "chrome/test/views/chrome_test_views_delegate.h"
#include "components/content_settings/core/browser/content_settings_uma_util.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/content_settings/core/common/cookie_blocking_3pcd_status.h"
#include "components/content_settings/core/common/cookie_controls_state.h"
#include "components/content_settings/core/common/features.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/history/core/browser/history_service.h"
#include "components/page_info/core/features.h"
#include "components/permissions/permission_recovery_success_rate_tracker.h"
#include "components/permissions/permission_uma_util.h"
#include "components/permissions/permission_util.h"
#include "components/privacy_sandbox/privacy_sandbox_features.h"
#include "components/strings/grit/components_strings.h"
#include "components/strings/grit/privacy_sandbox_strings.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/browser/ssl_status.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/test_web_contents_factory.h"
#include "google_apis/gaia/gaia_id.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "net/cert/cert_status_flags.h"
#include "net/ssl/ssl_connection_status_flags.h"
#include "net/ssl/ssl_info.h"
#include "net/test/cert_test_util.h"
#include "net/test/test_certificate_data.h"
#include "net/test/test_data_directory.h"
#include "ppapi/buildflags/buildflags.h"
#include "services/device/public/cpp/test/fake_usb_device_manager.h"
#include "services/device/public/mojom/usb_device.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_features.h"
#include "ui/events/event_utils.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/toggle_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/link.h"
#include "ui/views/controls/styled_label.h"
#include "ui/views/test/button_test_api.h"
#include "ui/views/test/scoped_views_test_helper.h"
#include "ui/views/test/test_views_delegate.h"

#if BUILDFLAG(ENABLE_PLUGINS)
#include "chrome/browser/plugins/chrome_plugin_service_filter.h"
#endif

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "components/account_id/account_id.h"
#include "components/user_manager/scoped_user_manager.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

const char* kUrl = "http://www.example.com/index.html";
const char* kSecureUrl = "https://www.example.com/index.html";
std::u16string kHostname = u"example.com";

namespace test {

class PageInfoBubbleViewTestApi {
 public:
  PageInfoBubbleViewTestApi(gfx::NativeWindow parent,
                            content::WebContents* web_contents)
      : bubble_delegate_(nullptr),
        parent_(parent),
        web_contents_(web_contents) {
    CreateView();
  }

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

  void CreateView() {
    if (bubble_delegate_) {
      bubble_delegate_->GetWidget()->CloseNow();
    }

    views::View* anchor_view = nullptr;
    auto* bubble = static_cast<PageInfoBubbleView*>(
        PageInfoBubbleView::CreatePageInfoBubble(
            anchor_view, gfx::Rect(), parent_, web_contents_, GURL(kUrl),
            base::DoNothing(),
            base::BindOnce(&PageInfoBubbleViewTestApi::OnPageInfoBubbleClosed,
                           base::Unretained(this), run_loop_.QuitClosure()),
            /*allow_extended_site_info=*/true));
    presenter_ = bubble->presenter_for_testing();
    navigation_handler_ = bubble;
    bubble_delegate_ = bubble;
    toggle_rows_ =
        &static_cast<PageInfoMainView*>(current_view())->toggle_rows_;
  }

  views::View* current_view() {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_CURRENT_VIEW);
  }
  bool reload_prompt() const { return *reload_prompt_; }
  views::Widget::ClosedReason closed_reason() const { return *closed_reason_; }

  views::View* permissions_view() {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_PERMISSION_VIEW);
  }

  const views::View* permissions_view() const {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_PERMISSION_VIEW);
  }

  views::View* cookie_button() {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_COOKIE_DIALOG);
  }

  views::View* cookies_buttons_container_view() {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_COOKIES_BUTTONS_CONTAINER);
  }
  views::View* cookies_dialog_button() {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_COOKIE_DIALOG);
  }

  views::View* blocking_third_party_cookies_row() {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_ROW);
  }

  views::View* blocking_third_party_cookies_subtitle() {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::
            VIEW_ID_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_SUBTITLE);
  }

  views::View* rws_button() {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_RWS_SETTINGS);
  }

  RichHoverButton* certificate_button() const {
    return static_cast<RichHoverButton*>(bubble_delegate_->GetViewByID(
        PageInfoViewFactory::
            VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_CERTIFICATE_VIEWER));
  }

  views::View* security_summary_label() {
    return bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_SECURITY_SUMMARY_LABEL);
  }

  views::StyledLabel* security_details_label() {
    return static_cast<views::StyledLabel*>(bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_SECURITY_DETAILS_LABEL));
  }

  views::LabelButton* reset_permissions_button() {
    return static_cast<views::LabelButton*>(bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_RESET_PERMISSIONS_BUTTON));
  }

  PageInfoNavigationHandler* navigation_handler() {
    return navigation_handler_;
  }

  std::u16string GetWindowTitle() { return bubble_delegate_->GetWindowTitle(); }

  PermissionToggleRowView* GetPermissionToggleRowAt(int index) {
    return (*toggle_rows_)[index];
  }

  views::ToggleButton* GetToggleViewAt(int index) {
    return GetPermissionToggleRowAt(index)->toggle_button_;
  }

  views::Label* GetStateLabelAt(int index) {
    return GetPermissionToggleRowAt(index)->state_label_;
  }

  std::u16string_view GetCookiesSubpageTitle() {
    navigation_handler()->OpenCookiesPage();
    auto* title_label = bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_SUBPAGE_TITLE);
    return static_cast<views::Label*>(title_label)->GetText();
  }

  std::u16string_view GetPrivacyAndSiteDataSubpageTitle() {
    navigation_handler()->OpenPrivacyAndSiteDataPage();
    auto* title_label = bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_SUBPAGE_TITLE);
    return static_cast<views::Label*>(title_label)->GetText();
  }

  // Returns the text shown on the view.
  std::u16string GetTextOnView(views::View* view) {
    EXPECT_TRUE(view);
    ui::AXNodeData data;
    view->GetViewAccessibility().GetAccessibleNodeData(&data);
    const std::string& name =
        data.GetStringAttribute(ax::mojom::StringAttribute::kName);
    return base::ASCIIToUTF16(name);
  }

  // Returns the number of cookies shown on the link or button to open the
  // collected cookies dialog. This should always be shown.
  std::u16string GetCookiesLinkText() {
    EXPECT_TRUE(cookie_button());
    ui::AXNodeData data;
    cookie_button()->GetViewAccessibility().GetAccessibleNodeData(&data);
    const std::string& name =
        data.GetStringAttribute(ax::mojom::StringAttribute::kName);
    return base::ASCIIToUTF16(name);
  }

  std::u16string_view GetSecurityInformationButtonText() {
    auto* button = bubble_delegate_->GetViewByID(
        PageInfoViewFactory::
            VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_SECURITY_INFORMATION);
    return static_cast<RichHoverButton*>(button)->GetTitleText();
  }

  std::u16string_view GetSecuritySummaryText() {
    EXPECT_TRUE(security_summary_label());
    return static_cast<views::StyledLabel*>(security_summary_label())
        ->GetText();
  }

  std::u16string_view GetCookiesButtonTitleText() {
    auto* button = bubble_delegate_->GetViewByID(
        PageInfoViewFactory::VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_COOKIES_SUBPAGE);
    return static_cast<RichHoverButton*>(button)->GetTitleText();
  }

  std::u16string_view GetPrivacyAndSiteDataButtonTitleText() {
    auto* button = bubble_delegate_->GetViewByID(
        PageInfoViewFactory::
            VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_PRIVACY_SITE_DATA_SUBPAGE);
    return static_cast<RichHoverButton*>(button)->GetTitleText();
  }

  std::u16string_view GetPermissionLabelTextAt(int index) {
    return GetPermissionToggleRowAt(index)->row_view_->GetTitleForTesting();
  }

  bool GetPermissionToggleIsOnAt(int index) {
    auto* toggle = GetToggleViewAt(index);
    return toggle->GetIsOn();
  }

  void SimulateTogglingPermissionAt(int index) {
    auto* toggle = GetToggleViewAt(index);
    toggle->SetIsOn(!toggle->GetIsOn());
  }

  size_t GetPermissionsCount() const {
    const views::View* parent = permissions_view();
    size_t actual_count = parent ? parent->children().size() : 0;

    // Non-empty permission section has a reset all button
    // after all permission rows.
    if (actual_count) {
      --actual_count;
    }

    return actual_count;
  }

  // Simulates updating the number of blocked and allowed sites and rws info.
  void SetCookieInfo(const PageInfoUI::CookiesNewInfo& cookie_info) {
    presenter_->ui_for_testing()->SetCookieInfo(cookie_info);
  }

  // Simulates recreating the dialog with a new PermissionInfoList.
  // It ignores `source` field and assumes that user is the source. It's because
  // in the actual UI, permission's state can be changed only if the source is
  // user.
  void SetPermissionInfo(const PermissionInfoList& list) {
    for (const PageInfo::PermissionInfo& info : list) {
      presenter_->OnSitePermissionChanged(info.type, info.setting,
                                          info.requesting_origin,
                                          /*is_one_time=*/false);
    }
    CreateView();
  }

  std::u16string_view GetCertificateButtonSubtitleText() const {
    EXPECT_TRUE(certificate_button());
    return certificate_button()->GetSubtitleText();
  }

  const views::View::Views& GetChosenObjectChildren() {
    const views::View* parent = permissions_view();
    const int object_view_index = 0;
    ChosenObjectView* object_view =
        static_cast<ChosenObjectView*>(parent->children()[object_view_index]);
    views::View* row_view = object_view->children()[0];
    return row_view->children();
  }

  void WaitForBubbleClose() { run_loop_.Run(); }

 private:
  void OnPageInfoBubbleClosed(base::RepeatingCallback<void()> quit_closure,
                              views::Widget::ClosedReason closed_reason,
                              bool reload_prompt) {
    closed_reason_ = closed_reason;
    reload_prompt_ = reload_prompt;
    quit_closure.Run();
  }

  raw_ptr<views::BubbleDialogDelegateView, DanglingUntriaged> bubble_delegate_;
  raw_ptr<PageInfo, DanglingUntriaged> presenter_ = nullptr;
  raw_ptr<std::vector<raw_ptr<PermissionToggleRowView, VectorExperimental>>,
          DanglingUntriaged>
      toggle_rows_ = nullptr;

  raw_ptr<PageInfoNavigationHandler, DanglingUntriaged> navigation_handler_ =
      nullptr;

  // For recreating the view.
  gfx::NativeWindow parent_;
  raw_ptr<content::WebContents> web_contents_;
  base::RunLoop run_loop_;
  std::optional<bool> reload_prompt_;
  std::optional<views::Widget::ClosedReason> closed_reason_;
};

}  // namespace test

namespace {

using ::base::test::ParseJson;
using ::testing::_;
using ::testing::Return;

constexpr char kTestUserEmail[] = "user@example.com";

// Helper class that wraps a TestingProfile and a TestWebContents for a test
// harness. Inspired by RenderViewHostTestHarness, but doesn't use inheritance
// so the helper can be composed with other helpers in the test harness.
class ScopedWebContentsTestHelper {
 public:
  explicit ScopedWebContentsTestHelper(bool off_the_record)
      : testing_profile_manager_(TestingBrowserProcess::GetGlobal()) {
#if BUILDFLAG(IS_CHROMEOS)
    auto fake_user_manager = std::make_unique<ash::FakeChromeUserManager>();
    auto* fake_user_manager_ptr = fake_user_manager.get();
    scoped_user_manager_ = std::make_unique<user_manager::ScopedUserManager>(
        std::move(fake_user_manager));

    const GaiaId kTestUserGaiaId("1111111111");
    auto account_id =
        AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId);
    fake_user_manager_ptr->AddUserWithAffiliation(account_id,
                                                  /*is_affiliated=*/true);
    fake_user_manager_ptr->LoginUser(account_id);
#endif  // BUILDFLAG(IS_CHROMEOS)

    EXPECT_TRUE(testing_profile_manager_.SetUp());
    profile_ = testing_profile_manager_.CreateTestingProfile(
        kTestUserEmail, {TestingProfile::TestingFactory{
                            HistoryServiceFactory::GetInstance(),
                            HistoryServiceFactory::GetDefaultFactory()}});
    EXPECT_TRUE(profile_);

    if (off_the_record) {
      profile_ = profile_->GetPrimaryOTRProfile(/*create_if_needed=*/true);
    }
    web_contents_ = factory_.CreateWebContents(profile_);
  }

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

  content::WebContents* web_contents() { return web_contents_; }
  Profile* profile() { return profile_; }
  TestingPrefServiceSimple* local_state() {
    return testing_profile_manager_.local_state()->Get();
  }

 private:
  content::BrowserTaskEnvironment task_environment_;

#if BUILDFLAG(IS_CHROMEOS)
  std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager_;
#endif

  TestingProfileManager testing_profile_manager_;
  raw_ptr<Profile> profile_ = nullptr;
  content::TestWebContentsFactory factory_;
  raw_ptr<content::WebContents> web_contents_;  // Weak. Owned by factory_.
};

class PageInfoBubbleViewTest : public testing::Test {
 public:
  PageInfoBubbleViewTest() = default;
  PageInfoBubbleViewTest(const PageInfoBubbleViewTest& chip) = delete;
  PageInfoBubbleViewTest& operator=(const PageInfoBubbleViewTest& chip) =
      delete;

  // testing::Test:
  void SetUp() override {
    TestingBrowserProcess::GetGlobal()->CreateGlobalFeaturesForTesting();

    // Create after the global features to ensure that there are no
    // dangling pointers during teardown.
    CHECK(!web_contents_helper_);
    web_contents_helper_ =
        std::make_unique<ScopedWebContentsTestHelper>(off_the_record_);

    views_helper_ = std::make_unique<views::ScopedViewsTestHelper>(
        std::make_unique<ChromeTestViewsDelegate<>>());
    views::Widget::InitParams parent_params(
        views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET);
    parent_params.context = views_helper_->GetContext();
    parent_window_ = new views::Widget();
    parent_window_->Init(std::move(parent_params));

    mock_sentiment_service_ = static_cast<MockTrustSafetySentimentService*>(
        TrustSafetySentimentServiceFactory::GetInstance()
            ->SetTestingFactoryAndUse(
                web_contents_helper_->profile(),
                base::BindRepeating(&BuildMockTrustSafetySentimentService)));

    content::WebContents* web_contents = web_contents_helper_->web_contents();
    content_settings::PageSpecificContentSettings::CreateForWebContents(
        web_contents,
        std::make_unique<PageSpecificContentSettingsDelegate>(web_contents));
    api_ = std::make_unique<test::PageInfoBubbleViewTestApi>(
        parent_window_->GetNativeWindow(), web_contents);

    permissions::PermissionRecoverySuccessRateTracker::CreateForWebContents(
        web_contents);
  }

  void TearDown() override { parent_window_->CloseNow(); }

 protected:
  bool off_the_record_ = false;

  std::unique_ptr<ScopedWebContentsTestHelper> web_contents_helper_;
  std::unique_ptr<views::ScopedViewsTestHelper> views_helper_;
  raw_ptr<MockTrustSafetySentimentService> mock_sentiment_service_;

  raw_ptr<views::Widget, DanglingUntriaged> parent_window_ =
      nullptr;  // Weak. Owned by the NativeWidget.
  std::unique_ptr<test::PageInfoBubbleViewTestApi> api_;
};

views::Label* GetChosenObjectTitle(const views::View::Views& children) {
  views::View* labels_container = children[1];
  return static_cast<views::Label*>(labels_container->children()[0]);
}

views::Button* GetChosenObjectButton(const views::View::Views& children) {
  return static_cast<views::Button*>(children[2]);
}

views::Label* GetChosenObjectDescriptionLabel(
    const views::View::Views& children) {
  views::View* labels_container = children[1];
  return static_cast<views::Label*>(labels_container->children()[1]);
}

}  // namespace

TEST_F(PageInfoBubbleViewTest, NotificationPermissionRevokeUkm) {
  GURL origin_url = GURL(kUrl).DeprecatedGetOriginAsURL();
  ukm::TestAutoSetUkmRecorder ukm_recorder;

  PermissionInfoList list(1);
  list.back().type = ContentSettingsType::NOTIFICATIONS;

  list.back().setting = CONTENT_SETTING_ALLOW;
  api_->SetPermissionInfo(list);

  list.back().setting = CONTENT_SETTING_BLOCK;
  api_->SetPermissionInfo(list);

  auto entries = ukm_recorder.GetEntriesByName("Permission");
  EXPECT_EQ(1u, entries.size());
  auto* entry = entries.front().get();

  ukm_recorder.ExpectEntrySourceHasUrl(entry, origin_url);
  EXPECT_EQ(*ukm_recorder.GetEntryMetric(entry, "Source"),
            static_cast<int64_t>(permissions::PermissionSourceUI::OIB));
  EXPECT_EQ(*ukm_recorder.GetEntryMetric(entry, "PermissionType"),
            content_settings_uma_util::ContentSettingTypeToHistogramValue(
                ContentSettingsType::NOTIFICATIONS));
  EXPECT_EQ(*ukm_recorder.GetEntryMetric(entry, "Action"),
            static_cast<int64_t>(permissions::PermissionAction::REVOKED));
}

// Test UI construction and reconstruction via
// PageInfoBubbleView::SetPermissionInfo().
TEST_F(PageInfoBubbleViewTest, SetPermissionInfo) {
  // Mock system-level location permission.
  system_permission_settings::ScopedSettingsForTesting system_location_settings(
      ContentSettingsType::GEOLOCATION, /*blocked=*/false);

  PermissionInfoList list(1);
  list.back().type = ContentSettingsType::GEOLOCATION;
  list.back().setting = CONTENT_SETTING_BLOCK;

  // Initially, no permissions are shown because they are all set to default.
  size_t num_expected_children = 0;
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());
  EXPECT_FALSE(api_->reset_permissions_button());

  num_expected_children += list.size();
  list.back().setting = CONTENT_SETTING_ALLOW;
  api_->SetPermissionInfo(list);
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());

  EXPECT_TRUE(api_->reset_permissions_button()->GetVisible());
  EXPECT_TRUE(api_->reset_permissions_button()->GetEnabled());
  EXPECT_EQ(u"Reset permission", api_->reset_permissions_button()->GetText());
  PermissionToggleRowView* toggle_view = api_->GetPermissionToggleRowAt(0);
  EXPECT_TRUE(toggle_view);

  // Verify labels match the settings on the PermissionInfoList.
  EXPECT_EQ(u"Location", api_->GetPermissionLabelTextAt(0));
  EXPECT_TRUE(api_->GetPermissionToggleIsOnAt(0));

  // Verify calling SetPermissionInfo() directly updates the UI.
  list.back().setting = CONTENT_SETTING_BLOCK;
  api_->SetPermissionInfo(list);
  EXPECT_FALSE(api_->GetPermissionToggleIsOnAt(0));

  // Simulate a user selection via the UI. Note this will also cover logic in
  // PageInfo to update the pref.
  api_->SimulateTogglingPermissionAt(0);
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());
  EXPECT_TRUE(api_->GetPermissionToggleIsOnAt(0));

  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);
  views::test::ButtonTestApi(api_->reset_permissions_button())
      .NotifyClick(event);
  // After resetting permissions, button doesn't disappear but is disabled.
  EXPECT_TRUE(api_->reset_permissions_button()->GetVisible());
  EXPECT_FALSE(api_->reset_permissions_button()->GetEnabled());

  // In the ask state, the toggle is in the off state, indicating that
  // permission isn't granted.
  EXPECT_FALSE(api_->GetPermissionToggleIsOnAt(0));

  // However, since the setting is now default, recreating the dialog with
  // those settings should omit the permission from the UI.
  //
  // TODO(crbug.com/40570388): Reconcile the comment above with the fact
  // that |num_expected_children| is not, at this point, 0 and therefore the
  // permission is not being omitted from the UI.
  api_->SetPermissionInfo(list);
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());
}

TEST_F(PageInfoBubbleViewTest, CheckToggleSettingForCapturedSurfaceControl) {
  PermissionInfoList list(1);
  list.back().type = ContentSettingsType::CAPTURED_SURFACE_CONTROL;
  api_->SetPermissionInfo(list);

  EXPECT_EQ(l10n_util::GetStringUTF16(
                IDS_SITE_SETTINGS_TYPE_CAPTURED_SURFACE_CONTROL_SHARED_TABS),
            api_->GetPermissionLabelTextAt(0));
  // Verifies that there is no toggle in the main page info.
  EXPECT_EQ(api_->GetToggleViewAt(0), nullptr);

  // Opens the submenu for Captured Surface Control permission.
  api_->navigation_handler()->OpenPermissionPage(
      ContentSettingsType::CAPTURED_SURFACE_CONTROL);
  ASSERT_GE(api_->current_view()->children().size(), 2u);
  auto* page_view = static_cast<PageInfoPermissionContentView*>(
      api_->current_view()->children()[1]);
  ASSERT_TRUE(page_view);
#if !BUILDFLAG(IS_CHROMEOS)
  EXPECT_EQ(l10n_util::GetStringUTF16(
                IDS_SITE_SETTINGS_TYPE_CAPTURED_SURFACE_CONTROL_SUB_MENU),
            page_view->GetTitleForTesting()->GetText());
#endif
  // Verifies that there is a toggle in the permission page view.
  EXPECT_NE(page_view->GetToggleButtonForTesting(), nullptr);
}

class PageInfoBubbleViewOffTheRecordTest : public PageInfoBubbleViewTest {
 public:
  PageInfoBubbleViewOffTheRecordTest() { off_the_record_ = true; }
};

// Test resetting blocked in Incognito permission.
TEST_F(PageInfoBubbleViewOffTheRecordTest, ResetBlockedInIncognitoPermission) {
  // No sentiment service in incognito.
  EXPECT_FALSE(mock_sentiment_service_);

  PermissionInfoList list(1);
  list.back().type = ContentSettingsType::NOTIFICATIONS;
  list.back().setting = CONTENT_SETTING_BLOCK;

  // Initially, no permissions are shown because they are all set to default.
  size_t num_expected_children = 0;
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());
  EXPECT_FALSE(api_->reset_permissions_button());

  num_expected_children = list.size();
  api_->SetPermissionInfo(list);
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());

  // Because permission is autoblocked, no reset button initially is shown.
  EXPECT_FALSE(api_->reset_permissions_button()->GetVisible());
  EXPECT_FALSE(api_->reset_permissions_button()->GetEnabled());

  // Autoblocked permissions don't have toggles or state labels.
  EXPECT_FALSE(api_->GetToggleViewAt(0));
  EXPECT_FALSE(api_->GetStateLabelAt(0));

  // Verify labels match the settings on the PermissionInfoList.
  EXPECT_EQ(u"Notifications", api_->GetPermissionLabelTextAt(0));

  PageInfo::PermissionInfo window_management_permission;
  window_management_permission.type = ContentSettingsType::WINDOW_MANAGEMENT;
  window_management_permission.setting = CONTENT_SETTING_ALLOW;
  window_management_permission.default_setting = CONTENT_SETTING_ASK;
  list.push_back(window_management_permission);

  num_expected_children = list.size();
  api_->SetPermissionInfo(list);
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());

  // Because a non-managed permission was added, reset button is visible and
  // enabled.
  EXPECT_TRUE(api_->reset_permissions_button()->GetVisible());
  EXPECT_TRUE(api_->reset_permissions_button()->GetEnabled());
  // Although there are only one resettable permission, multiple rows are
  // shown. Because of that use plural version of the "permission" word.
  EXPECT_EQ(u"Reset permissions", api_->reset_permissions_button()->GetText());

  // User managed permissions have toggles. |camera_permission| is allowed and
  // the toggle must be on.
  EXPECT_TRUE(api_->GetToggleViewAt(1));
  EXPECT_TRUE(api_->GetPermissionToggleIsOnAt(1));

  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);
  views::test::ButtonTestApi(api_->reset_permissions_button())
      .NotifyClick(event);
  // After resetting permissions, button doesn't disappear but is disabled.
  EXPECT_TRUE(api_->reset_permissions_button()->GetVisible());
  EXPECT_FALSE(api_->reset_permissions_button()->GetEnabled());

  // Show state label for user managed permission, indicating that permission
  // is in the default ask state now. Autoblocked permission doesn't change.
  EXPECT_FALSE(api_->GetStateLabelAt(0));
  EXPECT_EQ(u"Can ask to manage windows on all your displays",
            api_->GetStateLabelAt(1)->GetText());

  // In the ask state, the toggle is in the off state, indicating that
  // permission isn't granted.
  EXPECT_FALSE(api_->GetPermissionToggleIsOnAt(1));
}

// Test UI construction and reconstruction with USB devices.
TEST_F(PageInfoBubbleViewTest, SetPermissionInfoWithUsbDevice) {
  EXPECT_CALL(*mock_sentiment_service_, InteractedWithPageInfo);
  constexpr size_t kExpectedChildren = 0;
  EXPECT_EQ(kExpectedChildren, api_->GetPermissionsCount());

  const auto origin = url::Origin::Create(GURL(kUrl));

  // Connect the UsbChooserContext with FakeUsbDeviceManager.
  device::FakeUsbDeviceManager usb_device_manager;
  mojo::PendingRemote<device::mojom::UsbDeviceManager> usb_manager;
  usb_device_manager.AddReceiver(usb_manager.InitWithNewPipeAndPassReceiver());
  UsbChooserContext* store =
      UsbChooserContextFactory::GetForProfile(web_contents_helper_->profile());
  store->SetDeviceManagerForTesting(std::move(usb_manager));

  auto device_info = usb_device_manager.CreateAndAddDevice(
      0, 0, "Google", "Gizmo", "1234567890");
  store->GrantDevicePermission(origin, *device_info);

  PermissionInfoList list;
  api_->SetPermissionInfo(list);
  EXPECT_EQ(kExpectedChildren + 1, api_->GetPermissionsCount());

  const auto& chosen_object_children = api_->GetChosenObjectChildren();
  EXPECT_EQ(3u, chosen_object_children.size());

  views::Label* label = GetChosenObjectTitle(chosen_object_children);
  EXPECT_EQ(u"Gizmo", label->GetText());

  views::Button* button = GetChosenObjectButton(chosen_object_children);
  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);
  views::test::ButtonTestApi(button).NotifyClick(event);
  api_->SetPermissionInfo(list);
  EXPECT_EQ(kExpectedChildren, api_->GetPermissionsCount());
  EXPECT_FALSE(store->HasDevicePermission(origin, *device_info));
}

// Test resetting USB devices permission.
TEST_F(PageInfoBubbleViewTest, ResetPermissionInfoWithUsbDevice) {
  EXPECT_CALL(*mock_sentiment_service_, InteractedWithPageInfo).Times(2);

  constexpr size_t kExpectedChildren = 0;
  EXPECT_EQ(kExpectedChildren, api_->GetPermissionsCount());
  EXPECT_FALSE(api_->reset_permissions_button());

  const auto origin = url::Origin::Create(GURL(kUrl));

  // Connect the UsbChooserContext with FakeUsbDeviceManager.
  device::FakeUsbDeviceManager usb_device_manager;
  mojo::PendingRemote<device::mojom::UsbDeviceManager> usb_manager;
  usb_device_manager.AddReceiver(usb_manager.InitWithNewPipeAndPassReceiver());
  UsbChooserContext* store =
      UsbChooserContextFactory::GetForProfile(web_contents_helper_->profile());
  store->SetDeviceManagerForTesting(std::move(usb_manager));

  auto device_info = usb_device_manager.CreateAndAddDevice(
      0, 0, "Google", "Gizmo", "1234567890");
  store->GrantDevicePermission(origin, *device_info);

  PermissionInfoList list;
  api_->SetPermissionInfo(list);
  EXPECT_EQ(kExpectedChildren + 1, api_->GetPermissionsCount());
  EXPECT_TRUE(api_->reset_permissions_button()->GetVisible());
  EXPECT_TRUE(api_->reset_permissions_button()->GetEnabled());
  EXPECT_EQ(u"Reset permission", api_->reset_permissions_button()->GetText());

  const auto& chosen_object_children = api_->GetChosenObjectChildren();
  EXPECT_EQ(3u, chosen_object_children.size());

  views::Label* label = GetChosenObjectTitle(chosen_object_children);
  EXPECT_EQ(u"Gizmo", label->GetText());

  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);
  views::test::ButtonTestApi(api_->reset_permissions_button())
      .NotifyClick(event);
  api_->SetPermissionInfo(list);
  EXPECT_EQ(kExpectedChildren, api_->GetPermissionsCount());
  EXPECT_FALSE(api_->reset_permissions_button());
  EXPECT_FALSE(store->HasDevicePermission(origin, *device_info));
}

namespace {

constexpr char kWebUsbPolicySetting[] = R"(
    [
      {
        "devices": [{ "vendor_id": 6353, "product_id": 5678 }],
        "urls": ["http://www.example.com"]
      }
    ])";

}  // namespace

// Test UI construction and reconstruction with policy USB devices.
TEST_F(PageInfoBubbleViewTest, SetPermissionInfoWithPolicyUsbDevices) {
  constexpr size_t kExpectedChildren = 0;
  EXPECT_EQ(kExpectedChildren, api_->GetPermissionsCount());

  const auto origin = url::Origin::Create(GURL(kUrl));

  // Add the policy setting to prefs.
  Profile* profile = web_contents_helper_->profile();
  profile->GetPrefs()->Set(prefs::kManagedWebUsbAllowDevicesForUrls,
                           ParseJson(kWebUsbPolicySetting));
  UsbChooserContext* store = UsbChooserContextFactory::GetForProfile(profile);

  auto objects = store->GetGrantedObjects(origin);
  EXPECT_EQ(objects.size(), 1u);

  PermissionInfoList list;
  api_->SetPermissionInfo(list);
  EXPECT_EQ(kExpectedChildren + 1, api_->GetPermissionsCount());

  const auto& chosen_object_children = api_->GetChosenObjectChildren();
  EXPECT_EQ(3u, chosen_object_children.size());

  views::Label* label = GetChosenObjectTitle(chosen_object_children);
  EXPECT_EQ(u"Unknown product 0x162E from Google Inc.", label->GetText());

  views::Button* button = GetChosenObjectButton(chosen_object_children);
  EXPECT_EQ(button->GetState(), views::Button::STATE_DISABLED);

  views::Label* desc_label =
      GetChosenObjectDescriptionLabel(chosen_object_children);
  EXPECT_EQ(u"USB device allowed by your administrator", desc_label->GetText());

  // Policy granted USB permissions should not be able to be deleted.
  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);
  views::test::ButtonTestApi(button).NotifyClick(event);
  api_->SetPermissionInfo(list);
  EXPECT_EQ(kExpectedChildren + 1, api_->GetPermissionsCount());
}

// Test UI construction and reconstruction with both user and policy USB
// devices.
TEST_F(PageInfoBubbleViewTest, SetPermissionInfoWithUserAndPolicyUsbDevices) {
  EXPECT_CALL(*mock_sentiment_service_, InteractedWithPageInfo);
  constexpr size_t kExpectedChildren = 0;
  EXPECT_EQ(kExpectedChildren, api_->GetPermissionsCount());

  const auto origin = url::Origin::Create(GURL(kUrl));

  // Add the policy setting to prefs.
  Profile* profile = web_contents_helper_->profile();
  profile->GetPrefs()->Set(prefs::kManagedWebUsbAllowDevicesForUrls,
                           ParseJson(kWebUsbPolicySetting));

  // Connect the UsbChooserContext with FakeUsbDeviceManager.
  device::FakeUsbDeviceManager usb_device_manager;
  mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager;
  usb_device_manager.AddReceiver(
      device_manager.InitWithNewPipeAndPassReceiver());
  UsbChooserContext* store = UsbChooserContextFactory::GetForProfile(profile);
  store->SetDeviceManagerForTesting(std::move(device_manager));

  auto device_info = usb_device_manager.CreateAndAddDevice(
      0, 0, "Google", "Gizmo", "1234567890");
  store->GrantDevicePermission(origin, *device_info);

  auto objects = store->GetGrantedObjects(origin);
  EXPECT_EQ(objects.size(), 2u);

  PermissionInfoList list;
  api_->SetPermissionInfo(list);
  EXPECT_EQ(kExpectedChildren + 2, api_->GetPermissionsCount());

  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);

  // The first object is the user granted permission for the "Gizmo" device.
  {
    const auto& chosen_object_children = api_->GetChosenObjectChildren();
    EXPECT_EQ(3u, chosen_object_children.size());

    views::Label* label = GetChosenObjectTitle(chosen_object_children);
    EXPECT_EQ(u"Gizmo", label->GetText());

    views::Button* button = GetChosenObjectButton(chosen_object_children);
    EXPECT_NE(button->GetState(), views::Button::STATE_DISABLED);

    views::Label* desc_label =
        GetChosenObjectDescriptionLabel(chosen_object_children);
    EXPECT_EQ(u"USB device", desc_label->GetText());

    views::test::ButtonTestApi(button).NotifyClick(event);
    api_->SetPermissionInfo(list);
    EXPECT_EQ(kExpectedChildren + 1, api_->GetPermissionsCount());
    EXPECT_FALSE(store->HasDevicePermission(origin, *device_info));
  }

  // The policy granted permission should now be the first child, since the user
  // permission was deleted.
  {
    const auto& chosen_object_children = api_->GetChosenObjectChildren();
    EXPECT_EQ(3u, chosen_object_children.size());

    views::Label* label = GetChosenObjectTitle(chosen_object_children);
    EXPECT_EQ(u"Unknown product 0x162E from Google Inc.", label->GetText());

    views::Button* button = GetChosenObjectButton(chosen_object_children);
    EXPECT_EQ(button->GetState(), views::Button::STATE_DISABLED);

    views::Label* desc_label =
        GetChosenObjectDescriptionLabel(chosen_object_children);
    EXPECT_EQ(u"USB device allowed by your administrator",
              desc_label->GetText());

    views::test::ButtonTestApi(button).NotifyClick(event);
    api_->SetPermissionInfo(list);
    EXPECT_EQ(kExpectedChildren + 1, api_->GetPermissionsCount());
  }
}

TEST_F(PageInfoBubbleViewTest, SetPermissionInfoForUsbGuard) {
  PermissionInfoList list(1);
  list.back().type = ContentSettingsType::USB_GUARD;
  list.back().setting = CONTENT_SETTING_ASK;

  // Initially, no permissions are shown because they are all set to default.
  size_t num_expected_children = 0;
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());

  // Verify calling SetPermissionInfo() directly updates the UI.
  num_expected_children += list.size();
  list.back().setting = CONTENT_SETTING_BLOCK;
  api_->SetPermissionInfo(list);
  EXPECT_FALSE(api_->GetPermissionToggleIsOnAt(0));

  // Simulate a user selection via the UI. Note this will also cover logic in
  // PageInfo to update the pref.
  api_->SimulateTogglingPermissionAt(0);
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());
  EXPECT_TRUE(api_->GetPermissionToggleIsOnAt(0));

  // However, since the setting is now default, recreating the dialog with
  // those settings should omit the permission from the UI.
  //
  // TODO(crbug.com/40570388): Reconcile the comment above with the fact
  // that |num_expected_children| is not, at this point, 0 and therefore the
  // permission is not being omitted from the UI.
  api_->SetPermissionInfo(list);
  EXPECT_EQ(num_expected_children, api_->GetPermissionsCount());
}

// Test UI construction and reconstruction with policy USB devices.
TEST_F(PageInfoBubbleViewTest, SetPermissionInfoWithPolicySerialPorts) {
  constexpr size_t kExpectedChildren = 0;
  EXPECT_EQ(kExpectedChildren, api_->GetPermissionsCount());

  // Add the policy setting to prefs.
  web_contents_helper_->local_state()->Set(
      prefs::kManagedSerialAllowUsbDevicesForUrls, ParseJson(R"([
               {
                 "devices": [{ "vendor_id": 6353, "product_id": 5678 }],
                 "urls": [ "http://www.example.com" ]
               }
             ])"));

  PermissionInfoList list;
  api_->SetPermissionInfo(list);
  EXPECT_EQ(kExpectedChildren + 1, api_->GetPermissionsCount());

  const auto& chosen_object_children = api_->GetChosenObjectChildren();
  EXPECT_EQ(3u, chosen_object_children.size());

  views::Label* label = GetChosenObjectTitle(chosen_object_children);
  EXPECT_EQ(u"USB device from Google Inc. (product 162E)", label->GetText());

  views::Button* button = GetChosenObjectButton(chosen_object_children);
  EXPECT_EQ(button->GetState(), views::Button::STATE_DISABLED);

  views::Label* desc_label =
      GetChosenObjectDescriptionLabel(chosen_object_children);
  EXPECT_EQ(u"Serial port allowed by your administrator",
            desc_label->GetText());

  // Policy granted serial port permissions should not be able to be deleted.
  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);
  views::test::ButtonTestApi(button).NotifyClick(event);
  api_->SetPermissionInfo(list);
  EXPECT_EQ(kExpectedChildren + 1, api_->GetPermissionsCount());
}

// Test that updating the number of cookies used by the current page doesn't add
// any extra views to Page Info.
TEST_F(PageInfoBubbleViewTest, UpdatingSiteDataRetainsLayout) {
#if BUILDFLAG(IS_WIN) && BUILDFLAG(ENABLE_VR)
  size_t kExpectedChildren = 6;
#else
  size_t kExpectedChildren = 5;
#endif
  if (page_info::IsAboutThisSiteFeatureEnabled(
          g_browser_process->GetApplicationLocale())) {
    ++kExpectedChildren;
  }

  EXPECT_EQ(kExpectedChildren, api_->current_view()->children().size());

  // Create a fake cookies info.
  PageInfoUI::CookiesNewInfo cookies;
  cookies.allowed_sites_count = 10;
  cookies.enforcement = CookieControlsEnforcement::kNoEnforcement;
  cookies.blocking_status = CookieBlocking3pcdStatus::kNotIn3pcd;

  // Update the cookies info.
  api_->SetCookieInfo(cookies);

  EXPECT_EQ(kExpectedChildren, api_->current_view()->children().size());
}

// Tests opening the bubble between navigation start and finish. The bubble
// should be updated to reflect the secure state after the navigation commits.
TEST_F(PageInfoBubbleViewTest, OpenPageInfoBubbleAfterNavigationStart) {
  ChromeSecurityStateTabHelper::CreateForWebContents(
      web_contents_helper_->web_contents());
  std::unique_ptr<content::NavigationSimulator> navigation =
      content::NavigationSimulator::CreateRendererInitiated(
          GURL(kSecureUrl),
          web_contents_helper_->web_contents()->GetPrimaryMainFrame());
  navigation->Start();
  api_->CreateView();
  EXPECT_EQ(kHostname, api_->GetWindowTitle());
  EXPECT_FALSE(api_->certificate_button());
  EXPECT_TRUE(api_->security_details_label());
  EXPECT_EQ(api_->GetSecuritySummaryText(),
            l10n_util::GetStringUTF16(IDS_PAGE_INFO_NOT_SECURE_SUMMARY));

  // Set up a test SSLInfo so that Page Info sees the connection as secure.
  uint16_t cipher_suite = 0xc02f;  // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  int connection_status = 0;
  net::SSLConnectionStatusSetCipherSuite(cipher_suite, &connection_status);
  net::SSLConnectionStatusSetVersion(net::SSL_CONNECTION_VERSION_TLS1_2,
                                     &connection_status);
  net::SSLInfo ssl_info;
  ssl_info.connection_status = connection_status;
  ssl_info.cert =
      net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem");
  ASSERT_TRUE(ssl_info.cert);

  navigation->SetSSLInfo(ssl_info);

  navigation->Commit();
  // In page info v2, in secure state description and learn more link aren't
  // shown on the main page.
  EXPECT_EQ(kHostname, api_->GetWindowTitle());
  EXPECT_FALSE(api_->security_details_label());
  EXPECT_EQ(api_->GetSecurityInformationButtonText(),
            l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURE_SUMMARY));

  api_->navigation_handler()->OpenSecurityPage();
  EXPECT_TRUE(api_->security_details_label());
}

TEST_F(PageInfoBubbleViewTest, EnsureCloseCallback) {
  api_->current_view()->GetWidget()->CloseWithReason(
      views::Widget::ClosedReason::kCloseButtonClicked);
  api_->WaitForBubbleClose();
  EXPECT_EQ(false, api_->reload_prompt());
  EXPECT_EQ(views::Widget::ClosedReason::kCloseButtonClicked,
            api_->closed_reason());
}

TEST_F(PageInfoBubbleViewTest, CheckHeaderInteractions) {
  // Confirm that interactions with the header tips are reported to the
  // sentiment service correctly.
  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);
  // Navigating to the security page constitutes an interaction.
  EXPECT_CALL(*mock_sentiment_service_, InteractedWithPageInfo).Times(3);
  api_->navigation_handler()->OpenSecurityPage();
  auto* page_view = static_cast<PageInfoSecurityContentView*>(
      api_->current_view()->children()[1]);
  page_view->SecurityDetailsClicked(event);
  page_view->ResetDecisionsClicked();
}

TEST_F(PageInfoBubbleViewTest, CertificateButtonShowsEvCertDetails) {
  ChromeSecurityStateTabHelper::CreateForWebContents(
      web_contents_helper_->web_contents());
  std::unique_ptr<content::NavigationSimulator> navigation =
      content::NavigationSimulator::CreateRendererInitiated(
          GURL(kSecureUrl),
          web_contents_helper_->web_contents()->GetPrimaryMainFrame());
  navigation->Start();
  api_->CreateView();

  // Set up a test SSLInfo so that Page Info sees the connection as secure and
  // using an EV certificate.
  uint16_t cipher_suite = 0xc02f;  // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  int connection_status = 0;
  net::SSLConnectionStatusSetCipherSuite(cipher_suite, &connection_status);
  net::SSLConnectionStatusSetVersion(net::SSL_CONNECTION_VERSION_TLS1_2,
                                     &connection_status);
  net::SSLInfo ssl_info;
  ssl_info.connection_status = connection_status;
  ssl_info.cert =
      net::ImportCertFromFile(net::GetTestCertsDirectory(), "ev_test.pem");
  ASSERT_TRUE(ssl_info.cert);
  ssl_info.cert_status = net::CERT_STATUS_IS_EV;

  navigation->SetSSLInfo(ssl_info);

  navigation->Commit();
  // In page info v2, in secure state certificate button isn't shown on the
  // main page.
  EXPECT_EQ(kHostname, api_->GetWindowTitle());
  EXPECT_FALSE(api_->certificate_button());
  EXPECT_FALSE(api_->security_summary_label());
  EXPECT_EQ(api_->GetSecurityInformationButtonText(),
            l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURE_SUMMARY));

  api_->navigation_handler()->OpenSecurityPage();
  EXPECT_TRUE(api_->certificate_button());
  EXPECT_EQ(l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURE_SUMMARY),
            api_->GetSecuritySummaryText());

  // The certificate button subtitle should show the EV certificate organization
  // name and country of incorporation.
  EXPECT_EQ(l10n_util::GetStringFUTF16(
                IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED,
                u"Test Org", u"US"),
            api_->GetCertificateButtonSubtitleText());
}

// Regression test for crbug.com/1069113. Test cert includes country and state
// but not locality.
TEST_F(PageInfoBubbleViewTest, EvDetailsShowForCertWithStateButNoLocality) {
  ChromeSecurityStateTabHelper::CreateForWebContents(
      web_contents_helper_->web_contents());
  std::unique_ptr<content::NavigationSimulator> navigation =
      content::NavigationSimulator::CreateRendererInitiated(
          GURL(kSecureUrl),
          web_contents_helper_->web_contents()->GetPrimaryMainFrame());
  navigation->Start();
  api_->CreateView();

  // Set up a test SSLInfo so that Page Info sees the connection as secure and
  // using an EV certificate.
  uint16_t cipher_suite = 0xc02f;  // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  int connection_status = 0;
  net::SSLConnectionStatusSetCipherSuite(cipher_suite, &connection_status);
  net::SSLConnectionStatusSetVersion(net::SSL_CONNECTION_VERSION_TLS1_2,
                                     &connection_status);
  net::SSLInfo ssl_info;
  ssl_info.connection_status = connection_status;
  ssl_info.cert = net::ImportCertFromFile(net::GetTestCertsDirectory(),
                                          "ev_test_state_only.pem");
  ASSERT_TRUE(ssl_info.cert);

  ssl_info.cert_status = net::CERT_STATUS_IS_EV;

  navigation->SetSSLInfo(ssl_info);

  navigation->Commit();
  // In page info v2, in secure state certificate button isn't shown on the
  // main page.
  EXPECT_EQ(kHostname, api_->GetWindowTitle());
  EXPECT_FALSE(api_->certificate_button());
  EXPECT_FALSE(api_->security_summary_label());
  EXPECT_EQ(api_->GetSecurityInformationButtonText(),
            l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURE_SUMMARY));

  api_->navigation_handler()->OpenSecurityPage();
  EXPECT_TRUE(api_->certificate_button());
  EXPECT_EQ(l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURE_SUMMARY),
            api_->GetSecuritySummaryText());

  // The certificate button subtitle should show the EV certificate organization
  // name and country of incorporation.
  EXPECT_EQ(l10n_util::GetStringFUTF16(
                IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED,
                u"Test Org", u"US"),
            api_->GetCertificateButtonSubtitleText());
}

class PageInfoBubbleViewCookies3pcdButtonTest
    : public PageInfoBubbleViewTest,
      public testing::WithParamInterface<bool> {
 public:
  PageInfoBubbleViewCookies3pcdButtonTest() {
    feature_list_.InitWithFeatures(
        {content_settings::features::kTrackingProtection3pcd}, {});
    off_the_record_ = GetParam();
  }

 protected:
  void NavigateToPage(content::WebContents* web_contents,
                      const std::string& url) {
    web_contents->GetController().LoadURL(GURL(url), content::Referrer(),
                                          ui::PAGE_TRANSITION_FROM_ADDRESS_BAR,
                                          std::string());
    content::RenderFrameHostTester::CommitPendingLoad(
        &web_contents->GetController());
  }

  void CreateCookieExceptionForSite(const std::string& pattern) {
    auto top_level_domain_pattern = ContentSettingsPattern::FromString(pattern);
    HostContentSettingsMapFactory::GetForProfile(
        web_contents_helper_->profile())
        ->SetContentSettingCustomScope(ContentSettingsPattern::Wildcard(),
                                       top_level_domain_pattern,
                                       ContentSettingsType::COOKIES,
                                       ContentSetting::CONTENT_SETTING_ALLOW);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_P(PageInfoBubbleViewCookies3pcdButtonTest, DisplaysCookiesButtonLabel) {
  // Block all 3PC
  web_contents_helper_->profile()->GetPrefs()->SetBoolean(
      prefs::kBlockAll3pcToggleEnabled, true);
  // Rerender with the new pref set
  api_->CreateView();

  EXPECT_EQ(api_->GetCookiesButtonTitleText(),
            l10n_util::GetStringUTF16(IDS_PAGE_INFO_COOKIES_HEADER));

  // Turn off toggle
  web_contents_helper_->profile()->GetPrefs()->SetBoolean(
      prefs::kBlockAll3pcToggleEnabled, false);
  // Rerender with the new pref set
  api_->CreateView();

  EXPECT_EQ(api_->GetCookiesButtonTitleText(),
            l10n_util::GetStringUTF16(IDS_PAGE_INFO_COOKIES_HEADER));
}

INSTANTIATE_TEST_SUITE_P(All,
                         PageInfoBubbleViewCookies3pcdButtonTest,
                         /*is_otr*/ testing::Bool());

class PageInfoBubbleViewCookiesSubpageTitleTest
    : public PageInfoBubbleViewTest,
      public testing::WithParamInterface<
          testing::tuple<CookieControlsState,
                         CookieBlocking3pcdStatus,
                         /*is_otr*/ bool>> {
 public:
  PageInfoBubbleViewCookiesSubpageTitleTest() {
    feature_list_.InitWithFeatures(
        {content_settings::features::kTrackingProtection3pcd}, {});
    off_the_record_ = testing::get<2>(GetParam());
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_P(PageInfoBubbleViewCookiesSubpageTitleTest,
       DisplaysCookiesAndSiteDataTitle) {
  PageInfoUI::CookiesNewInfo cookie_info;
  cookie_info.controls_state = testing::get<0>(GetParam());
  cookie_info.blocking_status = testing::get<1>(GetParam());
  api_->SetCookieInfo(cookie_info);
  EXPECT_EQ(api_->GetCookiesSubpageTitle(),
            l10n_util::GetStringUTF16(IDS_PAGE_INFO_COOKIES_HEADER));
}

INSTANTIATE_TEST_SUITE_P(
    All,
    PageInfoBubbleViewCookiesSubpageTitleTest,
    testing::Combine(testing::Values(CookieControlsState::kAllowed3pc,
                                     CookieControlsState::kBlocked3pc),
                     testing::Values(CookieBlocking3pcdStatus::kNotIn3pcd,
                                     CookieBlocking3pcdStatus::kAll),
                     /*is_otr*/ testing::Bool()));

class PageInfoBubbleViewPrivacyAndSiteDataSubpageTitleTest
    : public PageInfoBubbleViewTest,
      public testing::WithParamInterface<CookieControlsState> {
 public:
  PageInfoBubbleViewPrivacyAndSiteDataSubpageTitleTest() {
    feature_list_.InitWithFeatures(
        {privacy_sandbox::kActUserBypassUx,
         privacy_sandbox::kFingerprintingProtectionUx},
        {});
    off_the_record_ = true;
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_P(PageInfoBubbleViewPrivacyAndSiteDataSubpageTitleTest,
       DisplaysPrivacyAndSiteDataTitle) {
  PageInfoUI::CookiesNewInfo cookie_info;
  cookie_info.controls_state = GetParam();
  api_->SetCookieInfo(cookie_info);

  EXPECT_EQ(api_->GetPrivacyAndSiteDataButtonTitleText(),
            l10n_util::GetStringUTF16(IDS_PAGE_INFO_PRIVACY_SITE_DATA_HEADER));
  EXPECT_EQ(api_->GetPrivacyAndSiteDataSubpageTitle(),
            l10n_util::GetStringUTF16(IDS_PAGE_INFO_PRIVACY_SITE_DATA_HEADER));
}

INSTANTIATE_TEST_SUITE_P(All,
                         PageInfoBubbleViewPrivacyAndSiteDataSubpageTitleTest,
                         testing::Values(CookieControlsState::kActiveTp,
                                         CookieControlsState::kPausedTp));