summaryrefslogtreecommitdiff
path: root/chromium/components/sync_bookmarks/bookmark_model_observer_impl_unittest.cc
blob: 190a5440bcb5219b3819719a86064455af3cd699 (plain)
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
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/sync_bookmarks/bookmark_model_observer_impl.h"

#include <algorithm>
#include <list>
#include <map>
#include <memory>
#include <utility>
#include <vector>

#include "base/callback_helpers.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/mock_callback.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/test/test_bookmark_client.h"
#include "components/favicon_base/favicon_types.h"
#include "components/sync/base/time.h"
#include "components/sync/base/unique_position.h"
#include "components/sync/protocol/bookmark_specifics.pb.h"
#include "components/sync/protocol/entity_metadata.pb.h"
#include "components/sync/protocol/entity_specifics.pb.h"
#include "components/sync/protocol/model_type_state.pb.h"
#include "components/sync_bookmarks/bookmark_specifics_conversions.h"
#include "components/sync_bookmarks/synced_bookmark_tracker.h"
#include "components/sync_bookmarks/synced_bookmark_tracker_entity.h"
#include "components/undo/bookmark_undo_service.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/image/image.h"

namespace sync_bookmarks {

namespace {

using testing::ElementsAre;
using testing::Eq;
using testing::IsEmpty;
using testing::IsNull;
using testing::Ne;
using testing::NiceMock;
using testing::NotNull;
using testing::SizeIs;
using testing::UnorderedElementsAre;

const char kBookmarkBarId[] = "bookmark_bar_id";
const char kBookmarkBarTag[] = "bookmark_bar";
const char kOtherBookmarksId[] = "other_bookmarks_id";
const char kOtherBookmarksTag[] = "other_bookmarks";
const char kMobileBookmarksId[] = "synced_bookmarks_id";
const char kMobileBookmarksTag[] = "synced_bookmarks";

// Matches |arg| of type SyncedBookmarkTrackerEntity*.
MATCHER_P(HasBookmarkNode, node, "") {
  return arg->bookmark_node() == node;
}

// Returns a single-color 16x16 image using |color|.
gfx::Image CreateTestImage(SkColor color) {
  SkBitmap bitmap;
  bitmap.allocN32Pixels(16, 16);
  bitmap.eraseColor(color);
  return gfx::Image::CreateFrom1xBitmap(bitmap);
}

class BookmarkModelObserverImplTest : public testing::Test {
 public:
  BookmarkModelObserverImplTest()
      : bookmark_tracker_(
            SyncedBookmarkTracker::CreateEmpty(sync_pb::ModelTypeState())),
        observer_(nudge_for_commit_closure_.Get(),
                  /*on_bookmark_model_being_deleted_closure=*/base::DoNothing(),
                  bookmark_tracker_.get()),
        bookmark_model_(bookmarks::TestBookmarkClient::CreateModel()) {
    bookmark_model_->AddObserver(&observer_);
    sync_pb::EntitySpecifics specifics;
    specifics.mutable_bookmark()->set_legacy_canonicalized_title(
        kBookmarkBarTag);
    bookmark_tracker_->Add(
        /*bookmark_node=*/bookmark_model()->bookmark_bar_node(),
        /*sync_id=*/kBookmarkBarId,
        /*server_version=*/0, /*creation_time=*/base::Time::Now(), specifics);
    specifics.mutable_bookmark()->set_legacy_canonicalized_title(
        kOtherBookmarksTag);
    bookmark_tracker_->Add(
        /*bookmark_node=*/bookmark_model()->other_node(),
        /*sync_id=*/kOtherBookmarksId,
        /*server_version=*/0, /*creation_time=*/base::Time::Now(), specifics);
    specifics.mutable_bookmark()->set_legacy_canonicalized_title(
        kMobileBookmarksTag);
    bookmark_tracker_->Add(
        /*bookmark_node=*/bookmark_model()->mobile_node(),
        /*sync_id=*/kMobileBookmarksId,
        /*server_version=*/0, /*creation_time=*/base::Time::Now(), specifics);
  }

  ~BookmarkModelObserverImplTest() override {
    bookmark_model_->RemoveObserver(&observer_);
  }

  void SimulateCommitResponseForAllLocalChanges() {
    for (const SyncedBookmarkTrackerEntity* entity :
         bookmark_tracker()->GetEntitiesWithLocalChanges()) {
      const std::string id = entity->metadata().server_id();
      // Don't simulate change in id for simplicity.
      bookmark_tracker()->UpdateUponCommitResponse(
          entity, id,
          /*server_version=*/1,
          /*acked_sequence_number=*/entity->metadata().sequence_number());
    }
  }

  syncer::UniquePosition PositionOf(
      const bookmarks::BookmarkNode* bookmark_node) {
    const SyncedBookmarkTrackerEntity* entity =
        bookmark_tracker()->GetEntityForBookmarkNode(bookmark_node);
    return syncer::UniquePosition::FromProto(
        entity->metadata().unique_position());
  }

  std::vector<const bookmarks::BookmarkNode*> GenerateBookmarkNodes(
      size_t num_bookmarks) {
    const std::string kTitle = "title";
    const std::string kUrl = "http://www.url.com";

    const bookmarks::BookmarkNode* bookmark_bar_node =
        bookmark_model()->bookmark_bar_node();
    std::vector<const bookmarks::BookmarkNode*> nodes;
    for (size_t i = 0; i < num_bookmarks; ++i) {
      nodes.push_back(bookmark_model()->AddURL(
          /*parent=*/bookmark_bar_node, /*index=*/i, base::UTF8ToUTF16(kTitle),
          GURL(kUrl)));
    }

    // Verify number of entities local changes. Should be the same as number of
    // new nodes.
    DCHECK_EQ(bookmark_tracker()->GetEntitiesWithLocalChanges().size(),
              num_bookmarks);

    // All bookmarks should be tracked now (including permanent nodes).
    DCHECK_EQ(bookmark_tracker()->TrackedEntitiesCountForTest(),
              3 + num_bookmarks);

    return nodes;
  }

