Componentize HistoryURLProvider/ScoredHistoryMatch.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service_bookmark_unittest.cc
blob6d834a9f231ca2234da78fda3247c2e3e3ede524
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // TODO(akalin): This file is basically just a unit test for
6 // BookmarkChangeProcessor. Write unit tests for
7 // BookmarkModelAssociator separately.
9 #include <map>
10 #include <queue>
11 #include <stack>
12 #include <vector>
14 #include "base/command_line.h"
15 #include "base/files/file_path.h"
16 #include "base/location.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/test/mock_entropy_provider.h"
25 #include "base/time/time.h"
26 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
27 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
28 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
29 #include "chrome/browser/sync/glue/bookmark_change_processor.h"
30 #include "chrome/browser/sync/glue/bookmark_model_associator.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/test/base/testing_profile.h"
33 #include "components/bookmarks/browser/base_bookmark_model_observer.h"
34 #include "components/bookmarks/browser/bookmark_model.h"
35 #include "components/bookmarks/test/bookmark_test_helpers.h"
36 #include "components/sync_driver/data_type_error_handler.h"
37 #include "components/sync_driver/data_type_error_handler_mock.h"
38 #include "content/public/test/test_browser_thread_bundle.h"
39 #include "sync/api/sync_error.h"
40 #include "sync/internal_api/public/change_record.h"
41 #include "sync/internal_api/public/read_node.h"
42 #include "sync/internal_api/public/read_transaction.h"
43 #include "sync/internal_api/public/test/test_user_share.h"
44 #include "sync/internal_api/public/write_node.h"
45 #include "sync/internal_api/public/write_transaction.h"
46 #include "sync/internal_api/syncapi_internal.h"
47 #include "sync/syncable/mutable_entry.h"
48 #include "sync/syncable/syncable_id.h"
49 #include "sync/syncable/syncable_util.h"
50 #include "sync/syncable/syncable_write_transaction.h"
51 #include "testing/gmock/include/gmock/gmock.h"
52 #include "testing/gtest/include/gtest/gtest.h"
54 namespace browser_sync {
56 using bookmarks::BookmarkModel;
57 using bookmarks::BookmarkNode;
58 using syncer::BaseNode;
59 using testing::_;
60 using testing::InvokeWithoutArgs;
61 using testing::Mock;
62 using testing::Return;
63 using testing::StrictMock;
65 #if defined(OS_ANDROID) || defined(OS_IOS)
66 static const bool kExpectMobileBookmarks = true;
67 #else
68 static const bool kExpectMobileBookmarks = false;
69 #endif // defined(OS_ANDROID) || defined(OS_IOS)
71 namespace {
73 void MakeServerUpdate(syncer::WriteTransaction* trans,
74 syncer::WriteNode* node) {
75 syncer::syncable::ChangeEntryIDAndUpdateChildren(
76 trans->GetWrappedWriteTrans(), node->GetMutableEntryForTest(),
77 syncer::syncable::Id::CreateFromServerId(
78 base::Int64ToString(node->GetId())));
79 node->GetMutableEntryForTest()->PutBaseVersion(10);
80 node->GetMutableEntryForTest()->PutIsUnappliedUpdate(true);
83 void MakeServerUpdate(syncer::WriteTransaction* trans, int64 id) {
84 syncer::WriteNode node(trans);
85 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
86 MakeServerUpdate(trans, &node);
89 // FakeServerChange constructs a list of syncer::ChangeRecords while modifying
90 // the sync model, and can pass the ChangeRecord list to a
91 // syncer::SyncObserver (i.e., the ProfileSyncService) to test the client
92 // change-application behavior.
93 // Tests using FakeServerChange should be careful to avoid back-references,
94 // since FakeServerChange will send the edits in the order specified.
95 class FakeServerChange {
96 public:
97 explicit FakeServerChange(syncer::WriteTransaction* trans) : trans_(trans) {
100 // Pretend that the server told the syncer to add a bookmark object.
101 int64 AddWithMetaInfo(const std::string& title,
102 const std::string& url,
103 const BookmarkNode::MetaInfoMap* meta_info_map,
104 bool is_folder,
105 int64 parent_id,
106 int64 predecessor_id) {
107 syncer::ReadNode parent(trans_);
108 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
109 syncer::WriteNode node(trans_);
110 if (predecessor_id == 0) {
111 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
112 } else {
113 syncer::ReadNode predecessor(trans_);
114 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
115 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
116 EXPECT_TRUE(node.InitBookmarkByCreation(parent, &predecessor));
118 EXPECT_EQ(node.GetPredecessorId(), predecessor_id);
119 EXPECT_EQ(node.GetParentId(), parent_id);
120 node.SetIsFolder(is_folder);
121 node.SetTitle(title);
123 sync_pb::BookmarkSpecifics specifics(node.GetBookmarkSpecifics());
124 const base::Time creation_time(base::Time::Now());
125 specifics.set_creation_time_us(creation_time.ToInternalValue());
126 if (!is_folder)
127 specifics.set_url(url);
128 if (meta_info_map)
129 SetNodeMetaInfo(*meta_info_map, &specifics);
130 node.SetBookmarkSpecifics(specifics);
132 syncer::ChangeRecord record;
133 record.action = syncer::ChangeRecord::ACTION_ADD;
134 record.id = node.GetId();
135 changes_.push_back(record);
136 return node.GetId();
139 int64 Add(const std::string& title,
140 const std::string& url,
141 bool is_folder,
142 int64 parent_id,
143 int64 predecessor_id) {
144 return AddWithMetaInfo(title, url, NULL, is_folder, parent_id,
145 predecessor_id);
148 // Add a bookmark folder.
149 int64 AddFolder(const std::string& title,
150 int64 parent_id,
151 int64 predecessor_id) {
152 return Add(title, std::string(), true, parent_id, predecessor_id);
154 int64 AddFolderWithMetaInfo(const std::string& title,
155 const BookmarkNode::MetaInfoMap* meta_info_map,
156 int64 parent_id,
157 int64 predecessor_id) {
158 return AddWithMetaInfo(title, std::string(), meta_info_map, true, parent_id,
159 predecessor_id);
162 // Add a bookmark.
163 int64 AddURL(const std::string& title,
164 const std::string& url,
165 int64 parent_id,
166 int64 predecessor_id) {
167 return Add(title, url, false, parent_id, predecessor_id);
169 int64 AddURLWithMetaInfo(const std::string& title,
170 const std::string& url,
171 const BookmarkNode::MetaInfoMap* meta_info_map,
172 int64 parent_id,
173 int64 predecessor_id) {
174 return AddWithMetaInfo(title, url, meta_info_map, false, parent_id,
175 predecessor_id);
178 // Pretend that the server told the syncer to delete an object.
179 void Delete(int64 id) {
181 // Delete the sync node.
182 syncer::WriteNode node(trans_);
183 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
184 if (node.GetIsFolder())
185 EXPECT_FALSE(node.GetFirstChildId());
186 node.GetMutableEntryForTest()->PutServerIsDel(true);
187 node.Tombstone();
190 // Verify the deletion.
191 syncer::ReadNode node(trans_);
192 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL, node.InitByIdLookup(id));
195 syncer::ChangeRecord record;
196 record.action = syncer::ChangeRecord::ACTION_DELETE;
197 record.id = id;
198 // Deletions are always first in the changelist, but we can't actually do
199 // WriteNode::Remove() on the node until its children are moved. So, as
200 // a practical matter, users of FakeServerChange must move or delete
201 // children before parents. Thus, we must insert the deletion record
202 // at the front of the vector.
203 changes_.insert(changes_.begin(), record);
206 // Set a new title value, and return the old value.
207 std::string ModifyTitle(int64 id, const std::string& new_title) {
208 syncer::WriteNode node(trans_);
209 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
210 std::string old_title = node.GetTitle();
211 node.SetTitle(new_title);
212 SetModified(id);
213 return old_title;
216 // Set a new parent and predecessor value. Return the old parent id.
217 // We could return the old predecessor id, but it turns out not to be
218 // very useful for assertions.
219 int64 ModifyPosition(int64 id, int64 parent_id, int64 predecessor_id) {
220 syncer::ReadNode parent(trans_);
221 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
222 syncer::WriteNode node(trans_);
223 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
224 int64 old_parent_id = node.GetParentId();
225 if (predecessor_id == 0) {
226 EXPECT_TRUE(node.SetPosition(parent, NULL));
227 } else {
228 syncer::ReadNode predecessor(trans_);
229 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
230 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
231 EXPECT_TRUE(node.SetPosition(parent, &predecessor));
233 SetModified(id);
234 return old_parent_id;
237 void ModifyCreationTime(int64 id, int64 creation_time_us) {
238 syncer::WriteNode node(trans_);
239 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
240 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
241 specifics.set_creation_time_us(creation_time_us);
242 node.SetBookmarkSpecifics(specifics);
243 SetModified(id);
246 void ModifyMetaInfo(int64 id,
247 const BookmarkNode::MetaInfoMap& meta_info_map) {
248 syncer::WriteNode node(trans_);
249 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
250 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
251 SetNodeMetaInfo(meta_info_map, &specifics);
252 node.SetBookmarkSpecifics(specifics);
253 SetModified(id);
256 // Pass the fake change list to |service|.
257 void ApplyPendingChanges(sync_driver::ChangeProcessor* processor) {
258 processor->ApplyChangesFromSyncModel(
259 trans_, 0, syncer::ImmutableChangeRecordList(&changes_));
262 const syncer::ChangeRecordList& changes() {
263 return changes_;
266 private:
267 // Helper function to push an ACTION_UPDATE record onto the back
268 // of the changelist.
269 void SetModified(int64 id) {
270 // Coalesce multi-property edits.
271 if (!changes_.empty() && changes_.back().id == id &&
272 changes_.back().action ==
273 syncer::ChangeRecord::ACTION_UPDATE)
274 return;
275 syncer::ChangeRecord record;
276 record.action = syncer::ChangeRecord::ACTION_UPDATE;
277 record.id = id;
278 changes_.push_back(record);
281 void SetNodeMetaInfo(const BookmarkNode::MetaInfoMap& meta_info_map,
282 sync_pb::BookmarkSpecifics* specifics) {
283 specifics->clear_meta_info();
284 // Deliberatly set MetaInfoMap entries in opposite order (compared
285 // to the implementation in BookmarkChangeProcessor) to ensure that
286 // (a) the implementation isn't sensitive to the order and
287 // (b) the original meta info isn't blindly overwritten by
288 // BookmarkChangeProcessor unless there is a real change.
289 BookmarkNode::MetaInfoMap::const_iterator it = meta_info_map.end();
290 while (it != meta_info_map.begin()) {
291 --it;
292 sync_pb::MetaInfo* meta_info = specifics->add_meta_info();
293 meta_info->set_key(it->first);
294 meta_info->set_value(it->second);
298 // The transaction on which everything happens.
299 syncer::WriteTransaction *trans_;
301 // The change list we construct.
302 syncer::ChangeRecordList changes_;
305 class ExtensiveChangesBookmarkModelObserver
306 : public bookmarks::BaseBookmarkModelObserver {
307 public:
308 ExtensiveChangesBookmarkModelObserver()
309 : started_count_(0),
310 completed_count_at_started_(0),
311 completed_count_(0) {}
313 void ExtensiveBookmarkChangesBeginning(BookmarkModel* model) override {
314 ++started_count_;
315 completed_count_at_started_ = completed_count_;
318 void ExtensiveBookmarkChangesEnded(BookmarkModel* model) override {
319 ++completed_count_;
322 void BookmarkModelChanged() override {}
324 int get_started() const {
325 return started_count_;
328 int get_completed_count_at_started() const {
329 return completed_count_at_started_;
332 int get_completed() const {
333 return completed_count_;
336 private:
337 int started_count_;
338 int completed_count_at_started_;
339 int completed_count_;
341 DISALLOW_COPY_AND_ASSIGN(ExtensiveChangesBookmarkModelObserver);
345 class ProfileSyncServiceBookmarkTest : public testing::Test {
346 protected:
347 enum LoadOption { LOAD_FROM_STORAGE, DELETE_EXISTING_STORAGE };
348 enum SaveOption { SAVE_TO_STORAGE, DONT_SAVE_TO_STORAGE };
350 ProfileSyncServiceBookmarkTest()
351 : model_(NULL),
352 local_merge_result_(syncer::BOOKMARKS),
353 syncer_merge_result_(syncer::BOOKMARKS) {}
355 virtual ~ProfileSyncServiceBookmarkTest() {
356 StopSync();
357 UnloadBookmarkModel();
360 virtual void SetUp() {
361 test_user_share_.SetUp();
364 virtual void TearDown() {
365 test_user_share_.TearDown();
368 bool CanSyncNode(const BookmarkNode* node) {
369 return model_->client()->CanSyncNode(node);
372 // Inserts a folder directly to the share.
373 // Do not use this after model association is complete.
375 // This function differs from the AddFolder() function declared elsewhere in
376 // this file in that it only affects the sync model. It would be invalid to
377 // change the sync model directly after ModelAssociation. This function can
378 // be invoked prior to model association to set up first-time sync model
379 // association scenarios.
380 int64 AddFolderToShare(syncer::WriteTransaction* trans, std::string title) {
381 EXPECT_FALSE(model_associator_);
383 // Be sure to call CreatePermanentBookmarkNodes(), otherwise this will fail.
384 syncer::ReadNode bookmark_bar(trans);
385 EXPECT_EQ(BaseNode::INIT_OK,
386 bookmark_bar.InitByTagLookupForBookmarks("bookmark_bar"));
388 syncer::WriteNode node(trans);
389 EXPECT_TRUE(node.InitBookmarkByCreation(bookmark_bar, NULL));
390 node.SetIsFolder(true);
391 node.SetTitle(title);
393 return node.GetId();
396 // Inserts a bookmark directly to the share.
397 // Do not use this after model association is complete.
399 // This function differs from the AddURL() function declared elsewhere in this
400 // file in that it only affects the sync model. It would be invalid to change
401 // the sync model directly after ModelAssociation. This function can be
402 // invoked prior to model association to set up first-time sync model
403 // association scenarios.
404 int64 AddBookmarkToShare(syncer::WriteTransaction* trans,
405 int64 parent_id,
406 const std::string& title,
407 const std::string& url) {
408 EXPECT_FALSE(model_associator_);
410 syncer::ReadNode parent(trans);
411 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
413 sync_pb::BookmarkSpecifics specifics;
414 specifics.set_url(url);
415 specifics.set_title(title);
417 syncer::WriteNode node(trans);
418 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
419 node.SetIsFolder(false);
420 node.SetTitle(title);
421 node.SetBookmarkSpecifics(specifics);
423 return node.GetId();
426 // Load (or re-load) the bookmark model. |load| controls use of the
427 // bookmarks file on disk. |save| controls whether the newly loaded
428 // bookmark model will write out a bookmark file as it goes.
429 void LoadBookmarkModel(LoadOption load, SaveOption save) {
430 bool delete_bookmarks = load == DELETE_EXISTING_STORAGE;
431 profile_.CreateBookmarkModel(delete_bookmarks);
432 model_ = BookmarkModelFactory::GetForProfile(&profile_);
433 bookmarks::test::WaitForBookmarkModelToLoad(model_);
434 // This noticeably speeds up the unit tests that request it.
435 if (save == DONT_SAVE_TO_STORAGE)
436 model_->ClearStore();
437 base::MessageLoop::current()->RunUntilIdle();
440 int GetSyncBookmarkCount() {
441 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
442 syncer::ReadNode node(&trans);
443 if (node.InitTypeRoot(syncer::BOOKMARKS) != syncer::BaseNode::INIT_OK)
444 return 0;
445 return node.GetTotalNodeCount();
448 // Creates the bookmark root node and the permanent nodes if they don't
449 // already exist.
450 bool CreatePermanentBookmarkNodes() {
451 bool root_exists = false;
452 syncer::ModelType type = syncer::BOOKMARKS;
454 syncer::WriteTransaction trans(FROM_HERE,
455 test_user_share_.user_share());
456 syncer::ReadNode uber_root(&trans);
457 uber_root.InitByRootLookup();
459 syncer::ReadNode root(&trans);
460 root_exists = (root.InitTypeRoot(type) == BaseNode::INIT_OK);
463 if (!root_exists) {
464 if (!syncer::TestUserShare::CreateRoot(type,
465 test_user_share_.user_share()))
466 return false;
469 const int kNumPermanentNodes = 3;
470 const std::string permanent_tags[kNumPermanentNodes] = {
471 #if defined(OS_IOS)
472 "synced_bookmarks",
473 #endif
474 "bookmark_bar",
475 "other_bookmarks",
476 #if !defined(OS_IOS)
477 "synced_bookmarks",
478 #endif
480 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
481 syncer::ReadNode root(&trans);
482 EXPECT_EQ(BaseNode::INIT_OK, root.InitTypeRoot(type));
484 // Loop through creating permanent nodes as necessary.
485 int64 last_child_id = syncer::kInvalidId;
486 for (int i = 0; i < kNumPermanentNodes; ++i) {
487 // First check if the node already exists. This is for tests that involve
488 // persistence and set up sync more than once.
489 syncer::ReadNode lookup(&trans);
490 if (lookup.InitByTagLookupForBookmarks(permanent_tags[i]) ==
491 syncer::ReadNode::INIT_OK) {
492 last_child_id = lookup.GetId();
493 continue;
496 // If it doesn't exist, create the permanent node at the end of the
497 // ordering.
498 syncer::ReadNode predecessor_node(&trans);
499 syncer::ReadNode* predecessor = NULL;
500 if (last_child_id != syncer::kInvalidId) {
501 EXPECT_EQ(BaseNode::INIT_OK,
502 predecessor_node.InitByIdLookup(last_child_id));
503 predecessor = &predecessor_node;
505 syncer::WriteNode node(&trans);
506 if (!node.InitBookmarkByCreation(root, predecessor))
507 return false;
508 node.SetIsFolder(true);
509 node.GetMutableEntryForTest()->PutUniqueServerTag(permanent_tags[i]);
510 node.SetTitle(permanent_tags[i]);
511 node.SetExternalId(0);
512 last_child_id = node.GetId();
514 return true;
517 bool AssociateModels() {
518 DCHECK(!model_associator_);
520 // Set up model associator.
521 model_associator_.reset(new BookmarkModelAssociator(
522 BookmarkModelFactory::GetForProfile(&profile_),
523 &profile_,
524 test_user_share_.user_share(),
525 &mock_error_handler_,
526 kExpectMobileBookmarks));
528 local_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
529 syncer_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
530 int local_count_before = model_->root_node()->GetTotalNodeCount();
531 int syncer_count_before = GetSyncBookmarkCount();
533 syncer::SyncError error = model_associator_->AssociateModels(
534 &local_merge_result_,
535 &syncer_merge_result_);
536 if (error.IsSet())
537 return false;
539 base::MessageLoop::current()->RunUntilIdle();
541 // Verify the merge results were calculated properly.
542 EXPECT_EQ(local_count_before,
543 local_merge_result_.num_items_before_association());
544 EXPECT_EQ(syncer_count_before,
545 syncer_merge_result_.num_items_before_association());
546 EXPECT_EQ(local_merge_result_.num_items_after_association(),
547 local_merge_result_.num_items_before_association() +
548 local_merge_result_.num_items_added() -
549 local_merge_result_.num_items_deleted());
550 EXPECT_EQ(syncer_merge_result_.num_items_after_association(),
551 syncer_merge_result_.num_items_before_association() +
552 syncer_merge_result_.num_items_added() -
553 syncer_merge_result_.num_items_deleted());
554 EXPECT_EQ(model_->root_node()->GetTotalNodeCount(),
555 local_merge_result_.num_items_after_association());
556 EXPECT_EQ(GetSyncBookmarkCount(),
557 syncer_merge_result_.num_items_after_association());
558 return true;
561 void StartSync() {
562 test_user_share_.Reload();
564 ASSERT_TRUE(CreatePermanentBookmarkNodes());
565 ASSERT_TRUE(AssociateModels());
567 // Set up change processor.
568 change_processor_.reset(
569 new BookmarkChangeProcessor(&profile_,
570 model_associator_.get(),
571 &mock_error_handler_));
572 change_processor_->Start(test_user_share_.user_share());
575 void StopSync() {
576 change_processor_.reset();
577 if (model_associator_) {
578 syncer::SyncError error = model_associator_->DisassociateModels();
579 EXPECT_FALSE(error.IsSet());
581 model_associator_.reset();
583 base::MessageLoop::current()->RunUntilIdle();
585 // TODO(akalin): Actually close the database and flush it to disk
586 // (and make StartSync reload from disk). This would require
587 // refactoring TestUserShare.
590 void UnloadBookmarkModel() {
591 profile_.CreateBookmarkModel(false /* delete_bookmarks */);
592 model_ = NULL;
593 base::MessageLoop::current()->RunUntilIdle();
596 bool InitSyncNodeFromChromeNode(const BookmarkNode* bnode,
597 syncer::BaseNode* sync_node) {
598 return model_associator_->InitSyncNodeFromChromeId(bnode->id(),
599 sync_node);
602 void ExpectSyncerNodeMatching(syncer::BaseTransaction* trans,
603 const BookmarkNode* bnode) {
604 std::string truncated_title = base::UTF16ToUTF8(bnode->GetTitle());
605 syncer::SyncAPINameToServerName(truncated_title, &truncated_title);
606 base::TruncateUTF8ToByteSize(truncated_title, 255, &truncated_title);
607 syncer::ServerNameToSyncAPIName(truncated_title, &truncated_title);
609 syncer::ReadNode gnode(trans);
610 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnode, &gnode));
611 // Non-root node titles and parents must match.
612 if (!model_->is_permanent_node(bnode)) {
613 EXPECT_EQ(truncated_title, gnode.GetTitle());
614 EXPECT_EQ(
615 model_associator_->GetChromeNodeFromSyncId(gnode.GetParentId()),
616 bnode->parent());
618 EXPECT_EQ(bnode->is_folder(), gnode.GetIsFolder());
619 if (bnode->is_url())
620 EXPECT_EQ(bnode->url(), GURL(gnode.GetBookmarkSpecifics().url()));
622 // Check that meta info matches.
623 const BookmarkNode::MetaInfoMap* meta_info_map = bnode->GetMetaInfoMap();
624 sync_pb::BookmarkSpecifics specifics = gnode.GetBookmarkSpecifics();
625 if (!meta_info_map) {
626 EXPECT_EQ(0, specifics.meta_info_size());
627 } else {
628 EXPECT_EQ(meta_info_map->size(),
629 static_cast<size_t>(specifics.meta_info_size()));
630 for (int i = 0; i < specifics.meta_info_size(); i++) {
631 BookmarkNode::MetaInfoMap::const_iterator it =
632 meta_info_map->find(specifics.meta_info(i).key());
633 EXPECT_TRUE(it != meta_info_map->end());
634 EXPECT_EQ(it->second, specifics.meta_info(i).value());
638 // Check for position matches.
639 int browser_index = bnode->parent()->GetIndexOf(bnode);
640 if (browser_index == 0) {
641 EXPECT_EQ(gnode.GetPredecessorId(), 0);
642 } else {
643 const BookmarkNode* bprev =
644 bnode->parent()->GetChild(browser_index - 1);
645 syncer::ReadNode gprev(trans);
646 ASSERT_TRUE(InitSyncNodeFromChromeNode(bprev, &gprev));
647 EXPECT_EQ(gnode.GetPredecessorId(), gprev.GetId());
648 EXPECT_EQ(gnode.GetParentId(), gprev.GetParentId());
650 // Note: the managed node is the last child of the root_node but isn't
651 // synced; if CanSyncNode() is false then there is no next node to sync.
652 const BookmarkNode* bnext = NULL;
653 if (browser_index + 1 < bnode->parent()->child_count())
654 bnext = bnode->parent()->GetChild(browser_index + 1);
655 if (!bnext || !CanSyncNode(bnext)) {
656 EXPECT_EQ(gnode.GetSuccessorId(), 0);
657 } else {
658 syncer::ReadNode gnext(trans);
659 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnext, &gnext));
660 EXPECT_EQ(gnode.GetSuccessorId(), gnext.GetId());
661 EXPECT_EQ(gnode.GetParentId(), gnext.GetParentId());
663 if (!bnode->empty())
664 EXPECT_TRUE(gnode.GetFirstChildId());
667 void ExpectSyncerNodeMatching(const BookmarkNode* bnode) {
668 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
669 ExpectSyncerNodeMatching(&trans, bnode);
672 void ExpectBrowserNodeMatching(syncer::BaseTransaction* trans,
673 int64 sync_id) {
674 EXPECT_TRUE(sync_id);
675 const BookmarkNode* bnode =
676 model_associator_->GetChromeNodeFromSyncId(sync_id);
677 ASSERT_TRUE(bnode);
678 ASSERT_TRUE(CanSyncNode(bnode));
680 int64 id = model_associator_->GetSyncIdFromChromeId(bnode->id());
681 EXPECT_EQ(id, sync_id);
682 ExpectSyncerNodeMatching(trans, bnode);
685 void ExpectBrowserNodeUnknown(int64 sync_id) {
686 EXPECT_FALSE(model_associator_->GetChromeNodeFromSyncId(sync_id));
689 void ExpectBrowserNodeKnown(int64 sync_id) {
690 EXPECT_TRUE(model_associator_->GetChromeNodeFromSyncId(sync_id));
693 void ExpectSyncerNodeKnown(const BookmarkNode* node) {
694 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
695 EXPECT_NE(sync_id, syncer::kInvalidId);
698 void ExpectSyncerNodeUnknown(const BookmarkNode* node) {
699 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
700 EXPECT_EQ(sync_id, syncer::kInvalidId);
703 void ExpectBrowserNodeTitle(int64 sync_id, const std::string& title) {
704 const BookmarkNode* bnode =
705 model_associator_->GetChromeNodeFromSyncId(sync_id);
706 ASSERT_TRUE(bnode);
707 EXPECT_EQ(bnode->GetTitle(), base::UTF8ToUTF16(title));
710 void ExpectBrowserNodeURL(int64 sync_id, const std::string& url) {
711 const BookmarkNode* bnode =
712 model_associator_->GetChromeNodeFromSyncId(sync_id);
713 ASSERT_TRUE(bnode);
714 EXPECT_EQ(GURL(url), bnode->url());
717 void ExpectBrowserNodeParent(int64 sync_id, int64 parent_sync_id) {
718 const BookmarkNode* node =
719 model_associator_->GetChromeNodeFromSyncId(sync_id);
720 ASSERT_TRUE(node);
721 const BookmarkNode* parent =
722 model_associator_->GetChromeNodeFromSyncId(parent_sync_id);
723 EXPECT_TRUE(parent);
724 EXPECT_EQ(node->parent(), parent);
727 void ExpectModelMatch(syncer::BaseTransaction* trans) {
728 const BookmarkNode* root = model_->root_node();
729 #if defined(OS_IOS)
730 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 0);
731 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 1);
732 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 2);
733 #else
734 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 0);
735 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 1);
736 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 2);
737 #endif
739 std::stack<int64> stack;
740 stack.push(bookmark_bar_id());
741 while (!stack.empty()) {
742 int64 id = stack.top();
743 stack.pop();
744 if (!id) continue;
746 ExpectBrowserNodeMatching(trans, id);
748 syncer::ReadNode gnode(trans);
749 ASSERT_EQ(BaseNode::INIT_OK, gnode.InitByIdLookup(id));
750 stack.push(gnode.GetSuccessorId());
751 if (gnode.GetIsFolder())
752 stack.push(gnode.GetFirstChildId());
756 void ExpectModelMatch() {
757 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
758 ExpectModelMatch(&trans);
761 int64 mobile_bookmarks_id() {
762 return
763 model_associator_->GetSyncIdFromChromeId(model_->mobile_node()->id());
766 int64 other_bookmarks_id() {
767 return
768 model_associator_->GetSyncIdFromChromeId(model_->other_node()->id());
771 int64 bookmark_bar_id() {
772 return model_associator_->GetSyncIdFromChromeId(
773 model_->bookmark_bar_node()->id());
776 private:
777 content::TestBrowserThreadBundle thread_bundle_;
779 protected:
780 TestingProfile profile_;
781 BookmarkModel* model_;
782 syncer::TestUserShare test_user_share_;
783 scoped_ptr<BookmarkChangeProcessor> change_processor_;
784 StrictMock<sync_driver::DataTypeErrorHandlerMock> mock_error_handler_;
785 scoped_ptr<BookmarkModelAssociator> model_associator_;
787 private:
788 syncer::SyncMergeResult local_merge_result_;
789 syncer::SyncMergeResult syncer_merge_result_;
792 TEST_F(ProfileSyncServiceBookmarkTest, InitialState) {
793 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
794 StartSync();
796 EXPECT_TRUE(other_bookmarks_id());
797 EXPECT_TRUE(bookmark_bar_id());
798 EXPECT_TRUE(mobile_bookmarks_id());
800 ExpectModelMatch();
803 // Populate the sync database then start model association. Sync's bookmarks
804 // should end up being copied into the native model, resulting in a successful
805 // "ExpectModelMatch()".
807 // This code has some use for verifying correctness. It's also a very useful
808 // for profiling bookmark ModelAssociation, an important part of some first-time
809 // sync scenarios. Simply increase the kNumFolders and kNumBookmarksPerFolder
810 // as desired, then run the test under a profiler to find hot spots in the model
811 // association code.
812 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociate) {
813 const int kNumBookmarksPerFolder = 10;
814 const int kNumFolders = 10;
816 CreatePermanentBookmarkNodes();
819 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
820 for (int i = 0; i < kNumFolders; ++i) {
821 int64 folder_id =
822 AddFolderToShare(&trans, base::StringPrintf("folder%05d", i));
823 for (int j = 0; j < kNumBookmarksPerFolder; ++j) {
824 AddBookmarkToShare(
825 &trans, folder_id, base::StringPrintf("bookmark%05d", j),
826 base::StringPrintf("http://www.google.com/search?q=%05d", j));
831 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
832 StartSync();
834 ExpectModelMatch();
837 // Tests bookmark association when nodes exists in the native model only.
838 // These entries should be copied to Sync directory during association process.
839 TEST_F(ProfileSyncServiceBookmarkTest,
840 InitialModelAssociateWithBookmarkModelNodes) {
841 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
842 const BookmarkNode* folder =
843 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("foobar"));
844 model_->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
845 model_->AddURL(folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
846 GURL("http://www.easypie.com/"));
847 model_->AddURL(folder, 1, base::ASCIIToUTF16("Airplanes"),
848 GURL("http://www.easyjet.com/"));
850 StartSync();
851 ExpectModelMatch();
854 // Tests bookmark association case when there is an entry in the delete journal
855 // that matches one of native bookmarks.
856 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociateWithDeleteJournal) {
857 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
858 const BookmarkNode* folder = model_->AddFolder(model_->bookmark_bar_node(), 0,
859 base::ASCIIToUTF16("foobar"));
860 const BookmarkNode* bookmark =
861 model_->AddURL(folder, 0, base::ASCIIToUTF16("Airplanes"),
862 GURL("http://www.easyjet.com/"));
864 CreatePermanentBookmarkNodes();
866 // Create entries matching the folder and the bookmark above.
867 int64 folder_id, bookmark_id;
869 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
870 folder_id = AddFolderToShare(&trans, "foobar");
871 bookmark_id = AddBookmarkToShare(&trans, folder_id, "Airplanes",
872 "http://www.easyjet.com/");
875 // Associate the bookmark sync node with the native model one and make
876 // it look like it was deleted by a server update.
878 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
879 syncer::WriteNode node(&trans);
880 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(bookmark_id));
882 node.GetMutableEntryForTest()->PutLocalExternalId(bookmark->id());
884 MakeServerUpdate(&trans, &node);
885 node.GetMutableEntryForTest()->PutServerIsDel(true);
886 node.GetMutableEntryForTest()->PutIsDel(true);
889 ASSERT_TRUE(AssociateModels());
890 ExpectModelMatch();
892 // The bookmark node should be deleted.
893 EXPECT_EQ(0, folder->child_count());
896 // Tests that the external ID is used to match the right folder amoung
897 // multiple folders with the same name during the native model traversal.
898 // Also tests that the external ID is used to match the right bookmark
899 // among multiple identical bookmarks when dealing with the delete journal.
900 TEST_F(ProfileSyncServiceBookmarkTest,
901 InitialModelAssociateVerifyExternalIdMatch) {
902 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
903 const int kNumFolders = 10;
904 const int kNumBookmarks = 10;
905 const int kFolderToIncludeBookmarks = 7;
906 const int kBookmarkToDelete = 4;
908 int64 folder_ids[kNumFolders];
909 int64 bookmark_ids[kNumBookmarks];
911 // Create native folders and bookmarks with identical names. Only
912 // one of the folders contains bookmarks and others are empty. Here is the
913 // expected tree shape:
914 // Bookmarks bar
915 // +- folder (#0)
916 // +- folder (#1)
917 // ...
918 // +- folder (#7) <-- Only this folder contains bookmarks.
919 // +- bookmark (#0)
920 // +- bookmark (#1)
921 // ...
922 // +- bookmark (#4) <-- Only this one bookmark should be removed later.
923 // ...
924 // +- bookmark (#9)
925 // ...
926 // +- folder (#9)
928 const BookmarkNode* parent_folder = nullptr;
929 for (int i = 0; i < kNumFolders; i++) {
930 const BookmarkNode* folder = model_->AddFolder(
931 model_->bookmark_bar_node(), i, base::ASCIIToUTF16("folder"));
932 folder_ids[i] = folder->id();
933 if (i == kFolderToIncludeBookmarks) {
934 parent_folder = folder;
938 for (int i = 0; i < kNumBookmarks; i++) {
939 const BookmarkNode* bookmark =
940 model_->AddURL(parent_folder, i, base::ASCIIToUTF16("bookmark"),
941 GURL("http://www.google.com/"));
942 bookmark_ids[i] = bookmark->id();
945 // Number of nodes in bookmark bar before association.
946 int total_node_count = model_->bookmark_bar_node()->GetTotalNodeCount();
948 CreatePermanentBookmarkNodes();
950 int64 sync_bookmark_id_to_delete = 0;
952 // Create sync folders matching native folders above.
953 int64 parent_id = 0;
954 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
955 // Create in reverse order because AddFolderToShare passes NULL for
956 // |predecessor| argument.
957 for (int i = kNumFolders - 1; i >= 0; i--) {
958 int64 id = AddFolderToShare(&trans, "folder");
960 // Pre-map sync folders to native folders by setting
961 // external ID. This will verify that the association algorithm picks
962 // the right ones despite all of them having identical names.
963 // More specifically this will help to avoid cloning bookmarks from
964 // a wrong folder.
965 syncer::WriteNode node(&trans);
966 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
967 node.GetMutableEntryForTest()->PutLocalExternalId(folder_ids[i]);
969 if (i == kFolderToIncludeBookmarks) {
970 parent_id = id;
974 // Create sync bookmark matching native bookmarks above in reverse order
975 // because AddBookmarkToShare passes NULL for |predecessor| argument.
976 for (int i = kNumBookmarks - 1; i >= 0; i--) {
977 int id = AddBookmarkToShare(&trans, parent_id, "bookmark",
978 "http://www.google.com/");
980 // Pre-map sync bookmarks to native bookmarks by setting
981 // external ID. This will verify that the association algorithm picks
982 // the right ones despite all of them having identical names and URLs.
983 syncer::WriteNode node(&trans);
984 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
985 node.GetMutableEntryForTest()->PutLocalExternalId(bookmark_ids[i]);
987 if (i == kBookmarkToDelete) {
988 sync_bookmark_id_to_delete = id;
993 // Make one bookmark deleted.
995 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
996 syncer::WriteNode node(&trans);
997 EXPECT_EQ(BaseNode::INIT_OK,
998 node.InitByIdLookup(sync_bookmark_id_to_delete));
1000 MakeServerUpdate(&trans, &node);
1001 node.GetMutableEntryForTest()->PutServerIsDel(true);
1002 node.GetMutableEntryForTest()->PutIsDel(true);
1005 // Perform association.
1006 ASSERT_TRUE(AssociateModels());
1007 ExpectModelMatch();
1009 // Only one native node should have been deleted and no nodes cloned due to
1010 // matching folder names.
1011 EXPECT_EQ(kNumFolders, model_->bookmark_bar_node()->child_count());
1012 EXPECT_EQ(kNumBookmarks - 1, parent_folder->child_count());
1013 EXPECT_EQ(total_node_count - 1,
1014 model_->bookmark_bar_node()->GetTotalNodeCount());
1016 // Verify that the right bookmark got deleted and no bookmarks reordered.
1017 for (int i = 0; i < parent_folder->child_count(); i++) {
1018 int index_in_bookmark_ids = (i < kBookmarkToDelete) ? i : i + 1;
1019 EXPECT_EQ(bookmark_ids[index_in_bookmark_ids],
1020 parent_folder->GetChild(i)->id());
1024 // Verifies that the bookmark association skips sync nodes with invalid URLs.
1025 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociateWithInvalidUrl) {
1026 EXPECT_CALL(mock_error_handler_, CreateAndUploadError(_, _, _))
1027 .WillOnce(Return(syncer::SyncError()));
1029 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1030 // On the local side create a folder and two nodes.
1031 const BookmarkNode* folder = model_->AddFolder(model_->bookmark_bar_node(), 0,
1032 base::ASCIIToUTF16("folder"));
1033 model_->AddURL(folder, 0, base::ASCIIToUTF16("node1"),
1034 GURL("http://www.node1.com/"));
1035 model_->AddURL(folder, 1, base::ASCIIToUTF16("node2"),
1036 GURL("http://www.node2.com/"));
1038 // On the sync side create a matching folder, one matching node, one
1039 // unmatching node, and one node with an invalid URL.
1040 CreatePermanentBookmarkNodes();
1042 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1043 int64 folder_id = AddFolderToShare(&trans, "folder");
1044 // Please note that each AddBookmarkToShare inserts the node at the front
1045 // so the actual order of children in the directory will be opposite.
1046 AddBookmarkToShare(&trans, folder_id, "node2", "http://www.node2.com/");
1047 AddBookmarkToShare(&trans, folder_id, "node3", "");
1048 AddBookmarkToShare(&trans, folder_id, "node4", "http://www.node4.com/");
1051 // Perform association.
1052 StartSync();
1054 // Concatenate resulting titles of native nodes.
1055 std::string native_titles;
1056 for (int i = 0; i < folder->child_count(); i++) {
1057 if (!native_titles.empty())
1058 native_titles += ",";
1059 const BookmarkNode* child = folder->GetChild(i);
1060 native_titles += base::UTF16ToUTF8(child->GetTitle());
1063 // Expect the order of nodes to follow the sync order (see note above), the
1064 // node with the invalid URL to be skipped, and the extra native node to be
1065 // at the end.
1066 EXPECT_EQ("node4,node2,node1", native_titles);
1069 TEST_F(ProfileSyncServiceBookmarkTest, BookmarkModelOperations) {
1070 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1071 StartSync();
1073 // Test addition.
1074 const BookmarkNode* folder =
1075 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("foobar"));
1076 ExpectSyncerNodeMatching(folder);
1077 ExpectModelMatch();
1078 const BookmarkNode* folder2 =
1079 model_->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
1080 ExpectSyncerNodeMatching(folder2);
1081 ExpectModelMatch();
1082 const BookmarkNode* url1 = model_->AddURL(
1083 folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
1084 GURL("http://www.easypie.com/"));
1085 ExpectSyncerNodeMatching(url1);
1086 ExpectModelMatch();
1087 const BookmarkNode* url2 = model_->AddURL(
1088 folder, 1, base::ASCIIToUTF16("Airplanes"),
1089 GURL("http://www.easyjet.com/"));
1090 ExpectSyncerNodeMatching(url2);
1091 ExpectModelMatch();
1092 // Test addition.
1093 const BookmarkNode* mobile_folder =
1094 model_->AddFolder(model_->mobile_node(), 0, base::ASCIIToUTF16("pie"));
1095 ExpectSyncerNodeMatching(mobile_folder);
1096 ExpectModelMatch();
1098 // Test modification.
1099 model_->SetTitle(url2, base::ASCIIToUTF16("EasyJet"));
1100 ExpectModelMatch();
1101 model_->Move(url1, folder2, 0);
1102 ExpectModelMatch();
1103 model_->Move(folder2, model_->bookmark_bar_node(), 0);
1104 ExpectModelMatch();
1105 model_->SetTitle(folder2, base::ASCIIToUTF16("Not Nested"));
1106 ExpectModelMatch();
1107 model_->Move(folder, folder2, 0);
1108 ExpectModelMatch();
1109 model_->SetTitle(folder, base::ASCIIToUTF16("who's nested now?"));
1110 ExpectModelMatch();
1111 model_->Copy(url2, model_->bookmark_bar_node(), 0);
1112 ExpectModelMatch();
1113 model_->SetTitle(mobile_folder, base::ASCIIToUTF16("strawberry"));
1114 ExpectModelMatch();
1116 // Test deletion.
1117 // Delete a single item.
1118 model_->Remove(url2);
1119 ExpectModelMatch();
1120 // Delete an item with several children.
1121 model_->Remove(folder2);
1122 ExpectModelMatch();
1123 model_->Remove(model_->mobile_node()->GetChild(0));
1124 ExpectModelMatch();
1127 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeProcessing) {
1128 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1129 StartSync();
1131 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1133 FakeServerChange adds(&trans);
1134 int64 f1 = adds.AddFolder("Server Folder B", bookmark_bar_id(), 0);
1135 int64 f2 = adds.AddFolder("Server Folder A", bookmark_bar_id(), f1);
1136 int64 u1 = adds.AddURL("Some old site", "ftp://nifty.andrew.cmu.edu/",
1137 bookmark_bar_id(), f2);
1138 int64 u2 = adds.AddURL("Nifty", "ftp://nifty.andrew.cmu.edu/", f1, 0);
1139 // u3 is a duplicate URL
1140 int64 u3 = adds.AddURL("Nifty2", "ftp://nifty.andrew.cmu.edu/", f1, u2);
1141 // u4 is a duplicate title, different URL.
1142 adds.AddURL("Some old site", "http://slog.thestranger.com/",
1143 bookmark_bar_id(), u1);
1144 // u5 tests an empty-string title.
1145 std::string javascript_url(
1146 "javascript:(function(){var w=window.open(" \
1147 "'about:blank','gnotesWin','location=0,menubar=0," \
1148 "scrollbars=0,status=0,toolbar=0,width=300," \
1149 "height=300,resizable');});");
1150 adds.AddURL(std::string(), javascript_url, other_bookmarks_id(), 0);
1151 int64 u6 = adds.AddURL(
1152 "Sync1", "http://www.syncable.edu/", mobile_bookmarks_id(), 0);
1154 syncer::ChangeRecordList::const_iterator it;
1155 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
1156 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1157 ExpectBrowserNodeUnknown(it->id);
1159 adds.ApplyPendingChanges(change_processor_.get());
1161 // Make sure the bookmark model received all of the nodes in |adds|.
1162 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1163 ExpectBrowserNodeMatching(&trans, it->id);
1164 ExpectModelMatch(&trans);
1166 // Part two: test modifications.
1167 FakeServerChange mods(&trans);
1168 // Mess with u2, and move it into empty folder f2
1169 // TODO(ncarter): Determine if we allow ModifyURL ops or not.
1170 /* std::string u2_old_url = mods.ModifyURL(u2, "http://www.google.com"); */
1171 std::string u2_old_title = mods.ModifyTitle(u2, "The Google");
1172 int64 u2_old_parent = mods.ModifyPosition(u2, f2, 0);
1174 // Now move f1 after u2.
1175 std::string f1_old_title = mods.ModifyTitle(f1, "Server Folder C");
1176 int64 f1_old_parent = mods.ModifyPosition(f1, f2, u2);
1178 // Then add u3 after f1.
1179 int64 u3_old_parent = mods.ModifyPosition(u3, f2, f1);
1181 std::string u6_old_title = mods.ModifyTitle(u6, "Mobile Folder A");
1183 // Test that the property changes have not yet taken effect.
1184 ExpectBrowserNodeTitle(u2, u2_old_title);
1185 /* ExpectBrowserNodeURL(u2, u2_old_url); */
1186 ExpectBrowserNodeParent(u2, u2_old_parent);
1188 ExpectBrowserNodeTitle(f1, f1_old_title);
1189 ExpectBrowserNodeParent(f1, f1_old_parent);
1191 ExpectBrowserNodeParent(u3, u3_old_parent);
1193 ExpectBrowserNodeTitle(u6, u6_old_title);
1195 // Apply the changes.
1196 mods.ApplyPendingChanges(change_processor_.get());
1198 // Check for successful application.
1199 for (it = mods.changes().begin(); it != mods.changes().end(); ++it)
1200 ExpectBrowserNodeMatching(&trans, it->id);
1201 ExpectModelMatch(&trans);
1203 // Part 3: Test URL deletion.
1204 FakeServerChange dels(&trans);
1205 dels.Delete(u2);
1206 dels.Delete(u3);
1207 dels.Delete(u6);
1209 ExpectBrowserNodeKnown(u2);
1210 ExpectBrowserNodeKnown(u3);
1212 dels.ApplyPendingChanges(change_processor_.get());
1214 ExpectBrowserNodeUnknown(u2);
1215 ExpectBrowserNodeUnknown(u3);
1216 ExpectBrowserNodeUnknown(u6);
1217 ExpectModelMatch(&trans);
1220 // Tests a specific case in ApplyModelChanges where we move the
1221 // children out from under a parent, and then delete the parent
1222 // in the same changelist. The delete shows up first in the changelist,
1223 // requiring the children to be moved to a temporary location.
1224 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeRequiringFosterParent) {
1225 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1226 StartSync();
1228 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1230 // Stress the immediate children of other_node because that's where
1231 // ApplyModelChanges puts a temporary foster parent node.
1232 std::string url("http://dev.chromium.org/");
1233 FakeServerChange adds(&trans);
1234 int64 f0 = other_bookmarks_id(); // + other_node
1235 int64 f1 = adds.AddFolder("f1", f0, 0); // + f1
1236 int64 f2 = adds.AddFolder("f2", f1, 0); // + f2
1237 int64 u3 = adds.AddURL( "u3", url, f2, 0); // + u3 NOLINT
1238 int64 u4 = adds.AddURL( "u4", url, f2, u3); // + u4 NOLINT
1239 int64 u5 = adds.AddURL( "u5", url, f1, f2); // + u5 NOLINT
1240 int64 f6 = adds.AddFolder("f6", f1, u5); // + f6
1241 int64 u7 = adds.AddURL( "u7", url, f0, f1); // + u7 NOLINT
1243 syncer::ChangeRecordList::const_iterator it;
1244 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
1245 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1246 ExpectBrowserNodeUnknown(it->id);
1248 adds.ApplyPendingChanges(change_processor_.get());
1250 // Make sure the bookmark model received all of the nodes in |adds|.
1251 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1252 ExpectBrowserNodeMatching(&trans, it->id);
1253 ExpectModelMatch(&trans);
1255 // We have to do the moves before the deletions, but FakeServerChange will
1256 // put the deletion at the front of the changelist.
1257 FakeServerChange ops(&trans);
1258 ops.ModifyPosition(f6, other_bookmarks_id(), 0);
1259 ops.ModifyPosition(u3, other_bookmarks_id(), f1); // Prev == f1 is OK here.
1260 ops.ModifyPosition(f2, other_bookmarks_id(), u7);
1261 ops.ModifyPosition(u7, f2, 0);
1262 ops.ModifyPosition(u4, other_bookmarks_id(), f2);
1263 ops.ModifyPosition(u5, f6, 0);
1264 ops.Delete(f1);
1266 ops.ApplyPendingChanges(change_processor_.get());
1268 ExpectModelMatch(&trans);
1271 // Simulate a server change record containing a valid but non-canonical URL.
1272 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeWithNonCanonicalURL) {
1273 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1274 StartSync();
1277 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1279 FakeServerChange adds(&trans);
1280 std::string url("http://dev.chromium.org");
1281 EXPECT_NE(GURL(url).spec(), url);
1282 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1284 adds.ApplyPendingChanges(change_processor_.get());
1286 EXPECT_EQ(1, model_->other_node()->child_count());
1287 ExpectModelMatch(&trans);
1290 // Now reboot the sync service, forcing a merge step.
1291 StopSync();
1292 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1293 StartSync();
1295 // There should still be just the one bookmark.
1296 EXPECT_EQ(1, model_->other_node()->child_count());
1297 ExpectModelMatch();
1300 // Simulate a server change record containing an invalid URL (per GURL).
1301 // TODO(ncarter): Disabled due to crashes. Fix bug 1677563.
1302 TEST_F(ProfileSyncServiceBookmarkTest, DISABLED_ServerChangeWithInvalidURL) {
1303 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1304 StartSync();
1306 int child_count = 0;
1308 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1310 FakeServerChange adds(&trans);
1311 std::string url("x");
1312 EXPECT_FALSE(GURL(url).is_valid());
1313 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1315 adds.ApplyPendingChanges(change_processor_.get());
1317 // We're lenient about what should happen -- the model could wind up with
1318 // the node or without it; but things should be consistent, and we
1319 // shouldn't crash.
1320 child_count = model_->other_node()->child_count();
1321 EXPECT_TRUE(child_count == 0 || child_count == 1);
1322 ExpectModelMatch(&trans);
1325 // Now reboot the sync service, forcing a merge step.
1326 StopSync();
1327 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1328 StartSync();
1330 // Things ought not to have changed.
1331 EXPECT_EQ(model_->other_node()->child_count(), child_count);
1332 ExpectModelMatch();
1336 // Test strings that might pose a problem if the titles ever became used as
1337 // file names in the sync backend.
1338 TEST_F(ProfileSyncServiceBookmarkTest, CornerCaseNames) {
1339 // TODO(ncarter): Bug 1570238 explains the failure of this test.
1340 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1341 StartSync();
1343 const char* names[] = {
1344 // The empty string.
1346 // Illegal Windows filenames.
1347 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4",
1348 "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3",
1349 "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1350 // Current/parent directory markers.
1351 ".", "..", "...",
1352 // Files created automatically by the Windows shell.
1353 "Thumbs.db", ".DS_Store",
1354 // Names including Win32-illegal characters, and path separators.
1355 "foo/bar", "foo\\bar", "foo?bar", "foo:bar", "foo|bar", "foo\"bar",
1356 "foo'bar", "foo<bar", "foo>bar", "foo%bar", "foo*bar", "foo]bar",
1357 "foo[bar",
1358 // A name with title > 255 characters
1359 "012345678901234567890123456789012345678901234567890123456789012345678901"
1360 "234567890123456789012345678901234567890123456789012345678901234567890123"
1361 "456789012345678901234567890123456789012345678901234567890123456789012345"
1362 "678901234567890123456789012345678901234567890123456789012345678901234567"
1363 "890123456789"
1365 // Create both folders and bookmarks using each name.
1366 GURL url("http://www.doublemint.com");
1367 for (size_t i = 0; i < arraysize(names); ++i) {
1368 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16(names[i]));
1369 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16(names[i]), url);
1372 // Verify that the browser model matches the sync model.
1373 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1374 2*arraysize(names));
1375 ExpectModelMatch();
1377 // Restart and re-associate. Verify things still match.
1378 StopSync();
1379 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1380 StartSync();
1381 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1382 2*arraysize(names));
1383 ExpectModelMatch();
1386 // Stress the internal representation of position by sparse numbers. We want
1387 // to repeatedly bisect the range of available positions, to force the
1388 // syncer code to renumber its ranges. Pick a number big enough so that it
1389 // would exhaust 32bits of room between items a couple of times.
1390 TEST_F(ProfileSyncServiceBookmarkTest, RepeatedMiddleInsertion) {
1391 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1392 StartSync();
1394 static const int kTimesToInsert = 256;
1396 // Create two book-end nodes to insert between.
1397 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("Alpha"));
1398 model_->AddFolder(model_->other_node(), 1, base::ASCIIToUTF16("Omega"));
1399 int count = 2;
1401 // Test insertion in first half of range by repeatedly inserting in second
1402 // position.
1403 for (int i = 0; i < kTimesToInsert; ++i) {
1404 base::string16 title =
1405 base::ASCIIToUTF16("Pre-insertion ") + base::IntToString16(i);
1406 model_->AddFolder(model_->other_node(), 1, title);
1407 count++;
1410 // Test insertion in second half of range by repeatedly inserting in
1411 // second-to-last position.
1412 for (int i = 0; i < kTimesToInsert; ++i) {
1413 base::string16 title =
1414 base::ASCIIToUTF16("Post-insertion ") + base::IntToString16(i);
1415 model_->AddFolder(model_->other_node(), count - 1, title);
1416 count++;
1419 // Verify that the browser model matches the sync model.
1420 EXPECT_EQ(model_->other_node()->child_count(), count);
1421 ExpectModelMatch();
1424 // Introduce a consistency violation into the model, and see that it
1425 // puts itself into a lame, error state.
1426 TEST_F(ProfileSyncServiceBookmarkTest, UnrecoverableErrorSuspendsService) {
1427 EXPECT_CALL(mock_error_handler_,
1428 OnSingleDataTypeUnrecoverableError(_));
1430 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1431 StartSync();
1433 // Add a node which will be the target of the consistency violation.
1434 const BookmarkNode* node =
1435 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("node"));
1436 ExpectSyncerNodeMatching(node);
1438 // Now destroy the syncer node as if we were the ProfileSyncService without
1439 // updating the ProfileSyncService state. This should introduce
1440 // inconsistency between the two models.
1442 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1443 syncer::WriteNode sync_node(&trans);
1444 ASSERT_TRUE(InitSyncNodeFromChromeNode(node, &sync_node));
1445 sync_node.Tombstone();
1447 // The models don't match at this point, but the ProfileSyncService
1448 // doesn't know it yet.
1449 ExpectSyncerNodeKnown(node);
1451 // Add a child to the inconsistent node. This should cause detection of the
1452 // problem and the syncer should stop processing changes.
1453 model_->AddFolder(node, 0, base::ASCIIToUTF16("nested"));
1456 // See what happens if we run model association when there are two exact URL
1457 // duplicate bookmarks. The BookmarkModelAssociator should not fall over when
1458 // this happens.
1459 TEST_F(ProfileSyncServiceBookmarkTest, MergeDuplicates) {
1460 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1461 StartSync();
1463 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1464 GURL("http://dup.com/"));
1465 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1466 GURL("http://dup.com/"));
1468 EXPECT_EQ(2, model_->other_node()->child_count());
1470 // Restart the sync service to trigger model association.
1471 StopSync();
1472 StartSync();
1474 EXPECT_EQ(2, model_->other_node()->child_count());
1475 ExpectModelMatch();
1478 TEST_F(ProfileSyncServiceBookmarkTest, ApplySyncDeletesFromJournal) {
1479 // Initialize sync model and bookmark model as:
1480 // URL 0
1481 // Folder 1
1482 // |-- URL 1
1483 // +-- Folder 2
1484 // +-- URL 2
1485 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1486 int64 u0 = 0;
1487 int64 f1 = 0;
1488 int64 u1 = 0;
1489 int64 f2 = 0;
1490 int64 u2 = 0;
1491 StartSync();
1492 int fixed_sync_bk_count = GetSyncBookmarkCount();
1494 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1495 FakeServerChange adds(&trans);
1496 u0 = adds.AddURL("URL 0", "http://plus.google.com/", bookmark_bar_id(), 0);
1497 f1 = adds.AddFolder("Folder 1", bookmark_bar_id(), u0);
1498 u1 = adds.AddURL("URL 1", "http://www.google.com/", f1, 0);
1499 f2 = adds.AddFolder("Folder 2", f1, u1);
1500 u2 = adds.AddURL("URL 2", "http://mail.google.com/", f2, 0);
1501 adds.ApplyPendingChanges(change_processor_.get());
1503 StopSync();
1505 // Reload bookmark model and disable model saving to make sync changes not
1506 // persisted.
1507 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1508 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1509 EXPECT_EQ(fixed_sync_bk_count + 5, GetSyncBookmarkCount());
1510 StartSync();
1512 // Remove all folders/bookmarks except u3 added above.
1513 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1514 MakeServerUpdate(&trans, f1);
1515 MakeServerUpdate(&trans, u1);
1516 MakeServerUpdate(&trans, f2);
1517 MakeServerUpdate(&trans, u2);
1518 FakeServerChange dels(&trans);
1519 dels.Delete(u2);
1520 dels.Delete(f2);
1521 dels.Delete(u1);
1522 dels.Delete(f1);
1523 dels.ApplyPendingChanges(change_processor_.get());
1525 StopSync();
1526 // Bookmark bar itself and u0 remain.
1527 EXPECT_EQ(2, model_->bookmark_bar_node()->GetTotalNodeCount());
1529 // Reload bookmarks including ones deleted in sync model from storage.
1530 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1531 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1532 // Add a bookmark under f1 when sync is off so that f1 will not be
1533 // deleted even when f1 matches delete journal because it's not empty.
1534 model_->AddURL(model_->bookmark_bar_node()->GetChild(1),
1535 0, base::UTF8ToUTF16("local"), GURL("http://www.youtube.com"));
1536 // Sync model has fixed bookmarks nodes and u3.
1537 EXPECT_EQ(fixed_sync_bk_count + 1, GetSyncBookmarkCount());
1538 StartSync();
1539 // Expect 4 bookmarks after model association because u2, f2, u1 are removed
1540 // by delete journal, f1 is not removed by delete journal because it's
1541 // not empty due to www.youtube.com added above.
1542 EXPECT_EQ(4, model_->bookmark_bar_node()->GetTotalNodeCount());
1543 EXPECT_EQ(base::UTF8ToUTF16("URL 0"),
1544 model_->bookmark_bar_node()->GetChild(0)->GetTitle());
1545 EXPECT_EQ(base::UTF8ToUTF16("Folder 1"),
1546 model_->bookmark_bar_node()->GetChild(1)->GetTitle());
1547 EXPECT_EQ(base::UTF8ToUTF16("local"),
1548 model_->bookmark_bar_node()->GetChild(1)->GetChild(0)->GetTitle());
1549 StopSync();
1551 // Verify purging of delete journals.
1552 // Delete journals for u2, f2, u1 remains because they are used in last
1553 // association.
1554 EXPECT_EQ(3u, test_user_share_.GetDeleteJournalSize());
1555 StartSync();
1556 StopSync();
1557 // Reload again and all delete journals should be gone because none is used
1558 // in last association.
1559 ASSERT_TRUE(test_user_share_.Reload());
1560 EXPECT_EQ(0u, test_user_share_.GetDeleteJournalSize());
1563 struct TestData {
1564 const char* title;
1565 const char* url;
1568 // Map from bookmark node ID to its version.
1569 typedef std::map<int64, int64> BookmarkNodeVersionMap;
1571 // TODO(ncarter): Integrate the existing TestNode/PopulateNodeFromString code
1572 // in the bookmark model unittest, to make it simpler to set up test data
1573 // here (and reduce the amount of duplication among tests), and to reduce the
1574 // duplication.
1575 class ProfileSyncServiceBookmarkTestWithData
1576 : public ProfileSyncServiceBookmarkTest {
1577 public:
1578 ProfileSyncServiceBookmarkTestWithData();
1580 protected:
1581 // Populates or compares children of the given bookmark node from/with the
1582 // given test data array with the given size. |running_count| is updated as
1583 // urls are added. It is used to set the creation date (or test the creation
1584 // date for CompareWithTestData()).
1585 void PopulateFromTestData(const BookmarkNode* node,
1586 const TestData* data,
1587 int size,
1588 int* running_count);
1589 void CompareWithTestData(const BookmarkNode* node,
1590 const TestData* data,
1591 int size,
1592 int* running_count);
1594 void ExpectBookmarkModelMatchesTestData();
1595 void WriteTestDataToBookmarkModel();
1597 // Output transaction versions of |node| and nodes under it to
1598 // |node_versions|.
1599 void GetTransactionVersions(const BookmarkNode* root,
1600 BookmarkNodeVersionMap* node_versions);
1602 // Verify transaction versions of bookmark nodes and sync nodes are equal
1603 // recursively. If node is in |version_expected|, versions should match
1604 // there, too.
1605 void ExpectTransactionVersionMatch(
1606 const BookmarkNode* node,
1607 const BookmarkNodeVersionMap& version_expected);
1609 private:
1610 const base::Time start_time_;
1612 DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceBookmarkTestWithData);
1615 namespace {
1617 // Constants for bookmark model that looks like:
1618 // |-- Bookmark bar
1619 // | |-- u2, http://www.u2.com/
1620 // | |-- f1
1621 // | | |-- f1u4, http://www.f1u4.com/
1622 // | | |-- f1u2, http://www.f1u2.com/
1623 // | | |-- f1u3, http://www.f1u3.com/
1624 // | | +-- f1u1, http://www.f1u1.com/
1625 // | |-- u1, http://www.u1.com/
1626 // | +-- f2
1627 // | |-- f2u2, http://www.f2u2.com/
1628 // | |-- f2u4, http://www.f2u4.com/
1629 // | |-- f2u3, http://www.f2u3.com/
1630 // | +-- f2u1, http://www.f2u1.com/
1631 // +-- Other bookmarks
1632 // | |-- f3
1633 // | | |-- f3u4, http://www.f3u4.com/
1634 // | | |-- f3u2, http://www.f3u2.com/
1635 // | | |-- f3u3, http://www.f3u3.com/
1636 // | | +-- f3u1, http://www.f3u1.com/
1637 // | |-- u4, http://www.u4.com/
1638 // | |-- u3, http://www.u3.com/
1639 // | --- f4
1640 // | | |-- f4u1, http://www.f4u1.com/
1641 // | | |-- f4u2, http://www.f4u2.com/
1642 // | | |-- f4u3, http://www.f4u3.com/
1643 // | | +-- f4u4, http://www.f4u4.com/
1644 // | |-- dup
1645 // | | +-- dupu1, http://www.dupu1.com/
1646 // | +-- dup
1647 // | | +-- dupu2, http://www.dupu1.com/
1648 // | +-- ls , http://www.ls.com/
1649 // |
1650 // +-- Mobile bookmarks
1651 // |-- f5
1652 // | |-- f5u1, http://www.f5u1.com/
1653 // |-- f6
1654 // | |-- f6u1, http://www.f6u1.com/
1655 // | |-- f6u2, http://www.f6u2.com/
1656 // +-- u5, http://www.u5.com/
1658 static TestData kBookmarkBarChildren[] = {
1659 { "u2", "http://www.u2.com/" },
1660 { "f1", NULL },
1661 { "u1", "http://www.u1.com/" },
1662 { "f2", NULL },
1664 static TestData kF1Children[] = {
1665 { "f1u4", "http://www.f1u4.com/" },
1666 { "f1u2", "http://www.f1u2.com/" },
1667 { "f1u3", "http://www.f1u3.com/" },
1668 { "f1u1", "http://www.f1u1.com/" },
1670 static TestData kF2Children[] = {
1671 { "f2u2", "http://www.f2u2.com/" },
1672 { "f2u4", "http://www.f2u4.com/" },
1673 { "f2u3", "http://www.f2u3.com/" },
1674 { "f2u1", "http://www.f2u1.com/" },
1677 static TestData kOtherBookmarkChildren[] = {
1678 { "f3", NULL },
1679 { "u4", "http://www.u4.com/" },
1680 { "u3", "http://www.u3.com/" },
1681 { "f4", NULL },
1682 { "dup", NULL },
1683 { "dup", NULL },
1684 { " ls ", "http://www.ls.com/" }
1686 static TestData kF3Children[] = {
1687 { "f3u4", "http://www.f3u4.com/" },
1688 { "f3u2", "http://www.f3u2.com/" },
1689 { "f3u3", "http://www.f3u3.com/" },
1690 { "f3u1", "http://www.f3u1.com/" },
1692 static TestData kF4Children[] = {
1693 { "f4u1", "http://www.f4u1.com/" },
1694 { "f4u2", "http://www.f4u2.com/" },
1695 { "f4u3", "http://www.f4u3.com/" },
1696 { "f4u4", "http://www.f4u4.com/" },
1698 static TestData kDup1Children[] = {
1699 { "dupu1", "http://www.dupu1.com/" },
1701 static TestData kDup2Children[] = {
1702 { "dupu2", "http://www.dupu2.com/" },
1705 static TestData kMobileBookmarkChildren[] = {
1706 { "f5", NULL },
1707 { "f6", NULL },
1708 { "u5", "http://www.u5.com/" },
1710 static TestData kF5Children[] = {
1711 { "f5u1", "http://www.f5u1.com/" },
1712 { "f5u2", "http://www.f5u2.com/" },
1714 static TestData kF6Children[] = {
1715 { "f6u1", "http://www.f6u1.com/" },
1716 { "f6u2", "http://www.f6u2.com/" },
1719 } // anonymous namespace.
1721 ProfileSyncServiceBookmarkTestWithData::
1722 ProfileSyncServiceBookmarkTestWithData()
1723 : start_time_(base::Time::Now()) {
1726 void ProfileSyncServiceBookmarkTestWithData::PopulateFromTestData(
1727 const BookmarkNode* node,
1728 const TestData* data,
1729 int size,
1730 int* running_count) {
1731 DCHECK(node);
1732 DCHECK(data);
1733 DCHECK(node->is_folder());
1734 for (int i = 0; i < size; ++i) {
1735 const TestData& item = data[i];
1736 if (item.url) {
1737 const base::Time add_time =
1738 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1739 model_->AddURLWithCreationTimeAndMetaInfo(node,
1741 base::UTF8ToUTF16(item.title),
1742 GURL(item.url),
1743 add_time,
1744 NULL);
1745 } else {
1746 model_->AddFolder(node, i, base::UTF8ToUTF16(item.title));
1748 (*running_count)++;
1752 void ProfileSyncServiceBookmarkTestWithData::CompareWithTestData(
1753 const BookmarkNode* node,
1754 const TestData* data,
1755 int size,
1756 int* running_count) {
1757 DCHECK(node);
1758 DCHECK(data);
1759 DCHECK(node->is_folder());
1760 ASSERT_EQ(size, node->child_count());
1761 for (int i = 0; i < size; ++i) {
1762 const BookmarkNode* child_node = node->GetChild(i);
1763 const TestData& item = data[i];
1764 GURL url = GURL(item.url == NULL ? "" : item.url);
1765 BookmarkNode test_node(url);
1766 test_node.SetTitle(base::UTF8ToUTF16(item.title));
1767 EXPECT_EQ(child_node->GetTitle(), test_node.GetTitle());
1768 if (item.url) {
1769 EXPECT_FALSE(child_node->is_folder());
1770 EXPECT_TRUE(child_node->is_url());
1771 EXPECT_EQ(child_node->url(), test_node.url());
1772 const base::Time expected_time =
1773 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1774 EXPECT_EQ(expected_time.ToInternalValue(),
1775 child_node->date_added().ToInternalValue());
1776 } else {
1777 EXPECT_TRUE(child_node->is_folder());
1778 EXPECT_FALSE(child_node->is_url());
1780 (*running_count)++;
1784 // TODO(munjal): We should implement some way of generating random data and can
1785 // use the same seed to generate the same sequence.
1786 void ProfileSyncServiceBookmarkTestWithData::WriteTestDataToBookmarkModel() {
1787 const BookmarkNode* bookmarks_bar_node = model_->bookmark_bar_node();
1788 int count = 0;
1789 PopulateFromTestData(bookmarks_bar_node,
1790 kBookmarkBarChildren,
1791 arraysize(kBookmarkBarChildren),
1792 &count);
1794 ASSERT_GE(bookmarks_bar_node->child_count(), 4);
1795 const BookmarkNode* f1_node = bookmarks_bar_node->GetChild(1);
1796 PopulateFromTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1797 const BookmarkNode* f2_node = bookmarks_bar_node->GetChild(3);
1798 PopulateFromTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1800 const BookmarkNode* other_bookmarks_node = model_->other_node();
1801 PopulateFromTestData(other_bookmarks_node,
1802 kOtherBookmarkChildren,
1803 arraysize(kOtherBookmarkChildren),
1804 &count);
1806 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1807 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1808 PopulateFromTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1809 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1810 PopulateFromTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1811 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1812 PopulateFromTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1813 &count);
1814 dup_node = other_bookmarks_node->GetChild(5);
1815 PopulateFromTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1816 &count);
1818 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1819 PopulateFromTestData(mobile_bookmarks_node,
1820 kMobileBookmarkChildren,
1821 arraysize(kMobileBookmarkChildren),
1822 &count);
1824 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1825 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1826 PopulateFromTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1827 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1828 PopulateFromTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1830 ExpectBookmarkModelMatchesTestData();
1833 void ProfileSyncServiceBookmarkTestWithData::
1834 ExpectBookmarkModelMatchesTestData() {
1835 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1836 int count = 0;
1837 CompareWithTestData(bookmark_bar_node,
1838 kBookmarkBarChildren,
1839 arraysize(kBookmarkBarChildren),
1840 &count);
1842 ASSERT_GE(bookmark_bar_node->child_count(), 4);
1843 const BookmarkNode* f1_node = bookmark_bar_node->GetChild(1);
1844 CompareWithTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1845 const BookmarkNode* f2_node = bookmark_bar_node->GetChild(3);
1846 CompareWithTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1848 const BookmarkNode* other_bookmarks_node = model_->other_node();
1849 CompareWithTestData(other_bookmarks_node,
1850 kOtherBookmarkChildren,
1851 arraysize(kOtherBookmarkChildren),
1852 &count);
1854 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1855 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1856 CompareWithTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1857 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1858 CompareWithTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1859 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1860 CompareWithTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1861 &count);
1862 dup_node = other_bookmarks_node->GetChild(5);
1863 CompareWithTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1864 &count);
1866 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1867 CompareWithTestData(mobile_bookmarks_node,
1868 kMobileBookmarkChildren,
1869 arraysize(kMobileBookmarkChildren),
1870 &count);
1872 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1873 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1874 CompareWithTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1875 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1876 CompareWithTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1879 // Tests persistence of the profile sync service by unloading the
1880 // database and then reloading it from disk.
1881 TEST_F(ProfileSyncServiceBookmarkTestWithData, Persistence) {
1882 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1883 StartSync();
1885 WriteTestDataToBookmarkModel();
1887 ExpectModelMatch();
1889 // Force both models to discard their data and reload from disk. This
1890 // simulates what would happen if the browser were to shutdown normally,
1891 // and then relaunch.
1892 StopSync();
1893 UnloadBookmarkModel();
1894 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1895 StartSync();
1897 ExpectBookmarkModelMatchesTestData();
1899 // With the BookmarkModel contents verified, ExpectModelMatch will
1900 // verify the contents of the sync model.
1901 ExpectModelMatch();
1904 // Tests the merge case when the BookmarkModel is non-empty but the
1905 // sync model is empty. This corresponds to uploading browser
1906 // bookmarks to an initially empty, new account.
1907 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptySyncModel) {
1908 // Don't start the sync service until we've populated the bookmark model.
1909 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1911 WriteTestDataToBookmarkModel();
1913 // Restart sync. This should trigger a merge step during
1914 // initialization -- we expect the browser bookmarks to be written
1915 // to the sync service during this call.
1916 StartSync();
1918 // Verify that the bookmark model hasn't changed, and that the sync model
1919 // matches it exactly.
1920 ExpectBookmarkModelMatchesTestData();
1921 ExpectModelMatch();
1924 // Tests the merge case when the BookmarkModel is empty but the sync model is
1925 // non-empty. This corresponds (somewhat) to a clean install of the browser,
1926 // with no bookmarks, connecting to a sync account that has some bookmarks.
1927 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptyBookmarkModel) {
1928 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1929 StartSync();
1931 WriteTestDataToBookmarkModel();
1933 ExpectModelMatch();
1935 // Force the databse to unload and write itself to disk.
1936 StopSync();
1938 // Blow away the bookmark model -- it should be empty afterwards.
1939 UnloadBookmarkModel();
1940 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1941 EXPECT_EQ(model_->bookmark_bar_node()->child_count(), 0);
1942 EXPECT_EQ(model_->other_node()->child_count(), 0);
1943 EXPECT_EQ(model_->mobile_node()->child_count(), 0);
1945 // Now restart the sync service. Starting it should populate the bookmark
1946 // model -- test for consistency.
1947 StartSync();
1948 ExpectBookmarkModelMatchesTestData();
1949 ExpectModelMatch();
1952 // Tests the merge cases when both the models are expected to be identical
1953 // after the merge.
1954 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeExpectedIdenticalModels) {
1955 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1956 StartSync();
1957 WriteTestDataToBookmarkModel();
1958 ExpectModelMatch();
1959 StopSync();
1960 UnloadBookmarkModel();
1962 // At this point both the bookmark model and the server should have the
1963 // exact same data and it should match the test data.
1964 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1965 StartSync();
1966 ExpectBookmarkModelMatchesTestData();
1967 ExpectModelMatch();
1968 StopSync();
1969 UnloadBookmarkModel();
1971 // Now reorder some bookmarks in the bookmark model and then merge. Make
1972 // sure we get the order of the server after merge.
1973 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1974 ExpectBookmarkModelMatchesTestData();
1975 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
1976 ASSERT_TRUE(bookmark_bar);
1977 ASSERT_GT(bookmark_bar->child_count(), 1);
1978 model_->Move(bookmark_bar->GetChild(0), bookmark_bar, 1);
1979 StartSync();
1980 ExpectModelMatch();
1981 ExpectBookmarkModelMatchesTestData();
1984 // Tests the merge cases when both the models are expected to be identical
1985 // after the merge.
1986 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeModelsWithSomeExtras) {
1987 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1988 WriteTestDataToBookmarkModel();
1989 ExpectBookmarkModelMatchesTestData();
1991 // Remove some nodes and reorder some nodes.
1992 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1993 int remove_index = 2;
1994 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1995 const BookmarkNode* child_node = bookmark_bar_node->GetChild(remove_index);
1996 ASSERT_TRUE(child_node);
1997 ASSERT_TRUE(child_node->is_url());
1998 model_->Remove(bookmark_bar_node->GetChild(remove_index));
1999 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2000 child_node = bookmark_bar_node->GetChild(remove_index);
2001 ASSERT_TRUE(child_node);
2002 ASSERT_TRUE(child_node->is_folder());
2003 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2005 const BookmarkNode* other_node = model_->other_node();
2006 ASSERT_GE(other_node->child_count(), 1);
2007 const BookmarkNode* f3_node = other_node->GetChild(0);
2008 ASSERT_TRUE(f3_node);
2009 ASSERT_TRUE(f3_node->is_folder());
2010 remove_index = 2;
2011 ASSERT_GT(f3_node->child_count(), remove_index);
2012 model_->Remove(f3_node->GetChild(remove_index));
2013 ASSERT_GT(f3_node->child_count(), remove_index);
2014 model_->Remove(f3_node->GetChild(remove_index));
2016 StartSync();
2017 ExpectModelMatch();
2018 StopSync();
2020 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2021 WriteTestDataToBookmarkModel();
2022 ExpectBookmarkModelMatchesTestData();
2024 // Remove some nodes and reorder some nodes.
2025 bookmark_bar_node = model_->bookmark_bar_node();
2026 remove_index = 0;
2027 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2028 child_node = bookmark_bar_node->GetChild(remove_index);
2029 ASSERT_TRUE(child_node);
2030 ASSERT_TRUE(child_node->is_url());
2031 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2032 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2033 child_node = bookmark_bar_node->GetChild(remove_index);
2034 ASSERT_TRUE(child_node);
2035 ASSERT_TRUE(child_node->is_folder());
2036 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2038 ASSERT_GE(bookmark_bar_node->child_count(), 2);
2039 model_->Move(bookmark_bar_node->GetChild(0), bookmark_bar_node, 1);
2041 other_node = model_->other_node();
2042 ASSERT_GE(other_node->child_count(), 1);
2043 f3_node = other_node->GetChild(0);
2044 ASSERT_TRUE(f3_node);
2045 ASSERT_TRUE(f3_node->is_folder());
2046 remove_index = 0;
2047 ASSERT_GT(f3_node->child_count(), remove_index);
2048 model_->Remove(f3_node->GetChild(remove_index));
2049 ASSERT_GT(f3_node->child_count(), remove_index);
2050 model_->Remove(f3_node->GetChild(remove_index));
2052 ASSERT_GE(other_node->child_count(), 4);
2053 model_->Move(other_node->GetChild(0), other_node, 1);
2054 model_->Move(other_node->GetChild(2), other_node, 3);
2056 StartSync();
2057 ExpectModelMatch();
2059 // After the merge, the model should match the test data.
2060 ExpectBookmarkModelMatchesTestData();
2063 // Tests the optimistic bookmark association case where some nodes are moved
2064 // and untracked by the sync before the association.
2065 TEST_F(ProfileSyncServiceBookmarkTestWithData, OptimisticMergeWithMoves) {
2066 // TODO(stanisc): crbug.com/456876: Remove this once the optimistic
2067 // association experiment has ended.
2068 base::FieldTrialList field_trial_list(new base::MockEntropyProvider());
2069 base::FieldTrialList::CreateFieldTrial("SyncOptimisticBookmarkAssociation",
2070 "Enabled");
2072 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2073 WriteTestDataToBookmarkModel();
2075 int num_bookmarks = model_->root_node()->GetTotalNodeCount();
2077 StartSync();
2078 ExpectModelMatch();
2079 StopSync();
2081 EXPECT_EQ(num_bookmarks, model_->root_node()->GetTotalNodeCount());
2083 // Move one folder into another
2084 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2085 const BookmarkNode* f1 = bookmark_bar_node->GetChild(1);
2086 ASSERT_TRUE(f1->is_folder());
2087 const BookmarkNode* f2 = bookmark_bar_node->GetChild(3);
2088 ASSERT_TRUE(f2->is_folder());
2089 model_->Move(f2, f1, 0);
2091 StartSync();
2092 ExpectModelMatch();
2093 StopSync();
2095 // Expect folders to not duplicate.
2096 EXPECT_EQ(num_bookmarks, model_->root_node()->GetTotalNodeCount());
2098 // Perform one more cycle and make sure that the number of nodes stays
2099 // the same.
2100 StartSync();
2101 ExpectModelMatch();
2102 StopSync();
2103 EXPECT_EQ(num_bookmarks, model_->root_node()->GetTotalNodeCount());
2106 // Tests that when persisted model associations are used, things work fine.
2107 TEST_F(ProfileSyncServiceBookmarkTestWithData, ModelAssociationPersistence) {
2108 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2109 WriteTestDataToBookmarkModel();
2110 StartSync();
2111 ExpectModelMatch();
2112 // Force sync to shut down and write itself to disk.
2113 StopSync();
2114 // Now restart sync. This time it should use the persistent
2115 // associations.
2116 StartSync();
2117 ExpectModelMatch();
2120 // Tests that when persisted model associations are used, things work fine.
2121 TEST_F(ProfileSyncServiceBookmarkTestWithData,
2122 ModelAssociationInvalidPersistence) {
2123 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2124 WriteTestDataToBookmarkModel();
2125 StartSync();
2126 ExpectModelMatch();
2127 // Force sync to shut down and write itself to disk.
2128 StopSync();
2129 // Change the bookmark model before restarting sync service to simulate
2130 // the situation where bookmark model is different from sync model and
2131 // make sure model associator correctly rebuilds associations.
2132 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2133 model_->AddURL(bookmark_bar_node, 0, base::ASCIIToUTF16("xtra"),
2134 GURL("http://www.xtra.com"));
2135 // Now restart sync. This time it will try to use the persistent
2136 // associations and realize that they are invalid and hence will rebuild
2137 // associations.
2138 StartSync();
2139 ExpectModelMatch();
2142 TEST_F(ProfileSyncServiceBookmarkTestWithData, SortChildren) {
2143 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2144 StartSync();
2146 // Write test data to bookmark model and verify that the models match.
2147 WriteTestDataToBookmarkModel();
2148 const BookmarkNode* folder_added = model_->other_node()->GetChild(0);
2149 ASSERT_TRUE(folder_added);
2150 ASSERT_TRUE(folder_added->is_folder());
2152 ExpectModelMatch();
2154 // Sort the other-bookmarks children and expect that the models match.
2155 model_->SortChildren(folder_added);
2156 ExpectModelMatch();
2159 // See what happens if we enable sync but then delete the "Sync Data"
2160 // folder.
2161 TEST_F(ProfileSyncServiceBookmarkTestWithData,
2162 RecoverAfterDeletingSyncDataDirectory) {
2163 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
2164 StartSync();
2166 WriteTestDataToBookmarkModel();
2168 StopSync();
2170 // Nuke the sync DB and reload.
2171 TearDown();
2172 SetUp();
2174 // First attempt fails due to a persistence error.
2175 EXPECT_TRUE(CreatePermanentBookmarkNodes());
2176 EXPECT_FALSE(AssociateModels());
2178 // Second attempt succeeds due to the previous error resetting the native
2179 // transaction version.
2180 model_associator_.reset();
2181 EXPECT_TRUE(CreatePermanentBookmarkNodes());
2182 EXPECT_TRUE(AssociateModels());
2184 // Make sure we're back in sync. In real life, the user would need
2185 // to reauthenticate before this happens, but in the test, authentication
2186 // is sidestepped.
2187 ExpectBookmarkModelMatchesTestData();
2188 ExpectModelMatch();
2191 // Verify that the bookmark model is updated about whether the
2192 // associator is currently running.
2193 TEST_F(ProfileSyncServiceBookmarkTest, AssociationState) {
2194 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2196 ExtensiveChangesBookmarkModelObserver observer;
2197 model_->AddObserver(&observer);
2199 StartSync();
2201 EXPECT_EQ(1, observer.get_started());
2202 EXPECT_EQ(0, observer.get_completed_count_at_started());
2203 EXPECT_EQ(1, observer.get_completed());
2205 model_->RemoveObserver(&observer);
2208 // Verify that the creation_time_us changes are applied in the local model at
2209 // association time and update time.
2210 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateDateAdded) {
2211 // TODO(stanisc): crbug.com/456876: Remove this once the optimistic
2212 // association experiment has ended.
2213 base::FieldTrialList field_trial_list(new base::MockEntropyProvider());
2214 base::FieldTrialList::CreateFieldTrial("SyncOptimisticBookmarkAssociation",
2215 "Enabled");
2217 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2218 WriteTestDataToBookmarkModel();
2220 // Start and stop sync in order to create bookmark nodes in the sync db.
2221 StartSync();
2222 StopSync();
2224 // Modify the date_added field of a bookmark so it doesn't match with
2225 // the sync data.
2226 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2227 int modified_index = 2;
2228 ASSERT_GT(bookmark_bar_node->child_count(), modified_index);
2229 const BookmarkNode* child_node = bookmark_bar_node->GetChild(modified_index);
2230 ASSERT_TRUE(child_node);
2231 EXPECT_TRUE(child_node->is_url());
2232 model_->SetDateAdded(child_node, base::Time::FromInternalValue(10));
2234 StartSync();
2235 StopSync();
2237 // Verify that transaction versions are in sync between the native model
2238 // and Sync.
2240 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2241 int64 sync_version = trans.GetModelVersion(syncer::BOOKMARKS);
2242 int64 native_version = model_->root_node()->sync_transaction_version();
2243 EXPECT_EQ(native_version, sync_version);
2246 // Since the version is in sync the association above should have skipped
2247 // updating the native node above. That is expected optimization (see
2248 // crbug/464907.
2249 EXPECT_EQ(child_node->date_added(), base::Time::FromInternalValue(10));
2251 // Reset transaction version on the native model to trigger conservative
2252 // association algorithm.
2253 model_->SetNodeSyncTransactionVersion(
2254 model_->root_node(), syncer::syncable::kInvalidTransactionVersion);
2256 StartSync();
2258 // Everything should be back in sync after model association.
2259 ExpectBookmarkModelMatchesTestData();
2260 ExpectModelMatch();
2262 // Now trigger a change while syncing. We add a new bookmark, sync it, then
2263 // updates it's creation time.
2264 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2265 FakeServerChange adds(&trans);
2266 const std::string kTitle = "Some site";
2267 const std::string kUrl = "http://www.whatwhat.yeah/";
2268 const int kCreationTime = 30;
2269 int64 id = adds.AddURL(kTitle, kUrl,
2270 bookmark_bar_id(), 0);
2271 adds.ApplyPendingChanges(change_processor_.get());
2272 FakeServerChange updates(&trans);
2273 updates.ModifyCreationTime(id, kCreationTime);
2274 updates.ApplyPendingChanges(change_processor_.get());
2276 const BookmarkNode* node = model_->bookmark_bar_node()->GetChild(0);
2277 ASSERT_TRUE(node);
2278 EXPECT_TRUE(node->is_url());
2279 EXPECT_EQ(base::UTF8ToUTF16(kTitle), node->GetTitle());
2280 EXPECT_EQ(kUrl, node->url().possibly_invalid_spec());
2281 EXPECT_EQ(node->date_added(), base::Time::FromInternalValue(30));
2284 // Tests that changes to the sync nodes meta info gets reflected in the local
2285 // bookmark model.
2286 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromSync) {
2287 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2288 WriteTestDataToBookmarkModel();
2289 StartSync();
2291 // Create bookmark nodes containing meta info.
2292 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2293 FakeServerChange adds(&trans);
2294 BookmarkNode::MetaInfoMap folder_meta_info;
2295 folder_meta_info["folder"] = "foldervalue";
2296 int64 folder_id = adds.AddFolderWithMetaInfo(
2297 "folder title", &folder_meta_info, bookmark_bar_id(), 0);
2298 BookmarkNode::MetaInfoMap node_meta_info;
2299 node_meta_info["node"] = "nodevalue";
2300 node_meta_info["other"] = "othervalue";
2301 int64 id = adds.AddURLWithMetaInfo("node title", "http://www.foo.com",
2302 &node_meta_info, folder_id, 0);
2303 adds.ApplyPendingChanges(change_processor_.get());
2305 // Verify that the nodes are created with the correct meta info.
2306 ASSERT_LT(0, model_->bookmark_bar_node()->child_count());
2307 const BookmarkNode* folder_node = model_->bookmark_bar_node()->GetChild(0);
2308 ASSERT_TRUE(folder_node->GetMetaInfoMap());
2309 EXPECT_EQ(folder_meta_info, *folder_node->GetMetaInfoMap());
2310 ASSERT_LT(0, folder_node->child_count());
2311 const BookmarkNode* node = folder_node->GetChild(0);
2312 ASSERT_TRUE(node->GetMetaInfoMap());
2313 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
2315 // Update meta info on nodes on server
2316 FakeServerChange updates(&trans);
2317 folder_meta_info.erase("folder");
2318 updates.ModifyMetaInfo(folder_id, folder_meta_info);
2319 node_meta_info["node"] = "changednodevalue";
2320 node_meta_info.erase("other");
2321 node_meta_info["newkey"] = "newkeyvalue";
2322 updates.ModifyMetaInfo(id, node_meta_info);
2323 updates.ApplyPendingChanges(change_processor_.get());
2325 // Confirm that the updated values are reflected in the bookmark nodes.
2326 EXPECT_FALSE(folder_node->GetMetaInfoMap());
2327 ASSERT_TRUE(node->GetMetaInfoMap());
2328 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
2331 // Tests that changes to the local bookmark nodes meta info gets reflected in
2332 // the sync nodes.
2333 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromModel) {
2334 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2335 WriteTestDataToBookmarkModel();
2336 StartSync();
2337 ExpectBookmarkModelMatchesTestData();
2339 const BookmarkNode* folder_node =
2340 model_->AddFolder(model_->bookmark_bar_node(), 0,
2341 base::ASCIIToUTF16("folder title"));
2342 const BookmarkNode* node = model_->AddURL(folder_node, 0,
2343 base::ASCIIToUTF16("node title"),
2344 GURL("http://www.foo.com"));
2345 ExpectModelMatch();
2347 // Add some meta info and verify sync model matches the changes.
2348 model_->SetNodeMetaInfo(folder_node, "folder", "foldervalue");
2349 model_->SetNodeMetaInfo(node, "node", "nodevalue");
2350 model_->SetNodeMetaInfo(node, "other", "othervalue");
2351 ExpectModelMatch();
2353 // Change/delete existing meta info and verify.
2354 model_->DeleteNodeMetaInfo(folder_node, "folder");
2355 model_->SetNodeMetaInfo(node, "node", "changednodevalue");
2356 model_->DeleteNodeMetaInfo(node, "other");
2357 model_->SetNodeMetaInfo(node, "newkey", "newkeyvalue");
2358 ExpectModelMatch();
2361 // Tests that node's specifics doesn't get unnecessarily overwritten (causing
2362 // a subsequent commit) when BookmarkChangeProcessor handles a notification
2363 // (such as BookmarkMetaInfoChanged) without an actual data change.
2364 TEST_F(ProfileSyncServiceBookmarkTestWithData, MetaInfoPreservedOnNonChange) {
2365 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2366 WriteTestDataToBookmarkModel();
2367 StartSync();
2369 std::string orig_specifics;
2370 int64 sync_id;
2371 const BookmarkNode* bookmark;
2373 // Create bookmark folder node containing meta info.
2375 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2376 FakeServerChange adds(&trans);
2378 int64 folder_id = adds.AddFolder("folder title", bookmark_bar_id(), 0);
2380 BookmarkNode::MetaInfoMap node_meta_info;
2381 node_meta_info["one"] = "1";
2382 node_meta_info["two"] = "2";
2383 node_meta_info["three"] = "3";
2385 sync_id = adds.AddURLWithMetaInfo("node title", "http://www.foo.com/",
2386 &node_meta_info, folder_id, 0);
2388 // Verify that the node propagates to the bookmark model
2389 adds.ApplyPendingChanges(change_processor_.get());
2391 bookmark = model_->bookmark_bar_node()->GetChild(0)->GetChild(0);
2392 EXPECT_EQ(node_meta_info, *bookmark->GetMetaInfoMap());
2394 syncer::ReadNode sync_node(&trans);
2395 EXPECT_EQ(BaseNode::INIT_OK, sync_node.InitByIdLookup(sync_id));
2396 orig_specifics = sync_node.GetBookmarkSpecifics().SerializeAsString();
2399 // Force change processor to update the sync node.
2400 change_processor_->BookmarkMetaInfoChanged(model_, bookmark);
2402 // Read bookmark specifics again and verify that there is no change.
2404 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2405 syncer::ReadNode sync_node(&trans);
2406 EXPECT_EQ(BaseNode::INIT_OK, sync_node.InitByIdLookup(sync_id));
2407 std::string new_specifics =
2408 sync_node.GetBookmarkSpecifics().SerializeAsString();
2409 ASSERT_EQ(orig_specifics, new_specifics);
2413 void ProfileSyncServiceBookmarkTestWithData::GetTransactionVersions(
2414 const BookmarkNode* root,
2415 BookmarkNodeVersionMap* node_versions) {
2416 node_versions->clear();
2417 std::queue<const BookmarkNode*> nodes;
2418 nodes.push(root);
2419 while (!nodes.empty()) {
2420 const BookmarkNode* n = nodes.front();
2421 nodes.pop();
2423 int64 version = n->sync_transaction_version();
2424 EXPECT_NE(BookmarkNode::kInvalidSyncTransactionVersion, version);
2426 (*node_versions)[n->id()] = version;
2427 for (int i = 0; i < n->child_count(); ++i) {
2428 if (!CanSyncNode(n->GetChild(i)))
2429 continue;
2430 nodes.push(n->GetChild(i));
2435 void ProfileSyncServiceBookmarkTestWithData::ExpectTransactionVersionMatch(
2436 const BookmarkNode* node,
2437 const BookmarkNodeVersionMap& version_expected) {
2438 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2440 BookmarkNodeVersionMap bnodes_versions;
2441 GetTransactionVersions(node, &bnodes_versions);
2442 for (BookmarkNodeVersionMap::const_iterator it = bnodes_versions.begin();
2443 it != bnodes_versions.end(); ++it) {
2444 syncer::ReadNode sync_node(&trans);
2445 ASSERT_TRUE(model_associator_->InitSyncNodeFromChromeId(it->first,
2446 &sync_node));
2447 EXPECT_EQ(sync_node.GetEntry()->GetTransactionVersion(), it->second);
2448 BookmarkNodeVersionMap::const_iterator expected_ver_it =
2449 version_expected.find(it->first);
2450 if (expected_ver_it != version_expected.end())
2451 EXPECT_EQ(expected_ver_it->second, it->second);
2455 // Test transaction versions of model and nodes are incremented after changes
2456 // are applied.
2457 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateTransactionVersion) {
2458 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2459 StartSync();
2460 WriteTestDataToBookmarkModel();
2461 base::MessageLoop::current()->RunUntilIdle();
2463 BookmarkNodeVersionMap initial_versions;
2465 // Verify transaction versions in sync model and bookmark model (saved as
2466 // transaction version of root node) are equal after
2467 // WriteTestDataToBookmarkModel() created bookmarks.
2469 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2470 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2471 GetTransactionVersions(model_->root_node(), &initial_versions);
2472 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2473 initial_versions[model_->root_node()->id()]);
2475 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2476 BookmarkNodeVersionMap());
2477 ExpectTransactionVersionMatch(model_->other_node(),
2478 BookmarkNodeVersionMap());
2479 ExpectTransactionVersionMatch(model_->mobile_node(),
2480 BookmarkNodeVersionMap());
2482 // Verify model version is incremented and bookmark node versions remain
2483 // the same.
2484 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
2485 model_->Remove(bookmark_bar->GetChild(0));
2486 base::MessageLoop::current()->RunUntilIdle();
2487 BookmarkNodeVersionMap new_versions;
2488 GetTransactionVersions(model_->root_node(), &new_versions);
2489 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 1,
2490 new_versions[model_->root_node()->id()]);
2491 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2492 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2493 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2495 // Verify model version and version of changed bookmark are incremented and
2496 // versions of others remain same.
2497 const BookmarkNode* changed_bookmark =
2498 model_->bookmark_bar_node()->GetChild(0);
2499 model_->SetTitle(changed_bookmark, base::ASCIIToUTF16("test"));
2500 base::MessageLoop::current()->RunUntilIdle();
2501 GetTransactionVersions(model_->root_node(), &new_versions);
2502 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 2,
2503 new_versions[model_->root_node()->id()]);
2504 EXPECT_LT(initial_versions[changed_bookmark->id()],
2505 new_versions[changed_bookmark->id()]);
2506 initial_versions.erase(changed_bookmark->id());
2507 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2508 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2509 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2512 // Test that sync persistence errors are detected and trigger a failed
2513 // association.
2514 TEST_F(ProfileSyncServiceBookmarkTestWithData, PersistenceError) {
2515 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2516 StartSync();
2517 WriteTestDataToBookmarkModel();
2518 base::MessageLoop::current()->RunUntilIdle();
2520 BookmarkNodeVersionMap initial_versions;
2522 // Verify transaction versions in sync model and bookmark model (saved as
2523 // transaction version of root node) are equal after
2524 // WriteTestDataToBookmarkModel() created bookmarks.
2526 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2527 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2528 GetTransactionVersions(model_->root_node(), &initial_versions);
2529 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2530 initial_versions[model_->root_node()->id()]);
2532 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2533 BookmarkNodeVersionMap());
2534 ExpectTransactionVersionMatch(model_->other_node(),
2535 BookmarkNodeVersionMap());
2536 ExpectTransactionVersionMatch(model_->mobile_node(),
2537 BookmarkNodeVersionMap());
2539 // Now shut down sync and artificially increment the native model's version.
2540 StopSync();
2541 int64 root_version = initial_versions[model_->root_node()->id()];
2542 model_->SetNodeSyncTransactionVersion(model_->root_node(), root_version + 1);
2544 // Upon association, bookmarks should fail to associate.
2545 EXPECT_FALSE(AssociateModels());
2548 // It's possible for update/add calls from the bookmark model to be out of
2549 // order, or asynchronous. Handle that without triggering an error.
2550 TEST_F(ProfileSyncServiceBookmarkTest, UpdateThenAdd) {
2551 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2552 StartSync();
2554 EXPECT_TRUE(other_bookmarks_id());
2555 EXPECT_TRUE(bookmark_bar_id());
2556 EXPECT_TRUE(mobile_bookmarks_id());
2558 ExpectModelMatch();
2560 // Now destroy the change processor then add a bookmark, to simulate
2561 // missing the Update call.
2562 change_processor_.reset();
2563 const BookmarkNode* node = model_->AddURL(model_->bookmark_bar_node(),
2565 base::ASCIIToUTF16("title"),
2566 GURL("http://www.url.com"));
2568 // Recreate the change processor then update that bookmark. Sync should
2569 // receive the update call and gracefully treat that as if it were an add.
2570 change_processor_.reset(new BookmarkChangeProcessor(
2571 &profile_, model_associator_.get(), &mock_error_handler_));
2572 change_processor_->Start(test_user_share_.user_share());
2573 model_->SetTitle(node, base::ASCIIToUTF16("title2"));
2574 ExpectModelMatch();
2576 // Then simulate the add call arriving late.
2577 change_processor_->BookmarkNodeAdded(model_, model_->bookmark_bar_node(), 0);
2578 ExpectModelMatch();
2581 } // namespace
2583 } // namespace browser_sync