File: single_client_themes_sync_test.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 (1076 lines) | stat: -rw-r--r-- 42,604 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
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/test/metrics/histogram_tester.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "build/build_config.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/test/integration/committed_all_nudged_changes_checker.h"
#include "chrome/browser/sync/test/integration/fake_server_match_status_checker.h"
#include "chrome/browser/sync/test/integration/preferences_helper.h"
#include "chrome/browser/sync/test/integration/sync_service_impl_harness.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/browser/sync/test/integration/themes_helper.h"
#include "chrome/browser/sync/test/integration/updated_progress_marker_checker.h"
#include "chrome/browser/themes/theme_local_data_batch_uploader.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/themes/theme_service_utils.h"
#include "chrome/browser/themes/theme_syncable_service.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/signin_pref_names.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/sync/base/data_type.h"
#include "components/sync/base/features.h"
#include "components/sync/engine/loopback_server/persistent_unique_client_entity.h"
#include "components/sync/protocol/theme_specifics.pb.h"
#include "components/sync/test/fake_server.h"
#include "components/sync/test/test_matchers.h"
#include "content/public/test/browser_test.h"
#include "testing/gmock/include/gmock/gmock.h"

namespace {

using syncer::MatchesLocalDataDescription;
using syncer::MatchesLocalDataItemModel;
using testing::IsEmpty;
using themes_helper::GetCustomTheme;
using themes_helper::IsSystemThemeDistinctFromDefaultTheme;
using themes_helper::UseCustomTheme;
using themes_helper::UseDefaultTheme;
using themes_helper::UseSystemTheme;
using themes_helper::UsingCustomTheme;
using themes_helper::UsingDefaultTheme;
using themes_helper::UsingGrayscaleTheme;
using themes_helper::UsingSystemTheme;

// Note: All of these matchers take a sync_pb::ThemeSpecifics.

MATCHER(HasDefaultTheme, "") {
  return !arg.use_custom_theme() && !arg.use_system_theme_by_default() &&
         !arg.has_custom_theme_id();
}

MATCHER(HasSystemTheme, "") {
  return !arg.use_custom_theme() && arg.use_system_theme_by_default() &&
         !arg.has_custom_theme_id();
}

MATCHER_P(HasCustomThemeWithId, theme_id, "") {
  return arg.use_custom_theme() && arg.custom_theme_id() == theme_id;
}

MATCHER_P(HasBrowserColorScheme, color_scheme, "") {
  return arg.browser_color_scheme() == color_scheme;
}

MATCHER_P(HasAutogeneratedThemeColor, color, "") {
  return arg.has_autogenerated_color_theme() &&
         arg.autogenerated_color_theme().color() == color;
}

MATCHER_P(HasUserColor, color, "") {
  return arg.has_user_color_theme() && arg.user_color_theme().color() == color;
}

MATCHER(HasGrayscaleTheme, "") {
  return arg.has_grayscale_theme_enabled();
}

std::unique_ptr<syncer::LoopbackServerEntity> CreateDefaultThemeEntity() {
  sync_pb::EntitySpecifics specifics;
  // Clients always write `browser_color_scheme` field.
  specifics.mutable_theme()->set_browser_color_scheme(
      sync_pb::ThemeSpecifics_BrowserColorScheme_SYSTEM);
  return syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
      ThemeSyncableService::kSyncEntityClientTag,
      ThemeSyncableService::kSyncEntityClientTag, specifics,
      /*creation_time=*/0, /*last_modified_time=*/0);
}

std::unique_ptr<syncer::LoopbackServerEntity> CreateSystemThemeEntity() {
  sync_pb::EntitySpecifics specifics;
  // Clients always write `browser_color_scheme` field.
  specifics.mutable_theme()->set_browser_color_scheme(
      sync_pb::ThemeSpecifics_BrowserColorScheme_SYSTEM);
  specifics.mutable_theme()->set_use_system_theme_by_default(true);
  return syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
      ThemeSyncableService::kSyncEntityTitle,
      ThemeSyncableService::kSyncEntityClientTag, specifics,
      /*creation_time=*/0, /*last_modified_time=*/0);
}

std::unique_ptr<syncer::LoopbackServerEntity> CreateCustomThemeEntity(
    const std::string& theme_id) {
  sync_pb::EntitySpecifics specifics;
  specifics.mutable_theme()->set_use_custom_theme(true);
  specifics.mutable_theme()->set_custom_theme_id(theme_id);
  specifics.mutable_theme()->set_custom_theme_name("custom theme");
  return syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
      ThemeSyncableService::kSyncEntityTitle,
      ThemeSyncableService::kSyncEntityClientTag, specifics,
      /*creation_time=*/0, /*last_modified_time=*/0);
}

std::unique_ptr<syncer::LoopbackServerEntity> CreateGrayscaleThemeEntity() {
  sync_pb::EntitySpecifics specifics;
  specifics.mutable_theme()->set_use_custom_theme(false);
  specifics.mutable_theme()->mutable_grayscale_theme_enabled();
  return syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
      ThemeSyncableService::kSyncEntityTitle,
      ThemeSyncableService::kSyncEntityClientTag, specifics,
      /*creation_time=*/0, /*last_modified_time=*/0);
}

