File: keyword_editor_controller_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (959 lines) | stat: -rw-r--r-- 34,582 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
// Copyright 2012 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/search_engines/keyword_editor_controller.h"

#include <array>
#include <memory>
#include <string>

#include "base/compiler_specific.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url_service_factory_test_util.h"
#include "chrome/browser/search_engines/template_url_service_test_util.h"
#include "chrome/browser/ui/search_engines/template_url_table_model.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/test/base/testing_profile.h"
#include "components/omnibox/common/omnibox_features.h"
#include "components/search_engines/choice_made_location.h"
#include "components/search_engines/enterprise/enterprise_search_manager.h"
#include "components/search_engines/template_url.h"
#include "components/search_engines/template_url_data.h"
#include "components/search_engines/template_url_service.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/table_model_observer.h"

using base::ASCIIToUTF16;

static const std::u16string kA(u"a");
static const std::u16string kA1(u"a1");
static const std::u16string kB(u"b");
static const std::u16string kB1(u"b1");
static const std::u16string kManaged(u"managed");

// Base class for keyword editor tests. Creates a profile containing an
// empty TemplateURLService.
class KeywordEditorControllerTest : public testing::Test,
                                    public ui::TableModelObserver {
 public:
  KeywordEditorControllerTest()
      : util_(&profile_),
        simulate_load_failure_(false),
        model_changed_count_(0) {}

  explicit KeywordEditorControllerTest(bool simulate_load_failure)
      : util_(&profile_),
        simulate_load_failure_(simulate_load_failure),
        model_changed_count_(0) {}

  void SetUp() override {
    if (simulate_load_failure_) {
      util_.model()->OnWebDataServiceRequestDone(0, nullptr);
    } else {
      util_.VerifyLoad();
    }

    controller_ = std::make_unique<KeywordEditorController>(&profile_);
    controller_->table_model()->SetObserver(this);
  }

  void TearDown() override { controller_.reset(); }

  void OnModelChanged() override { model_changed_count_++; }

  void OnItemsChanged(size_t start, size_t length) override {}

  void OnItemsAdded(size_t start, size_t length) override {}

  void OnItemsRemoved(size_t start, size_t length) override {}

  void VerifyChanged() {
    ASSERT_EQ(1, model_changed_count_);
    ClearChangeCount();
  }

  void ClearChangeCount() { model_changed_count_ = 0; }

  void SimulateDefaultSearchIsManaged(const std::string& url,
                                      bool is_mandatory) {
    TemplateURLData managed_engine;
    managed_engine.SetShortName(kManaged);
    managed_engine.SetKeyword(kManaged);
    managed_engine.SetURL(url);
    managed_engine.policy_origin =
        TemplateURLData::PolicyOrigin::kDefaultSearchProvider;
    managed_engine.enforced_by_policy = is_mandatory;
    is_mandatory
        ? SetManagedDefaultSearchPreferences(managed_engine, true, &profile_)
        : SetRecommendedDefaultSearchPreferences(managed_engine, true,
                                                 &profile_);
  }

  TemplateURLTableModel* table_model() { return controller_->table_model(); }
  KeywordEditorController* controller() { return controller_.get(); }
  const TemplateURLServiceFactoryTestUtil* util() const { return &util_; }
  const TestingProfile& profile() const { return profile_; }

 private:
  content::BrowserTaskEnvironment task_environment_;
  TestingProfile profile_;
  std::unique_ptr<KeywordEditorController> controller_;
  TemplateURLServiceFactoryTestUtil util_;
  bool simulate_load_failure_;

  int model_changed_count_;
};

class KeywordEditorControllerNoWebDataTest
    : public KeywordEditorControllerTest {
 public:
  KeywordEditorControllerNoWebDataTest() : KeywordEditorControllerTest(true) {}
};

class KeywordEditorControllerManagedDSPTest
    : public KeywordEditorControllerTest {
 public:
  KeywordEditorControllerManagedDSPTest()
      : KeywordEditorControllerTest(false) {}
  ~KeywordEditorControllerManagedDSPTest() override = default;
};

// Tests adding a TemplateURL.
TEST_F(KeywordEditorControllerTest, Add) {
  size_t original_row_count = table_model()->RowCount();
  controller()->AddTemplateURL(kA, kB, "http://c");

  // Verify the observer was notified.
  VerifyChanged();
  if (HasFatalFailure()) {
    return;
  }

  // Verify the TableModel has the new data.
  ASSERT_EQ(original_row_count + 1, table_model()->RowCount());

  // Verify the TemplateURLService has the new data.
  const TemplateURL* turl = util()->model()->GetTemplateURLForKeyword(kB);
  ASSERT_TRUE(turl);
  EXPECT_EQ(u"a", turl->short_name());
  EXPECT_EQ(u"b", turl->keyword());
  EXPECT_EQ("http://c", turl->url());
}

