File: model_load_manager_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 (825 lines) | stat: -rw-r--r-- 35,702 bytes parent folder | download | duplicates (6)
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
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/sync/service/model_load_manager.h"

#include <memory>

#include "base/test/task_environment.h"
#include "components/sync/base/sync_stop_metadata_fate.h"
#include "components/sync/service/configure_context.h"
#include "components/sync/service/sync_error.h"
#include "components/sync/test/fake_data_type_controller.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::_;

namespace syncer {

namespace {

ConfigureContext BuildConfigureContext(SyncMode sync_mode = SyncMode::kFull) {
  ConfigureContext context;
  context.sync_mode = sync_mode;
  context.cache_guid = "test_cache_guid";
  return context;
}

}  // namespace

class MockModelLoadManagerDelegate : public ModelLoadManagerDelegate {
 public:
  MockModelLoadManagerDelegate() = default;
  ~MockModelLoadManagerDelegate() override = default;
  MOCK_METHOD(void, OnAllDataTypesReadyForConfigure, (), (override));
  MOCK_METHOD(void,
              OnSingleDataTypeWillStop,
              (DataType, const std::optional<SyncError>& error),
              (override));
};

class SyncModelLoadManagerTest : public testing::Test {
 public:
  SyncModelLoadManagerTest() = default;

  FakeDataTypeController* GetController(DataType data_type) {
    auto it = controllers_.find(data_type);
    if (it == controllers_.end()) {
      return nullptr;
    }
    return static_cast<FakeDataTypeController*>(it->second.get());
  }

 protected:
  base::test::SingleThreadTaskEnvironment task_environment_{
      base::test::SingleThreadTaskEnvironment::MainThreadType::UI,
      base::test::SingleThreadTaskEnvironment::TimeSource::MOCK_TIME};
  testing::NiceMock<MockModelLoadManagerDelegate> delegate_;
  DataTypeController::TypeMap controllers_;
};

// Start a type and make sure ModelLoadManager callst the `Start`
// method and calls the callback when it is done.
TEST_F(SyncModelLoadManagerTest, SimpleModelStart) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types = {BOOKMARKS, APPS};
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  EXPECT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);
  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::NOT_RUNNING);

  // Configure() kicks off model loading.
  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  EXPECT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
}

// Start a type, let it finish and then call stop.
TEST_F(SyncModelLoadManagerTest, StopAfterFinish) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types;
  types.Put(BOOKMARKS);
  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(BOOKMARKS, _));

  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);

  model_load_manager.Stop(SyncStopMetadataFate::KEEP_METADATA);
  EXPECT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);
  EXPECT_EQ(0, GetController(BOOKMARKS)->model()->clear_metadata_count());
}

// Test that a model that failed to load is reported and stopped properly.
TEST_F(SyncModelLoadManagerTest, ModelLoadFail) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  GetController(BOOKMARKS)->model()->SimulateModelError(
      ModelError(FROM_HERE, "Test error"));
  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types;
  types.Put(BOOKMARKS);
  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(BOOKMARKS, _));

  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  EXPECT_EQ(DataTypeController::FAILED, GetController(BOOKMARKS)->state());
}

// Test that a runtime error is handled by stopping the type.
TEST_F(SyncModelLoadManagerTest, StopAfterConfiguration) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types;
  types.Put(BOOKMARKS);

  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);

  testing::Mock::VerifyAndClearExpectations(&delegate_);
  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(BOOKMARKS, _));
  GetController(BOOKMARKS)->model()->SimulateModelError(
      ModelError(FROM_HERE, "Test error"));
}