// A helper class that waits for the (single) THEME entity on the FakeServer to
// match a given matcher.
class ServerThemeMatchChecker
    : public fake_server::FakeServerMatchStatusChecker {
 public:
  using Matcher = testing::Matcher<sync_pb::ThemeSpecifics>;

  explicit ServerThemeMatchChecker(const Matcher& matcher);
  ~ServerThemeMatchChecker() override;
  ServerThemeMatchChecker(const ServerThemeMatchChecker&) = delete;
  ServerThemeMatchChecker& operator=(const ServerThemeMatchChecker&) = delete;

  // FakeServer::Observer overrides.
  void OnCommit(syncer::DataTypeSet committed_data_types) override;

  // StatusChangeChecker overrides.
  bool IsExitConditionSatisfied(std::ostream* os) override;

 private:
  const Matcher matcher_;
};

ServerThemeMatchChecker::ServerThemeMatchChecker(const Matcher& matcher)
    : matcher_(matcher) {}

ServerThemeMatchChecker::~ServerThemeMatchChecker() = default;

void ServerThemeMatchChecker::OnCommit(
    syncer::DataTypeSet committed_data_types) {
  if (committed_data_types.Has(syncer::THEMES)) {
    CheckExitCondition();
  }
}

bool ServerThemeMatchChecker::IsExitConditionSatisfied(std::ostream* os) {
  std::vector<sync_pb::SyncEntity> entities =
      fake_server()->GetSyncEntitiesByDataType(syncer::THEMES);

  if (entities.empty()) {
    return false;
  }
  DCHECK_EQ(entities.size(), 1u);
  DCHECK(entities[0].specifics().has_theme());

  testing::StringMatchResultListener result_listener;
  const bool matches = testing::ExplainMatchResult(
      matcher_, entities[0].specifics().theme(), &result_listener);
  *os << result_listener.str();
  return matches;
}

class SingleClientThemesSyncTest : public SyncTest {
 public:
  SingleClientThemesSyncTest() : SyncTest(SINGLE_CLIENT) {}
  ~SingleClientThemesSyncTest() override = default;

  bool TestUsesSelfNotifications() override { return false; }
};

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTest, UploadsThemesOnInstall) {
  ASSERT_TRUE(SetupSync());

  ASSERT_FALSE(UsingCustomTheme(GetProfile(0)));
  UseCustomTheme(GetProfile(0), 0);
  EXPECT_TRUE(
      ServerThemeMatchChecker(HasCustomThemeWithId(GetCustomTheme(0))).Wait());

  if (IsSystemThemeDistinctFromDefaultTheme(GetProfile(0))) {
    ASSERT_FALSE(UsingSystemTheme(GetProfile(0)));
    UseSystemTheme(GetProfile(0));
    EXPECT_TRUE(ServerThemeMatchChecker(HasSystemTheme()).Wait());
  }

  ASSERT_FALSE(UsingDefaultTheme(GetProfile(0)));
  UseDefaultTheme(GetProfile(0));
  EXPECT_TRUE(ServerThemeMatchChecker(HasDefaultTheme()).Wait());
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTest, DownloadsCustomTheme) {
  ASSERT_TRUE(SetupSync());

  GetFakeServer()->InjectEntity(CreateCustomThemeEntity(GetCustomTheme(0)));
  // Note: The custom theme won't actually get installed; just check that it's
  // pending for installation.
  EXPECT_TRUE(
      ThemePendingInstallChecker(GetProfile(0), GetCustomTheme(0)).Wait());
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTest, DownloadsSystemTheme) {
  // Skip if this platform doesn't distinguish between system and default theme.
  ASSERT_TRUE(SetupClients());
  if (!IsSystemThemeDistinctFromDefaultTheme(GetProfile(0))) {
    return;
  }

  ASSERT_TRUE(SetupSync());

  // Set up a custom theme first, so we can then switch back to system.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(
      ServerThemeMatchChecker(HasCustomThemeWithId(GetCustomTheme(0))).Wait());
  ASSERT_TRUE(UsingCustomTheme(GetProfile(0)));

  ASSERT_FALSE(UsingSystemTheme(GetProfile(0)));
  GetFakeServer()->InjectEntity(CreateSystemThemeEntity());
  EXPECT_TRUE(SystemThemeChecker(GetProfile(0)).Wait());
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTest, DownloadsDefaultTheme) {
  ASSERT_TRUE(SetupSync());

  // Set up a custom theme first, so we can then switch back to default.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(
      ServerThemeMatchChecker(HasCustomThemeWithId(GetCustomTheme(0))).Wait());
  ASSERT_TRUE(UsingCustomTheme(GetProfile(0)));

  ASSERT_FALSE(UsingDefaultTheme(GetProfile(0)));
  GetFakeServer()->InjectEntity(CreateDefaultThemeEntity());
  EXPECT_TRUE(DefaultThemeChecker(GetProfile(0)).Wait());
}