// Tests modifying a TemplateURL.
TEST_F(KeywordEditorControllerTest, Modify) {
  controller()->AddTemplateURL(kA, kB, "http://c");
  ClearChangeCount();

  // Modify the entry.
  TemplateURL* turl = util()->model()->GetTemplateURLs()[0];
  controller()->ModifyTemplateURL(turl, kA1, kB1, "http://c1");

  // Make sure it was updated appropriately.
  VerifyChanged();
  EXPECT_EQ(u"a1", turl->short_name());
  EXPECT_EQ(u"b1", turl->keyword());
  EXPECT_EQ("http://c1", turl->url());

  // Verify preference was not updated.
  const base::Value::List& overridden_keywords = profile().GetPrefs()->GetList(
      EnterpriseSearchManager::kSiteSearchSettingsOverriddenKeywordsPrefName);
  EXPECT_TRUE(overridden_keywords.empty());
}

// Tests modifying a SiteSearch TemplateURL.
TEST_F(KeywordEditorControllerTest, Modify_SiteSearchPolicyEngine) {
  // Create an entry from Site Search policy.
  TemplateURLData data;
  data.SetShortName(kA);
  data.SetKeyword(kB);
  data.SetURL("http://c");
  data.policy_origin = TemplateURLData::PolicyOrigin::kSiteSearch;
  TemplateURL* turl = util()->model()->Add(std::make_unique<TemplateURL>(data));
  ClearChangeCount();

  // Modify the entry.
  controller()->ModifyTemplateURL(turl, kA1, kB1, "http://c1");

  // Make sure it was updated appropriately.
  VerifyChanged();
  EXPECT_EQ(u"a1", turl->short_name());
  EXPECT_EQ(u"b1", turl->keyword());
  EXPECT_EQ("http://c1", turl->url());

  // Verify preference was updated to include keyword.
  const base::Value::List& overridden_keywords = profile().GetPrefs()->GetList(
      EnterpriseSearchManager::kSiteSearchSettingsOverriddenKeywordsPrefName);
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || \
    BUILDFLAG(IS_CHROMEOS)
  EXPECT_EQ(1u, overridden_keywords.size());
  EXPECT_EQ(base::UTF16ToUTF8(kB), overridden_keywords[0].GetString());
#else
  EXPECT_TRUE(overridden_keywords.empty());
#endif
}

// Tests removing a TemplateURL.
TEST_F(KeywordEditorControllerTest, Remove) {
  int index = controller()->AddTemplateURL(kA, kB, "http://c");
  auto original_size = util()->model()->GetTemplateURLs().size();
  ClearChangeCount();

  // Remove the entry.
  controller()->RemoveTemplateURL(index);

  // Make sure it was deleted appropriately.
  VerifyChanged();
  EXPECT_FALSE(util()->model()->GetTemplateURLForKeyword(kB));
  EXPECT_EQ(original_size - 1, util()->model()->GetTemplateURLs().size());

  // Verify preference was not updated.
  const base::Value::List& overridden_keywords = profile().GetPrefs()->GetList(
      EnterpriseSearchManager::kSiteSearchSettingsOverriddenKeywordsPrefName);
  EXPECT_TRUE(overridden_keywords.empty());
}

// Tests removing a SiteSearch TemplateURL.
TEST_F(KeywordEditorControllerTest, Remove_SiteSearchPolicyEngine) {
  // Create an entry from Site Search policy.
  TemplateURLData data;
  data.SetShortName(kA);
  data.SetKeyword(kB);
  data.SetURL("http://c");
  data.policy_origin = TemplateURLData::PolicyOrigin::kSiteSearch;
  TemplateURL* turl = util()->model()->Add(std::make_unique<TemplateURL>(data));
  auto original_size = util()->model()->GetTemplateURLs().size();
  ClearChangeCount();

  // Remove the entry.
  int index = table_model()->IndexOfTemplateURL(turl).value();
  controller()->RemoveTemplateURL(index);

  // Make sure it was deleted appropriately.
  VerifyChanged();
  EXPECT_FALSE(util()->model()->GetTemplateURLForKeyword(kB));
  EXPECT_EQ(original_size - 1, util()->model()->GetTemplateURLs().size());

  // Verify preference was updated to include keyword.
  const base::Value::List& overridden_keywords = profile().GetPrefs()->GetList(
      EnterpriseSearchManager::kSiteSearchSettingsOverriddenKeywordsPrefName);
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || \
    BUILDFLAG(IS_CHROMEOS)
  EXPECT_EQ(1u, overridden_keywords.size());
  EXPECT_EQ(base::UTF16ToUTF8(kB), overridden_keywords[0].GetString());
#else
  EXPECT_TRUE(overridden_keywords.empty());
#endif
}

