forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofile_sync_service_bookmark_unittest.cc
2601 lines (2234 loc) · 98 KB
/
profile_sync_service_bookmark_unittest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 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.
// TODO(akalin): This file is basically just a unit test for
// BookmarkChangeProcessor. Write unit tests for
// BookmarkModelAssociator separately.
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <memory>
#include <queue>
#include <stack>
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/test_message_loop.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/bookmarks/browser/base_bookmark_model_observer.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/browser/bookmark_utils.h"
#include "components/bookmarks/managed/managed_bookmark_service.h"
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "components/bookmarks/test/test_bookmark_client.h"
#include "components/browser_sync/profile_sync_test_util.h"
#include "components/sync/driver/fake_sync_client.h"
#include "components/sync/engine/engine_util.h"
#include "components/sync/model/data_type_error_handler.h"
#include "components/sync/model/data_type_error_handler_mock.h"
#include "components/sync/model/sync_error.h"
#include "components/sync/model/sync_merge_result.h"
#include "components/sync/syncable/change_record.h"
#include "components/sync/syncable/mutable_entry.h"
#include "components/sync/syncable/read_node.h"
#include "components/sync/syncable/read_transaction.h"
#include "components/sync/syncable/syncable_id.h"
#include "components/sync/syncable/syncable_util.h"
#include "components/sync/syncable/syncable_write_transaction.h"
#include "components/sync/syncable/test_user_share.h"
#include "components/sync/syncable/write_node.h"
#include "components/sync/syncable/write_transaction.h"
#include "components/sync_bookmarks/bookmark_change_processor.h"
#include "components/sync_bookmarks/bookmark_model_associator.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using sync_bookmarks::BookmarkChangeProcessor;
using sync_bookmarks::BookmarkModelAssociator;
using syncer::BaseNode;
using testing::_;
using testing::Return;
using testing::StrictMock;
namespace browser_sync {
namespace {
#if defined(OS_ANDROID) || defined(OS_IOS)
static const bool kExpectMobileBookmarks = true;
#else
static const bool kExpectMobileBookmarks = false;
#endif // defined(OS_ANDROID) || defined(OS_IOS)
std::string ReturnEmptyString() {
return std::string();
}
void MakeServerUpdate(syncer::WriteTransaction* trans,
syncer::WriteNode* node) {
syncer::syncable::ChangeEntryIDAndUpdateChildren(
trans->GetWrappedWriteTrans(), node->GetMutableEntryForTest(),
syncer::syncable::Id::CreateFromServerId(
base::Int64ToString(node->GetId())));
node->GetMutableEntryForTest()->PutBaseVersion(10);
node->GetMutableEntryForTest()->PutIsUnappliedUpdate(true);
}
void MakeServerUpdate(syncer::WriteTransaction* trans, int64_t id) {
syncer::WriteNode node(trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
MakeServerUpdate(trans, &node);
}
// FakeServerChange constructs a list of syncer::ChangeRecords while modifying
// the sync model, and can pass the ChangeRecord list to a
// syncer::SyncObserver (i.e., the ProfileSyncService) to test the client
// change-application behavior.
// Tests using FakeServerChange should be careful to avoid back-references,
// since FakeServerChange will send the edits in the order specified.
class FakeServerChange {
public:
explicit FakeServerChange(syncer::WriteTransaction* trans) : trans_(trans) {}
// Pretend that the server told the syncer to add a bookmark object.
int64_t AddWithMetaInfo(const std::string& title,
const std::string& url,
const BookmarkNode::MetaInfoMap* meta_info_map,
bool is_folder,
int64_t parent_id,
int64_t predecessor_id) {
syncer::ReadNode parent(trans_);
EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
syncer::WriteNode node(trans_);
if (predecessor_id == 0) {
EXPECT_TRUE(node.InitBookmarkByCreation(parent, nullptr));
} else {
syncer::ReadNode predecessor(trans_);
EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
EXPECT_TRUE(node.InitBookmarkByCreation(parent, &predecessor));
}
EXPECT_EQ(node.GetPredecessorId(), predecessor_id);
EXPECT_EQ(node.GetParentId(), parent_id);
node.SetIsFolder(is_folder);
node.SetTitle(title);
sync_pb::BookmarkSpecifics specifics(node.GetBookmarkSpecifics());
const base::Time creation_time(base::Time::Now());
specifics.set_creation_time_us(creation_time.ToInternalValue());
if (!is_folder)
specifics.set_url(url);
if (meta_info_map)
SetNodeMetaInfo(*meta_info_map, &specifics);
node.SetBookmarkSpecifics(specifics);
syncer::ChangeRecord record;
record.action = syncer::ChangeRecord::ACTION_ADD;
record.id = node.GetId();
changes_.push_back(record);
return node.GetId();
}
int64_t Add(const std::string& title,
const std::string& url,
bool is_folder,
int64_t parent_id,
int64_t predecessor_id) {
return AddWithMetaInfo(title, url, nullptr, is_folder, parent_id,
predecessor_id);
}
// Add a bookmark folder.
int64_t AddFolder(const std::string& title,
int64_t parent_id,
int64_t predecessor_id) {
return Add(title, std::string(), true, parent_id, predecessor_id);
}
int64_t AddFolderWithMetaInfo(const std::string& title,
const BookmarkNode::MetaInfoMap* meta_info_map,
int64_t parent_id,
int64_t predecessor_id) {
return AddWithMetaInfo(title, std::string(), meta_info_map, true, parent_id,
predecessor_id);
}
// Add a bookmark.
int64_t AddURL(const std::string& title,
const std::string& url,
int64_t parent_id,
int64_t predecessor_id) {
return Add(title, url, false, parent_id, predecessor_id);
}
int64_t AddURLWithMetaInfo(const std::string& title,
const std::string& url,
const BookmarkNode::MetaInfoMap* meta_info_map,
int64_t parent_id,
int64_t predecessor_id) {
return AddWithMetaInfo(title, url, meta_info_map, false, parent_id,
predecessor_id);
}
// Pretend that the server told the syncer to delete an object.
void Delete(int64_t id) {
{
// Delete the sync node.
syncer::WriteNode node(trans_);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
if (node.GetIsFolder())
EXPECT_FALSE(node.GetFirstChildId());
node.GetMutableEntryForTest()->PutServerIsDel(true);
node.Tombstone();
}
{
// Verify the deletion.
syncer::ReadNode node(trans_);
EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL, node.InitByIdLookup(id));
}
syncer::ChangeRecord record;
record.action = syncer::ChangeRecord::ACTION_DELETE;
record.id = id;
// Deletions are always first in the changelist, but we can't actually do
// WriteNode::Remove() on the node until its children are moved. So, as
// a practical matter, users of FakeServerChange must move or delete
// children before parents. Thus, we must insert the deletion record
// at the front of the vector.
changes_.insert(changes_.begin(), record);
}
// Set a new title value, and return the old value.
std::string ModifyTitle(int64_t id, const std::string& new_title) {
syncer::WriteNode node(trans_);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
std::string old_title = node.GetTitle();
node.SetTitle(new_title);
SetModified(id);
return old_title;
}
// Set a new parent and predecessor value. Return the old parent id.
// We could return the old predecessor id, but it turns out not to be
// very useful for assertions.
int64_t ModifyPosition(int64_t id,
int64_t parent_id,
int64_t predecessor_id) {
syncer::ReadNode parent(trans_);
EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
syncer::WriteNode node(trans_);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
int64_t old_parent_id = node.GetParentId();
if (predecessor_id == 0) {
EXPECT_TRUE(node.SetPosition(parent, nullptr));
} else {
syncer::ReadNode predecessor(trans_);
EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
EXPECT_TRUE(node.SetPosition(parent, &predecessor));
}
SetModified(id);
return old_parent_id;
}
void ModifyCreationTime(int64_t id, int64_t creation_time_us) {
syncer::WriteNode node(trans_);
ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
specifics.set_creation_time_us(creation_time_us);
node.SetBookmarkSpecifics(specifics);
SetModified(id);
}
void ModifyMetaInfo(int64_t id,
const BookmarkNode::MetaInfoMap& meta_info_map) {
syncer::WriteNode node(trans_);
ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
SetNodeMetaInfo(meta_info_map, &specifics);
node.SetBookmarkSpecifics(specifics);
SetModified(id);
}
// Pass the fake change list to |service|.
void ApplyPendingChanges(syncer::ChangeProcessor* processor) {
processor->ApplyChangesFromSyncModel(
trans_, 0, syncer::ImmutableChangeRecordList(&changes_));
}
const syncer::ChangeRecordList& changes() { return changes_; }
private:
// Helper function to push an ACTION_UPDATE record onto the back
// of the changelist.
void SetModified(int64_t id) {
// Coalesce multi-property edits.
if (!changes_.empty() && changes_.back().id == id &&
changes_.back().action == syncer::ChangeRecord::ACTION_UPDATE)
return;
syncer::ChangeRecord record;
record.action = syncer::ChangeRecord::ACTION_UPDATE;
record.id = id;
changes_.push_back(record);
}
void SetNodeMetaInfo(const BookmarkNode::MetaInfoMap& meta_info_map,
sync_pb::BookmarkSpecifics* specifics) {
specifics->clear_meta_info();
// Deliberatly set MetaInfoMap entries in opposite order (compared
// to the implementation in BookmarkChangeProcessor) to ensure that
// (a) the implementation isn't sensitive to the order and
// (b) the original meta info isn't blindly overwritten by
// BookmarkChangeProcessor unless there is a real change.
BookmarkNode::MetaInfoMap::const_iterator it = meta_info_map.end();
while (it != meta_info_map.begin()) {
--it;
sync_pb::MetaInfo* meta_info = specifics->add_meta_info();
meta_info->set_key(it->first);
meta_info->set_value(it->second);
}
}
// The transaction on which everything happens.
syncer::WriteTransaction* trans_;
// The change list we construct.
syncer::ChangeRecordList changes_;
DISALLOW_COPY_AND_ASSIGN(FakeServerChange);
};
class ExtensiveChangesBookmarkModelObserver
: public bookmarks::BaseBookmarkModelObserver {
public:
ExtensiveChangesBookmarkModelObserver()
: started_count_(0),
completed_count_at_started_(0),
completed_count_(0) {}
void ExtensiveBookmarkChangesBeginning(BookmarkModel* model) override {
++started_count_;
completed_count_at_started_ = completed_count_;
}
void ExtensiveBookmarkChangesEnded(BookmarkModel* model) override {
++completed_count_;
}
void BookmarkModelChanged() override {}
int get_started() const { return started_count_; }
int get_completed_count_at_started() const {
return completed_count_at_started_;
}
int get_completed() const { return completed_count_; }
private:
int started_count_;
int completed_count_at_started_;
int completed_count_;
DISALLOW_COPY_AND_ASSIGN(ExtensiveChangesBookmarkModelObserver);
};
class ProfileSyncServiceBookmarkTest : public testing::Test {
protected:
enum LoadOption { LOAD_FROM_STORAGE, DELETE_EXISTING_STORAGE };
enum SaveOption { SAVE_TO_STORAGE, DONT_SAVE_TO_STORAGE };
ProfileSyncServiceBookmarkTest()
: managed_bookmark_service_(new bookmarks::ManagedBookmarkService(
profile_sync_service_bundle_.pref_service(),
base::Bind(ReturnEmptyString))),
local_merge_result_(syncer::BOOKMARKS),
syncer_merge_result_(syncer::BOOKMARKS) {
CHECK(data_dir_.CreateUniqueTempDir());
ProfileSyncServiceBundle::SyncClientBuilder builder(
&profile_sync_service_bundle_);
builder.SetBookmarkModelCallback(base::Bind(
&ProfileSyncServiceBookmarkTest::model, base::Unretained(this)));
sync_client_ = builder.Build();
bookmarks::RegisterProfilePrefs(
profile_sync_service_bundle_.pref_service()->registry());
}
~ProfileSyncServiceBookmarkTest() override {
static_cast<KeyedService*>(managed_bookmark_service_.get())->Shutdown();
StopSync();
}
void SetUp() override { test_user_share_.SetUp(); }
void TearDown() override { test_user_share_.TearDown(); }
bool CanSyncNode(const BookmarkNode* node) {
return model_->client()->CanSyncNode(node);
}
// Inserts a folder directly to the share.
// Do not use this after model association is complete.
//
// This function differs from the AddFolder() function declared elsewhere in
// this file in that it only affects the sync model. It would be invalid to
// change the sync model directly after ModelAssociation. This function can
// be invoked prior to model association to set up first-time sync model
// association scenarios.
int64_t AddFolderToShare(syncer::WriteTransaction* trans,
const std::string& title) {
EXPECT_FALSE(model_associator_);
// Be sure to call CreatePermanentBookmarkNodes(), otherwise this will fail.
syncer::ReadNode bookmark_bar(trans);
EXPECT_EQ(BaseNode::INIT_OK,
bookmark_bar.InitByTagLookupForBookmarks("bookmark_bar"));
syncer::WriteNode node(trans);
EXPECT_TRUE(node.InitBookmarkByCreation(bookmark_bar, nullptr));
node.SetIsFolder(true);
node.SetTitle(title);
return node.GetId();
}
// Inserts a bookmark directly to the share.
// Do not use this after model association is complete.
//
// This function differs from the AddURL() function declared elsewhere in this
// file in that it only affects the sync model. It would be invalid to change
// the sync model directly after ModelAssociation. This function can be
// invoked prior to model association to set up first-time sync model
// association scenarios.
int64_t AddBookmarkToShare(syncer::WriteTransaction* trans,
int64_t parent_id,
const std::string& title,
const std::string& url) {
EXPECT_FALSE(model_associator_);
syncer::ReadNode parent(trans);
EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
sync_pb::BookmarkSpecifics specifics;
specifics.set_url(url);
specifics.set_title(title);
syncer::WriteNode node(trans);
EXPECT_TRUE(node.InitBookmarkByCreation(parent, nullptr));
node.SetIsFolder(false);
node.SetTitle(title);
node.SetBookmarkSpecifics(specifics);
return node.GetId();
}
// Create a BookmarkModel. If |delete_bookmarks| is true, the bookmarks file
// will be deleted before starting up the BookmarkModel.
std::unique_ptr<BookmarkModel> CreateBookmarkModel(bool delete_bookmarks) {
const base::FilePath& data_path = data_dir_.GetPath();
auto model = base::MakeUnique<BookmarkModel>(
base::WrapUnique(new bookmarks::TestBookmarkClient()));
managed_bookmark_service_->BookmarkModelCreated(model.get());
int64_t next_id = 0;
static_cast<bookmarks::TestBookmarkClient*>(model->client())
->SetExtraNodesToLoad(
managed_bookmark_service_->GetLoadExtraNodesCallback().Run(
&next_id));
if (delete_bookmarks) {
base::DeleteFile(data_path.Append(FILE_PATH_LITERAL("dummy_bookmarks")),
false);
}
model->Load(profile_sync_service_bundle_.pref_service(), data_path,
base::ThreadTaskRunnerHandle::Get(),
base::ThreadTaskRunnerHandle::Get());
bookmarks::test::WaitForBookmarkModelToLoad(model.get());
return model;
}
// Load (or re-load) the bookmark model. |load| controls use of the
// bookmarks file on disk. |save| controls whether the newly loaded
// bookmark model will write out a bookmark file as it goes.
void LoadBookmarkModel(LoadOption load, SaveOption save) {
bool delete_bookmarks = load == DELETE_EXISTING_STORAGE;
model_.reset();
model_ = CreateBookmarkModel(delete_bookmarks);
// This noticeably speeds up the unit tests that request it.
if (save == DONT_SAVE_TO_STORAGE)
model_->ClearStore();
base::RunLoop().RunUntilIdle();
}
int GetSyncBookmarkCount() {
syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
syncer::ReadNode node(&trans);
if (node.InitTypeRoot(syncer::BOOKMARKS) != BaseNode::INIT_OK)
return 0;
return node.GetTotalNodeCount();
}
// Creates the bookmark root node and the permanent nodes if they don't
// already exist.
bool CreatePermanentBookmarkNodes() {
bool root_exists = false;
syncer::ModelType type = syncer::BOOKMARKS;
{
syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
syncer::ReadNode uber_root(&trans);
uber_root.InitByRootLookup();
syncer::ReadNode root(&trans);
root_exists = (root.InitTypeRoot(type) == BaseNode::INIT_OK);
}
if (!root_exists) {
if (!syncer::TestUserShare::CreateRoot(type,
test_user_share_.user_share()))
return false;
}
const int kNumPermanentNodes = 3;
const std::string permanent_tags[kNumPermanentNodes] = {
"bookmark_bar", "other_bookmarks", "synced_bookmarks",
};
syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
syncer::ReadNode root(&trans);
EXPECT_EQ(BaseNode::INIT_OK, root.InitTypeRoot(type));
// Loop through creating permanent nodes as necessary.
int64_t last_child_id = syncer::kInvalidId;
for (int i = 0; i < kNumPermanentNodes; ++i) {
// First check if the node already exists. This is for tests that involve
// persistence and set up sync more than once.
syncer::ReadNode lookup(&trans);
if (lookup.InitByTagLookupForBookmarks(permanent_tags[i]) ==
syncer::ReadNode::INIT_OK) {
last_child_id = lookup.GetId();
continue;
}
// If it doesn't exist, create the permanent node at the end of the
// ordering.
syncer::ReadNode predecessor_node(&trans);
syncer::ReadNode* predecessor = nullptr;
if (last_child_id != syncer::kInvalidId) {
EXPECT_EQ(BaseNode::INIT_OK,
predecessor_node.InitByIdLookup(last_child_id));
predecessor = &predecessor_node;
}
syncer::WriteNode node(&trans);
if (!node.InitBookmarkByCreation(root, predecessor))
return false;
node.SetIsFolder(true);
node.GetMutableEntryForTest()->PutUniqueServerTag(permanent_tags[i]);
node.SetTitle(permanent_tags[i]);
node.SetExternalId(0);
last_child_id = node.GetId();
}
return true;
}
bool AssociateModels() {
DCHECK(!model_associator_);
// Set up model associator.
model_associator_ = base::MakeUnique<BookmarkModelAssociator>(
model_.get(), sync_client_.get(), test_user_share_.user_share(),
base::MakeUnique<syncer::DataTypeErrorHandlerMock>(),
kExpectMobileBookmarks);
local_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
syncer_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
int local_count_before = model_->root_node()->GetTotalNodeCount();
int syncer_count_before = GetSyncBookmarkCount();
syncer::SyncError error = model_associator_->AssociateModels(
&local_merge_result_, &syncer_merge_result_);
if (error.IsSet())
return false;
base::RunLoop().RunUntilIdle();
// Verify the merge results were calculated properly.
EXPECT_EQ(local_count_before,
local_merge_result_.num_items_before_association());
EXPECT_EQ(syncer_count_before,
syncer_merge_result_.num_items_before_association());
EXPECT_EQ(local_merge_result_.num_items_after_association(),
local_merge_result_.num_items_before_association() +
local_merge_result_.num_items_added() -
local_merge_result_.num_items_deleted());
EXPECT_EQ(syncer_merge_result_.num_items_after_association(),
syncer_merge_result_.num_items_before_association() +
syncer_merge_result_.num_items_added() -
syncer_merge_result_.num_items_deleted());
EXPECT_EQ(model_->root_node()->GetTotalNodeCount(),
local_merge_result_.num_items_after_association());
EXPECT_EQ(GetSyncBookmarkCount(),
syncer_merge_result_.num_items_after_association());
return true;
}
void StartSync() {
test_user_share_.Reload();
ASSERT_TRUE(CreatePermanentBookmarkNodes());
ASSERT_TRUE(AssociateModels());
// Set up change processor.
ResetChangeProcessor();
change_processor_->Start(test_user_share_.user_share());
}
void StopSync() {
change_processor_.reset();
if (model_associator_) {
syncer::SyncError error = model_associator_->DisassociateModels();
EXPECT_FALSE(error.IsSet());
}
model_associator_.reset();
base::RunLoop().RunUntilIdle();
// TODO(akalin): Actually close the database and flush it to disk
// (and make StartSync reload from disk). This would require
// refactoring TestUserShare.
}
bool InitSyncNodeFromChromeNode(const BookmarkNode* bnode,
BaseNode* sync_node) {
return model_associator_->InitSyncNodeFromChromeId(bnode->id(), sync_node);
}
void ExpectSyncerNodeMatching(syncer::BaseTransaction* trans,
const BookmarkNode* bnode) {
std::string truncated_title = base::UTF16ToUTF8(bnode->GetTitle());
syncer::SyncAPINameToServerName(truncated_title, &truncated_title);
base::TruncateUTF8ToByteSize(truncated_title, 255, &truncated_title);
syncer::ServerNameToSyncAPIName(truncated_title, &truncated_title);
syncer::ReadNode gnode(trans);
ASSERT_TRUE(InitSyncNodeFromChromeNode(bnode, &gnode));
// Non-root node titles and parents must match.
if (!model_->is_permanent_node(bnode)) {
EXPECT_EQ(truncated_title, gnode.GetTitle());
EXPECT_EQ(model_associator_->GetChromeNodeFromSyncId(gnode.GetParentId()),
bnode->parent());
}
EXPECT_EQ(bnode->is_folder(), gnode.GetIsFolder());
if (bnode->is_url())
EXPECT_EQ(bnode->url(), GURL(gnode.GetBookmarkSpecifics().url()));
// Check that meta info matches.
const BookmarkNode::MetaInfoMap* meta_info_map = bnode->GetMetaInfoMap();
sync_pb::BookmarkSpecifics specifics = gnode.GetBookmarkSpecifics();
if (!meta_info_map) {
EXPECT_EQ(0, specifics.meta_info_size());
} else {
EXPECT_EQ(meta_info_map->size(),
static_cast<size_t>(specifics.meta_info_size()));
for (int i = 0; i < specifics.meta_info_size(); i++) {
BookmarkNode::MetaInfoMap::const_iterator it =
meta_info_map->find(specifics.meta_info(i).key());
EXPECT_TRUE(it != meta_info_map->end());
EXPECT_EQ(it->second, specifics.meta_info(i).value());
}
}
// Check for position matches.
int browser_index = bnode->parent()->GetIndexOf(bnode);
if (browser_index == 0) {
EXPECT_EQ(gnode.GetPredecessorId(), 0);
} else {
const BookmarkNode* bprev = bnode->parent()->GetChild(browser_index - 1);
syncer::ReadNode gprev(trans);
ASSERT_TRUE(InitSyncNodeFromChromeNode(bprev, &gprev));
EXPECT_EQ(gnode.GetPredecessorId(), gprev.GetId());
EXPECT_EQ(gnode.GetParentId(), gprev.GetParentId());
}
// Note: the managed node is the last child of the root_node but isn't
// synced; if CanSyncNode() is false then there is no next node to sync.
const BookmarkNode* bnext = nullptr;
if (browser_index + 1 < bnode->parent()->child_count())
bnext = bnode->parent()->GetChild(browser_index + 1);
if (!bnext || !CanSyncNode(bnext)) {
EXPECT_EQ(gnode.GetSuccessorId(), 0);
} else {
syncer::ReadNode gnext(trans);
ASSERT_TRUE(InitSyncNodeFromChromeNode(bnext, &gnext));
EXPECT_EQ(gnode.GetSuccessorId(), gnext.GetId());
EXPECT_EQ(gnode.GetParentId(), gnext.GetParentId());
}
if (!bnode->empty())
EXPECT_TRUE(gnode.GetFirstChildId());
}
void ExpectSyncerNodeMatching(const BookmarkNode* bnode) {
syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
ExpectSyncerNodeMatching(&trans, bnode);
}
void ExpectBrowserNodeMatching(syncer::BaseTransaction* trans,
int64_t sync_id) {
EXPECT_TRUE(sync_id);
const BookmarkNode* bnode =
model_associator_->GetChromeNodeFromSyncId(sync_id);
ASSERT_TRUE(bnode);
ASSERT_TRUE(CanSyncNode(bnode));
int64_t id = model_associator_->GetSyncIdFromChromeId(bnode->id());
EXPECT_EQ(id, sync_id);
ExpectSyncerNodeMatching(trans, bnode);
}
void ExpectBrowserNodeUnknown(int64_t sync_id) {
EXPECT_FALSE(model_associator_->GetChromeNodeFromSyncId(sync_id));
}
void ExpectBrowserNodeKnown(int64_t sync_id) {
EXPECT_TRUE(model_associator_->GetChromeNodeFromSyncId(sync_id));
}
void ExpectSyncerNodeKnown(const BookmarkNode* node) {
int64_t sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
EXPECT_NE(sync_id, syncer::kInvalidId);
}
void ExpectSyncerNodeUnknown(const BookmarkNode* node) {
int64_t sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
EXPECT_EQ(sync_id, syncer::kInvalidId);
}
void ExpectBrowserNodeTitle(int64_t sync_id, const std::string& title) {
const BookmarkNode* bnode =
model_associator_->GetChromeNodeFromSyncId(sync_id);
ASSERT_TRUE(bnode);
EXPECT_EQ(bnode->GetTitle(), base::UTF8ToUTF16(title));
}
void ExpectBrowserNodeURL(int64_t sync_id, const std::string& url) {
const BookmarkNode* bnode =
model_associator_->GetChromeNodeFromSyncId(sync_id);
ASSERT_TRUE(bnode);
EXPECT_EQ(GURL(url), bnode->url());
}
void ExpectBrowserNodeParent(int64_t sync_id, int64_t parent_sync_id) {
const BookmarkNode* node =
model_associator_->GetChromeNodeFromSyncId(sync_id);
ASSERT_TRUE(node);
const BookmarkNode* parent =
model_associator_->GetChromeNodeFromSyncId(parent_sync_id);
EXPECT_TRUE(parent);
EXPECT_EQ(node->parent(), parent);
}
void ExpectModelMatch(syncer::BaseTransaction* trans) {
const BookmarkNode* root = model_->root_node();
EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 0);
EXPECT_EQ(root->GetIndexOf(model_->other_node()), 1);
EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 2);
std::stack<int64_t> stack;
stack.push(bookmark_bar_id());
while (!stack.empty()) {
int64_t id = stack.top();
stack.pop();
if (!id)
continue;
ExpectBrowserNodeMatching(trans, id);
syncer::ReadNode gnode(trans);
ASSERT_EQ(BaseNode::INIT_OK, gnode.InitByIdLookup(id));
stack.push(gnode.GetSuccessorId());
if (gnode.GetIsFolder())
stack.push(gnode.GetFirstChildId());
}
}
void ExpectModelMatch() {
syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
ExpectModelMatch(&trans);
}
int64_t mobile_bookmarks_id() {
return model_associator_->GetSyncIdFromChromeId(
model_->mobile_node()->id());
}
int64_t other_bookmarks_id() {
return model_associator_->GetSyncIdFromChromeId(model_->other_node()->id());
}
int64_t bookmark_bar_id() {
return model_associator_->GetSyncIdFromChromeId(
model_->bookmark_bar_node()->id());
}
BookmarkModel* model() { return model_.get(); }
syncer::TestUserShare* test_user_share() { return &test_user_share_; }
BookmarkChangeProcessor* change_processor() {
return change_processor_.get();
}
void delete_change_processor() { change_processor_.reset(); }
void ResetChangeProcessor() {
std::unique_ptr<syncer::DataTypeErrorHandlerMock> error_handler =
base::MakeUnique<syncer::DataTypeErrorHandlerMock>();
mock_error_handler_ = error_handler.get();
change_processor_ = base::MakeUnique<BookmarkChangeProcessor>(
sync_client_.get(), model_associator_.get(), std::move(error_handler));
}
syncer::DataTypeErrorHandlerMock* mock_error_handler() {
return mock_error_handler_;
}
void delete_model_associator() { model_associator_.reset(); }
BookmarkModelAssociator* model_associator() {
return model_associator_.get();
}
bookmarks::ManagedBookmarkService* managed_bookmark_service() {
return managed_bookmark_service_.get();
}
private:
base::TestMessageLoop message_loop_;
base::ScopedTempDir data_dir_;
ProfileSyncServiceBundle profile_sync_service_bundle_;
std::unique_ptr<syncer::FakeSyncClient> sync_client_;
std::unique_ptr<BookmarkModel> model_;
syncer::TestUserShare test_user_share_;
std::unique_ptr<BookmarkChangeProcessor> change_processor_;
syncer::DataTypeErrorHandlerMock* mock_error_handler_;
std::unique_ptr<BookmarkModelAssociator> model_associator_;
std::unique_ptr<bookmarks::ManagedBookmarkService> managed_bookmark_service_;
syncer::SyncMergeResult local_merge_result_;
syncer::SyncMergeResult syncer_merge_result_;
DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceBookmarkTest);
};
TEST_F(ProfileSyncServiceBookmarkTest, InitialState) {
LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
StartSync();
EXPECT_TRUE(other_bookmarks_id());
EXPECT_TRUE(bookmark_bar_id());
EXPECT_TRUE(mobile_bookmarks_id());
ExpectModelMatch();
}
// Populate the sync database then start model association. Sync's bookmarks
// should end up being copied into the native model, resulting in a successful
// "ExpectModelMatch()".
//
// This code has some use for verifying correctness. It's also a very useful
// for profiling bookmark ModelAssociation, an important part of some first-time
// sync scenarios. Simply increase the kNumFolders and kNumBookmarksPerFolder
// as desired, then run the test under a profiler to find hot spots in the model
// association code.
TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociate) {
const int kNumBookmarksPerFolder = 10;
const int kNumFolders = 10;
CreatePermanentBookmarkNodes();
{
syncer::WriteTransaction trans(FROM_HERE, test_user_share()->user_share());
for (int i = 0; i < kNumFolders; ++i) {
int64_t folder_id =
AddFolderToShare(&trans, base::StringPrintf("folder%05d", i));
for (int j = 0; j < kNumBookmarksPerFolder; ++j) {
AddBookmarkToShare(
&trans, folder_id, base::StringPrintf("bookmark%05d", j),
base::StringPrintf("http://www.google.com/search?q=%05d", j));
}
}
}
LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
StartSync();
ExpectModelMatch();
}
// Tests bookmark association when nodes exists in the native model only.
// These entries should be copied to Sync directory during association process.
TEST_F(ProfileSyncServiceBookmarkTest,
InitialModelAssociateWithBookmarkModelNodes) {
LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
const BookmarkNode* folder = model()->AddFolder(model()->other_node(), 0,
base::ASCIIToUTF16("foobar"));
model()->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
model()->AddURL(folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
GURL("http://www.easypie.com/"));
model()->AddURL(folder, 1, base::ASCIIToUTF16("Airplanes"),
GURL("http://www.easyjet.com/"));
StartSync();
ExpectModelMatch();
}
// Tests bookmark association case when there is an entry in the delete journal
// that matches one of native bookmarks.
TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociateWithDeleteJournal) {
LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
const BookmarkNode* folder = model()->AddFolder(
model()->bookmark_bar_node(), 0, base::ASCIIToUTF16("foobar"));
const BookmarkNode* bookmark =
model()->AddURL(folder, 0, base::ASCIIToUTF16("Airplanes"),
GURL("http://www.easyjet.com/"));
CreatePermanentBookmarkNodes();
// Create entries matching the folder and the bookmark above.
int64_t folder_id, bookmark_id;
{
syncer::WriteTransaction trans(FROM_HERE, test_user_share()->user_share());
folder_id = AddFolderToShare(&trans, "foobar");
bookmark_id = AddBookmarkToShare(&trans, folder_id, "Airplanes",
"http://www.easyjet.com/");
}
// Associate the bookmark sync node with the native model one and make
// it look like it was deleted by a server update.
{
syncer::WriteTransaction trans(FROM_HERE, test_user_share()->user_share());
syncer::WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(bookmark_id));
node.GetMutableEntryForTest()->PutLocalExternalId(bookmark->id());
MakeServerUpdate(&trans, &node);
node.GetMutableEntryForTest()->PutServerIsDel(true);
node.GetMutableEntryForTest()->PutIsDel(true);
}
ASSERT_TRUE(AssociateModels());
ExpectModelMatch();
// The bookmark node should be deleted.
EXPECT_EQ(0, folder->child_count());
}
// Tests that the external ID is used to match the right folder amoung
// multiple folders with the same name during the native model traversal.
// Also tests that the external ID is used to match the right bookmark
// among multiple identical bookmarks when dealing with the delete journal.
TEST_F(ProfileSyncServiceBookmarkTest,
InitialModelAssociateVerifyExternalIdMatch) {
LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
const int kNumFolders = 10;
const int kNumBookmarks = 10;
const int kFolderToIncludeBookmarks = 7;
const int kBookmarkToDelete = 4;
int64_t folder_ids[kNumFolders];
int64_t bookmark_ids[kNumBookmarks];
// Create native folders and bookmarks with identical names. Only
// one of the folders contains bookmarks and others are empty. Here is the
// expected tree shape:
// Bookmarks bar
// +- folder (#0)
// +- folder (#1)
// ...
// +- folder (#7) <-- Only this folder contains bookmarks.
// +- bookmark (#0)
// +- bookmark (#1)
// ...
// +- bookmark (#4) <-- Only this one bookmark should be removed later.
// ...
// +- bookmark (#9)
// ...
// +- folder (#9)
const BookmarkNode* parent_folder = nullptr;
for (int i = 0; i < kNumFolders; i++) {
const BookmarkNode* folder = model()->AddFolder(
model()->bookmark_bar_node(), i, base::ASCIIToUTF16("folder"));
folder_ids[i] = folder->id();
if (i == kFolderToIncludeBookmarks) {
parent_folder = folder;
}
}
for (int i = 0; i < kNumBookmarks; i++) {
const BookmarkNode* bookmark =
model()->AddURL(parent_folder, i, base::ASCIIToUTF16("bookmark"),
GURL("http://www.google.com/"));
bookmark_ids[i] = bookmark->id();
}
// Number of nodes in bookmark bar before association.
int total_node_count = model()->bookmark_bar_node()->GetTotalNodeCount();
CreatePermanentBookmarkNodes();
int64_t sync_bookmark_id_to_delete = 0;
{
// Create sync folders matching native folders above.
int64_t parent_id = 0;
syncer::WriteTransaction trans(FROM_HERE, test_user_share()->user_share());
// Create in reverse order because AddFolderToShare passes null for
// |predecessor| argument.
for (int i = kNumFolders - 1; i >= 0; i--) {
int64_t id = AddFolderToShare(&trans, "folder");