// Verifies that theme from syncing theme prefs get applied if the migration is
// unset. After this, the migration flag should get set to disallow future reads
// from the syncing theme prefs. The incoming theme is committed to the server
// with the new fields in the ThemeSpecifics.
IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTest,
                       ShouldApplyThemeFromSyncingPrefsIfFlagUnmarked) {
  ASSERT_TRUE(SetupClients());
  // Migration flag is unset.
  ASSERT_TRUE(preferences_helper::GetPrefs(/*index=*/0)
                  ->GetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs));

  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::PreferenceSpecifics* preference_specifics =
        specifics.mutable_preference();
    preference_specifics->set_name(
        prefs::kDeprecatedBrowserColorSchemeDoNotUse);
    preference_specifics->set_value(
        preferences_helper::ConvertPrefValueToValueInSpecifics(base::Value(
            static_cast<int>(ThemeService::BrowserColorScheme::kLight))));

    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            /*non_unique_name=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            /*client_tag=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }
  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::PreferenceSpecifics* preference_specifics =
        specifics.mutable_preference();
    preference_specifics->set_name(prefs::kDeprecatedUserColorDoNotUse);
    preference_specifics->set_value(
        preferences_helper::ConvertPrefValueToValueInSpecifics(
            base::Value(static_cast<int>(SK_ColorRED))));

    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            /*non_unique_name=*/prefs::kDeprecatedUserColorDoNotUse,
            /*client_tag=*/prefs::kDeprecatedUserColorDoNotUse, specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }

  ASSERT_TRUE(SetupSync());
  // Themes was applied from the syncing theme prefs.
  EXPECT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))
                ->GetBrowserColorScheme(),
            ThemeService::BrowserColorScheme::kLight);
  EXPECT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))->GetUserColor(),
            SK_ColorRED);
  // Migration flag is set.
  EXPECT_FALSE(preferences_helper::GetPrefs(/*index=*/0)
                   ->GetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs));

  // The theme should get committed to the server with the new fields in
  // ThemeSpecifics.
  EXPECT_TRUE(ServerThemeMatchChecker(HasUserColor(SK_ColorRED)).Wait());
  EXPECT_TRUE(ServerThemeMatchChecker(
                  HasBrowserColorScheme(
                      sync_pb::ThemeSpecifics_BrowserColorScheme_LIGHT))
                  .Wait());
}

// Simulate pref migration being run in the previous browser session by setting
// the migration flag.
IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTest,
                       PRE_ShouldNotApplyThemeFromSyncingPrefsIfFlagMarked) {
  ASSERT_TRUE(SetupClients());

  // Set the flag to not read incoming prefs.
  preferences_helper::GetPrefs(/*index=*/0)
      ->SetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs, false);

  // Wait for data to be committed to disk.
  base::RunLoop loop;
  preferences_helper::GetPrefs(/*index=*/0)
      ->CommitPendingWrite(loop.QuitClosure());
  loop.Run();
}

// Verifies that the syncing theme prefs are not read if the migration is set.
IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTest,
                       ShouldNotApplyThemeFromSyncingPrefsIfFlagMarked) {
  ASSERT_TRUE(SetupClients());

  // Migration flag is already set.
  ASSERT_FALSE(preferences_helper::GetPrefs(/*index=*/0)
                   ->GetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs));

  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::PreferenceSpecifics* preference_specifics =
        specifics.mutable_preference();
    preference_specifics->set_name(
        prefs::kDeprecatedBrowserColorSchemeDoNotUse);
    preference_specifics->set_value(
        preferences_helper::ConvertPrefValueToValueInSpecifics(base::Value(
            static_cast<int>(ThemeService::BrowserColorScheme::kDark))));

    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            /*non_unique_name=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            /*client_tag=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }
  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::PreferenceSpecifics* preference_specifics =
        specifics.mutable_preference();
    preference_specifics->set_name(prefs::kDeprecatedUserColorDoNotUse);
    preference_specifics->set_value(
        preferences_helper::ConvertPrefValueToValueInSpecifics(
            base::Value(static_cast<int>(SK_ColorBLUE))));

    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            /*non_unique_name=*/prefs::kDeprecatedUserColorDoNotUse,
            /*client_tag=*/prefs::kDeprecatedUserColorDoNotUse, specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }

  ASSERT_TRUE(SetupSync());

  // Themes was not applied from the syncing theme prefs.
  EXPECT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))
                ->GetBrowserColorScheme(),
            ThemeService::BrowserColorScheme::kSystem);
  EXPECT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))->GetUserColor(),
            std::nullopt);
}