// Tests making a TemplateURL the default search provider.
TEST_F(KeywordEditorControllerTest, MakeDefault) {
  int index = controller()->AddTemplateURL(kA, kB, "http://c{searchTerms}");
  ClearChangeCount();

  const TemplateURL* turl = util()->model()->GetTemplateURLForKeyword(kB);
  controller()->MakeDefaultTemplateURL(
      index, search_engines::ChoiceMadeLocation::kOther);
  // Making an item the default sends a handful of changes. Which are sent isn't
  // important, what is important is 'something' is sent.
  VerifyChanged();
  ASSERT_EQ(turl, util()->model()->GetDefaultSearchProvider());

  // Making it default a second time should fail.
  controller()->MakeDefaultTemplateURL(
      index, search_engines::ChoiceMadeLocation::kOther);
  EXPECT_EQ(turl, util()->model()->GetDefaultSearchProvider());
}

// Tests that a TemplateURL can't be made the default if the default search
// provider is managed via policy.
TEST_F(KeywordEditorControllerManagedDSPTest, CannotSetDefaultWhileManaged) {
  controller()->AddTemplateURL(kA, kB, "http://c{searchTerms}");
  controller()->AddTemplateURL(kA1, kB1, "http://d{searchTerms}");
  ClearChangeCount();

  const TemplateURL* turl1 = util()->model()->GetTemplateURLForKeyword(u"b");
  ASSERT_NE(turl1, nullptr);
  const TemplateURL* turl2 = util()->model()->GetTemplateURLForKeyword(u"b1");
  ASSERT_NE(turl2, nullptr);

  EXPECT_TRUE(controller()->CanMakeDefault(turl1));
  EXPECT_FALSE(controller()->IsManaged(turl1));
  EXPECT_TRUE(controller()->CanMakeDefault(turl2));
  EXPECT_FALSE(controller()->IsManaged(turl2));

  SimulateDefaultSearchIsManaged(turl2->url(), /*is_mandatory=*/true);
  EXPECT_TRUE(util()->model()->is_default_search_managed());

  EXPECT_FALSE(controller()->CanMakeDefault(turl1));
  EXPECT_FALSE(controller()->IsManaged(turl1));
  EXPECT_FALSE(controller()->CanMakeDefault(turl2));
  EXPECT_TRUE(
      controller()->IsManaged(util()->model()->GetDefaultSearchProvider()));
}

// Tests that a TemplateURL can be made the default if the default search
// provider is recommended via policy.
TEST_F(KeywordEditorControllerManagedDSPTest, SetDefaultWhileRecommended) {
  controller()->AddTemplateURL(kA, kB, "http://c{searchTerms}");
  ClearChangeCount();
  const TemplateURL* turl1 = util()->model()->GetTemplateURLForKeyword(kB);
  ASSERT_NE(turl1, nullptr);
  EXPECT_TRUE(controller()->CanMakeDefault(turl1));

  // Simulate setting a recommended default provider. This adds another template
  // URL to the model.
  SimulateDefaultSearchIsManaged(turl1->url(), /*is_mandatory=*/false);
  EXPECT_EQ(kManaged,
            util()->model()->GetDefaultSearchProvider()->short_name());
  EXPECT_FALSE(util()->model()->is_default_search_managed());
  EXPECT_TRUE(controller()->CanMakeDefault(turl1));
  EXPECT_FALSE(
      controller()->IsManaged(util()->model()->GetDefaultSearchProvider()));

  int index = controller()->AddTemplateURL(kA1, kB1, "http://d{searchTerms}");
  ClearChangeCount();
  const TemplateURL* turl2 = util()->model()->GetTemplateURLForKeyword(kB1);
  ASSERT_NE(turl2, nullptr);
  EXPECT_TRUE(controller()->CanMakeDefault(turl2));

  // Update the default search provider.
  EXPECT_NE(turl2, util()->model()->GetDefaultSearchProvider());
  controller()->MakeDefaultTemplateURL(
      index, search_engines::ChoiceMadeLocation::kOther);
  VerifyChanged();
  EXPECT_EQ(turl2, util()->model()->GetDefaultSearchProvider());

  // Ensure that the recommended search provider is not deleted.
  ASSERT_NE(util()->model()->GetTemplateURLForKeyword(kManaged), nullptr);
}