// Test that OnAllDataTypesReadyForConfigure is called when all datatypes that
// require LoadModels before configuration are loaded.
TEST_F(SyncModelLoadManagerTest, OnAllDataTypesReadyForConfigure) {
  // Create two controllers with delayed model load.
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  GetController(BOOKMARKS)->model()->EnableManualModelStart();
  GetController(APPS)->model()->EnableManualModelStart();

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types = {BOOKMARKS, APPS};
  // OnAllDataTypesReadyForConfigure shouldn't be called, APPS data type is not
  // loaded yet.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()).Times(0);

  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  EXPECT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_STARTING);
  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_STARTING);

  // Finish loading BOOKMARKS, but APPS are still loading.
  GetController(BOOKMARKS)->model()->SimulateModelStartFinished();
  EXPECT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);

  testing::Mock::VerifyAndClearExpectations(&delegate_);

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());
  // Finish loading APPS. This should trigger OnAllDataTypesReadyForConfigure.
  GetController(APPS)->model()->SimulateModelStartFinished();
  EXPECT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);

  // Call ModelLoadManager::Configure with reduced set of datatypes.
  // All datatypes in reduced set are already loaded.
  // OnAllDataTypesReadyForConfigure() should be called.
  testing::Mock::VerifyAndClearExpectations(&delegate_);

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  DataTypeSet reduced_types = {APPS};
  model_load_manager.Configure(
      /*preferred_types_without_errors=*/reduced_types,
      /*preferred_types=*/reduced_types, BuildConfigureContext());

  EXPECT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);
  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
  EXPECT_EQ(1, GetController(BOOKMARKS)->model()->clear_metadata_count());
}

// Test that OnAllDataTypesReadyForConfigure() is called correctly after
// LoadModels fails for one of datatypes.
TEST_F(SyncModelLoadManagerTest,
       OnAllDataTypesReadyForConfigure_FailedLoadModels) {
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  GetController(APPS)->model()->EnableManualModelStart();

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types = {APPS};
  // OnAllDataTypesReadyForConfigure shouldn't be called, APPS data type is not
  // loaded yet.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()).Times(0);

  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_STARTING);

  testing::Mock::VerifyAndClearExpectations(&delegate_);

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());
  // Simulate model load error for APPS and finish loading it. This should
  // trigger OnAllDataTypesReadyForConfigure.
  GetController(APPS)->model()->SimulateModelError(
      ModelError(FROM_HERE, "Test error"));
  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::FAILED);
}

// Test that if one of the types fails while another is still being loaded then
// OnAllDataTypesReadyForConfgiure is still called correctly.
TEST_F(SyncModelLoadManagerTest,
       OnAllDataTypesReadyForConfigure_TypeFailedAfterLoadModels) {
  // Create two controllers with delayed model load. Both should block
  // configuration.
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  GetController(BOOKMARKS)->model()->EnableManualModelStart();
  GetController(APPS)->model()->EnableManualModelStart();

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types = {BOOKMARKS, APPS};

  // Apps will finish loading but bookmarks won't.
  // OnAllDataTypesReadyForConfigure shouldn't be called.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()).Times(0);

  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  GetController(APPS)->model()->SimulateModelStartFinished();

  EXPECT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_STARTING);
  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);

  testing::Mock::VerifyAndClearExpectations(&delegate_);

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()).Times(0);

  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(APPS, _));
  // Apps datatype reports failure.
  GetController(APPS)->model()->SimulateModelError(
      ModelError(FROM_HERE, "Test error"));

  testing::Mock::VerifyAndClearExpectations(&delegate_);

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());
  // Finish loading BOOKMARKS. This should trigger
  // OnAllDataTypesReadyForConfigure().
  GetController(BOOKMARKS)->model()->SimulateModelStartFinished();
  EXPECT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
}

// Test that Stop clears metadata for disabled type.
TEST_F(SyncModelLoadManagerTest, StopClearMetadata) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);

  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);

  DataTypeSet types = {BOOKMARKS};

  // Configure() kicks off model loading.
  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);

  model_load_manager.Stop(SyncStopMetadataFate::CLEAR_METADATA);

  EXPECT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);
  EXPECT_EQ(1, GetController(BOOKMARKS)->model()->clear_metadata_count());
}

// Test that stopping a single type clears the metadata for the disabled type.
TEST_F(SyncModelLoadManagerTest, StopDataType) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);

  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);

  // Configure() kicks off model loading.
  model_load_manager.Configure(
      /*preferred_types_without_errors=*/{BOOKMARKS},
      /*preferred_types=*/{BOOKMARKS}, BuildConfigureContext());

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);

  model_load_manager.StopDatatype(
      BOOKMARKS, SyncStopMetadataFate::CLEAR_METADATA,
      SyncError(FROM_HERE, SyncError::PRECONDITION_ERROR_WITH_KEEP_DATA,
                "Data type is unready."));

  EXPECT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);
  EXPECT_EQ(1, GetController(BOOKMARKS)->model()->clear_metadata_count());
}