// Verifies that syncing theme prefs are not read with the incremental updates.
// They can only be applied when the prefs sync starts (which will set the
// migration flag to disallow future reads).
IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTest,
                       ShouldNotApplyThemeFromSyncingPrefsAfterSyncHasStarted) {
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(preferences_helper::GetPrefs(/*index=*/0)
                  ->GetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs));

  ASSERT_TRUE(SetupSync());

  // The migration flag gets set upon sync start.
  EXPECT_FALSE(preferences_helper::GetPrefs(/*index=*/0)
                   ->GetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs));

  ASSERT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))
                ->GetBrowserColorScheme(),
            ThemeService::BrowserColorScheme::kSystem);

  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::PreferenceSpecifics* preference_specifics =
        specifics.mutable_preference();
    preference_specifics->set_name(
        prefs::kDeprecatedBrowserColorSchemeDoNotUse);
    preference_specifics->set_value(
        preferences_helper::ConvertPrefValueToValueInSpecifics(base::Value(
            static_cast<int>(ThemeService::BrowserColorScheme::kLight))));

    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            /*non_unique_name=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            /*client_tag=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }

  ASSERT_TRUE(PrefValueChecker(preferences_helper::GetPrefs(/*index=*/0),
                               prefs::kDeprecatedBrowserColorSchemeDoNotUse,
                               base::Value(static_cast<int>(
                                   ThemeService::BrowserColorScheme::kLight)))
                  .Wait());

  // The incoming theme pref is not applied.
  EXPECT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))
                ->GetBrowserColorScheme(),
            ThemeService::BrowserColorScheme::kSystem);
}

// Verifies that the syncing theme prefs are not applied if the incoming
// ThemeSpecifics has the new fields, which implies another client has already
// updated the ThemeSpecifics using the prefs.
IN_PROC_BROWSER_TEST_F(
    SingleClientThemesSyncTest,
    ShouldNotApplyThemeFromSyncingPrefsIfReceivedViaSpecifics) {
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(preferences_helper::GetPrefs(/*index=*/0)
                  ->GetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs));
  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::PreferenceSpecifics* preference_specifics =
        specifics.mutable_preference();
    preference_specifics->set_name(
        prefs::kDeprecatedBrowserColorSchemeDoNotUse);
    preference_specifics->set_value(
        preferences_helper::ConvertPrefValueToValueInSpecifics(base::Value(
            static_cast<int>(ThemeService::BrowserColorScheme::kLight))));
    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            /*non_unique_name=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            /*client_tag=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }
  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::PreferenceSpecifics* preference_specifics =
        specifics.mutable_preference();
    preference_specifics->set_name(prefs::kDeprecatedUserColorDoNotUse);
    preference_specifics->set_value(
        preferences_helper::ConvertPrefValueToValueInSpecifics(
            base::Value(static_cast<int>(SK_ColorBLUE))));

    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            /*non_unique_name=*/prefs::kDeprecatedUserColorDoNotUse,
            /*client_tag=*/prefs::kDeprecatedUserColorDoNotUse, specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }
  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::ThemeSpecifics* theme_specifics = specifics.mutable_theme();
    theme_specifics->set_browser_color_scheme(
        sync_pb::ThemeSpecifics_BrowserColorScheme_DARK);

    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            ThemeSyncableService::kSyncEntityTitle,
            ThemeSyncableService::kSyncEntityClientTag, specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }

  ASSERT_TRUE(SetupSync());

  EXPECT_FALSE(preferences_helper::GetPrefs(/*index=*/0)
                   ->GetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs));
  // Theme from prefs is not applied.
  EXPECT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))
                ->GetBrowserColorScheme(),
            ThemeService::BrowserColorScheme::kDark);
  EXPECT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))->GetUserColor(),
            std::nullopt);
}

// Verifies that the syncing theme prefs are applied if the incoming
// ThemeSpecifics does not have the new fields.
IN_PROC_BROWSER_TEST_F(
    SingleClientThemesSyncTest,
    ShouldApplyThemeFromSyncingPrefsIfNotReceivedViaSpecifics) {
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(preferences_helper::GetPrefs(/*index=*/0)
                  ->GetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs));
  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::PreferenceSpecifics* preference_specifics =
        specifics.mutable_preference();
    preference_specifics->set_name(
        prefs::kDeprecatedBrowserColorSchemeDoNotUse);
    preference_specifics->set_value(
        preferences_helper::ConvertPrefValueToValueInSpecifics(base::Value(
            static_cast<int>(ThemeService::BrowserColorScheme::kLight))));
    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            /*non_unique_name=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            /*client_tag=*/prefs::kDeprecatedBrowserColorSchemeDoNotUse,
            specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }
  {
    sync_pb::EntitySpecifics specifics;
    sync_pb::ThemeSpecifics* theme_specifics = specifics.mutable_theme();
    theme_specifics->mutable_autogenerated_color_theme()->set_color(
        SK_ColorRED);

    GetFakeServer()->InjectEntity(
        syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
            ThemeSyncableService::kSyncEntityTitle,
            ThemeSyncableService::kSyncEntityClientTag, specifics,
            /*creation_time=*/0, /*last_modified_time=*/0));
  }

  ASSERT_TRUE(SetupSync());

  EXPECT_FALSE(preferences_helper::GetPrefs(/*index=*/0)
                   ->GetBoolean(prefs::kShouldReadIncomingSyncingThemePrefs));

  // Theme from prefs is applied.
  EXPECT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))
                ->GetBrowserColorScheme(),
            ThemeService::BrowserColorScheme::kLight);
  EXPECT_EQ(ThemeServiceFactory::GetForProfile(GetProfile(0))
                ->GetAutogeneratedThemeColor(),
            SK_ColorRED);
  // The theme is also committed to the server using the new fields in
  // ThemeSpecifics.
  EXPECT_TRUE(ServerThemeMatchChecker(
                  HasBrowserColorScheme(
                      sync_pb::ThemeSpecifics_BrowserColorScheme_LIGHT))
                  .Wait());
}