  bookmarks::BookmarkModel* bookmark_model() { return bookmark_model_.get(); }
  SyncedBookmarkTracker* bookmark_tracker() { return bookmark_tracker_.get(); }
  BookmarkModelObserverImpl* observer() { return &observer_; }
  base::MockCallback<base::RepeatingClosure>* nudge_for_commit_closure() {
    return &nudge_for_commit_closure_;
  }
  bookmarks::TestBookmarkClient* bookmark_client() {
    return static_cast<bookmarks::TestBookmarkClient*>(
        bookmark_model_->client());
  }

 private:
  NiceMock<base::MockCallback<base::RepeatingClosure>>
      nudge_for_commit_closure_;
  std::unique_ptr<SyncedBookmarkTracker> bookmark_tracker_;
  BookmarkModelObserverImpl observer_;
  std::unique_ptr<bookmarks::BookmarkModel> bookmark_model_;
};

TEST_F(BookmarkModelObserverImplTest,
       BookmarkAddedShouldPutInTheTrackerAndNudgeForCommit) {
  const std::string kTitle = "title";
  const std::string kUrl = "http://www.url.com";

  EXPECT_CALL(*nudge_for_commit_closure(), Run());
  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* bookmark_node = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/0, base::UTF8ToUTF16(kTitle),
      GURL(kUrl));

  EXPECT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), 4U);

  std::vector<const SyncedBookmarkTrackerEntity*> local_changes =
      bookmark_tracker()->GetEntitiesWithLocalChanges();
  ASSERT_THAT(local_changes.size(), 1U);
  EXPECT_THAT(local_changes[0]->bookmark_node(), Eq(bookmark_node));
  EXPECT_THAT(local_changes[0]->metadata().server_id(),
              Eq(bookmark_node->guid().AsLowercaseString()));
}

TEST_F(BookmarkModelObserverImplTest,
       BookmarkChangedShouldUpdateTheTrackerAndNudgeForCommit) {
  const std::string kTitle1 = "title1";
  const std::string kUrl1 = "http://www.url1.com";
  const std::string kNewUrl1 = "http://www.new-url1.com";
  const std::string kTitle2 = "title2";
  const std::string kUrl2 = "http://www.url2.com";
  const std::string kNewTitle2 = "new_title2";

  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* bookmark_node1 = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/0, base::UTF8ToUTF16(kTitle1),
      GURL(kUrl1));
  const bookmarks::BookmarkNode* bookmark_node2 = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/0, base::UTF8ToUTF16(kTitle2),
      GURL(kUrl2));
  // Both bookmarks should be tracked now.
  ASSERT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), 5U);
  // There should be two local changes now for both entities.
  ASSERT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges().size(), 2U);

  SimulateCommitResponseForAllLocalChanges();

  // There should be no local changes now.
  ASSERT_TRUE(bookmark_tracker()->GetEntitiesWithLocalChanges().empty());

  // Now update the title of the 2nd node.
  EXPECT_CALL(*nudge_for_commit_closure(), Run());
  bookmark_model()->SetTitle(bookmark_node2, base::UTF8ToUTF16(kNewTitle2));
  // Node 2 should be in the local changes list.
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(),
              ElementsAre(HasBookmarkNode(bookmark_node2)));

  // Now update the url of the 1st node.
  EXPECT_CALL(*nudge_for_commit_closure(), Run());
  bookmark_model()->SetURL(bookmark_node1, GURL(kNewUrl1));

  // Node 1 and 2 should be in the local changes list.
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(),
              UnorderedElementsAre(HasBookmarkNode(bookmark_node1),
                                   HasBookmarkNode(bookmark_node2)));

  // Now update metainfo of the 1st node.
  EXPECT_CALL(*nudge_for_commit_closure(), Run());
  bookmark_model()->SetNodeMetaInfo(bookmark_node1, "key", "value");
}

TEST_F(BookmarkModelObserverImplTest,
       BookmarkMovedShouldUpdateTheTrackerAndNudgeForCommit) {
  // Build this structure:
  // bookmark_bar
  //  |- folder1
  //      |- bookmark1
  const GURL kUrl("http://www.url1.com");

  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* folder1_node = bookmark_model()->AddFolder(
      /*parent=*/bookmark_bar_node, /*index=*/0, u"folder1");
  const bookmarks::BookmarkNode* bookmark1_node = bookmark_model()->AddURL(
      /*parent=*/folder1_node, /*index=*/0, u"bookmark1", kUrl);

  // Verify number of entities local changes. Should be the same as number of
  // new nodes.
  ASSERT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges().size(), 2U);

  // All bookmarks should be tracked now.
  ASSERT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), 5U);

  SimulateCommitResponseForAllLocalChanges();

  // There should be no local changes now.
  ASSERT_TRUE(bookmark_tracker()->GetEntitiesWithLocalChanges().empty());

  // Now change it to this structure.
  // Build this structure:
  // bookmark_bar
  //  |- bookmark1
  //  |- folder1

  EXPECT_CALL(*nudge_for_commit_closure(), Run());
  bookmark_model()->Move(bookmark1_node, bookmark_bar_node, 0);
  EXPECT_TRUE(PositionOf(bookmark1_node).LessThan(PositionOf(folder1_node)));
}