// Tests that a recomended search provider does not persist when a different
// recommended provider is applied via policy.
TEST_F(KeywordEditorControllerManagedDSPTest, UpdateRecommended) {
  // Simulate setting a recommended default provider.
  SimulateDefaultSearchIsManaged("url1", /*is_mandatory=*/false);
  EXPECT_EQ(kManaged,
            util()->model()->GetDefaultSearchProvider()->short_name());
  EXPECT_EQ("url1", util()->model()->GetDefaultSearchProvider()->url());
  EXPECT_FALSE(util()->model()->is_default_search_managed());
  EXPECT_FALSE(
      controller()->IsManaged(util()->model()->GetDefaultSearchProvider()));
  auto original_size = util()->model()->GetTemplateURLs().size();

  // Update the default search provider to a different recommended provider.
  SimulateDefaultSearchIsManaged("url2", /*is_mandatory=*/false);
  EXPECT_EQ("url2", util()->model()->GetDefaultSearchProvider()->url());
  EXPECT_FALSE(util()->model()->is_default_search_managed());
  EXPECT_FALSE(
      util()->model()->GetDefaultSearchProvider()->enforced_by_policy());
  EXPECT_FALSE(
      controller()->IsManaged(util()->model()->GetDefaultSearchProvider()));
  EXPECT_EQ(original_size, util()->model()->GetTemplateURLs().size());
}

// Tests that a recomended search provider does not persist when a managed
// provider is applied via policy.
TEST_F(KeywordEditorControllerManagedDSPTest, SetManagedWhileRecommended) {
  // Simulate setting a recommended default provider.
  SimulateDefaultSearchIsManaged("url1", /*is_mandatory=*/false);
  EXPECT_EQ(kManaged,
            util()->model()->GetDefaultSearchProvider()->short_name());
  EXPECT_EQ("url1", util()->model()->GetDefaultSearchProvider()->url());
  EXPECT_FALSE(util()->model()->is_default_search_managed());
  EXPECT_FALSE(
      controller()->IsManaged(util()->model()->GetDefaultSearchProvider()));
  auto original_size = util()->model()->GetTemplateURLs().size();

  // Update the default search provider to a managed (enforced) provider.
  SimulateDefaultSearchIsManaged("url2", /*is_mandatory=*/true);
  EXPECT_EQ("url2", util()->model()->GetDefaultSearchProvider()->url());
  EXPECT_TRUE(util()->model()->is_default_search_managed());
  EXPECT_TRUE(
      util()->model()->GetDefaultSearchProvider()->enforced_by_policy());
  EXPECT_TRUE(
      controller()->IsManaged(util()->model()->GetDefaultSearchProvider()));
  EXPECT_EQ(original_size, util()->model()->GetTemplateURLs().size());
}

// Tests that a TemplateURL can't be edited if it is the managed default search
// provider.
TEST_F(KeywordEditorControllerManagedDSPTest, EditManagedDefault) {
  controller()->AddTemplateURL(kA, kB, "http://c{searchTerms}");
  controller()->AddTemplateURL(kA1, kB1, "http://d{searchTerms}");
  ClearChangeCount();

  const TemplateURL* turl1 = util()->model()->GetTemplateURLForKeyword(u"b");
  ASSERT_NE(turl1, nullptr);
  const TemplateURL* turl2 = util()->model()->GetTemplateURLForKeyword(u"b1");
  ASSERT_NE(turl2, nullptr);

  EXPECT_TRUE(controller()->CanEdit(turl1));
  EXPECT_TRUE(controller()->CanEdit(turl2));

  // Simulate setting a managed default.  This will add another template URL to
  // the model.
  SimulateDefaultSearchIsManaged(turl2->url(), /*is_mandatory=*/true);
  EXPECT_TRUE(util()->model()->is_default_search_managed());
  EXPECT_TRUE(controller()->CanEdit(turl1));
  EXPECT_TRUE(controller()->CanEdit(turl2));
  EXPECT_FALSE(
      controller()->CanEdit(util()->model()->GetDefaultSearchProvider()));
  EXPECT_TRUE(
      controller()->IsManaged(util()->model()->GetDefaultSearchProvider()));
}