class SingleClientThemesSyncTestWithoutAccountThemesSeparation
    : public SingleClientThemesSyncTest {
 public:
  SingleClientThemesSyncTestWithoutAccountThemesSeparation() {
    feature_list_.InitAndDisableFeature(syncer::kSeparateLocalAndAccountThemes);
  }

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

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithoutAccountThemesSeparation,
                       UploadsPreexistingTheme) {
  ASSERT_TRUE(SetupClients());

  UseCustomTheme(GetProfile(0), 0);

  ASSERT_TRUE(SetupSync());

  EXPECT_TRUE(
      ServerThemeMatchChecker(HasCustomThemeWithId(GetCustomTheme(0))).Wait());
}

class SingleClientThemesSyncTestWithAccountThemesSeparation
    : public SingleClientThemesSyncTest {
 public:
  SingleClientThemesSyncTestWithAccountThemesSeparation()
      : feature_list_(syncer::kSeparateLocalAndAccountThemes) {}

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

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       ShouldNotUploadPreexistingTheme) {
  ASSERT_TRUE(SetupClients());

  // Use custom theme locally.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  // Default theme on the server.
  ASSERT_FALSE(UsingDefaultTheme(GetProfile(0)));
  GetFakeServer()->InjectEntity(CreateDefaultThemeEntity());

  // Enable sync.
  ASSERT_TRUE(SetupSync());
  ASSERT_TRUE(GetSyncService(0)->GetActiveDataTypes().Has(syncer::THEMES));

  // Local custom theme is not uploaded to the account.
  EXPECT_TRUE(ServerThemeMatchChecker(HasDefaultTheme()).Wait());
  EXPECT_TRUE(UsingCustomTheme(GetProfile(0)));
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       ShouldRestoreLocalThemeUponSyncStop) {
  ASSERT_TRUE(SetupClients());

  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  GetFakeServer()->InjectEntity(CreateGrayscaleThemeEntity());

  ASSERT_TRUE(SetupSync());
  EXPECT_TRUE(GrayscaleThemeChecker(GetProfile(0)).Wait());

  // Disable sync.
  ASSERT_TRUE(
      GetClient(0)->DisableSyncForType(syncer::UserSelectableType::kThemes));

  // Original local theme should get re-applied.
  EXPECT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());
  EXPECT_FALSE(UsingGrayscaleTheme(GetProfile(0)));
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       PRE_ShouldPersistSavedLocalThemeOverBrowserRestart) {
  ASSERT_TRUE(SetupClients());

  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  GetFakeServer()->InjectEntity(CreateGrayscaleThemeEntity());

  ASSERT_TRUE(SetupSync());
  EXPECT_TRUE(GrayscaleThemeChecker(GetProfile(0)).Wait());
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       ShouldPersistSavedLocalThemeOverBrowserRestart) {
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(GetClient(0)->AwaitSyncSetupCompletion());
  ASSERT_TRUE(GetSyncService(0)->GetActiveDataTypes().Has(syncer::THEMES));

  // Disable sync.
  ASSERT_TRUE(
      GetClient(0)->DisableSyncForType(syncer::UserSelectableType::kThemes));

  // Original local theme should get re-applied.
  EXPECT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());
  EXPECT_FALSE(UsingGrayscaleTheme(GetProfile(0)));
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       ShouldNotApplyLocalUpdateOnLocalThemeWhenSignedIn) {
  ASSERT_TRUE(SetupSync());

  // Change to a custom theme.
  UseCustomTheme(GetProfile(0), 0);
  // Custom theme is uploaded to account.
  EXPECT_TRUE(
      ServerThemeMatchChecker(HasCustomThemeWithId(GetCustomTheme(0))).Wait());

  // Disable syncing of themes.
  ASSERT_TRUE(
      GetClient(0)->DisableSyncForType(syncer::UserSelectableType::kThemes));

  // Original local theme is restored.
  EXPECT_TRUE(DefaultThemeChecker(GetProfile(0)).Wait());
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       ShouldNotApplyRemoteUpdateOnLocalTheme) {
  ASSERT_TRUE(SetupClients());

  // Set up a custom theme first, so we can then switch back to default.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  ASSERT_TRUE(SetupSync());

  // Remote update.
  GetFakeServer()->InjectEntity(CreateDefaultThemeEntity());
  EXPECT_TRUE(DefaultThemeChecker(GetProfile(0)).Wait());

  // Disable sync.
  ASSERT_TRUE(
      GetClient(0)->DisableSyncForType(syncer::UserSelectableType::kThemes));

  // Original local theme should get re-applied.
  EXPECT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());
  EXPECT_FALSE(UsingGrayscaleTheme(GetProfile(0)));
}