TEST_F(BookmarkModelObserverImplTest,
       ReorderChildrenShouldUpdateTheTrackerAndNudgeForCommit) {
  std::vector<const bookmarks::BookmarkNode*> nodes =
      GenerateBookmarkNodes(/*num_bookmarks=*/4);

  SimulateCommitResponseForAllLocalChanges();

  // Reorder it to be (2 bookmarks have been moved):
  // bookmark_bar
  //  |- node1
  //  |- node3
  //  |- node0
  //  |- node2
  bookmark_model()->ReorderChildren(bookmark_model()->bookmark_bar_node(),
                                    {nodes[1], nodes[3], nodes[0], nodes[2]});
  EXPECT_TRUE(PositionOf(nodes[1]).LessThan(PositionOf(nodes[3])));
  EXPECT_TRUE(PositionOf(nodes[3]).LessThan(PositionOf(nodes[0])));
  EXPECT_TRUE(PositionOf(nodes[0]).LessThan(PositionOf(nodes[2])));

  // Only 2 moved nodes should have local changes to commit.
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(), SizeIs(2));
}

TEST_F(BookmarkModelObserverImplTest,
       ShouldReorderChildrenAndUpdateOnlyMovedToRightBookmark) {
  std::vector<const bookmarks::BookmarkNode*> nodes =
      GenerateBookmarkNodes(/*num_bookmarks=*/4);

  SimulateCommitResponseForAllLocalChanges();

  // Reorder it to be:
  // bookmark_bar
  //  |- node1
  //  |- node2
  //  |- node0 (moved)
  //  |- node3
  bookmark_model()->ReorderChildren(bookmark_model()->bookmark_bar_node(),
                                    {nodes[1], nodes[2], nodes[0], nodes[3]});
  EXPECT_TRUE(PositionOf(nodes[1]).LessThan(PositionOf(nodes[2])));
  EXPECT_TRUE(PositionOf(nodes[2]).LessThan(PositionOf(nodes[0])));
  EXPECT_TRUE(PositionOf(nodes[0]).LessThan(PositionOf(nodes[3])));

  // Only one moved node should have local changes to commit.
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(),
              UnorderedElementsAre(HasBookmarkNode(nodes[0])));
}

TEST_F(BookmarkModelObserverImplTest,
       ShouldReorderChildrenAndUpdateOnlyMovedToLeftBookmark) {
  std::vector<const bookmarks::BookmarkNode*> nodes =
      GenerateBookmarkNodes(/*num_bookmarks=*/4);

  SimulateCommitResponseForAllLocalChanges();

  // Reorder it to be:
  // bookmark_bar
  //  |- node0
  //  |- node3 (moved)
  //  |- node1
  //  |- node2
  bookmark_model()->ReorderChildren(bookmark_model()->bookmark_bar_node(),
                                    {nodes[0], nodes[3], nodes[1], nodes[2]});
  EXPECT_TRUE(PositionOf(nodes[0]).LessThan(PositionOf(nodes[3])));
  EXPECT_TRUE(PositionOf(nodes[3]).LessThan(PositionOf(nodes[1])));
  EXPECT_TRUE(PositionOf(nodes[1]).LessThan(PositionOf(nodes[2])));

  // Only one moved node should have local changes to commit.
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(),
              UnorderedElementsAre(HasBookmarkNode(nodes[3])));
}

TEST_F(BookmarkModelObserverImplTest,
       ShouldReorderWhenBookmarkMovedToLastPosition) {
  std::vector<const bookmarks::BookmarkNode*> nodes =
      GenerateBookmarkNodes(/*num_bookmarks=*/4);

  SimulateCommitResponseForAllLocalChanges();

  // Reorder it to be:
  // bookmark_bar
  //  |- node1
  //  |- node2
  //  |- node3
  //  |- node0 (moved)
  bookmark_model()->ReorderChildren(bookmark_model()->bookmark_bar_node(),
                                    {nodes[1], nodes[2], nodes[3], nodes[0]});
  EXPECT_TRUE(PositionOf(nodes[1]).LessThan(PositionOf(nodes[2])));
  EXPECT_TRUE(PositionOf(nodes[2]).LessThan(PositionOf(nodes[3])));
  EXPECT_TRUE(PositionOf(nodes[3]).LessThan(PositionOf(nodes[0])));

  // Only one moved node should have local changes to commit.
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(),
              UnorderedElementsAre(HasBookmarkNode(nodes[0])));
}

TEST_F(BookmarkModelObserverImplTest,
       ShouldReorderWhenBookmarkMovedToFirstPosition) {
  std::vector<const bookmarks::BookmarkNode*> nodes =
      GenerateBookmarkNodes(/*num_bookmarks=*/4);

  SimulateCommitResponseForAllLocalChanges();

  // Reorder it to be:
  // bookmark_bar
  //  |- node3 (moved)
  //  |- node0
  //  |- node1
  //  |- node2
  bookmark_model()->ReorderChildren(bookmark_model()->bookmark_bar_node(),
                                    {nodes[3], nodes[0], nodes[1], nodes[2]});
  EXPECT_TRUE(PositionOf(nodes[3]).LessThan(PositionOf(nodes[0])));
  EXPECT_TRUE(PositionOf(nodes[0]).LessThan(PositionOf(nodes[1])));
  EXPECT_TRUE(PositionOf(nodes[1]).LessThan(PositionOf(nodes[2])));

  // Only one moved node should have local changes to commit.
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(),
              UnorderedElementsAre(HasBookmarkNode(nodes[3])));
}

