File: enable_disable_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 (641 lines) | stat: -rw-r--r-- 26,235 bytes parent folder | download | duplicates (5)
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
// 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 <memory>

#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/string_util.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/sync/test/integration/bookmarks_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/updated_progress_marker_checker.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/sync/base/data_type.h"
#include "components/sync/base/features.h"
#include "components/sync/base/user_selectable_type.h"
#include "components/sync/engine/cycle/entity_change_metric_recording.h"
#include "components/sync/protocol/sync.pb.h"
#include "components/sync/service/glue/sync_transport_data_prefs.h"
#include "components/sync/service/sync_service_impl.h"
#include "components/sync/test/bookmark_entity_builder.h"
#include "components/sync/test/entity_builder_factory.h"
#include "content/public/test/browser_test.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_CHROMEOS)
// To control Floating SSO (= sync of cookies) on ChromeOS.
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

namespace {

using fake_server::FakeServer;
using syncer::DataType;
using syncer::DataTypeSet;
using syncer::DataTypeToDebugString;
using syncer::UserSelectableType;
using syncer::UserSelectableTypeSet;
using testing::ElementsAre;
using testing::IsEmpty;

const char kSyncedBookmarkURL[] = "http://www.mybookmark.com";
// Non-utf8 string to make sure it gets handled well.
const char kTestServerChips[] = "\xed\xa0\x80\xed\xbf\xbf";

// A FakeServer observer than saves all issued GetUpdates requests to a vector.
class GetUpdatesRequestRecorder : public FakeServer::Observer {
 public:
  explicit GetUpdatesRequestRecorder(FakeServer* fake_server) {
    CHECK(fake_server);
    observation_.Observe(fake_server);
  }

  ~GetUpdatesRequestRecorder() override = default;

  const std::vector<sync_pb::ClientToServerMessage>& recorded_requests() const {
    return recorded_requests_;
  }

  // FakeServer::Observer overrides.
  void OnWillGetUpdates(
      const sync_pb::ClientToServerMessage& message) override {
    recorded_requests_.push_back(message);
  }

 private:
  std::vector<sync_pb::ClientToServerMessage> recorded_requests_;
  base::ScopedObservation<FakeServer, FakeServer::Observer> observation_{this};
};

MATCHER_P2(MatchesGetUpdatesRequest, origin, data_type_set, "") {
  if (!testing::ExplainMatchResult(
          origin, arg.get_updates().get_updates_origin(), result_listener)) {
    *result_listener << "Unexpected origin "
                     << arg.get_updates().get_updates_origin();
    return false;
  }

  DataTypeSet actual_data_types;
  for (const sync_pb::DataTypeProgressMarker& marker :
       arg.get_updates().from_progress_marker()) {
    actual_data_types.Put(
        syncer::GetDataTypeFromSpecificsFieldNumber(marker.data_type_id()));
  }
  return testing::ExplainMatchResult(data_type_set, actual_data_types,
                                     result_listener);
}

// Some types show up in multiple groups. This means that there are at least two
// user selectable groups that will cause these types to become enabled. This
// affects our tests because we cannot assume that before enabling a multi type
// it will be disabled, because the other selectable type(s) could already be
// enabling it. And vice versa for disabling.
DataTypeSet MultiGroupTypes(const DataTypeSet& registered_types) {
  DataTypeSet seen;
  DataTypeSet multi;
  for (UserSelectableType type : UserSelectableTypeSet::All()) {
    const DataTypeSet grouped_types =
        syncer::UserSelectableTypeToAllDataTypes(type);
    for (DataType grouped_type : grouped_types) {
      if (seen.Has(grouped_type)) {
        multi.Put(grouped_type);
      } else {
        seen.Put(grouped_type);
      }
    }
  }
  multi.RetainAll(registered_types);
  return multi;
}

// This test enables and disables types and verifies the type is active via
// SyncService::GetActiveDataTypes().
class EnableDisableSingleClientTest : public SyncTest {
 public:
  EnableDisableSingleClientTest() : SyncTest(SINGLE_CLIENT) {}

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

  ~EnableDisableSingleClientTest() override = default;

  // Don't use self-notifications as they can trigger additional sync cycles.
  bool TestUsesSelfNotifications() override { return false; }

  bool IsDataTypeActive(DataType type) {
    return GetSyncService(0)->GetActiveDataTypes().Has(type);
  }