// Test that stopping a single type is ignored when the type is not running.
TEST_F(SyncModelLoadManagerTest, StopDataType_NotRunning) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);

  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);

  model_load_manager.StopDatatype(
      BOOKMARKS, SyncStopMetadataFate::CLEAR_METADATA,
      SyncError(FROM_HERE, SyncError::PRECONDITION_ERROR_WITH_KEEP_DATA,
                "Data type is unready."));

  // The state should still be not running.
  EXPECT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);
}

// Test that Configure stops controllers with KEEP_METADATA for preferred
// types.
TEST_F(SyncModelLoadManagerTest, KeepsMetadataForPreferredDataType) {
  // Configure the manager with two data types.
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet preferred_types = {BOOKMARKS, APPS};
  DataTypeSet desired_types = preferred_types;

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  model_load_manager.Configure(desired_types, preferred_types,
                               BuildConfigureContext());

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
  testing::Mock::VerifyAndClearExpectations(&delegate_);

  // Stop one data type without disabling sync.
  desired_types.Remove(APPS);

  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(APPS, _));
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  model_load_manager.Configure(desired_types, preferred_types,
                               BuildConfigureContext());

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::NOT_RUNNING);
  EXPECT_EQ(0, GetController(APPS)->model()->clear_metadata_count());
}

// Test that Configure stops controllers with CLEAR_METADATA for
// no-longer-preferred types.
TEST_F(SyncModelLoadManagerTest, ClearsMetadataForNotPreferredDataType) {
  // Configure the manager with two data types.
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet preferred_types = {BOOKMARKS, APPS};
  DataTypeSet desired_types = preferred_types;

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  model_load_manager.Configure(desired_types, preferred_types,
                               BuildConfigureContext());

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
  testing::Mock::VerifyAndClearExpectations(&delegate_);

  // Disable one data type.
  preferred_types.Remove(APPS);
  desired_types.Remove(APPS);

  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(APPS, _));
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  model_load_manager.Configure(desired_types, preferred_types,
                               BuildConfigureContext());

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::NOT_RUNNING);
  EXPECT_EQ(1, GetController(APPS)->model()->clear_metadata_count());
}

TEST_F(SyncModelLoadManagerTest,
       SwitchFromFullSyncToTransportModeRestartsTypes) {
  // Configure the manager with two data types.
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(
      BOOKMARKS, /*enable_transport_only_model=*/true);
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(
      APPS, /*enable_transport_only_model=*/true);

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet preferred_types = {BOOKMARKS, APPS};

  ConfigureContext configure_context;
  configure_context.sync_mode = SyncMode::kFull;
  configure_context.cache_guid = "test_cache_guid";

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  model_load_manager.Configure(preferred_types, preferred_types,
                               configure_context);

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
  testing::Mock::VerifyAndClearExpectations(&delegate_);

  // Switch to transport mode.
  configure_context.sync_mode = SyncMode::kTransportOnly;
  // For this test, assume that APPS is not supported in transport mode, but
  // BOOKMARKS is.
  preferred_types.Remove(APPS);

  // Data types should get restarted.
  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(APPS, _));
  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(BOOKMARKS, _));
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  model_load_manager.Configure(preferred_types, preferred_types,
                               configure_context);

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::NOT_RUNNING);

  // When switching modes, the Sync-the-feature mode metadata should get cleared
  // for all datatypes, including datatypes that restarted in transport mode
  // (BOOKMARKS) and datatypes that were excluded (APPS).
  // Note that for BOOKMARKS, it actually gets cleared twice: Once by
  // ModelLoadManager itself, and again via ClearMetadataWhileStopped() from
  // DataTypeController::LoadModels().
  EXPECT_EQ(
      1, GetController(APPS)->model(SyncMode::kFull)->clear_metadata_count());
  EXPECT_EQ(
      2,
      GetController(BOOKMARKS)->model(SyncMode::kFull)->clear_metadata_count());
}