TEST_F(BookmarkModelObserverImplTest, ShouldReorderWhenAllBookmarksReversed) {
  // In this case almost all the bookmarks should be updated apart from only one
  // bookmark.
  std::vector<const bookmarks::BookmarkNode*> nodes =
      GenerateBookmarkNodes(/*num_bookmarks=*/4);

  SimulateCommitResponseForAllLocalChanges();

  // Reorder it to be (all nodes are moved):
  // bookmark_bar
  //  |- node3
  //  |- node2
  //  |- node1
  //  |- node0
  bookmark_model()->ReorderChildren(bookmark_model()->bookmark_bar_node(),
                                    {nodes[3], nodes[2], nodes[1], nodes[0]});
  EXPECT_TRUE(PositionOf(nodes[3]).LessThan(PositionOf(nodes[2])));
  EXPECT_TRUE(PositionOf(nodes[2]).LessThan(PositionOf(nodes[1])));
  EXPECT_TRUE(PositionOf(nodes[1]).LessThan(PositionOf(nodes[0])));

  // Do not verify which nodes exactly have been updated, it depends on the
  // implementation and any of the nodes may become a base node to calculate
  // relative positions of all other nodes.
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(), SizeIs(3));
}

TEST_F(BookmarkModelObserverImplTest,
       ShouldNotReorderIfAllBookmarksStillOrdered) {
  std::vector<const bookmarks::BookmarkNode*> nodes =
      GenerateBookmarkNodes(/*num_bookmarks=*/4);

  SimulateCommitResponseForAllLocalChanges();

  // Keep the original order.
  bookmark_model()->ReorderChildren(bookmark_model()->bookmark_bar_node(),
                                    {nodes[0], nodes[1], nodes[2], nodes[3]});
  EXPECT_TRUE(PositionOf(nodes[0]).LessThan(PositionOf(nodes[1])));
  EXPECT_TRUE(PositionOf(nodes[1]).LessThan(PositionOf(nodes[2])));
  EXPECT_TRUE(PositionOf(nodes[2]).LessThan(PositionOf(nodes[3])));

  // The bookmarks remain in the same order, nothing to commit.
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(), IsEmpty());
}

TEST_F(BookmarkModelObserverImplTest,
       BookmarkRemovalShouldUpdateTheTrackerAndNudgeForCommit) {
  // Build this structure:
  // bookmark_bar
  //  |- folder1
  //      |- bookmark1
  //      |- folder2
  //          |- bookmark2
  //          |- bookmark3

  // and then delete folder2.
  const GURL kUrl("http://www.url1.com");

  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* folder1_node = bookmark_model()->AddFolder(
      /*parent=*/bookmark_bar_node, /*index=*/0, u"folder1");
  const bookmarks::BookmarkNode* bookmark1_node = bookmark_model()->AddURL(
      /*parent=*/folder1_node, /*index=*/0, u"bookmark1", kUrl);
  const bookmarks::BookmarkNode* folder2_node = bookmark_model()->AddFolder(
      /*parent=*/folder1_node, /*index=*/1, u"folder2");
  const bookmarks::BookmarkNode* bookmark2_node = bookmark_model()->AddURL(
      /*parent=*/folder2_node, /*index=*/0, u"bookmark2", kUrl);
  const bookmarks::BookmarkNode* bookmark3_node = bookmark_model()->AddURL(
      /*parent=*/folder2_node, /*index=*/1, u"bookmark3", kUrl);

  // All bookmarks should be tracked now.
  ASSERT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), 8U);

  SimulateCommitResponseForAllLocalChanges();

  // There should be no local changes now.
  ASSERT_TRUE(bookmark_tracker()->GetEntitiesWithLocalChanges().empty());

  const SyncedBookmarkTrackerEntity* folder2_entity =
      bookmark_tracker()->GetEntityForBookmarkNode(folder2_node);
  const SyncedBookmarkTrackerEntity* bookmark2_entity =
      bookmark_tracker()->GetEntityForBookmarkNode(bookmark2_node);
  const SyncedBookmarkTrackerEntity* bookmark3_entity =
      bookmark_tracker()->GetEntityForBookmarkNode(bookmark3_node);

  ASSERT_FALSE(folder2_entity->metadata().is_deleted());
  ASSERT_FALSE(bookmark2_entity->metadata().is_deleted());
  ASSERT_FALSE(bookmark3_entity->metadata().is_deleted());

  const std::string& folder2_entity_id = folder2_entity->metadata().server_id();
  const std::string& bookmark2_entity_id =
      bookmark2_entity->metadata().server_id();
  const std::string& bookmark3_entity_id =
      bookmark3_entity->metadata().server_id();
  // Delete folder2.
  EXPECT_CALL(*nudge_for_commit_closure(), Run());
  bookmark_model()->Remove(folder2_node);

  // folder2, bookmark2, and bookmark3 should be marked deleted.
  EXPECT_TRUE(bookmark_tracker()
                  ->GetEntityForSyncId(folder2_entity_id)
                  ->metadata()
                  .is_deleted());
  EXPECT_TRUE(bookmark_tracker()
                  ->GetEntityForSyncId(bookmark2_entity_id)
                  ->metadata()
                  .is_deleted());
  EXPECT_TRUE(bookmark_tracker()
                  ->GetEntityForSyncId(bookmark3_entity_id)
                  ->metadata()
                  .is_deleted());

  // folder2, bookmark2, and bookmark3 should be in the local changes to be
  // committed and folder2 deletion should be the last one (after all children
  // deletions).
  EXPECT_THAT(
      bookmark_tracker()->GetEntitiesWithLocalChanges(),
      ElementsAre(bookmark_tracker()->GetEntityForSyncId(bookmark2_entity_id),
                  bookmark_tracker()->GetEntityForSyncId(bookmark3_entity_id),
                  bookmark_tracker()->GetEntityForSyncId(folder2_entity_id)));

  // folder1 and bookmark1 are still tracked.
  EXPECT_TRUE(bookmark_tracker()->GetEntityForBookmarkNode(folder1_node));
  EXPECT_TRUE(bookmark_tracker()->GetEntityForBookmarkNode(bookmark1_node));
}