  void InjectSyncedBookmark() {
    fake_server::BookmarkEntityBuilder bookmark_builder =
        entity_builder_factory_.NewBookmarkEntityBuilder("My Bookmark");
    GetFakeServer()->InjectEntity(
        bookmark_builder.BuildBookmark(GURL(kSyncedBookmarkURL)));
  }

  int GetNumUpdatesDownloadedInLastCycle() {
    return GetSyncService(0)
        ->GetLastCycleSnapshotForDebugging()
        .model_neutral_state()
        .num_updates_downloaded_total;
  }

 protected:
  void SetupTest(bool all_types_enabled) {
    ASSERT_TRUE(SetupClients());

#if BUILDFLAG(IS_CHROMEOS)
    // This unblocks sync of cookies on ChromeOS, see dedicated controller
    // CookieSyncDataTypeController. The tests in this file are not prepared
    // to handle selectable datatypes which are disabled by default via their
    // DataTypeController, so we have to enable the pref for them to pass.
    // TODO(crbug.com/378091718): think if we can also make the tests pass with
    // this preference disabled.
    GetProfile(0)->GetPrefs()->SetBoolean(::prefs::kFloatingSsoEnabled, true);
#endif  // BUILDFLAG(IS_CHROMEOS)

    ASSERT_TRUE(
        GetClient(0)->SetupSyncWithCustomSettings(base::BindLambdaForTesting(
            [all_types_enabled](syncer::SyncUserSettings* user_settings) {
              user_settings->SetSelectedTypes(all_types_enabled, {});
#if !BUILDFLAG(IS_CHROMEOS)
              user_settings->SetInitialSyncFeatureSetupComplete(
                  syncer::SyncFirstSetupCompleteSource::ADVANCED_FLOW_CONFIRM);
#endif  // !BUILDFLAG(IS_CHROMEOS)
            })));

    registered_data_types_ = GetSyncService(0)->GetRegisteredDataTypesForTest();

    multi_grouped_types_ = MultiGroupTypes(registered_data_types_);
    registered_selectable_types_ = GetRegisteredSelectableTypes(0);
  }

  DataTypeSet ResolveGroup(UserSelectableType type) {
    DataTypeSet grouped_types = syncer::UserSelectableTypeToAllDataTypes(type);
    grouped_types.RetainAll(registered_data_types_);
    return grouped_types;
  }

  DataTypeSet WithoutMultiTypes(const DataTypeSet& input) {
    return Difference(input, multi_grouped_types_);
  }

  DataTypeSet registered_data_types_;
  DataTypeSet multi_grouped_types_;
  UserSelectableTypeSet registered_selectable_types_;