// Tests that a `TemplateURL` can be edited if it is the recommended default
// search provider.
TEST_F(KeywordEditorControllerManagedDSPTest, EditRecommendedDefault) {
  controller()->AddTemplateURL(kA, kB, "http://c{searchTerms}");
  controller()->AddTemplateURL(kA1, kB1, "http://d{searchTerms}");
  ClearChangeCount();

  const TemplateURL* turl1 = util()->model()->GetTemplateURLForKeyword(u"b");
  ASSERT_NE(turl1, nullptr);
  const TemplateURL* turl2 = util()->model()->GetTemplateURLForKeyword(u"b1");
  ASSERT_NE(turl2, nullptr);

  EXPECT_TRUE(controller()->CanEdit(turl1));
  EXPECT_TRUE(controller()->CanEdit(turl2));

  // Simulate setting a recommended default. This will add another template URL
  // to the model.
  SimulateDefaultSearchIsManaged(turl2->url(), /*is_mandatory=*/false);
  EXPECT_EQ(kManaged,
            util()->model()->GetDefaultSearchProvider()->short_name());
  EXPECT_FALSE(util()->model()->is_default_search_managed());
  EXPECT_TRUE(controller()->CanEdit(turl1));
  EXPECT_TRUE(controller()->CanEdit(turl2));
  EXPECT_TRUE(
      controller()->CanEdit(util()->model()->GetDefaultSearchProvider()));
  EXPECT_FALSE(
      controller()->IsManaged(util()->model()->GetDefaultSearchProvider()));
}

TEST_F(KeywordEditorControllerNoWebDataTest, MakeDefaultNoWebData) {
  int index = controller()->AddTemplateURL(kA, kB, "http://c{searchTerms}");
  ClearChangeCount();

  // This should not result in a crash.
  controller()->MakeDefaultTemplateURL(
      index, search_engines::ChoiceMadeLocation::kOther);
  const TemplateURL* turl = util()->model()->GetTemplateURLForKeyword(kB);
  EXPECT_EQ(turl, util()->model()->GetDefaultSearchProvider());
}

// Mutates the TemplateURLService and make sure table model is updating
// appropriately.
TEST_F(KeywordEditorControllerTest, MutateTemplateURLService) {
  size_t original_row_count = table_model()->RowCount();

  TemplateURLData data;
  data.SetShortName(u"b");
  data.SetKeyword(u"a");
  TemplateURL* turl = util()->model()->Add(std::make_unique<TemplateURL>(data));

  // Table model should have updated.
  VerifyChanged();

  // And should contain the newly added TemplateURL.
  ASSERT_EQ(original_row_count + 1, table_model()->RowCount());
  ASSERT_TRUE(table_model()->IndexOfTemplateURL(turl).has_value());
}

// Specifies examples for tests that verify ordering of search engines.
struct SearchEngineOrderingTestCase {
  const char16_t* keyword;
  const char16_t* short_name;
  bool is_active;
  bool created_by_site_search_policy = false;
  bool created_by_search_aggregator_policy = false;
  bool featured_by_policy = false;
  bool safe_for_autoreplace = false;
};

std::unique_ptr<TemplateURL> CreateTemplateUrlForSortingTest(
    SearchEngineOrderingTestCase test_case) {
  TemplateURLData data;
  data.SetKeyword(test_case.keyword);
  data.SetShortName(test_case.short_name);
  data.is_active = test_case.is_active ? TemplateURLData::ActiveStatus::kTrue
                                       : TemplateURLData::ActiveStatus::kFalse;
  data.policy_origin = test_case.created_by_search_aggregator_policy
                           ? TemplateURLData::PolicyOrigin::kSearchAggregator
                       : test_case.created_by_site_search_policy
                           ? TemplateURLData::PolicyOrigin::kSiteSearch
                           : TemplateURLData::PolicyOrigin::kNoPolicy;
  data.featured_by_policy = test_case.featured_by_policy;
  data.safe_for_autoreplace = test_case.safe_for_autoreplace;
  return std::make_unique<TemplateURL>(data);
}