TEST_F(BookmarkModelObserverImplTest,
       BookmarkCreationAndRemovalShouldRequireTwoCommitResponsesBeforeRemoval) {
  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* folder_node = bookmark_model()->AddFolder(
      /*parent=*/bookmark_bar_node, /*index=*/0, u"folder");

  // Node should be tracked now.
  ASSERT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), 4U);
  const SyncedBookmarkTrackerEntity* entity =
      bookmark_tracker()->GetEntityForBookmarkNode(folder_node);
  const std::string id = entity->metadata().server_id();
  ASSERT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges().size(), 1U);

  bookmark_tracker()->MarkCommitMayHaveStarted(entity);

  // Remove the folder.
  bookmark_model()->Remove(folder_node);

  // Simulate a commit response for the first commit request (the creation).
  // Don't simulate change in id for simplicity.
  bookmark_tracker()->UpdateUponCommitResponse(entity, id,
                                               /*server_version=*/1,
                                               /*acked_sequence_number=*/1);

  // There should still be one local change (the deletion).
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges().size(), 1U);

  // Entity is still tracked.
  EXPECT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), 4U);

  // Commit the deletion.
  bookmark_tracker()->UpdateUponCommitResponse(entity, id,
                                               /*server_version=*/2,
                                               /*acked_sequence_number=*/2);
  // Entity should have been dropped.
  EXPECT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), 3U);
}

TEST_F(BookmarkModelObserverImplTest,
       BookmarkCreationAndRemovalBeforeCommitRequestShouldBeRemovedDirectly) {
  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* folder_node = bookmark_model()->AddFolder(
      /*parent=*/bookmark_bar_node, /*index=*/0, u"folder");

  // Node should be tracked now.
  ASSERT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), 4U);
  const std::string id = bookmark_tracker()
                             ->GetEntityForBookmarkNode(folder_node)
                             ->metadata()
                             .server_id();
  ASSERT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges().size(), 1U);

  // Remove the folder.
  bookmark_model()->Remove(folder_node);

  // Entity should have been dropped.
  EXPECT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), 3U);
}

TEST_F(BookmarkModelObserverImplTest, ShouldPositionSiblings) {
  const std::string kTitle = "title";
  const std::string kUrl = "http://www.url.com";

  // Build this structure:
  // bookmark_bar
  //  |- node1
  //  |- node2
  // Expectation:
  //  p1 < p2

  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* bookmark_node1 = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/0, base::UTF8ToUTF16(kTitle),
      GURL(kUrl));

  const bookmarks::BookmarkNode* bookmark_node2 = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/1, base::UTF8ToUTF16(kTitle),
      GURL(kUrl));

  EXPECT_TRUE(PositionOf(bookmark_node1).LessThan(PositionOf(bookmark_node2)));

  // Now insert node3 at index 1 to build this structure:
  // bookmark_bar
  //  |- node1
  //  |- node3
  //  |- node2
  // Expectation:
  //  p1 < p2 (still holds)
  //  p1 < p3
  //  p3 < p2

  const bookmarks::BookmarkNode* bookmark_node3 = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/1, base::UTF8ToUTF16(kTitle),
      GURL(kUrl));
  EXPECT_THAT(bookmark_tracker()->TrackedEntitiesCountForTest(), Eq(6U));

  EXPECT_TRUE(PositionOf(bookmark_node1).LessThan(PositionOf(bookmark_node2)));
  EXPECT_TRUE(PositionOf(bookmark_node1).LessThan(PositionOf(bookmark_node3)));
  EXPECT_TRUE(PositionOf(bookmark_node3).LessThan(PositionOf(bookmark_node2)));
}