 private:
  fake_server::EntityBuilderFactory entity_builder_factory_;
};

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest, PRE_EnableAndRestart) {
  GetUpdatesRequestRecorder get_updates_recorder(GetFakeServer());

  SetupTest(/*all_types_enabled=*/true);

  // Commit-only types don't issue GetUpdates (by definition) and supervised
  // user types are also excluded in this test, because the account being used
  // isn't supervised. Finally, a few types aren't launched so they should also
  // be excluded.
  const DataTypeSet types_without_updates =
      Union(syncer::CommitOnlyTypes(),
            {syncer::SUPERVISED_USER_SETTINGS, syncer::PLUS_ADDRESS,
             syncer::PLUS_ADDRESS_SETTING});
  // High priority types in this test are a subset of
  // syncer::HighPriorityUserTypes(), excluding those identified earlier.
  const DataTypeSet high_priority_types = Difference(
      Intersection(syncer::HighPriorityUserTypes(), registered_data_types_),
      types_without_updates);
  // Similarly, low priority types in this test are a subset of
  // syncer::LowPriorityUserTypes().
  const DataTypeSet low_priority_types = Difference(
      Intersection(syncer::LowPriorityUserTypes(), registered_data_types_),
      types_without_updates);
  // All other types have regular priority.
  const DataTypeSet regular_priority_types = Difference(
      registered_data_types_,
      Union(types_without_updates, Union(syncer::HighPriorityUserTypes(),
                                         syncer::LowPriorityUserTypes())));

  // Initial sync takes four GetUpdates requests to the server to download:
  // 1. Control types (NIGORI).
  // 2. High-priority user types.
  // 3. Regular-priority types.
  // 4. Low-priority types.
  //
  // The sequence of GetUpdatesOrigin below matches what is empirically
  // observed outside tests when Sync is turned on during desktop FRE using the
  // advanced sync setup flow (open settings), which is also what tests mimic.
  EXPECT_THAT(
      get_updates_recorder.recorded_requests(),
      ElementsAre(MatchesGetUpdatesRequest(sync_pb::SyncEnums::NEW_CLIENT,
                                           syncer::ControlTypes()),
                  MatchesGetUpdatesRequest(
                      sync_pb::SyncEnums::NEW_CLIENT,
                      Union(syncer::ControlTypes(), high_priority_types)),
                  MatchesGetUpdatesRequest(
                      sync_pb::SyncEnums::NEW_CLIENT,
                      Union(syncer::ControlTypes(), regular_priority_types)),
                  MatchesGetUpdatesRequest(
                      sync_pb::SyncEnums::NEW_CLIENT,
                      Union(syncer::ControlTypes(), low_priority_types))));
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest, EnableAndRestart) {
  GetUpdatesRequestRecorder get_updates_recorder(GetFakeServer());

  ASSERT_TRUE(SetupClients());

  EXPECT_TRUE(GetClient(0)->AwaitEngineInitialization());

  for (UserSelectableType type : UserSelectableTypeSet::All()) {
    for (DataType data_type : ResolveGroup(type)) {
      EXPECT_TRUE(IsDataTypeActive(data_type))
          << " for " << DataTypeToDebugString(data_type);
    }
  }

  EXPECT_THAT(get_updates_recorder.recorded_requests(), IsEmpty());
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest, EnableOneAtATime) {
  // Setup sync with no enabled types.
  SetupTest(/*all_types_enabled=*/false);

  // Certain datatypes like SESSIONS can be configured by multiple
  // user-selectable types. Hence, enabling a new user-selectable type doesn't
  // necessarily mean that the datatype (SESSIONS) will be newly-configured. In
  // this particular test, this influences whether the engine will issue UMA
  // corresponding to the configuration cycle.
  syncer::DataTypeSet previously_active_types;

  for (UserSelectableType type : registered_selectable_types_) {
    const DataTypeSet grouped_types = ResolveGroup(type);
    for (DataType single_grouped_type : WithoutMultiTypes(grouped_types)) {
      ASSERT_FALSE(IsDataTypeActive(single_grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }

    base::HistogramTester histogram_tester;
    EXPECT_TRUE(GetClient(0)->EnableSyncForType(type));

    for (DataType grouped_type : grouped_types) {
      EXPECT_TRUE(IsDataTypeActive(grouped_type))
          << " for " << GetUserSelectableTypeName(type);

      if (!syncer::ProtocolTypes().Has(grouped_type) ||
          syncer::CommitOnlyTypes().Has(grouped_type)) {
        EXPECT_EQ(0,
                  histogram_tester.GetBucketCount(
                      "Sync.PostedDataTypeGetUpdatesRequest",
                      static_cast<int>(DataTypeHistogramValue(grouped_type))))
            << " for " << DataTypeToDebugString(grouped_type);
      } else if (previously_active_types.Has(grouped_type)) {
        // If the type was already configured, no additional configuration cycle
        // is expected, but it's impossible to rule out that the type has issued
        // a GetUpdates request for different reasons (since it's actively
        // sync-ing).
      } else {
        EXPECT_NE(0,
                  histogram_tester.GetBucketCount(
                      "Sync.PostedDataTypeGetUpdatesRequest",
                      static_cast<int>(DataTypeHistogramValue(grouped_type))))
            << " for " << DataTypeToDebugString(grouped_type);
      }

      previously_active_types.Put(grouped_type);
    }
  }
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest, DisableOneAtATime) {
  // Setup sync with no disabled types.
  SetupTest(/*all_types_enabled=*/true);

  for (UserSelectableType type : registered_selectable_types_) {
    const DataTypeSet grouped_types = ResolveGroup(type);
    for (DataType grouped_type : grouped_types) {
      ASSERT_TRUE(IsDataTypeActive(grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }

    EXPECT_TRUE(GetClient(0)->DisableSyncForType(type));

    for (DataType single_grouped_type : WithoutMultiTypes(grouped_types)) {
      EXPECT_FALSE(IsDataTypeActive(single_grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }
  }

  // Lastly make sure that all the multi grouped times are all gone, since we
  // did not check these after disabling inside the above loop.
  for (DataType multi_grouped_type : multi_grouped_types_) {
    EXPECT_FALSE(IsDataTypeActive(multi_grouped_type))
        << " for " << DataTypeToDebugString(multi_grouped_type);
  }
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest,
                       FastEnableDisableOneAtATime) {
  // Setup sync with no enabled types.
  SetupTest(/*all_types_enabled=*/false);

  for (UserSelectableType type : registered_selectable_types_) {
    const DataTypeSet grouped_types = ResolveGroup(type);
    const DataTypeSet single_grouped_types = WithoutMultiTypes(grouped_types);
    for (DataType single_grouped_type : single_grouped_types) {
      ASSERT_FALSE(IsDataTypeActive(single_grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }

    // Enable and then disable immediately afterwards, before the datatype has
    // had the chance to finish startup (which usually involves task posting).
    EXPECT_TRUE(GetClient(0)->EnableSyncForType(type));
    EXPECT_TRUE(GetClient(0)->DisableSyncForType(type));

    for (DataType single_grouped_type : single_grouped_types) {
      EXPECT_FALSE(IsDataTypeActive(single_grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }
  }

  // Lastly make sure that all the multi grouped times are all gone, since we
  // did not check these after disabling inside the above loop.
  for (DataType multi_grouped_type : multi_grouped_types_) {
    EXPECT_FALSE(IsDataTypeActive(multi_grouped_type))
        << " for " << DataTypeToDebugString(multi_grouped_type);
  }
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest,
                       FastDisableEnableOneAtATime) {
  // Setup sync with no disabled types.
  SetupTest(/*all_types_enabled=*/true);

  for (UserSelectableType type : registered_selectable_types_) {
    const DataTypeSet grouped_types = ResolveGroup(type);
    for (DataType grouped_type : grouped_types) {
      ASSERT_TRUE(IsDataTypeActive(grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }

    // Disable and then reenable immediately afterwards, before the datatype has
    // had the chance to stop fully (which usually involves task posting).
    EXPECT_TRUE(GetClient(0)->DisableSyncForType(type));
    EXPECT_TRUE(GetClient(0)->EnableSyncForType(type));

    for (DataType grouped_type : grouped_types) {
      EXPECT_TRUE(IsDataTypeActive(grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }
  }
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest,
                       FastEnableDisableEnableOneAtATime) {
  // Setup sync with no enabled types.
  SetupTest(/*all_types_enabled=*/false);

  for (UserSelectableType type : registered_selectable_types_) {
    const DataTypeSet single_grouped_types =
        WithoutMultiTypes(ResolveGroup(type));
    for (DataType single_grouped_type : single_grouped_types) {
      ASSERT_FALSE(IsDataTypeActive(single_grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }

    // Fast enable-disable-enable sequence, before the datatype has had the
    // chance to transition fully across states (usually involves task posting).
    EXPECT_TRUE(GetClient(0)->EnableSyncForType(type));
    EXPECT_TRUE(GetClient(0)->DisableSyncForType(type));
    EXPECT_TRUE(GetClient(0)->EnableSyncForType(type));

    for (DataType single_grouped_type : single_grouped_types) {
      EXPECT_TRUE(IsDataTypeActive(single_grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }
  }
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest, EnableDisable) {
  SetupTest(/*all_types_enabled=*/false);

  // Enable all, and then disable immediately afterwards, before datatypes
  // have had the chance to finish startup (which usually involves task
  // posting).
  ASSERT_TRUE(GetClient(0)->EnableSyncForRegisteredDatatypes());
  ASSERT_TRUE(GetClient(0)->DisableSyncForAllDatatypes());

  for (UserSelectableType type : UserSelectableTypeSet::All()) {
    for (DataType grouped_type : ResolveGroup(type)) {
      EXPECT_FALSE(IsDataTypeActive(grouped_type))
          << " for " << GetUserSelectableTypeName(type);
    }
  }
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest, FastEnableDisableEnable) {
  SetupTest(/*all_types_enabled=*/false);

  // Enable all, and then disable+reenable immediately afterwards, before
  // datatypes have had the chance to finish startup (which usually involves
  // task posting).
  ASSERT_TRUE(GetClient(0)->EnableSyncForRegisteredDatatypes());
  ASSERT_TRUE(GetClient(0)->DisableSyncForAllDatatypes());
  ASSERT_TRUE(GetClient(0)->EnableSyncForRegisteredDatatypes());

  for (UserSelectableType type : UserSelectableTypeSet::All()) {
    for (DataType data_type : ResolveGroup(type)) {
      EXPECT_TRUE(IsDataTypeActive(data_type))
          << " for " << DataTypeToDebugString(data_type);
    }
  }
}

// This test makes sure that after a signout, Sync data gets redownloaded
// when Sync is started again. This does not actually verify that the data is
// gone from disk (which seems infeasible); it's mostly here as a baseline for
// the following tests.
//
// ChromeOS does not support signing out of a primary account.
#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest, RedownloadsAfterSignout) {
  ASSERT_TRUE(SetupClients());
  ASSERT_FALSE(bookmarks_helper::GetBookmarkModel(0)->IsBookmarked(
      GURL(kSyncedBookmarkURL)));

  // Create a bookmark on the server, then turn on Sync on the client.
  InjectSyncedBookmark();
  // Disable any LowPriorityUserTypes() (in practice, history, and incoming
  // password sharing invitations controlled by Passwords data type): This test
  // inspects the last-sync-cycle state. If low-prio types are active, they
  // cause another (uninteresting) cycle and mess up the stats we're interested
  // in.
  // TODO(crbug.com/40215602): Rewrite this test to avoid disabling low priotiy
  // types.
  ASSERT_TRUE(GetClient(0)->SetupSyncWithCustomSettings(
      base::BindOnce([](syncer::SyncUserSettings* settings) {
        UserSelectableTypeSet types = settings->GetRegisteredSelectableTypes();
        types.Remove(syncer::UserSelectableType::kHistory);
        types.Remove(syncer::UserSelectableType::kPasswords);
        settings->SetSelectedTypes(/*sync_everything=*/false, types);
#if !BUILDFLAG(IS_CHROMEOS)
        settings->SetInitialSyncFeatureSetupComplete(
            syncer::SyncFirstSetupCompleteSource::ADVANCED_FLOW_CONFIRM);
#endif  // !BUILDFLAG(IS_CHROMEOS)
      })));
  ASSERT_TRUE(GetSyncService(0)->IsSyncFeatureActive());
  ASSERT_FALSE(GetSyncService(0)->GetActiveDataTypes().HasAny(
      syncer::LowPriorityUserTypes()));

  // Make sure the bookmark got synced down.
  ASSERT_TRUE(bookmarks_helper::GetBookmarkModel(0)->IsBookmarked(
      GURL(kSyncedBookmarkURL)));
  // Note: The response may also contain permanent nodes, so we can't check the
  // exact count.
  const int initial_updates_downloaded = GetNumUpdatesDownloadedInLastCycle();
  ASSERT_GT(initial_updates_downloaded, 0);

  // Stop and restart Sync.
  GetClient(0)->SignOutPrimaryAccount();
  ASSERT_TRUE(GetClient(0)->SetupSync());
  ASSERT_TRUE(GetSyncService(0)->IsSyncFeatureActive());

  // Everything should have been redownloaded.
  ASSERT_TRUE(bookmarks_helper::GetBookmarkModel(0)->IsBookmarked(
      GURL(kSyncedBookmarkURL)));
  EXPECT_EQ(GetNumUpdatesDownloadedInLastCycle(), initial_updates_downloaded);
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest,
                       DoesNotRedownloadAfterSyncUnpaused) {
  ASSERT_TRUE(SetupClients());
  ASSERT_FALSE(bookmarks_helper::GetBookmarkModel(0)->IsBookmarked(
      GURL(kSyncedBookmarkURL)));

  // Create a bookmark on the server, then turn on Sync on the client.
  InjectSyncedBookmark();
  // Disable any LowPriorityUserTypes() (in practice, history, and incoming
  // password sharing invitations controlled by Passwords data type): This test
  // inspects the last-sync-cycle state. If low-prio types are active, they
  // cause another (uninteresting) cycle and mess up the stats we're interested
  // in.
  // TODO(crbug.com/40215602): Rewrite this test to avoid disabling low priotiy
  // types.
  ASSERT_TRUE(GetClient(0)->SetupSyncWithCustomSettings(
      base::BindOnce([](syncer::SyncUserSettings* settings) {
        UserSelectableTypeSet types = settings->GetRegisteredSelectableTypes();
        types.Remove(syncer::UserSelectableType::kHistory);
        types.Remove(syncer::UserSelectableType::kPasswords);
        settings->SetSelectedTypes(/*sync_everything=*/false, types);
#if !BUILDFLAG(IS_CHROMEOS)
        settings->SetInitialSyncFeatureSetupComplete(
            syncer::SyncFirstSetupCompleteSource::ADVANCED_FLOW_CONFIRM);
#endif  // !BUILDFLAG(IS_CHROMEOS)
      })));
  ASSERT_TRUE(GetSyncService(0)->IsSyncFeatureActive());
  ASSERT_FALSE(GetSyncService(0)->GetActiveDataTypes().HasAny(
      syncer::LowPriorityUserTypes()));

  // Make sure the bookmark got synced down.
  ASSERT_TRUE(bookmarks_helper::GetBookmarkModel(0)->IsBookmarked(
      GURL(kSyncedBookmarkURL)));
  // Note: The response may also contain permanent nodes, so we can't check the
  // exact count.
  ASSERT_GT(GetNumUpdatesDownloadedInLastCycle(), 0);

  // Pause sync.
  GetClient(0)->EnterSyncPausedStateForPrimaryAccount();
  ASSERT_FALSE(GetSyncService(0)->IsSyncFeatureActive());

  // Resume sync.
  base::HistogramTester histogram_tester;
  GetClient(0)->ExitSyncPausedStateForPrimaryAccount();
  ASSERT_TRUE(GetSyncService(0)->IsSyncFeatureActive());

  // The bookmark should still be there, *without* having been redownloaded.
  ASSERT_TRUE(SetupSync());
  ASSERT_TRUE(bookmarks_helper::GetBookmarkModel(0)->IsBookmarked(
      GURL(kSyncedBookmarkURL)));
  EXPECT_EQ(0, histogram_tester.GetBucketCount(
                   "Sync.DataTypeEntityChange.BOOKMARK",
                   syncer::DataTypeEntityChange::kRemoteNonInitialUpdate));
  EXPECT_EQ(0, histogram_tester.GetBucketCount(
                   "Sync.DataTypeEntityChange.BOOKMARK",
                   syncer::DataTypeEntityChange::kRemoteInitialUpdate));
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest,
                       DoesNotClearPrefsWithKeepData) {
  SetupTest(/*all_types_enabled=*/true);

  syncer::SyncTransportDataPrefs prefs(
      GetProfile(0)->GetPrefs(),
      GetClient(0)->GetGaiaIdHashForPrimaryAccount());
  const std::string cache_guid = prefs.GetCacheGuid();
  ASSERT_NE("", cache_guid);

  GetClient(0)->EnterSyncPausedStateForPrimaryAccount();
  EXPECT_EQ(cache_guid, prefs.GetCacheGuid());
}

class EnableDisableSingleClientSelfNotifyTest
    : public EnableDisableSingleClientTest {
 public:
  // UpdatedProgressMarkerChecker relies on the 'self-notify' feature.
  bool TestUsesSelfNotifications() override { return true; }

  sync_pb::ClientToServerMessage TriggerGetUpdatesCycleAndWait() {
    TriggerSyncForDataTypes(0, {syncer::BOOKMARKS});
    EXPECT_TRUE(UpdatedProgressMarkerChecker(GetSyncService(0)).Wait());

    sync_pb::ClientToServerMessage message;
    EXPECT_TRUE(GetFakeServer()->GetLastGetUpdatesMessage(&message));
    return message;
  }
};

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientSelfNotifyTest,
                       PRE_ResendsBagOfChips) {
  sync_pb::ChipBag bag_of_chips;
  bag_of_chips.set_server_chips(kTestServerChips);
  ASSERT_FALSE(base::IsStringUTF8(bag_of_chips.SerializeAsString()));
  GetFakeServer()->SetBagOfChips(bag_of_chips);

  SetupTest(/*all_types_enabled=*/true);

  syncer::SyncTransportDataPrefs prefs(
      GetProfile(0)->GetPrefs(),
      GetClient(0)->GetGaiaIdHashForPrimaryAccount());
  EXPECT_EQ(bag_of_chips.SerializeAsString(), prefs.GetBagOfChips());

  sync_pb::ClientToServerMessage message = TriggerGetUpdatesCycleAndWait();
  EXPECT_TRUE(message.has_bag_of_chips());
  EXPECT_EQ(kTestServerChips, message.bag_of_chips().server_chips());
}

IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientSelfNotifyTest,
                       ResendsBagOfChips) {
  ASSERT_TRUE(SetupClients());
  syncer::SyncTransportDataPrefs prefs(
      GetProfile(0)->GetPrefs(),
      GetClient(0)->GetGaiaIdHashForPrimaryAccount());
  ASSERT_NE("", prefs.GetBagOfChips());
  ASSERT_TRUE(GetClient(0)->AwaitSyncSetupCompletion());

  sync_pb::ClientToServerMessage message = TriggerGetUpdatesCycleAndWait();
  EXPECT_TRUE(message.has_bag_of_chips());
  EXPECT_EQ(kTestServerChips, message.bag_of_chips().server_chips());
}

}  // namespace