// Signing out is not supported on ChromeOS, thus excluded from this test suite.
#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       ShouldReturnLocalDataDescriptions) {
  ASSERT_TRUE(SetupClients());

  // Use a custom theme locally on client 0.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  // Sign in and activate sync transport.
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  ASSERT_TRUE(GetSyncService(0)->GetActiveDataTypes().Has(syncer::THEMES));

  EXPECT_THAT(GetClient(0)->GetLocalDataDescriptionAndWait(syncer::THEMES),
              MatchesLocalDataDescription(
                  syncer::THEMES,
                  ElementsAre(MatchesLocalDataItemModel(
                      ThemeLocalDataBatchUploader::kThemesLocalDataItemModelId,
                      syncer::LocalDataItemModel::NoIcon(), "faketheme0",
                      /*subtitle=*/IsEmpty())),
                  // TODO(crbug.com/373568992): Merge Desktop and Mobile data
                  // under common struct.
                  /*item_count=*/0u,
                  /*domains=*/IsEmpty(),
                  /*domain_count=*/0u));
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       ShouldBatchUploadAllEntries) {
  ASSERT_TRUE(SetupClients());

  // Use custom theme locally.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  // Grayscale theme on the server.
  GetFakeServer()->InjectEntity(CreateGrayscaleThemeEntity());

  // Sign in and activate sync transport.
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  ASSERT_TRUE(GetSyncService(0)->GetActiveDataTypes().Has(syncer::THEMES));

  ASSERT_TRUE(GrayscaleThemeChecker(GetProfile(0)).Wait());
  // Local custom theme is not uploaded to the account.
  ASSERT_TRUE(ServerThemeMatchChecker(HasGrayscaleTheme()).Wait());
  ASSERT_THAT(GetClient(0)->GetLocalDataDescriptionAndWait(syncer::THEMES),
              MatchesLocalDataDescription(
                  syncer::THEMES,
                  ElementsAre(MatchesLocalDataItemModel(
                      ThemeLocalDataBatchUploader::kThemesLocalDataItemModelId,
                      syncer::LocalDataItemModel::NoIcon(), "faketheme0",
                      /*subtitle=*/IsEmpty())),
                  // TODO(crbug.com/373568992): Merge Desktop and Mobile data
                  // under common struct.
                  /*item_count=*/0u,
                  /*domains=*/IsEmpty(),
                  /*domain_count=*/0u));

  GetSyncService(0)->TriggerLocalDataMigration({syncer::THEMES});

  EXPECT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());
  // Local custom theme is now uploaded to the account.
  EXPECT_TRUE(
      ServerThemeMatchChecker(HasCustomThemeWithId(GetCustomTheme(0))).Wait());

  // Sign out.
  GetClient(0)->SignOutPrimaryAccount();
  EXPECT_TRUE(DefaultThemeChecker(GetProfile(0)).Wait());
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       ShouldBatchUploadSomeEntries) {
  ASSERT_TRUE(SetupClients());

  // Use custom theme locally.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  // Grayscale theme on the server.
  GetFakeServer()->InjectEntity(CreateGrayscaleThemeEntity());

  // Sign in and activate sync transport.
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  ASSERT_TRUE(GetSyncService(0)->GetActiveDataTypes().Has(syncer::THEMES));

  ASSERT_TRUE(GrayscaleThemeChecker(GetProfile(0)).Wait());
  // Local custom theme is not uploaded to the account.
  ASSERT_TRUE(ServerThemeMatchChecker(HasGrayscaleTheme()).Wait());
  ASSERT_THAT(GetClient(0)->GetLocalDataDescriptionAndWait(syncer::THEMES),
              MatchesLocalDataDescription(
                  syncer::THEMES,
                  ElementsAre(MatchesLocalDataItemModel(
                      ThemeLocalDataBatchUploader::kThemesLocalDataItemModelId,
                      syncer::LocalDataItemModel::NoIcon(), "faketheme0",
                      /*subtitle=*/IsEmpty())),
                  // TODO(crbug.com/373568992): Merge Desktop and Mobile data
                  // under common struct.
                  /*item_count=*/0u,
                  /*domains=*/IsEmpty(),
                  /*domain_count=*/0u));

  // Triggering batch upload without any item should be a no-op.
  GetSyncService(0)->TriggerLocalDataMigrationForItems({{syncer::THEMES, {}}});

  EXPECT_TRUE(GrayscaleThemeChecker(GetProfile(0)).Wait());
  // Local custom theme is not uploaded to the account.
  EXPECT_TRUE(ServerThemeMatchChecker(HasGrayscaleTheme()).Wait());
  EXPECT_THAT(GetClient(0)->GetLocalDataDescriptionAndWait(syncer::THEMES),
              MatchesLocalDataDescription(
                  syncer::THEMES,
                  ElementsAre(MatchesLocalDataItemModel(
                      ThemeLocalDataBatchUploader::kThemesLocalDataItemModelId,
                      syncer::LocalDataItemModel::NoIcon(), "faketheme0",
                      /*subtitle=*/IsEmpty())),
                  // TODO(crbug.com/373568992): Merge Desktop and Mobile data
                  // under common struct.
                  /*item_count=*/0u,
                  /*domains=*/IsEmpty(),
                  /*domain_count=*/0u));

  GetSyncService(0)->TriggerLocalDataMigrationForItems(
      {{syncer::DataType::THEMES,
        {ThemeLocalDataBatchUploader::kThemesLocalDataItemModelId}}});

  EXPECT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());
  // Local custom theme is now uploaded to the account.
  EXPECT_TRUE(
      ServerThemeMatchChecker(HasCustomThemeWithId(GetCustomTheme(0))).Wait());

  // Sign out.
  GetClient(0)->SignOutPrimaryAccount();
  EXPECT_TRUE(DefaultThemeChecker(GetProfile(0)).Wait());
}