TEST_F(BookmarkModelObserverImplTest, ShouldNotSyncUnsyncableBookmarks) {
  auto client = std::make_unique<bookmarks::TestBookmarkClient>();
  bookmarks::BookmarkNode* managed_node = client->EnableManagedNode();

  std::unique_ptr<bookmarks::BookmarkModel> model =
      bookmarks::TestBookmarkClient::CreateModelWithClient(std::move(client));

  std::unique_ptr<SyncedBookmarkTracker> bookmark_tracker =
      SyncedBookmarkTracker::CreateEmpty(sync_pb::ModelTypeState());
  sync_pb::EntitySpecifics specifics;
  specifics.mutable_bookmark()->set_legacy_canonicalized_title(kBookmarkBarTag);
  *specifics.mutable_bookmark()->mutable_unique_position() =
      syncer::UniquePosition::InitialPosition(
          syncer::UniquePosition::RandomSuffix())
          .ToProto();
  bookmark_tracker->Add(
      /*bookmark_node=*/model->bookmark_bar_node(),
      /*sync_id=*/kBookmarkBarId,
      /*server_version=*/0, /*creation_time=*/base::Time::Now(), specifics);
  specifics.mutable_bookmark()->set_legacy_canonicalized_title(
      kOtherBookmarksTag);
  bookmark_tracker->Add(
      /*bookmark_node=*/model->other_node(),
      /*sync_id=*/kOtherBookmarksId,
      /*server_version=*/0, /*creation_time=*/base::Time::Now(), specifics);
  specifics.mutable_bookmark()->set_legacy_canonicalized_title(
      kMobileBookmarksTag);
  bookmark_tracker->Add(
      /*bookmark_node=*/model->mobile_node(),
      /*sync_id=*/kMobileBookmarksId,
      /*server_version=*/0, /*creation_time=*/base::Time::Now(), specifics);
  BookmarkModelObserverImpl observer(
      nudge_for_commit_closure()->Get(),
      /*on_bookmark_model_being_deleted_closure=*/base::DoNothing(),
      bookmark_tracker.get());

  model->AddObserver(&observer);

  EXPECT_CALL(*nudge_for_commit_closure(), Run()).Times(0);
  // In the TestBookmarkClient, descendants of managed nodes shouldn't be
  // synced.
  const bookmarks::BookmarkNode* unsyncable_node =
      model->AddURL(/*parent=*/managed_node, /*index=*/0, u"Title",
                    GURL("http://www.url.com"));
  // Only permanent folders should be tracked.
  EXPECT_THAT(bookmark_tracker->TrackedEntitiesCountForTest(), 3U);

  EXPECT_CALL(*nudge_for_commit_closure(), Run()).Times(0);
  // In the TestBookmarkClient, descendants of managed nodes shouldn't be
  // synced.
  model->SetTitle(unsyncable_node, u"NewTitle");
  // Only permanent folders should be tracked.
  EXPECT_THAT(bookmark_tracker->TrackedEntitiesCountForTest(), 3U);

  EXPECT_CALL(*nudge_for_commit_closure(), Run()).Times(0);
  // In the TestBookmarkClient, descendants of managed nodes shouldn't be
  // synced.
  model->Remove(unsyncable_node);

  // Only permanent folders should be tracked.
  EXPECT_THAT(bookmark_tracker->TrackedEntitiesCountForTest(), 3U);
  model->RemoveObserver(&observer);
}

TEST_F(BookmarkModelObserverImplTest, ShouldAddChildrenInArbitraryOrder) {
  std::unique_ptr<SyncedBookmarkTracker> bookmark_tracker =
      SyncedBookmarkTracker::CreateEmpty(sync_pb::ModelTypeState());
  BookmarkModelObserverImpl observer(
      /*nudge_for_commit_closure=*/base::DoNothing(),
      /*on_bookmark_model_being_deleted_closure=*/base::DoNothing(),
      bookmark_tracker.get());
  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  // Add the bookmark bar to the tracker.
  sync_pb::EntitySpecifics specifics;
  specifics.mutable_bookmark()->set_legacy_canonicalized_title(kBookmarkBarTag);
  *specifics.mutable_bookmark()->mutable_unique_position() =
      syncer::UniquePosition::InitialPosition(
          syncer::UniquePosition::RandomSuffix())
          .ToProto();
  bookmark_tracker->Add(
      /*bookmark_node=*/bookmark_model()->bookmark_bar_node(),
      /*sync_id=*/kBookmarkBarId,
      /*server_version=*/0, /*creation_time=*/base::Time::Now(), specifics);

  // Build this structure:
  // bookmark_bar
  //  |- folder0
  //  |- folder1
  //  |- folder2
  //  |- folder3
  //  |- folder4

  const bookmarks::BookmarkNode* nodes[5];
  for (size_t i = 0; i < 5; i++) {
    nodes[i] = bookmark_model()->AddFolder(
        /*parent=*/bookmark_bar_node, /*index=*/i,
        base::UTF8ToUTF16("folder" + std::to_string(i)));
  }

  // Now simulate calling the observer as if the nodes are added in that order.
  // 4,0,2,3,1.
  observer.BookmarkNodeAdded(bookmark_model(), bookmark_bar_node, 4);
  observer.BookmarkNodeAdded(bookmark_model(), bookmark_bar_node, 0);
  observer.BookmarkNodeAdded(bookmark_model(), bookmark_bar_node, 2);
  observer.BookmarkNodeAdded(bookmark_model(), bookmark_bar_node, 3);
  observer.BookmarkNodeAdded(bookmark_model(), bookmark_bar_node, 1);

  ASSERT_THAT(bookmark_tracker->TrackedEntitiesCountForTest(), 6U);

  // Check that position information match the children order.
  EXPECT_TRUE(PositionOf(nodes[0]).LessThan(PositionOf(nodes[1])));
  EXPECT_TRUE(PositionOf(nodes[1]).LessThan(PositionOf(nodes[2])));
  EXPECT_TRUE(PositionOf(nodes[2]).LessThan(PositionOf(nodes[3])));
  EXPECT_TRUE(PositionOf(nodes[3]).LessThan(PositionOf(nodes[4])));
}

TEST_F(BookmarkModelObserverImplTest,
       ShouldCallOnBookmarkModelBeingDeletedClosure) {
  std::unique_ptr<SyncedBookmarkTracker> bookmark_tracker =
      SyncedBookmarkTracker::CreateEmpty(sync_pb::ModelTypeState());

  NiceMock<base::MockCallback<base::OnceClosure>>
      on_bookmark_model_being_deleted_closure_mock;

  BookmarkModelObserverImpl observer(
      /*nudge_for_commit_closure=*/base::DoNothing(),
      on_bookmark_model_being_deleted_closure_mock.Get(),
      bookmark_tracker.get());

  EXPECT_CALL(on_bookmark_model_being_deleted_closure_mock, Run());
  observer.BookmarkModelBeingDeleted(/*model=*/nullptr);
}