TEST_F(KeywordEditorControllerTest, EnginesSortedByName) {
  const SearchEngineOrderingTestCase kTestCases[] = {
      {
          .keyword = u"kw1",
          .short_name = u"Active 3",
          .is_active = true,
      },
      {
          .keyword = u"kw2",
          .short_name = u"Active 1",
          .is_active = true,
      },
      {
          .keyword = u"kw3",
          .short_name = u"inactive 1",
          .is_active = false,
      },
      {
          .keyword = u"kw4",
          .short_name = u"active 2",
          .is_active = true,
      },
      {
          .keyword = u"kw5",
          .short_name = u"Inactive 2",
          .is_active = false,
      },
  };

  const auto kExpectedShortNamesOrder = std::to_array<std::u16string>({
      u"Active 1",
      u"active 2",
      u"Active 3",
      u"inactive 1",
      u"Inactive 2",
  });

  std::vector<TemplateURL*> engines;
  for (SearchEngineOrderingTestCase test_case : kTestCases) {
    engines.push_back(
        util()->model()->Add(CreateTemplateUrlForSortingTest(test_case)));
    // Table model should have updated.
    VerifyChanged();
  }

  ASSERT_EQ(table_model()->last_active_engine_index(),
            table_model()->last_search_engine_index() + 3);
  ASSERT_EQ(table_model()->last_other_engine_index(),
            table_model()->last_active_engine_index() + 2);

  for (size_t i = 0; i < std::size(kExpectedShortNamesOrder); ++i) {
    const TemplateURL* template_url = table_model()->GetTemplateURL(
        table_model()->last_search_engine_index() + i);
    ASSERT_TRUE(template_url);
    EXPECT_EQ(template_url->short_name(), kExpectedShortNamesOrder[i]);
  }
}

TEST_F(KeywordEditorControllerTest, EnginesSortedByNameWithManagedSiteSearch) {
  const SearchEngineOrderingTestCase kTestCases[] = {
      {
          .keyword = u"kw1",
          .short_name = u"Non-managed 3",
          .is_active = true,
      },
      {
          .keyword = u"kw2",
          .short_name = u"Non-managed 1",
          .is_active = true,
      },
      {
          .keyword = u"kw3",
          .short_name = u"policy 1",
          .is_active = true,
          .created_by_site_search_policy = true,
      },
      {
          .keyword = u"kw4",
          .short_name = u"non-managed 2",
          .is_active = true,
      },
      {
          .keyword = u"kw5",
          .short_name = u"Policy 2",
          .is_active = true,
          .created_by_site_search_policy = true,
      },
  };

  const auto kExpectedShortNamesOrder = std::to_array<std::u16string>({
      u"policy 1",
      u"Policy 2",
      u"Non-managed 1",
      u"non-managed 2",
      u"Non-managed 3",
  });

  std::vector<TemplateURL*> engines;
  for (SearchEngineOrderingTestCase test_case : kTestCases) {
    engines.push_back(
        util()->model()->Add(CreateTemplateUrlForSortingTest(test_case)));
    // Table model should have updated.
    VerifyChanged();
  }

  ASSERT_EQ(table_model()->last_active_engine_index(),
            table_model()->last_search_engine_index() +
                std::size(kExpectedShortNamesOrder));
  ASSERT_EQ(table_model()->last_other_engine_index(),
            table_model()->last_active_engine_index());

  for (size_t i = 0; i < std::size(kExpectedShortNamesOrder); ++i) {
    const TemplateURL* template_url = table_model()->GetTemplateURL(
        table_model()->last_search_engine_index() + i);
    ASSERT_TRUE(template_url);
    EXPECT_EQ(template_url->short_name(), kExpectedShortNamesOrder[i]);
  }
}

void CheckKeywordsToDisplay(
    const std::vector<std::u16string>& kExpectedShortNamesOrder,
    const std::vector<std::u16string>& kExpectedKeywordsToDisplay,
    size_t numExpectedKeywords,
    TemplateURLTableModel* table_model) {
  ASSERT_TRUE(table_model);
  ASSERT_EQ(table_model->last_active_engine_index(),
            table_model->last_search_engine_index() + numExpectedKeywords);
  ASSERT_EQ(table_model->last_other_engine_index(),
            table_model->last_active_engine_index());

  for (size_t i = 0; i < numExpectedKeywords; ++i) {
    size_t row = table_model->last_search_engine_index() + i;
    const TemplateURL* template_url = table_model->GetTemplateURL(row);
    ASSERT_TRUE(template_url);
    EXPECT_EQ(template_url->short_name(), kExpectedShortNamesOrder[i]);
    EXPECT_EQ(
        table_model->GetText(row, IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN),
        kExpectedKeywordsToDisplay[i]);
  }
}