TEST_F(SyncModelLoadManagerTest,
       SwitchFromTransportOnlyToFullSyncRestartsTypes) {
  // Configure the manager with two data types.
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(
      BOOKMARKS, /*enable_transport_only_model=*/true);
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(
      APPS, /*enable_transport_only_model=*/true);

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet preferred_types = {BOOKMARKS, APPS};
  DataTypeSet desired_types = preferred_types;

  ConfigureContext configure_context;
  configure_context.sync_mode = SyncMode::kTransportOnly;
  configure_context.cache_guid = "test_cache_guid";

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  model_load_manager.Configure(desired_types, preferred_types,
                               configure_context);

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
  testing::Mock::VerifyAndClearExpectations(&delegate_);

  // Switch to full-sync mode.
  configure_context.sync_mode = SyncMode::kFull;
  desired_types.Remove(APPS);
  preferred_types.Remove(APPS);

  // Data types should get restarted.
  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(APPS, _));
  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(BOOKMARKS, _));
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure());

  model_load_manager.Configure(desired_types, preferred_types,
                               configure_context);

  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::NOT_RUNNING);
  // The transport-mode metadata for all types should get cleared. Note that for
  // BOOKMARKS, it actually gets cleared twice: Once by ModelLoadManager itself,
  // and again via ClearMetadataWhileStopped() from
  // DataTypeController::LoadModels().
  EXPECT_EQ(1, GetController(APPS)
                   ->model(SyncMode::kTransportOnly)
                   ->clear_metadata_count());
  EXPECT_EQ(2, GetController(BOOKMARKS)
                   ->model(SyncMode::kTransportOnly)
                   ->clear_metadata_count());
}

TEST_F(SyncModelLoadManagerTest, ShouldClearMetadataAfterStopped) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types;
  types.Put(BOOKMARKS);

  // Bring the type to a stopped state.
  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());
  model_load_manager.Stop(SyncStopMetadataFate::KEEP_METADATA);
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);

  ASSERT_EQ(0, GetController(BOOKMARKS)->model()->clear_metadata_count());
  model_load_manager.Stop(SyncStopMetadataFate::CLEAR_METADATA);
  // Clearing metadata should work even though the type is already stopped.
  EXPECT_EQ(1, GetController(BOOKMARKS)->model()->clear_metadata_count());
}

TEST_F(SyncModelLoadManagerTest, ShouldClearMetadataIfNotRunning) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  ModelLoadManager model_load_manager(&controllers_, &delegate_);

  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING);

  ASSERT_EQ(0, GetController(BOOKMARKS)->model()->clear_metadata_count());
  model_load_manager.Stop(SyncStopMetadataFate::CLEAR_METADATA);

  // Clearing metadata should work even though the type is not running.
  EXPECT_EQ(1, GetController(BOOKMARKS)->model()->clear_metadata_count());
}

TEST_F(SyncModelLoadManagerTest, ShouldNotClearMetadataIfFailed) {
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  EXPECT_CALL(delegate_, OnSingleDataTypeWillStop(BOOKMARKS, _)).Times(2);

  // Bring the underlying model to a failed state. Note that this does *not*
  // bring the controller into the FAILED state yet.
  GetController(BOOKMARKS)->model()->SimulateModelError(
      ModelError(FROM_HERE, "Test error"));

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types{BOOKMARKS};

  ASSERT_EQ(0, GetController(BOOKMARKS)->model()->clear_metadata_count());
  // Trying to configure exposes the error to the controller (which calls back
  // into the ModelLoadManager).
  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());
  ASSERT_EQ(DataTypeController::FAILED, GetController(BOOKMARKS)->state());
  // Failure during model load does *not* clear metadata (see
  // ModelLoadManager::ModelLoadCallback()).
  EXPECT_EQ(0, GetController(BOOKMARKS)->model()->clear_metadata_count());

  // Clearing metadata should (again) have no effect since the type is not
  // considered stopped.
  model_load_manager.Stop(SyncStopMetadataFate::CLEAR_METADATA);
  EXPECT_EQ(0, GetController(BOOKMARKS)->model()->clear_metadata_count());
}