TEST_F(BookmarkModelObserverImplTest, ShouldNotIssueCommitUponFaviconLoad) {
  const GURL kBookmarkUrl("http://www.url.com");
  const GURL kIconUrl("http://www.url.com/favicon.ico");
  const SkColor kColor = SK_ColorRED;

  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* bookmark_node = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/0, u"title", kBookmarkUrl);

  ASSERT_TRUE(bookmark_client()->SimulateFaviconLoaded(
      kBookmarkUrl, kIconUrl, CreateTestImage(kColor)));
  SimulateCommitResponseForAllLocalChanges();
  ASSERT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(), IsEmpty());

  const SyncedBookmarkTrackerEntity* entity =
      bookmark_tracker()->GetEntityForBookmarkNode(bookmark_node);
  ASSERT_THAT(entity, NotNull());
  ASSERT_TRUE(entity->metadata().has_bookmark_favicon_hash());
  const uint32_t initial_favicon_hash =
      entity->metadata().bookmark_favicon_hash();

  // Clear the specifics hash (as if the proto definition would have changed).
  // This is needed because otherwise the commit is trivially optimized away
  // (i.e. literally nothing changed).
  bookmark_tracker()->ClearSpecificsHashForTest(entity);

  // Mimic the very same favicon being loaded again (similar to a startup
  // scenario). Note that OnFaviconsChanged() needs no icon URL to invalidate
  // the favicon of a bookmark.
  EXPECT_CALL(*nudge_for_commit_closure(), Run()).Times(0);
  bookmark_model()->OnFaviconsChanged(/*page_urls=*/{kBookmarkUrl},
                                      /*icon_url=*/GURL());
  ASSERT_TRUE(bookmark_node->is_favicon_loading());
  ASSERT_TRUE(bookmark_client()->SimulateFaviconLoaded(
      kBookmarkUrl, kIconUrl, CreateTestImage(kColor)));

  EXPECT_TRUE(entity->metadata().has_bookmark_favicon_hash());
  EXPECT_THAT(entity->metadata().bookmark_favicon_hash(),
              Eq(initial_favicon_hash));
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(), IsEmpty());
}

TEST_F(BookmarkModelObserverImplTest, ShouldCommitLocalFaviconChange) {
  const GURL kBookmarkUrl("http://www.url.com");
  const GURL kInitialIconUrl("http://www.url.com/initial.ico");
  const GURL kFinalIconUrl("http://www.url.com/final.ico");

  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* bookmark_node = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/0, u"title", kBookmarkUrl);

  ASSERT_TRUE(bookmark_node->is_favicon_loading());
  ASSERT_TRUE(bookmark_client()->SimulateFaviconLoaded(
      kBookmarkUrl, kInitialIconUrl, CreateTestImage(SK_ColorRED)));
  SimulateCommitResponseForAllLocalChanges();
  ASSERT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(), IsEmpty());

  const SyncedBookmarkTrackerEntity* entity =
      bookmark_tracker()->GetEntityForBookmarkNode(bookmark_node);
  ASSERT_THAT(entity, NotNull());
  ASSERT_TRUE(entity->metadata().has_bookmark_favicon_hash());
  const uint32_t initial_favicon_hash =
      entity->metadata().bookmark_favicon_hash();

  // A favicon change should trigger a commit nudge once the favicon loads, but
  // not earlier. Note that OnFaviconsChanged() needs no icon URL to invalidate
  // the favicon of a bookmark.
  EXPECT_CALL(*nudge_for_commit_closure(), Run()).Times(0);
  bookmark_model()->OnFaviconsChanged(/*page_urls=*/{kBookmarkUrl},
                                      /*icon_url=*/GURL());
  ASSERT_TRUE(bookmark_node->is_favicon_loading());

  EXPECT_CALL(*nudge_for_commit_closure(), Run());
  ASSERT_TRUE(bookmark_client()->SimulateFaviconLoaded(
      kBookmarkUrl, kFinalIconUrl, CreateTestImage(SK_ColorBLUE)));

  EXPECT_TRUE(entity->metadata().has_bookmark_favicon_hash());
  EXPECT_THAT(entity->metadata().bookmark_favicon_hash(),
              Ne(initial_favicon_hash));
  EXPECT_THAT(bookmark_tracker()->GetEntitiesWithLocalChanges(),
              ElementsAre(HasBookmarkNode(bookmark_node)));
}