TEST_F(KeywordEditorControllerTest, FeaturedEnterpriseSiteSearch) {
  const SearchEngineOrderingTestCase kTestCases[] = {
      {
          .keyword = u"@kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = true,
      },
      {
          .keyword = u"kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = false,
      },
      {
          .keyword = u"@kw2",
          .short_name = u"Featured 2",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = true,
      },
      {
          .keyword = u"kw2",
          .short_name = u"User-defined engine",
          .is_active = true,
          .created_by_site_search_policy = false,
      },
      {
          .keyword = u"kw3",
          .short_name = u"Non-featured",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = false,
      },
  };

  std::vector<TemplateURL*> engines;
  for (SearchEngineOrderingTestCase test_case : kTestCases) {
    engines.push_back(
        util()->model()->Add(CreateTemplateUrlForSortingTest(test_case)));
    // Table model should have updated.
    VerifyChanged();
  }

  const auto kExpectedShortNamesOrder = std::vector<std::u16string>({
      u"Featured 1",
      u"Featured 1",
      u"Featured 2",
      u"Non-featured",
      u"User-defined engine",
  });
  const auto kExpectedKeywordsToDisplay = std::vector<std::u16string>({
      u"@kw1",
      u"kw1",
      u"@kw2",
      u"kw3",
      u"kw2",
  });

  size_t numExpectedKeywords = kExpectedShortNamesOrder.size();
  CheckKeywordsToDisplay(kExpectedShortNamesOrder, kExpectedKeywordsToDisplay,
                         numExpectedKeywords, table_model());
}

TEST_F(KeywordEditorControllerTest,
       EnterpriseSiteSearchConflictWithExistingEngines) {
  const SearchEngineOrderingTestCase kTestCases[] = {
      {
          .keyword = u"kw1",
          .short_name = u"User-defined engine",
          .is_active = true,
          .created_by_site_search_policy = false,
          .safe_for_autoreplace = false,
      },
      {
          .keyword = u"@kw1",
          .short_name = u"User-defined engine with @",
          .is_active = true,
          .created_by_site_search_policy = false,
          .safe_for_autoreplace = false,
      },
      {
          .keyword = u"kw2",
          .short_name = u"Auto-created engine",
          .is_active = true,
          .created_by_site_search_policy = false,
          .featured_by_policy = false,
          .safe_for_autoreplace = true,
      },
      {
          .keyword = u"@kw2",
          .short_name = u"Auto-created engine with @",
          .is_active = true,
          .created_by_site_search_policy = false,
          .featured_by_policy = false,
          .safe_for_autoreplace = true,
      },
      {
          .keyword = u"@kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = true,
      },
      {
          .keyword = u"kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = false,
      },
      {
          .keyword = u"@kw2",
          .short_name = u"Featured 2",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = true,
      },
      {
          .keyword = u"kw2",
          .short_name = u"Featured 2",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = false,
      },
  };

  std::vector<TemplateURL*> engines;
  for (SearchEngineOrderingTestCase test_case : kTestCases) {
    engines.push_back(
        util()->model()->Add(CreateTemplateUrlForSortingTest(test_case)));
    // Table model should have updated.
    VerifyChanged();
  }

  const auto kExpectedShortNamesOrder = std::vector<std::u16string>({
      u"Featured 1",
      u"Featured 2",
      u"Featured 2",
      u"User-defined engine",
  });
  const auto kExpectedKeywordsToDisplay = std::vector<std::u16string>({
      u"@kw1",
      u"@kw2",
      u"kw2",
      u"kw1",
  });

  size_t numExpectedKeywords = std::size(kExpectedShortNamesOrder);
  CheckKeywordsToDisplay(kExpectedShortNamesOrder, kExpectedKeywordsToDisplay,
                         numExpectedKeywords, table_model());
}

TEST_F(KeywordEditorControllerTest, EnterpriseSearchAggregator) {
  const SearchEngineOrderingTestCase kTestCases[] = {
      {
          .keyword = u"@kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_search_aggregator_policy = true,
          .featured_by_policy = true,
      },
      {
          .keyword = u"kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_search_aggregator_policy = true,
          .featured_by_policy = false,
      },
      {
          .keyword = u"kw2",
          .short_name = u"Non-featured",
          .is_active = true,
          .created_by_site_search_policy = false,
          .featured_by_policy = false,
      },
  };

  std::vector<TemplateURL*> engines;
  for (SearchEngineOrderingTestCase test_case : kTestCases) {
    engines.push_back(
        util()->model()->Add(CreateTemplateUrlForSortingTest(test_case)));
    // Table model should have updated.
    VerifyChanged();
  }

  const auto kExpectedShortNamesOrder = std::vector<std::u16string>(
      {u"Featured 1", u"Featured 1", u"Non-featured"});
  const auto kExpectedKeywordsToDisplay =
      std::vector<std::u16string>({u"@kw1", u"kw1", u"kw2"});

  size_t numExpectedKeywords = kExpectedShortNamesOrder.size();
  CheckKeywordsToDisplay(kExpectedShortNamesOrder, kExpectedKeywordsToDisplay,
                         numExpectedKeywords, table_model());
}