class SingleClientThemesSyncTestWithAccountThemesSeparationInSigninPendingState
    : public SingleClientThemesSyncTestWithAccountThemesSeparation {
 public:
  bool HasUnsyncedThemeData() {
    return GetClient(0)
        ->GetTypesWithUnsyncedDataAndWait({syncer::THEMES})
        .contains(syncer::THEMES);
  }

 private:
  // `kEnablePreferencesAccountStorage` is used to enable themes in transport
  // mode alongside some other data types.
  base::test::ScopedFeatureList feature_list_{
      switches::kEnablePreferencesAccountStorage};
};

IN_PROC_BROWSER_TEST_F(
    SingleClientThemesSyncTestWithAccountThemesSeparationInSigninPendingState,
    ShouldMarkThemeChangeWhileSigninPendingUnsynced) {
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(UsingDefaultTheme(GetProfile(0)));

  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());

  themes_helper::UseGrayscaleTheme(GetProfile(0));
  ASSERT_TRUE(CommittedAllNudgedChangesChecker(GetSyncService(0)).Wait());
  ASSERT_TRUE(UsingGrayscaleTheme(GetProfile(0)));

  // Enter sign-in pending state.
  ASSERT_TRUE(GetClient(0)->EnterSignInPendingStateForPrimaryAccount());
  ASSERT_FALSE(HasUnsyncedThemeData());

  // Set up a custom theme.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  // Themes should be checked for unsynced data when sign-out is attempted.
  ASSERT_TRUE(
      syncer::TypesRequiringUnsyncedDataCheckOnSignout().Has(syncer::THEMES));

  // Themes has unsynced data.
  EXPECT_TRUE(HasUnsyncedThemeData());

  // Sign out.
  GetClient(0)->SignOutPrimaryAccount();
  EXPECT_TRUE(DefaultThemeChecker(GetProfile(0)).Wait());
}

IN_PROC_BROWSER_TEST_F(
    SingleClientThemesSyncTestWithAccountThemesSeparationInSigninPendingState,
    ShouldCommitUnsyncedThemeChangeUponResolve) {
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(UsingDefaultTheme(GetProfile(0)));

  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());

  themes_helper::UseGrayscaleTheme(GetProfile(0));
  ASSERT_TRUE(CommittedAllNudgedChangesChecker(GetSyncService(0)).Wait());
  ASSERT_TRUE(UsingGrayscaleTheme(GetProfile(0)));

  // Enter sign-in pending state.
  ASSERT_TRUE(GetClient(0)->EnterSignInPendingStateForPrimaryAccount());
  ASSERT_FALSE(HasUnsyncedThemeData());

  // Set up a custom theme.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  // Themes should be checked for unsynced data when sign-out is attempted.
  ASSERT_TRUE(
      syncer::TypesRequiringUnsyncedDataCheckOnSignout().Has(syncer::THEMES));

  // Themes has unsynced data.
  EXPECT_TRUE(HasUnsyncedThemeData());
  // Server still has the old theme.
  ASSERT_TRUE(ServerThemeMatchChecker(HasGrayscaleTheme()).Wait());

  // Resolve sign-in pending state.
  ASSERT_TRUE(GetClient(0)->ExitSignInPendingStateForPrimaryAccount());
  ASSERT_TRUE(UsingCustomTheme(GetProfile(0)));
  ASSERT_TRUE(
      ServerThemeMatchChecker(HasCustomThemeWithId(GetCustomTheme(0))).Wait());
}

IN_PROC_BROWSER_TEST_F(
    SingleClientThemesSyncTestWithAccountThemesSeparationInSigninPendingState,
    PRE_ShouldPersistUnsyncedThemeChangeAcrossRestart) {
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(UsingDefaultTheme(GetProfile(0)));

  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());

  themes_helper::UseGrayscaleTheme(GetProfile(0));
  ASSERT_TRUE(CommittedAllNudgedChangesChecker(GetSyncService(0)).Wait());
  ASSERT_TRUE(UsingGrayscaleTheme(GetProfile(0)));

  // Enter sign-in pending state.
  ASSERT_TRUE(GetClient(0)->EnterSignInPendingStateForPrimaryAccount());
  ASSERT_FALSE(HasUnsyncedThemeData());

  // Set up a custom theme.
  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());
  ASSERT_TRUE(HasUnsyncedThemeData());
}