TEST_F(BookmarkModelObserverImplTest,
       ShouldNudgeForCommitOnFaviconLoadAfterRestart) {
  const GURL kBookmarkUrl("http://www.url.com");
  const GURL kIconUrl("http://www.url.com/favicon.ico");
  const SkColor kColor = SK_ColorRED;

  // Simulate work after restart. Add a new bookmark to a model and its
  // specifics to the tracker without loading favicon.
  bookmark_model()->RemoveObserver(observer());

  // Add a new node with specifics and mark it unsynced.
  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* bookmark_node = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/0, u"title", kBookmarkUrl);

  sync_pb::EntitySpecifics specifics = CreateSpecificsFromBookmarkNode(
      bookmark_node, bookmark_model(),
      syncer::UniquePosition::InitialPosition(
          syncer::UniquePosition::RandomSuffix())
          .ToProto(),
      /*force_favicon_load=*/false);
  const gfx::Image favicon_image = CreateTestImage(kColor);
  scoped_refptr<base::RefCountedMemory> favicon_bytes =
      favicon_image.As1xPNGBytes();
  specifics.mutable_bookmark()->set_favicon(favicon_bytes->front(),
                                            favicon_bytes->size());
  specifics.mutable_bookmark()->set_icon_url(kIconUrl.spec());
  *specifics.mutable_bookmark()->mutable_unique_position() =
      syncer::UniquePosition::InitialPosition(
          syncer::UniquePosition::RandomSuffix())
          .ToProto();

  const SyncedBookmarkTrackerEntity* entity = bookmark_tracker()->Add(
      bookmark_node, "id", /*server_version=*/1, base::Time::Now(), specifics);
  bookmark_tracker()->IncrementSequenceNumber(entity);

  // Restore state.
  bookmark_model()->AddObserver(observer());

  // Currently there is the unsynced |entity| which has no loaded favicon.
  ASSERT_FALSE(bookmark_node->is_favicon_loaded());
  ASSERT_TRUE(entity->IsUnsynced());

  EXPECT_CALL(*nudge_for_commit_closure(), Run());
  bookmark_model()->GetFavicon(bookmark_node);
  ASSERT_TRUE(bookmark_client()->SimulateFaviconLoaded(
      kBookmarkUrl, kIconUrl, CreateTestImage(SK_ColorRED)));
}

TEST_F(BookmarkModelObserverImplTest,
       ShouldAddRestoredBookmarkWhenTombstoneCommitMayHaveStarted) {
  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* folder =
      bookmark_model()->AddFolder(bookmark_bar_node, 0, u"Title");
  const syncer::ClientTagHash folder_client_tag_hash =
      SyncedBookmarkTracker::GetClientTagHashFromGUID(folder->guid());
  // Check that the bookmark was added by observer.
  const SyncedBookmarkTrackerEntity* folder_entity =
      bookmark_tracker()->GetEntityForBookmarkNode(folder);
  ASSERT_THAT(folder_entity, NotNull());
  ASSERT_TRUE(folder_entity->IsUnsynced());
  SimulateCommitResponseForAllLocalChanges();
  ASSERT_FALSE(folder_entity->IsUnsynced());

  // Now delete the entity and restore it with the same bookmark node.
  BookmarkUndoService undo_service;
  undo_service.Start(bookmark_model());
  bookmark_model()->Remove(folder);

  // The removed bookmark must be saved in the undo service.
  ASSERT_EQ(undo_service.undo_manager()->undo_count(), 1u);
  ASSERT_THAT(bookmark_tracker()->GetEntityForBookmarkNode(folder), IsNull());

  // Check that the entity is a tombstone now.
  const std::vector<const SyncedBookmarkTrackerEntity*> local_changes =
      bookmark_tracker()->GetEntitiesWithLocalChanges();
  ASSERT_THAT(local_changes, ElementsAre(folder_entity));
  ASSERT_TRUE(folder_entity->metadata().is_deleted());
  ASSERT_EQ(
      bookmark_tracker()->GetEntityForClientTagHash(folder_client_tag_hash),
      folder_entity);

  // Restore the removed bookmark.
  undo_service.undo_manager()->Undo();
  undo_service.Shutdown();

  EXPECT_EQ(folder_entity,
            bookmark_tracker()->GetEntityForBookmarkNode(folder));
  EXPECT_EQ(
      bookmark_tracker()->GetEntityForClientTagHash(folder_client_tag_hash),
      folder_entity);
  EXPECT_TRUE(folder_entity->IsUnsynced());
  EXPECT_FALSE(folder_entity->metadata().is_deleted());
  EXPECT_EQ(folder_entity->bookmark_node(), folder);
}

// Tests that the bookmark entity will be committed if its favicon is deleted.
TEST_F(BookmarkModelObserverImplTest, ShouldCommitOnDeleteFavicon) {
  const GURL kBookmarkUrl("http://www.url.com");
  const GURL kIconUrl("http://www.url.com/favicon.ico");

  // Add a new node with specifics.
  const bookmarks::BookmarkNode* bookmark_bar_node =
      bookmark_model()->bookmark_bar_node();
  const bookmarks::BookmarkNode* bookmark_node = bookmark_model()->AddURL(
      /*parent=*/bookmark_bar_node, /*index=*/0, u"title", kBookmarkUrl);

  ASSERT_TRUE(bookmark_node->is_favicon_loading());
  ASSERT_TRUE(bookmark_client()->SimulateFaviconLoaded(
      kBookmarkUrl, kIconUrl, CreateTestImage(SK_ColorRED)));

  const SyncedBookmarkTrackerEntity* entity =
      bookmark_tracker()->GetEntityForBookmarkNode(bookmark_node);
  ASSERT_THAT(entity, NotNull());
  ASSERT_TRUE(entity->IsUnsynced());

  SimulateCommitResponseForAllLocalChanges();

  ASSERT_FALSE(bookmark_tracker()->HasLocalChanges());

  // Delete favicon and check that its deletion is committed.
  bookmark_model()->OnFaviconsChanged({kBookmarkUrl}, GURL());
  ASSERT_TRUE(bookmark_node->is_favicon_loading());
  ASSERT_TRUE(bookmark_client()->SimulateEmptyFaviconLoaded(kBookmarkUrl));

  EXPECT_TRUE(entity->IsUnsynced());
}

}  // namespace

}  // namespace sync_bookmarks