// Test that Configure waits for desired types in STOPPING state to stop and
// reload before notifying data type manager.
TEST_F(SyncModelLoadManagerTest,
       ShouldWaitForStoppingDesiredTypesBeforeLoading) {
  // Create two controllers, one with delayed model load.
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  GetController(BOOKMARKS)->model()->EnableManualModelStart();

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet preferred_types = {APPS, BOOKMARKS};

  model_load_manager.Configure(
      /*preferred_types_without_errors=*/preferred_types, preferred_types,
      BuildConfigureContext());

  // Bring BOOKMARKS to a STOPPING state.
  model_load_manager.Stop(SyncStopMetadataFate::KEEP_METADATA);

  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::NOT_RUNNING);
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::STOPPING);

  // It should wait for BOOKMARKS to finish loading before notifying the data
  // type manager.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure).Times(0);

  model_load_manager.Configure(
      /*preferred_types_without_errors=*/preferred_types, preferred_types,
      BuildConfigureContext());

  // APPS is started right away.
  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
  // BOOKMARKS needs to finish stopping first before it can start again.
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::STOPPING);

  // Finish loading of BOOKMARKS for the first time. This should first move the
  // state to NOT_RUNNING. But, as part of the load callback,
  // DataTypeController::LoadModels() will be called which will set its state
  // to MODEL_STARTING.
  GetController(BOOKMARKS)->model()->SimulateModelStartFinished();
  EXPECT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_STARTING);

  // Finish loading of BOOKMARKS. This will lead to a call to notify the
  // delegate that all the types are ready.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure);
  GetController(BOOKMARKS)->model()->SimulateModelStartFinished();
  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);
}

// Test that Configure will not wait for no-longer-desired types in STOPPING
// state to stop before loading.
TEST_F(SyncModelLoadManagerTest,
       ShouldNotWaitForStoppingUndesiredTypesBeforeLoading) {
  // Create two controllers, one with delayed model load.
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  GetController(BOOKMARKS)->model()->EnableManualModelStart();

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet preferred_types = {APPS, BOOKMARKS};
  DataTypeSet preferred_types_without_errors = preferred_types;

  model_load_manager.Configure(preferred_types_without_errors, preferred_types,
                               BuildConfigureContext());

  // Bring BOOKMARKS to a STOPPING state.
  model_load_manager.Stop(SyncStopMetadataFate::KEEP_METADATA);

  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::NOT_RUNNING);
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::STOPPING);

  // Remove BOOKMARKS from `preferred_types_without_errors` which may happen in
  // case of failures/timeouts.
  preferred_types_without_errors.Remove(BOOKMARKS);

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure);
  model_load_manager.Configure(preferred_types_without_errors, preferred_types,
                               BuildConfigureContext());

  // APPS is started and DataTypeManager informed.
  EXPECT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
  // BOOKMARKS remains in STOPPING state.
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::STOPPING);
}

// Test that if one of the type is stuck at loading,
// OnAllDataTypesReadyForConfigure will get called after a timeout.
TEST_F(SyncModelLoadManagerTest, ShouldTimeoutIfNotAllTypesLoaded) {
  // Create two controllers with delayed model load. Both should block
  // configuration.
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  GetController(BOOKMARKS)->model()->EnableManualModelStart();
  GetController(APPS)->model()->EnableManualModelStart();

  // No calls to OnAllDataTypesReadyForConfigure() yet.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure).Times(0);

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types = {BOOKMARKS, APPS};

  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  // Simulate successful loading of APPS only.
  GetController(APPS)->model()->SimulateModelStartFinished();
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
  // BOOKMARKS blocks the configuration.
  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_STARTING);

  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure);
  // Types not loaded till now are skipped.
  task_environment_.FastForwardBy(kSyncLoadModelsTimeoutDuration);
}