TEST_F(KeywordEditorControllerTest,
       EnterpriseSearchAggregatorConflictWithExistingNonPolicyEngines) {
  const SearchEngineOrderingTestCase kTestCases[] = {
      {
          .keyword = u"kw1",
          .short_name = u"User-defined engine",
          .is_active = true,
          .created_by_search_aggregator_policy = false,
          .safe_for_autoreplace = false,
      },
      {
          .keyword = u"@kw1",
          .short_name = u"User-defined engine with @",
          .is_active = true,
          .created_by_search_aggregator_policy = false,
          .safe_for_autoreplace = false,
      },
      {
          .keyword = u"kw2",
          .short_name = u"Auto-created engine",
          .is_active = true,
          .created_by_search_aggregator_policy = false,
          .featured_by_policy = false,
          .safe_for_autoreplace = true,
      },
      {
          .keyword = u"@kw2",
          .short_name = u"Auto-created engine with @",
          .is_active = true,
          .created_by_search_aggregator_policy = false,
          .featured_by_policy = false,
          .safe_for_autoreplace = true,
      },
      {
          .keyword = u"@kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_search_aggregator_policy = true,
          .featured_by_policy = true,
      },
      {
          .keyword = u"kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_search_aggregator_policy = true,
          .featured_by_policy = false,
      },
  };

  std::vector<TemplateURL*> engines;
  for (SearchEngineOrderingTestCase test_case : kTestCases) {
    engines.push_back(
        util()->model()->Add(CreateTemplateUrlForSortingTest(test_case)));
    // Table model should have updated.
    VerifyChanged();
  }

  const auto kExpectedShortNamesOrder = std::vector<std::u16string>(
      {u"Featured 1", u"Auto-created engine", u"Auto-created engine with @",
       u"User-defined engine"});
  const auto kExpectedKeywordsToDisplay =
      std::vector<std::u16string>({u"@kw1", u"kw2", u"@kw2", u"kw1"});

  size_t numExpectedKeywords = kExpectedShortNamesOrder.size();
  CheckKeywordsToDisplay(kExpectedShortNamesOrder, kExpectedKeywordsToDisplay,
                         numExpectedKeywords, table_model());
}

TEST_F(KeywordEditorControllerTest, EnterpriseSiteSearchAndSearchAggregator) {
  const SearchEngineOrderingTestCase kTestCases[] = {
      {
          .keyword = u"@kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = true,
      },
      {
          .keyword = u"kw1",
          .short_name = u"Featured 1",
          .is_active = true,
          .created_by_site_search_policy = true,
          .featured_by_policy = false,
      },
      {
          .keyword = u"kw2",
          .short_name = u"Non-featured",
          .is_active = true,
          .created_by_site_search_policy = false,
          .featured_by_policy = false,
      },
      {
          .keyword = u"@kw3",
          .short_name = u"Featured 3",
          .is_active = true,
          .created_by_search_aggregator_policy = true,
          .featured_by_policy = true,
      },
      {
          .keyword = u"kw3",
          .short_name = u"Featured 3",
          .is_active = true,
          .created_by_search_aggregator_policy = true,
          .featured_by_policy = false,
      },
  };

  std::vector<TemplateURL*> engines;
  for (SearchEngineOrderingTestCase test_case : kTestCases) {
    engines.push_back(
        util()->model()->Add(CreateTemplateUrlForSortingTest(test_case)));
    // Table model should have updated.
    VerifyChanged();
  }

  const auto kExpectedShortNamesOrder =
      std::vector<std::u16string>({u"Featured 1", u"Featured 1", u"Featured 3",
                                   u"Featured 3", u"Non-featured"});
  const auto kExpectedKeywordsToDisplay =
      std::vector<std::u16string>({u"@kw1", u"kw1", u"@kw3", u"kw3", u"kw2"});

  size_t numExpectedKeywords = kExpectedShortNamesOrder.size();
  CheckKeywordsToDisplay(kExpectedShortNamesOrder, kExpectedKeywordsToDisplay,
                         numExpectedKeywords, table_model());
}