IN_PROC_BROWSER_TEST_F(
    SingleClientThemesSyncTestWithAccountThemesSeparationInSigninPendingState,
    ShouldPersistUnsyncedThemeChangeAcrossRestart) {
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(UsingCustomTheme(GetProfile(0)));
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportPaused());
  // Hacky wait for entity tracker to be loaded.
  ASSERT_TRUE(base::test::RunUntil([&]() {
    return ThemeServiceFactory::GetForProfile(GetProfile(0))
        ->GetThemeSyncableService()
        ->GetThemeSyncStartState()
        .has_value();
  }));

  // Themes has unsynced data.
  EXPECT_TRUE(HasUnsyncedThemeData());
  // Server still has the old theme.
  ASSERT_TRUE(ServerThemeMatchChecker(HasGrayscaleTheme()).Wait());

  // Resolve sign-in pending state.
  ASSERT_TRUE(GetClient(0)->ExitSignInPendingStateForPrimaryAccount());
  ASSERT_TRUE(UsingCustomTheme(GetProfile(0)));
  ASSERT_TRUE(
      ServerThemeMatchChecker(HasCustomThemeWithId(GetCustomTheme(0))).Wait());

  // Sign out.
  GetClient(0)->SignOutPrimaryAccount();
  ASSERT_TRUE(DefaultThemeChecker(GetProfile(0)).Wait());
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(
    SingleClientThemesSyncTestWithAccountThemesSeparation,
    PRE_ShouldClearAccountDataOnStartupIfSignInAllowedBitChanged) {
  ASSERT_TRUE(SetupClients());

  // Set the sign-in allowed bit to true initially.
  preferences_helper::GetPrefs(/*index=*/0)
      ->SetBoolean(prefs::kSigninAllowedOnNextStartup, true);

  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  GetFakeServer()->InjectEntity(CreateGrayscaleThemeEntity());

  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());

  // Account theme is effective.
  ASSERT_TRUE(GrayscaleThemeChecker(GetProfile(0)).Wait());

  // Simulate turning off the sign-in allowed bit on the settings page.
  preferences_helper::GetPrefs(/*index=*/0)
      ->SetBoolean(prefs::kSigninAllowedOnNextStartup, false);
}

IN_PROC_BROWSER_TEST_F(
    SingleClientThemesSyncTestWithAccountThemesSeparation,
    ShouldClearAccountDataOnStartupIfSignInAllowedBitChanged) {
  base::HistogramTester histogram_tester;
  ASSERT_TRUE(SetupClients());

  // Original local theme should get re-applied.
  // Note: The account theme is not cleared instantaneously upon startup, but
  // upon themes sync initialization.
  EXPECT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());
  EXPECT_FALSE(UsingGrayscaleTheme(GetProfile(0)));

  histogram_tester.ExpectUniqueSample(
      "Sync.SyncableService.MaybeClearDataIfMetadataEmptyOrInvalid.THEME", true,
      /*expected_bucket_count=*/1);
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

IN_PROC_BROWSER_TEST_F(
    SingleClientThemesSyncTestWithAccountThemesSeparation,
    PRE_ShouldClearAccountDataOnStartupIfAccountStateChanged) {
  ASSERT_TRUE(SetupClients());

  UseCustomTheme(GetProfile(0), 0);
  ASSERT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());

  GetFakeServer()->InjectEntity(CreateGrayscaleThemeEntity());

#if BUILDFLAG(IS_CHROMEOS)
  ASSERT_TRUE(SetupSync());
#else
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
#endif  // BUILDFLAG(IS_CHROMEOS)

  // Account theme is effective.
  ASSERT_TRUE(GrayscaleThemeChecker(GetProfile(0)).Wait());

  // Simulate a data type error to prevent clearing of account data.
  GetSyncService(0)->ReportDataTypeErrorForTest(syncer::THEMES);
#if BUILDFLAG(IS_CHROMEOS)
  // Disable sync.
  ASSERT_TRUE(
      GetClient(0)->DisableSyncForType(syncer::UserSelectableType::kThemes));
#else
  // Sign out. Account theme should stay because of the data type error.
  GetClient(0)->SignOutPrimaryAccount();
#endif  // BUILDFLAG(IS_CHROMEOS)
  // Local theme is not restored because stop sync is not called when there is a
  // data type error.
  ASSERT_TRUE(UsingGrayscaleTheme(GetProfile(0)));

  ExcludeDataTypesFromCheckForDataTypeFailures({syncer::THEMES});
}

IN_PROC_BROWSER_TEST_F(SingleClientThemesSyncTestWithAccountThemesSeparation,
                       ShouldClearAccountDataOnStartupIfAccountStateChanged) {
  base::HistogramTester histogram_tester;
  ASSERT_TRUE(SetupClients());

  // Original local theme should get re-applied.
  // Note: The account theme is not cleared instantaneously upon startup, but
  // upon themes sync initialization.
  EXPECT_TRUE(CustomThemeChecker(GetProfile(0)).Wait());
  EXPECT_FALSE(UsingGrayscaleTheme(GetProfile(0)));

  // Clearing happened with StayStoppedAndMaybeClearData() called upon startup.
  histogram_tester.ExpectUniqueSample(
      "Sync.SyncableService.MaybeClearDataIfMetadataEmptyOrInvalid.THEME", true,
      /*expected_bucket_count=*/1);
}

}  // namespace