// Test that if Stop() is called before all data types finish loading,
// OnAllDataTypesReadyForConfigure will *not* get called after a timeout.
// Regression test for crbug.com/333865298.
TEST_F(SyncModelLoadManagerTest, ShouldNotTimeoutAfterStop) {
  // Create a controllers with delayed model load.
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  GetController(BOOKMARKS)->model()->EnableManualModelStart();

  // No calls to OnAllDataTypesReadyForConfigure() should happen.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure).Times(0);

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet types = {BOOKMARKS};

  model_load_manager.Configure(/*preferred_types_without_errors=*/types,
                               /*preferred_types=*/types,
                               BuildConfigureContext());

  // BOOKMARKS blocks the configuration.
  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_STARTING);

  // The ModelLoadManager gets stopped again before BOOKMARKS finishes loading
  // or times out.
  model_load_manager.Stop(SyncStopMetadataFate::CLEAR_METADATA);

  // Even after the loading timeout period, OnAllDataTypesReadyForConfigure()
  // should *not* get called.
  task_environment_.FastForwardBy(kSyncLoadModelsTimeoutDuration);
}

// Regression test for crbug.com/1506701.
// Tests that if LoadModels is called for a failed type, it's a no-op.
TEST_F(SyncModelLoadManagerTest, ShouldNotStartFailedTypesUponLoadModels) {
  // Create two controllers, one with delayed model load.
  controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS);
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  GetController(BOOKMARKS)->model()->EnableManualModelStart();

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet preferred_types = {APPS, BOOKMARKS};

  model_load_manager.Configure(
      /*preferred_types_without_errors=*/preferred_types, preferred_types,
      BuildConfigureContext());

  // Bring BOOKMARKS to a STOPPING state.
  model_load_manager.Stop(SyncStopMetadataFate::KEEP_METADATA);

  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::NOT_RUNNING);
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::STOPPING);

  model_load_manager.Configure(
      /*preferred_types_without_errors=*/preferred_types, preferred_types,
      BuildConfigureContext());

  // APPS is started right away.
  ASSERT_EQ(GetController(APPS)->state(), DataTypeController::MODEL_LOADED);
  // BOOKMARKS needs to finish stopping first before it can start again.
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::STOPPING);

  // Simulate model error while the type is stopping. ModelLoadManager should
  // continue and not wait for the failed type.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure);
  GetController(BOOKMARKS)->model()->SimulateModelError(
      ModelError(FROM_HERE, "Test error"));
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::FAILED);

  // No crash from LoadModels.
}

// Regression test for crbug.com/1519806.
// Tests that stop callbacks for a type which is not in NOT_RUNNING state
// anymore are ignored.
TEST_F(SyncModelLoadManagerTest,
       ShouldHandleMultipleStopCallbacksForStoppingType) {
  // Create a controller with manual loading.
  controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS);
  GetController(BOOKMARKS)->model()->EnableManualModelStart();

  ModelLoadManager model_load_manager(&controllers_, &delegate_);
  DataTypeSet preferred_types = {BOOKMARKS};

  model_load_manager.Configure(
      /*preferred_types_without_errors=*/preferred_types, preferred_types,
      BuildConfigureContext());

  // Bring BOOKMARKS to a STOPPING state.
  model_load_manager.Stop(SyncStopMetadataFate::KEEP_METADATA);
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::STOPPING);

  // It should wait for BOOKMARKS to finish loading before notifying the data
  // type manager.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure).Times(0);

  model_load_manager.Configure(
      /*preferred_types_without_errors=*/preferred_types, preferred_types,
      BuildConfigureContext());

  // BOOKMARKS needs to finish stopping first before it can start again.
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::STOPPING);

  // Add the same stop callback again to be called after the type has finished
  // stopping.
  model_load_manager.Configure(
      /*preferred_types_without_errors=*/preferred_types, preferred_types,
      BuildConfigureContext());

  // BOOKMARKS needs to finish stopping first before it can start again.
  ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::STOPPING);

  // Finish loading of BOOKMARKS for the first time. This should first move the
  // state to NOT_RUNNING. But, as part of the load callback,
  // DataTypeController::LoadModels() will be called which will set its state
  // to MODEL_STARTING.
  GetController(BOOKMARKS)->model()->SimulateModelStartFinished();
  EXPECT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_STARTING);

  // Finish loading of BOOKMARKS. This will lead to a call to notify the
  // delegate that all the types are ready.
  EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure);
  GetController(BOOKMARKS)->model()->SimulateModelStartFinished();
  ASSERT_EQ(GetController(BOOKMARKS)->state(),
            DataTypeController::MODEL_LOADED);

  // Note: The second stop callback didn't do anything and was a no-op.
}

}  // namespace syncer