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.
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/time/time.h"
25 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
26 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
27 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
28 #include "chrome/browser/sync/glue/bookmark_change_processor.h"
29 #include "chrome/browser/sync/glue/bookmark_model_associator.h"
30 #include "chrome/common/chrome_switches.h"
31 #include "chrome/test/base/testing_profile.h"
32 #include "components/bookmarks/browser/base_bookmark_model_observer.h"
33 #include "components/bookmarks/browser/bookmark_model.h"
34 #include "components/bookmarks/test/bookmark_test_helpers.h"
35 #include "components/sync_driver/data_type_error_handler.h"
36 #include "components/sync_driver/data_type_error_handler_mock.h"
37 #include "content/public/test/test_browser_thread_bundle.h"
38 #include "sync/api/sync_error.h"
39 #include "sync/internal_api/public/change_record.h"
40 #include "sync/internal_api/public/read_node.h"
41 #include "sync/internal_api/public/read_transaction.h"
42 #include "sync/internal_api/public/test/test_user_share.h"
43 #include "sync/internal_api/public/write_node.h"
44 #include "sync/internal_api/public/write_transaction.h"
45 #include "sync/internal_api/syncapi_internal.h"
46 #include "sync/syncable/mutable_entry.h" // TODO(tim): Remove. Bug 131130.
47 #include "testing/gmock/include/gmock/gmock.h"
48 #include "testing/gtest/include/gtest/gtest.h"
50 namespace browser_sync {
52 using syncer::BaseNode;
54 using testing::InvokeWithoutArgs;
56 using testing::StrictMock;
58 #if defined(OS_ANDROID) || defined(OS_IOS)
59 static const bool kExpectMobileBookmarks = true;
61 static const bool kExpectMobileBookmarks = false;
62 #endif // defined(OS_ANDROID) || defined(OS_IOS)
66 // FakeServerChange constructs a list of syncer::ChangeRecords while modifying
67 // the sync model, and can pass the ChangeRecord list to a
68 // syncer::SyncObserver (i.e., the ProfileSyncService) to test the client
69 // change-application behavior.
70 // Tests using FakeServerChange should be careful to avoid back-references,
71 // since FakeServerChange will send the edits in the order specified.
72 class FakeServerChange {
74 explicit FakeServerChange(syncer::WriteTransaction* trans) : trans_(trans) {
77 // Pretend that the server told the syncer to add a bookmark object.
78 int64 AddWithMetaInfo(const std::string& title,
79 const std::string& url,
80 const BookmarkNode::MetaInfoMap* meta_info_map,
83 int64 predecessor_id) {
84 syncer::ReadNode parent(trans_);
85 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
86 syncer::WriteNode node(trans_);
87 if (predecessor_id == 0) {
88 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
90 syncer::ReadNode predecessor(trans_);
91 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
92 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
93 EXPECT_TRUE(node.InitBookmarkByCreation(parent, &predecessor));
95 EXPECT_EQ(node.GetPredecessorId(), predecessor_id);
96 EXPECT_EQ(node.GetParentId(), parent_id);
97 node.SetIsFolder(is_folder);
100 sync_pb::BookmarkSpecifics specifics(node.GetBookmarkSpecifics());
102 specifics.set_url(url);
104 SetNodeMetaInfo(*meta_info_map, &specifics);
105 node.SetBookmarkSpecifics(specifics);
107 syncer::ChangeRecord record;
108 record.action = syncer::ChangeRecord::ACTION_ADD;
109 record.id = node.GetId();
110 changes_.push_back(record);
114 int64 Add(const std::string& title,
115 const std::string& url,
118 int64 predecessor_id) {
119 return AddWithMetaInfo(title, url, NULL, is_folder, parent_id,
123 // Add a bookmark folder.
124 int64 AddFolder(const std::string& title,
126 int64 predecessor_id) {
127 return Add(title, std::string(), true, parent_id, predecessor_id);
129 int64 AddFolderWithMetaInfo(const std::string& title,
130 const BookmarkNode::MetaInfoMap* meta_info_map,
132 int64 predecessor_id) {
133 return AddWithMetaInfo(title, std::string(), meta_info_map, true, parent_id,
138 int64 AddURL(const std::string& title,
139 const std::string& url,
141 int64 predecessor_id) {
142 return Add(title, url, false, parent_id, predecessor_id);
144 int64 AddURLWithMetaInfo(const std::string& title,
145 const std::string& url,
146 const BookmarkNode::MetaInfoMap* meta_info_map,
148 int64 predecessor_id) {
149 return AddWithMetaInfo(title, url, meta_info_map, false, parent_id,
153 // Pretend that the server told the syncer to delete an object.
154 void Delete(int64 id) {
156 // Delete the sync node.
157 syncer::WriteNode node(trans_);
158 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
159 if (node.GetIsFolder())
160 EXPECT_FALSE(node.GetFirstChildId());
161 node.GetMutableEntryForTest()->PutServerIsDel(true);
165 // Verify the deletion.
166 syncer::ReadNode node(trans_);
167 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL, node.InitByIdLookup(id));
170 syncer::ChangeRecord record;
171 record.action = syncer::ChangeRecord::ACTION_DELETE;
173 // Deletions are always first in the changelist, but we can't actually do
174 // WriteNode::Remove() on the node until its children are moved. So, as
175 // a practical matter, users of FakeServerChange must move or delete
176 // children before parents. Thus, we must insert the deletion record
177 // at the front of the vector.
178 changes_.insert(changes_.begin(), record);
181 // Set a new title value, and return the old value.
182 std::string ModifyTitle(int64 id, const std::string& new_title) {
183 syncer::WriteNode node(trans_);
184 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
185 std::string old_title = node.GetTitle();
186 node.SetTitle(new_title);
191 // Set a new parent and predecessor value. Return the old parent id.
192 // We could return the old predecessor id, but it turns out not to be
193 // very useful for assertions.
194 int64 ModifyPosition(int64 id, int64 parent_id, int64 predecessor_id) {
195 syncer::ReadNode parent(trans_);
196 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
197 syncer::WriteNode node(trans_);
198 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
199 int64 old_parent_id = node.GetParentId();
200 if (predecessor_id == 0) {
201 EXPECT_TRUE(node.SetPosition(parent, NULL));
203 syncer::ReadNode predecessor(trans_);
204 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
205 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
206 EXPECT_TRUE(node.SetPosition(parent, &predecessor));
209 return old_parent_id;
212 void ModifyCreationTime(int64 id, int64 creation_time_us) {
213 syncer::WriteNode node(trans_);
214 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
215 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
216 specifics.set_creation_time_us(creation_time_us);
217 node.SetBookmarkSpecifics(specifics);
221 void ModifyMetaInfo(int64 id,
222 const BookmarkNode::MetaInfoMap& meta_info_map) {
223 syncer::WriteNode node(trans_);
224 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
225 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
226 SetNodeMetaInfo(meta_info_map, &specifics);
227 node.SetBookmarkSpecifics(specifics);
231 // Pass the fake change list to |service|.
232 void ApplyPendingChanges(sync_driver::ChangeProcessor* processor) {
233 processor->ApplyChangesFromSyncModel(
234 trans_, 0, syncer::ImmutableChangeRecordList(&changes_));
237 const syncer::ChangeRecordList& changes() {
242 // Helper function to push an ACTION_UPDATE record onto the back
243 // of the changelist.
244 void SetModified(int64 id) {
245 // Coalesce multi-property edits.
246 if (!changes_.empty() && changes_.back().id == id &&
247 changes_.back().action ==
248 syncer::ChangeRecord::ACTION_UPDATE)
250 syncer::ChangeRecord record;
251 record.action = syncer::ChangeRecord::ACTION_UPDATE;
253 changes_.push_back(record);
256 void SetNodeMetaInfo(const BookmarkNode::MetaInfoMap& meta_info_map,
257 sync_pb::BookmarkSpecifics* specifics) {
258 specifics->clear_meta_info();
259 for (BookmarkNode::MetaInfoMap::const_iterator it =
260 meta_info_map.begin(); it != meta_info_map.end(); ++it) {
261 sync_pb::MetaInfo* meta_info = specifics->add_meta_info();
262 meta_info->set_key(it->first);
263 meta_info->set_value(it->second);
268 // The transaction on which everything happens.
269 syncer::WriteTransaction *trans_;
271 // The change list we construct.
272 syncer::ChangeRecordList changes_;
275 class ExtensiveChangesBookmarkModelObserver : public BaseBookmarkModelObserver {
277 ExtensiveChangesBookmarkModelObserver()
279 completed_count_at_started_(0),
280 completed_count_(0) {}
282 void ExtensiveBookmarkChangesBeginning(BookmarkModel* model) override {
284 completed_count_at_started_ = completed_count_;
287 void ExtensiveBookmarkChangesEnded(BookmarkModel* model) override {
291 void BookmarkModelChanged() override {}
293 int get_started() const {
294 return started_count_;
297 int get_completed_count_at_started() const {
298 return completed_count_at_started_;
301 int get_completed() const {
302 return completed_count_;
307 int completed_count_at_started_;
308 int completed_count_;
310 DISALLOW_COPY_AND_ASSIGN(ExtensiveChangesBookmarkModelObserver);
314 class ProfileSyncServiceBookmarkTest : public testing::Test {
316 enum LoadOption { LOAD_FROM_STORAGE, DELETE_EXISTING_STORAGE };
317 enum SaveOption { SAVE_TO_STORAGE, DONT_SAVE_TO_STORAGE };
319 ProfileSyncServiceBookmarkTest()
321 thread_bundle_(content::TestBrowserThreadBundle::DEFAULT),
322 local_merge_result_(syncer::BOOKMARKS),
323 syncer_merge_result_(syncer::BOOKMARKS) {}
325 virtual ~ProfileSyncServiceBookmarkTest() {
327 UnloadBookmarkModel();
330 virtual void SetUp() {
331 test_user_share_.SetUp();
334 virtual void TearDown() {
335 test_user_share_.TearDown();
338 bool CanSyncNode(const BookmarkNode* node) {
339 return model_->client()->CanSyncNode(node);
342 // Inserts a folder directly to the share.
343 // Do not use this after model association is complete.
345 // This function differs from the AddFolder() function declared elsewhere in
346 // this file in that it only affects the sync model. It would be invalid to
347 // change the sync model directly after ModelAssociation. This function can
348 // be invoked prior to model association to set up first-time sync model
349 // association scenarios.
350 int64 AddFolderToShare(syncer::WriteTransaction* trans, std::string title) {
351 EXPECT_FALSE(model_associator_);
353 // Be sure to call CreatePermanentBookmarkNodes(), otherwise this will fail.
354 syncer::ReadNode bookmark_bar(trans);
355 EXPECT_EQ(BaseNode::INIT_OK,
356 bookmark_bar.InitByTagLookupForBookmarks("bookmark_bar"));
358 syncer::WriteNode node(trans);
359 EXPECT_TRUE(node.InitBookmarkByCreation(bookmark_bar, NULL));
360 node.SetIsFolder(true);
361 node.SetTitle(title);
366 // Inserts a bookmark directly to the share.
367 // Do not use this after model association is complete.
369 // This function differs from the AddURL() function declared elsewhere in this
370 // file in that it only affects the sync model. It would be invalid to change
371 // the sync model directly after ModelAssociation. This function can be
372 // invoked prior to model association to set up first-time sync model
373 // association scenarios.
374 int64 AddBookmarkToShare(syncer::WriteTransaction *trans,
377 EXPECT_FALSE(model_associator_);
379 syncer::ReadNode parent(trans);
380 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
382 sync_pb::BookmarkSpecifics specifics;
383 specifics.set_url("http://www.google.com/search?q=" + title);
384 specifics.set_title(title);
386 syncer::WriteNode node(trans);
387 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
388 node.SetIsFolder(false);
389 node.SetTitle(title);
390 node.SetBookmarkSpecifics(specifics);
395 // Load (or re-load) the bookmark model. |load| controls use of the
396 // bookmarks file on disk. |save| controls whether the newly loaded
397 // bookmark model will write out a bookmark file as it goes.
398 void LoadBookmarkModel(LoadOption load, SaveOption save) {
399 bool delete_bookmarks = load == DELETE_EXISTING_STORAGE;
400 profile_.CreateBookmarkModel(delete_bookmarks);
401 model_ = BookmarkModelFactory::GetForProfile(&profile_);
402 bookmarks::test::WaitForBookmarkModelToLoad(model_);
403 // This noticeably speeds up the unit tests that request it.
404 if (save == DONT_SAVE_TO_STORAGE)
405 model_->ClearStore();
406 base::MessageLoop::current()->RunUntilIdle();
409 int GetSyncBookmarkCount() {
410 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
411 syncer::ReadNode node(&trans);
412 if (node.InitTypeRoot(syncer::BOOKMARKS) != syncer::BaseNode::INIT_OK)
414 return node.GetTotalNodeCount();
417 // Creates the bookmark root node and the permanent nodes if they don't
419 bool CreatePermanentBookmarkNodes() {
420 bool root_exists = false;
421 syncer::ModelType type = syncer::BOOKMARKS;
423 syncer::WriteTransaction trans(FROM_HERE,
424 test_user_share_.user_share());
425 syncer::ReadNode uber_root(&trans);
426 uber_root.InitByRootLookup();
428 syncer::ReadNode root(&trans);
429 root_exists = (root.InitTypeRoot(type) == BaseNode::INIT_OK);
433 if (!syncer::TestUserShare::CreateRoot(type,
434 test_user_share_.user_share()))
438 const int kNumPermanentNodes = 3;
439 const std::string permanent_tags[kNumPermanentNodes] = {
449 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
450 syncer::ReadNode root(&trans);
451 EXPECT_EQ(BaseNode::INIT_OK, root.InitTypeRoot(type));
453 // Loop through creating permanent nodes as necessary.
454 int64 last_child_id = syncer::kInvalidId;
455 for (int i = 0; i < kNumPermanentNodes; ++i) {
456 // First check if the node already exists. This is for tests that involve
457 // persistence and set up sync more than once.
458 syncer::ReadNode lookup(&trans);
459 if (lookup.InitByTagLookupForBookmarks(permanent_tags[i]) ==
460 syncer::ReadNode::INIT_OK) {
461 last_child_id = lookup.GetId();
465 // If it doesn't exist, create the permanent node at the end of the
467 syncer::ReadNode predecessor_node(&trans);
468 syncer::ReadNode* predecessor = NULL;
469 if (last_child_id != syncer::kInvalidId) {
470 EXPECT_EQ(BaseNode::INIT_OK,
471 predecessor_node.InitByIdLookup(last_child_id));
472 predecessor = &predecessor_node;
474 syncer::WriteNode node(&trans);
475 if (!node.InitBookmarkByCreation(root, predecessor))
477 node.SetIsFolder(true);
478 node.GetMutableEntryForTest()->PutUniqueServerTag(permanent_tags[i]);
479 node.SetTitle(permanent_tags[i]);
480 node.SetExternalId(0);
481 last_child_id = node.GetId();
486 bool AssociateModels() {
487 DCHECK(!model_associator_);
489 // Set up model associator.
490 model_associator_.reset(new BookmarkModelAssociator(
491 BookmarkModelFactory::GetForProfile(&profile_),
493 test_user_share_.user_share(),
494 &mock_error_handler_,
495 kExpectMobileBookmarks));
497 local_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
498 syncer_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
499 int local_count_before = model_->root_node()->GetTotalNodeCount();
500 int syncer_count_before = GetSyncBookmarkCount();
502 syncer::SyncError error = model_associator_->AssociateModels(
503 &local_merge_result_,
504 &syncer_merge_result_);
508 base::MessageLoop::current()->RunUntilIdle();
510 // Verify the merge results were calculated properly.
511 EXPECT_EQ(local_count_before,
512 local_merge_result_.num_items_before_association());
513 EXPECT_EQ(syncer_count_before,
514 syncer_merge_result_.num_items_before_association());
515 EXPECT_EQ(local_merge_result_.num_items_after_association(),
516 local_merge_result_.num_items_before_association() +
517 local_merge_result_.num_items_added() -
518 local_merge_result_.num_items_deleted());
519 EXPECT_EQ(syncer_merge_result_.num_items_after_association(),
520 syncer_merge_result_.num_items_before_association() +
521 syncer_merge_result_.num_items_added() -
522 syncer_merge_result_.num_items_deleted());
523 EXPECT_EQ(model_->root_node()->GetTotalNodeCount(),
524 local_merge_result_.num_items_after_association());
525 EXPECT_EQ(GetSyncBookmarkCount(),
526 syncer_merge_result_.num_items_after_association());
531 test_user_share_.Reload();
533 ASSERT_TRUE(CreatePermanentBookmarkNodes());
534 ASSERT_TRUE(AssociateModels());
536 // Set up change processor.
537 change_processor_.reset(
538 new BookmarkChangeProcessor(&profile_,
539 model_associator_.get(),
540 &mock_error_handler_));
541 change_processor_->Start(test_user_share_.user_share());
545 change_processor_.reset();
546 if (model_associator_) {
547 syncer::SyncError error = model_associator_->DisassociateModels();
548 EXPECT_FALSE(error.IsSet());
550 model_associator_.reset();
552 base::MessageLoop::current()->RunUntilIdle();
554 // TODO(akalin): Actually close the database and flush it to disk
555 // (and make StartSync reload from disk). This would require
556 // refactoring TestUserShare.
559 void UnloadBookmarkModel() {
560 profile_.CreateBookmarkModel(false /* delete_bookmarks */);
562 base::MessageLoop::current()->RunUntilIdle();
565 bool InitSyncNodeFromChromeNode(const BookmarkNode* bnode,
566 syncer::BaseNode* sync_node) {
567 return model_associator_->InitSyncNodeFromChromeId(bnode->id(),
571 void ExpectSyncerNodeMatching(syncer::BaseTransaction* trans,
572 const BookmarkNode* bnode) {
573 std::string truncated_title = base::UTF16ToUTF8(bnode->GetTitle());
574 syncer::SyncAPINameToServerName(truncated_title, &truncated_title);
575 base::TruncateUTF8ToByteSize(truncated_title, 255, &truncated_title);
576 syncer::ServerNameToSyncAPIName(truncated_title, &truncated_title);
578 syncer::ReadNode gnode(trans);
579 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnode, &gnode));
580 // Non-root node titles and parents must match.
581 if (!model_->is_permanent_node(bnode)) {
582 EXPECT_EQ(truncated_title, gnode.GetTitle());
584 model_associator_->GetChromeNodeFromSyncId(gnode.GetParentId()),
587 EXPECT_EQ(bnode->is_folder(), gnode.GetIsFolder());
589 EXPECT_EQ(bnode->url(), GURL(gnode.GetBookmarkSpecifics().url()));
591 // Check that meta info matches.
592 const BookmarkNode::MetaInfoMap* meta_info_map = bnode->GetMetaInfoMap();
593 sync_pb::BookmarkSpecifics specifics = gnode.GetBookmarkSpecifics();
594 if (!meta_info_map) {
595 EXPECT_EQ(0, specifics.meta_info_size());
597 EXPECT_EQ(meta_info_map->size(),
598 static_cast<size_t>(specifics.meta_info_size()));
599 for (int i = 0; i < specifics.meta_info_size(); i++) {
600 BookmarkNode::MetaInfoMap::const_iterator it =
601 meta_info_map->find(specifics.meta_info(i).key());
602 EXPECT_TRUE(it != meta_info_map->end());
603 EXPECT_EQ(it->second, specifics.meta_info(i).value());
607 // Check for position matches.
608 int browser_index = bnode->parent()->GetIndexOf(bnode);
609 if (browser_index == 0) {
610 EXPECT_EQ(gnode.GetPredecessorId(), 0);
612 const BookmarkNode* bprev =
613 bnode->parent()->GetChild(browser_index - 1);
614 syncer::ReadNode gprev(trans);
615 ASSERT_TRUE(InitSyncNodeFromChromeNode(bprev, &gprev));
616 EXPECT_EQ(gnode.GetPredecessorId(), gprev.GetId());
617 EXPECT_EQ(gnode.GetParentId(), gprev.GetParentId());
619 // Note: the managed node is the last child of the root_node but isn't
620 // synced; if CanSyncNode() is false then there is no next node to sync.
621 const BookmarkNode* bnext = NULL;
622 if (browser_index + 1 < bnode->parent()->child_count())
623 bnext = bnode->parent()->GetChild(browser_index + 1);
624 if (!bnext || !CanSyncNode(bnext)) {
625 EXPECT_EQ(gnode.GetSuccessorId(), 0);
627 syncer::ReadNode gnext(trans);
628 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnext, &gnext));
629 EXPECT_EQ(gnode.GetSuccessorId(), gnext.GetId());
630 EXPECT_EQ(gnode.GetParentId(), gnext.GetParentId());
633 EXPECT_TRUE(gnode.GetFirstChildId());
636 void ExpectSyncerNodeMatching(const BookmarkNode* bnode) {
637 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
638 ExpectSyncerNodeMatching(&trans, bnode);
641 void ExpectBrowserNodeMatching(syncer::BaseTransaction* trans,
643 EXPECT_TRUE(sync_id);
644 const BookmarkNode* bnode =
645 model_associator_->GetChromeNodeFromSyncId(sync_id);
647 ASSERT_TRUE(CanSyncNode(bnode));
649 int64 id = model_associator_->GetSyncIdFromChromeId(bnode->id());
650 EXPECT_EQ(id, sync_id);
651 ExpectSyncerNodeMatching(trans, bnode);
654 void ExpectBrowserNodeUnknown(int64 sync_id) {
655 EXPECT_FALSE(model_associator_->GetChromeNodeFromSyncId(sync_id));
658 void ExpectBrowserNodeKnown(int64 sync_id) {
659 EXPECT_TRUE(model_associator_->GetChromeNodeFromSyncId(sync_id));
662 void ExpectSyncerNodeKnown(const BookmarkNode* node) {
663 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
664 EXPECT_NE(sync_id, syncer::kInvalidId);
667 void ExpectSyncerNodeUnknown(const BookmarkNode* node) {
668 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
669 EXPECT_EQ(sync_id, syncer::kInvalidId);
672 void ExpectBrowserNodeTitle(int64 sync_id, const std::string& title) {
673 const BookmarkNode* bnode =
674 model_associator_->GetChromeNodeFromSyncId(sync_id);
676 EXPECT_EQ(bnode->GetTitle(), base::UTF8ToUTF16(title));
679 void ExpectBrowserNodeURL(int64 sync_id, const std::string& url) {
680 const BookmarkNode* bnode =
681 model_associator_->GetChromeNodeFromSyncId(sync_id);
683 EXPECT_EQ(GURL(url), bnode->url());
686 void ExpectBrowserNodeParent(int64 sync_id, int64 parent_sync_id) {
687 const BookmarkNode* node =
688 model_associator_->GetChromeNodeFromSyncId(sync_id);
690 const BookmarkNode* parent =
691 model_associator_->GetChromeNodeFromSyncId(parent_sync_id);
693 EXPECT_EQ(node->parent(), parent);
696 void ExpectModelMatch(syncer::BaseTransaction* trans) {
697 const BookmarkNode* root = model_->root_node();
699 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 0);
700 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 1);
701 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 2);
703 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 0);
704 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 1);
705 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 2);
708 std::stack<int64> stack;
709 stack.push(bookmark_bar_id());
710 while (!stack.empty()) {
711 int64 id = stack.top();
715 ExpectBrowserNodeMatching(trans, id);
717 syncer::ReadNode gnode(trans);
718 ASSERT_EQ(BaseNode::INIT_OK, gnode.InitByIdLookup(id));
719 stack.push(gnode.GetSuccessorId());
720 if (gnode.GetIsFolder())
721 stack.push(gnode.GetFirstChildId());
725 void ExpectModelMatch() {
726 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
727 ExpectModelMatch(&trans);
730 int64 mobile_bookmarks_id() {
732 model_associator_->GetSyncIdFromChromeId(model_->mobile_node()->id());
735 int64 other_bookmarks_id() {
737 model_associator_->GetSyncIdFromChromeId(model_->other_node()->id());
740 int64 bookmark_bar_id() {
741 return model_associator_->GetSyncIdFromChromeId(
742 model_->bookmark_bar_node()->id());
746 TestingProfile profile_;
747 BookmarkModel* model_;
748 syncer::TestUserShare test_user_share_;
749 scoped_ptr<BookmarkChangeProcessor> change_processor_;
750 StrictMock<sync_driver::DataTypeErrorHandlerMock> mock_error_handler_;
751 scoped_ptr<BookmarkModelAssociator> model_associator_;
754 content::TestBrowserThreadBundle thread_bundle_;
755 syncer::SyncMergeResult local_merge_result_;
756 syncer::SyncMergeResult syncer_merge_result_;
759 TEST_F(ProfileSyncServiceBookmarkTest, InitialState) {
760 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
763 EXPECT_TRUE(other_bookmarks_id());
764 EXPECT_TRUE(bookmark_bar_id());
765 EXPECT_TRUE(mobile_bookmarks_id());
770 // Populate the sync database then start model association. Sync's bookmarks
771 // should end up being copied into the native model, resulting in a successful
772 // "ExpectModelMatch()".
774 // This code has some use for verifying correctness. It's also a very useful
775 // for profiling bookmark ModelAssociation, an important part of some first-time
776 // sync scenarios. Simply increase the kNumFolders and kNumBookmarksPerFolder
777 // as desired, then run the test under a profiler to find hot spots in the model
779 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociate) {
780 const int kNumBookmarksPerFolder = 10;
781 const int kNumFolders = 10;
783 CreatePermanentBookmarkNodes();
786 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
787 for (int i = 0; i < kNumFolders; ++i) {
788 int64 folder_id = AddFolderToShare(&trans,
789 base::StringPrintf("folder%05d", i));
790 for (int j = 0; j < kNumBookmarksPerFolder; ++j) {
791 AddBookmarkToShare(&trans,
793 base::StringPrintf("bookmark%05d", j));
798 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
805 TEST_F(ProfileSyncServiceBookmarkTest, BookmarkModelOperations) {
806 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
810 const BookmarkNode* folder =
811 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("foobar"));
812 ExpectSyncerNodeMatching(folder);
814 const BookmarkNode* folder2 =
815 model_->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
816 ExpectSyncerNodeMatching(folder2);
818 const BookmarkNode* url1 = model_->AddURL(
819 folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
820 GURL("http://www.easypie.com/"));
821 ExpectSyncerNodeMatching(url1);
823 const BookmarkNode* url2 = model_->AddURL(
824 folder, 1, base::ASCIIToUTF16("Airplanes"),
825 GURL("http://www.easyjet.com/"));
826 ExpectSyncerNodeMatching(url2);
829 const BookmarkNode* mobile_folder =
830 model_->AddFolder(model_->mobile_node(), 0, base::ASCIIToUTF16("pie"));
831 ExpectSyncerNodeMatching(mobile_folder);
834 // Test modification.
835 model_->SetTitle(url2, base::ASCIIToUTF16("EasyJet"));
837 model_->Move(url1, folder2, 0);
839 model_->Move(folder2, model_->bookmark_bar_node(), 0);
841 model_->SetTitle(folder2, base::ASCIIToUTF16("Not Nested"));
843 model_->Move(folder, folder2, 0);
845 model_->SetTitle(folder, base::ASCIIToUTF16("who's nested now?"));
847 model_->Copy(url2, model_->bookmark_bar_node(), 0);
849 model_->SetTitle(mobile_folder, base::ASCIIToUTF16("strawberry"));
853 // Delete a single item.
854 model_->Remove(url2->parent(), url2->parent()->GetIndexOf(url2));
856 // Delete an item with several children.
857 model_->Remove(folder2->parent(),
858 folder2->parent()->GetIndexOf(folder2));
860 model_->Remove(model_->mobile_node(), 0);
864 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeProcessing) {
865 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
868 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
870 FakeServerChange adds(&trans);
871 int64 f1 = adds.AddFolder("Server Folder B", bookmark_bar_id(), 0);
872 int64 f2 = adds.AddFolder("Server Folder A", bookmark_bar_id(), f1);
873 int64 u1 = adds.AddURL("Some old site", "ftp://nifty.andrew.cmu.edu/",
874 bookmark_bar_id(), f2);
875 int64 u2 = adds.AddURL("Nifty", "ftp://nifty.andrew.cmu.edu/", f1, 0);
876 // u3 is a duplicate URL
877 int64 u3 = adds.AddURL("Nifty2", "ftp://nifty.andrew.cmu.edu/", f1, u2);
878 // u4 is a duplicate title, different URL.
879 adds.AddURL("Some old site", "http://slog.thestranger.com/",
880 bookmark_bar_id(), u1);
881 // u5 tests an empty-string title.
882 std::string javascript_url(
883 "javascript:(function(){var w=window.open(" \
884 "'about:blank','gnotesWin','location=0,menubar=0," \
885 "scrollbars=0,status=0,toolbar=0,width=300," \
886 "height=300,resizable');});");
887 adds.AddURL(std::string(), javascript_url, other_bookmarks_id(), 0);
888 int64 u6 = adds.AddURL(
889 "Sync1", "http://www.syncable.edu/", mobile_bookmarks_id(), 0);
891 syncer::ChangeRecordList::const_iterator it;
892 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
893 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
894 ExpectBrowserNodeUnknown(it->id);
896 adds.ApplyPendingChanges(change_processor_.get());
898 // Make sure the bookmark model received all of the nodes in |adds|.
899 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
900 ExpectBrowserNodeMatching(&trans, it->id);
901 ExpectModelMatch(&trans);
903 // Part two: test modifications.
904 FakeServerChange mods(&trans);
905 // Mess with u2, and move it into empty folder f2
906 // TODO(ncarter): Determine if we allow ModifyURL ops or not.
907 /* std::string u2_old_url = mods.ModifyURL(u2, "http://www.google.com"); */
908 std::string u2_old_title = mods.ModifyTitle(u2, "The Google");
909 int64 u2_old_parent = mods.ModifyPosition(u2, f2, 0);
911 // Now move f1 after u2.
912 std::string f1_old_title = mods.ModifyTitle(f1, "Server Folder C");
913 int64 f1_old_parent = mods.ModifyPosition(f1, f2, u2);
915 // Then add u3 after f1.
916 int64 u3_old_parent = mods.ModifyPosition(u3, f2, f1);
918 std::string u6_old_title = mods.ModifyTitle(u6, "Mobile Folder A");
920 // Test that the property changes have not yet taken effect.
921 ExpectBrowserNodeTitle(u2, u2_old_title);
922 /* ExpectBrowserNodeURL(u2, u2_old_url); */
923 ExpectBrowserNodeParent(u2, u2_old_parent);
925 ExpectBrowserNodeTitle(f1, f1_old_title);
926 ExpectBrowserNodeParent(f1, f1_old_parent);
928 ExpectBrowserNodeParent(u3, u3_old_parent);
930 ExpectBrowserNodeTitle(u6, u6_old_title);
932 // Apply the changes.
933 mods.ApplyPendingChanges(change_processor_.get());
935 // Check for successful application.
936 for (it = mods.changes().begin(); it != mods.changes().end(); ++it)
937 ExpectBrowserNodeMatching(&trans, it->id);
938 ExpectModelMatch(&trans);
940 // Part 3: Test URL deletion.
941 FakeServerChange dels(&trans);
946 ExpectBrowserNodeKnown(u2);
947 ExpectBrowserNodeKnown(u3);
949 dels.ApplyPendingChanges(change_processor_.get());
951 ExpectBrowserNodeUnknown(u2);
952 ExpectBrowserNodeUnknown(u3);
953 ExpectBrowserNodeUnknown(u6);
954 ExpectModelMatch(&trans);
957 // Tests a specific case in ApplyModelChanges where we move the
958 // children out from under a parent, and then delete the parent
959 // in the same changelist. The delete shows up first in the changelist,
960 // requiring the children to be moved to a temporary location.
961 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeRequiringFosterParent) {
962 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
965 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
967 // Stress the immediate children of other_node because that's where
968 // ApplyModelChanges puts a temporary foster parent node.
969 std::string url("http://dev.chromium.org/");
970 FakeServerChange adds(&trans);
971 int64 f0 = other_bookmarks_id(); // + other_node
972 int64 f1 = adds.AddFolder("f1", f0, 0); // + f1
973 int64 f2 = adds.AddFolder("f2", f1, 0); // + f2
974 int64 u3 = adds.AddURL( "u3", url, f2, 0); // + u3 NOLINT
975 int64 u4 = adds.AddURL( "u4", url, f2, u3); // + u4 NOLINT
976 int64 u5 = adds.AddURL( "u5", url, f1, f2); // + u5 NOLINT
977 int64 f6 = adds.AddFolder("f6", f1, u5); // + f6
978 int64 u7 = adds.AddURL( "u7", url, f0, f1); // + u7 NOLINT
980 syncer::ChangeRecordList::const_iterator it;
981 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
982 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
983 ExpectBrowserNodeUnknown(it->id);
985 adds.ApplyPendingChanges(change_processor_.get());
987 // Make sure the bookmark model received all of the nodes in |adds|.
988 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
989 ExpectBrowserNodeMatching(&trans, it->id);
990 ExpectModelMatch(&trans);
992 // We have to do the moves before the deletions, but FakeServerChange will
993 // put the deletion at the front of the changelist.
994 FakeServerChange ops(&trans);
995 ops.ModifyPosition(f6, other_bookmarks_id(), 0);
996 ops.ModifyPosition(u3, other_bookmarks_id(), f1); // Prev == f1 is OK here.
997 ops.ModifyPosition(f2, other_bookmarks_id(), u7);
998 ops.ModifyPosition(u7, f2, 0);
999 ops.ModifyPosition(u4, other_bookmarks_id(), f2);
1000 ops.ModifyPosition(u5, f6, 0);
1003 ops.ApplyPendingChanges(change_processor_.get());
1005 ExpectModelMatch(&trans);
1008 // Simulate a server change record containing a valid but non-canonical URL.
1009 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeWithNonCanonicalURL) {
1010 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1014 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1016 FakeServerChange adds(&trans);
1017 std::string url("http://dev.chromium.org");
1018 EXPECT_NE(GURL(url).spec(), url);
1019 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1021 adds.ApplyPendingChanges(change_processor_.get());
1023 EXPECT_EQ(1, model_->other_node()->child_count());
1024 ExpectModelMatch(&trans);
1027 // Now reboot the sync service, forcing a merge step.
1029 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1032 // There should still be just the one bookmark.
1033 EXPECT_EQ(1, model_->other_node()->child_count());
1037 // Simulate a server change record containing an invalid URL (per GURL).
1038 // TODO(ncarter): Disabled due to crashes. Fix bug 1677563.
1039 TEST_F(ProfileSyncServiceBookmarkTest, DISABLED_ServerChangeWithInvalidURL) {
1040 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1043 int child_count = 0;
1045 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1047 FakeServerChange adds(&trans);
1048 std::string url("x");
1049 EXPECT_FALSE(GURL(url).is_valid());
1050 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1052 adds.ApplyPendingChanges(change_processor_.get());
1054 // We're lenient about what should happen -- the model could wind up with
1055 // the node or without it; but things should be consistent, and we
1057 child_count = model_->other_node()->child_count();
1058 EXPECT_TRUE(child_count == 0 || child_count == 1);
1059 ExpectModelMatch(&trans);
1062 // Now reboot the sync service, forcing a merge step.
1064 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1067 // Things ought not to have changed.
1068 EXPECT_EQ(model_->other_node()->child_count(), child_count);
1073 // Test strings that might pose a problem if the titles ever became used as
1074 // file names in the sync backend.
1075 TEST_F(ProfileSyncServiceBookmarkTest, CornerCaseNames) {
1076 // TODO(ncarter): Bug 1570238 explains the failure of this test.
1077 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1080 const char* names[] = {
1081 // The empty string.
1083 // Illegal Windows filenames.
1084 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4",
1085 "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3",
1086 "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1087 // Current/parent directory markers.
1089 // Files created automatically by the Windows shell.
1090 "Thumbs.db", ".DS_Store",
1091 // Names including Win32-illegal characters, and path separators.
1092 "foo/bar", "foo\\bar", "foo?bar", "foo:bar", "foo|bar", "foo\"bar",
1093 "foo'bar", "foo<bar", "foo>bar", "foo%bar", "foo*bar", "foo]bar",
1095 // A name with title > 255 characters
1096 "012345678901234567890123456789012345678901234567890123456789012345678901"
1097 "234567890123456789012345678901234567890123456789012345678901234567890123"
1098 "456789012345678901234567890123456789012345678901234567890123456789012345"
1099 "678901234567890123456789012345678901234567890123456789012345678901234567"
1102 // Create both folders and bookmarks using each name.
1103 GURL url("http://www.doublemint.com");
1104 for (size_t i = 0; i < arraysize(names); ++i) {
1105 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16(names[i]));
1106 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16(names[i]), url);
1109 // Verify that the browser model matches the sync model.
1110 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1111 2*arraysize(names));
1114 // Restart and re-associate. Verify things still match.
1116 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1118 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1119 2*arraysize(names));
1123 // Stress the internal representation of position by sparse numbers. We want
1124 // to repeatedly bisect the range of available positions, to force the
1125 // syncer code to renumber its ranges. Pick a number big enough so that it
1126 // would exhaust 32bits of room between items a couple of times.
1127 TEST_F(ProfileSyncServiceBookmarkTest, RepeatedMiddleInsertion) {
1128 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1131 static const int kTimesToInsert = 256;
1133 // Create two book-end nodes to insert between.
1134 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("Alpha"));
1135 model_->AddFolder(model_->other_node(), 1, base::ASCIIToUTF16("Omega"));
1138 // Test insertion in first half of range by repeatedly inserting in second
1140 for (int i = 0; i < kTimesToInsert; ++i) {
1141 base::string16 title =
1142 base::ASCIIToUTF16("Pre-insertion ") + base::IntToString16(i);
1143 model_->AddFolder(model_->other_node(), 1, title);
1147 // Test insertion in second half of range by repeatedly inserting in
1148 // second-to-last position.
1149 for (int i = 0; i < kTimesToInsert; ++i) {
1150 base::string16 title =
1151 base::ASCIIToUTF16("Post-insertion ") + base::IntToString16(i);
1152 model_->AddFolder(model_->other_node(), count - 1, title);
1156 // Verify that the browser model matches the sync model.
1157 EXPECT_EQ(model_->other_node()->child_count(), count);
1161 // Introduce a consistency violation into the model, and see that it
1162 // puts itself into a lame, error state.
1163 TEST_F(ProfileSyncServiceBookmarkTest, UnrecoverableErrorSuspendsService) {
1164 EXPECT_CALL(mock_error_handler_,
1165 OnSingleDataTypeUnrecoverableError(_));
1167 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1170 // Add a node which will be the target of the consistency violation.
1171 const BookmarkNode* node =
1172 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("node"));
1173 ExpectSyncerNodeMatching(node);
1175 // Now destroy the syncer node as if we were the ProfileSyncService without
1176 // updating the ProfileSyncService state. This should introduce
1177 // inconsistency between the two models.
1179 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1180 syncer::WriteNode sync_node(&trans);
1181 ASSERT_TRUE(InitSyncNodeFromChromeNode(node, &sync_node));
1182 sync_node.Tombstone();
1184 // The models don't match at this point, but the ProfileSyncService
1185 // doesn't know it yet.
1186 ExpectSyncerNodeKnown(node);
1188 // Add a child to the inconsistent node. This should cause detection of the
1189 // problem and the syncer should stop processing changes.
1190 model_->AddFolder(node, 0, base::ASCIIToUTF16("nested"));
1193 // See what happens if we run model association when there are two exact URL
1194 // duplicate bookmarks. The BookmarkModelAssociator should not fall over when
1196 TEST_F(ProfileSyncServiceBookmarkTest, MergeDuplicates) {
1197 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1200 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1201 GURL("http://dup.com/"));
1202 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1203 GURL("http://dup.com/"));
1205 EXPECT_EQ(2, model_->other_node()->child_count());
1207 // Restart the sync service to trigger model association.
1211 EXPECT_EQ(2, model_->other_node()->child_count());
1215 TEST_F(ProfileSyncServiceBookmarkTest, ApplySyncDeletesFromJournal) {
1216 // Initialize sync model and bookmark model as:
1222 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1229 int fixed_sync_bk_count = GetSyncBookmarkCount();
1231 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1232 FakeServerChange adds(&trans);
1233 u0 = adds.AddURL("URL 0", "http://plus.google.com/", bookmark_bar_id(), 0);
1234 f1 = adds.AddFolder("Folder 1", bookmark_bar_id(), u0);
1235 u1 = adds.AddURL("URL 1", "http://www.google.com/", f1, 0);
1236 f2 = adds.AddFolder("Folder 2", f1, u1);
1237 u2 = adds.AddURL("URL 2", "http://mail.google.com/", f2, 0);
1238 adds.ApplyPendingChanges(change_processor_.get());
1242 // Reload bookmark model and disable model saving to make sync changes not
1244 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1245 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1246 EXPECT_EQ(fixed_sync_bk_count + 5, GetSyncBookmarkCount());
1249 // Remove all folders/bookmarks except u3 added above.
1250 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1251 FakeServerChange dels(&trans);
1256 dels.ApplyPendingChanges(change_processor_.get());
1259 // Bookmark bar itself and u0 remain.
1260 EXPECT_EQ(2, model_->bookmark_bar_node()->GetTotalNodeCount());
1262 // Reload bookmarks including ones deleted in sync model from storage.
1263 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1264 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1265 // Add a bookmark under f1 when sync is off so that f1 will not be
1266 // deleted even when f1 matches delete journal because it's not empty.
1267 model_->AddURL(model_->bookmark_bar_node()->GetChild(1),
1268 0, base::UTF8ToUTF16("local"), GURL("http://www.youtube.com"));
1269 // Sync model has fixed bookmarks nodes and u3.
1270 EXPECT_EQ(fixed_sync_bk_count + 1, GetSyncBookmarkCount());
1272 // Expect 4 bookmarks after model association because u2, f2, u1 are removed
1273 // by delete journal, f1 is not removed by delete journal because it's
1274 // not empty due to www.youtube.com added above.
1275 EXPECT_EQ(4, model_->bookmark_bar_node()->GetTotalNodeCount());
1276 EXPECT_EQ(base::UTF8ToUTF16("URL 0"),
1277 model_->bookmark_bar_node()->GetChild(0)->GetTitle());
1278 EXPECT_EQ(base::UTF8ToUTF16("Folder 1"),
1279 model_->bookmark_bar_node()->GetChild(1)->GetTitle());
1280 EXPECT_EQ(base::UTF8ToUTF16("local"),
1281 model_->bookmark_bar_node()->GetChild(1)->GetChild(0)->GetTitle());
1284 // Verify purging of delete journals.
1285 // Delete journals for u2, f2, u1 remains because they are used in last
1287 EXPECT_EQ(3u, test_user_share_.GetDeleteJournalSize());
1290 // Reload again and all delete journals should be gone because none is used
1291 // in last association.
1292 ASSERT_TRUE(test_user_share_.Reload());
1293 EXPECT_EQ(0u, test_user_share_.GetDeleteJournalSize());
1301 // Map from bookmark node ID to its version.
1302 typedef std::map<int64, int64> BookmarkNodeVersionMap;
1304 // TODO(ncarter): Integrate the existing TestNode/PopulateNodeFromString code
1305 // in the bookmark model unittest, to make it simpler to set up test data
1306 // here (and reduce the amount of duplication among tests), and to reduce the
1308 class ProfileSyncServiceBookmarkTestWithData
1309 : public ProfileSyncServiceBookmarkTest {
1311 ProfileSyncServiceBookmarkTestWithData();
1314 // Populates or compares children of the given bookmark node from/with the
1315 // given test data array with the given size. |running_count| is updated as
1316 // urls are added. It is used to set the creation date (or test the creation
1317 // date for CompareWithTestData()).
1318 void PopulateFromTestData(const BookmarkNode* node,
1319 const TestData* data,
1321 int* running_count);
1322 void CompareWithTestData(const BookmarkNode* node,
1323 const TestData* data,
1325 int* running_count);
1327 void ExpectBookmarkModelMatchesTestData();
1328 void WriteTestDataToBookmarkModel();
1330 // Output transaction versions of |node| and nodes under it to
1332 void GetTransactionVersions(const BookmarkNode* root,
1333 BookmarkNodeVersionMap* node_versions);
1335 // Verify transaction versions of bookmark nodes and sync nodes are equal
1336 // recursively. If node is in |version_expected|, versions should match
1338 void ExpectTransactionVersionMatch(
1339 const BookmarkNode* node,
1340 const BookmarkNodeVersionMap& version_expected);
1343 const base::Time start_time_;
1345 DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceBookmarkTestWithData);
1350 // Constants for bookmark model that looks like:
1352 // | |-- u2, http://www.u2.com/
1354 // | | |-- f1u4, http://www.f1u4.com/
1355 // | | |-- f1u2, http://www.f1u2.com/
1356 // | | |-- f1u3, http://www.f1u3.com/
1357 // | | +-- f1u1, http://www.f1u1.com/
1358 // | |-- u1, http://www.u1.com/
1360 // | |-- f2u2, http://www.f2u2.com/
1361 // | |-- f2u4, http://www.f2u4.com/
1362 // | |-- f2u3, http://www.f2u3.com/
1363 // | +-- f2u1, http://www.f2u1.com/
1364 // +-- Other bookmarks
1366 // | | |-- f3u4, http://www.f3u4.com/
1367 // | | |-- f3u2, http://www.f3u2.com/
1368 // | | |-- f3u3, http://www.f3u3.com/
1369 // | | +-- f3u1, http://www.f3u1.com/
1370 // | |-- u4, http://www.u4.com/
1371 // | |-- u3, http://www.u3.com/
1373 // | | |-- f4u1, http://www.f4u1.com/
1374 // | | |-- f4u2, http://www.f4u2.com/
1375 // | | |-- f4u3, http://www.f4u3.com/
1376 // | | +-- f4u4, http://www.f4u4.com/
1378 // | | +-- dupu1, http://www.dupu1.com/
1380 // | | +-- dupu2, http://www.dupu1.com/
1381 // | +-- ls , http://www.ls.com/
1383 // +-- Mobile bookmarks
1385 // | |-- f5u1, http://www.f5u1.com/
1387 // | |-- f6u1, http://www.f6u1.com/
1388 // | |-- f6u2, http://www.f6u2.com/
1389 // +-- u5, http://www.u5.com/
1391 static TestData kBookmarkBarChildren[] = {
1392 { "u2", "http://www.u2.com/" },
1394 { "u1", "http://www.u1.com/" },
1397 static TestData kF1Children[] = {
1398 { "f1u4", "http://www.f1u4.com/" },
1399 { "f1u2", "http://www.f1u2.com/" },
1400 { "f1u3", "http://www.f1u3.com/" },
1401 { "f1u1", "http://www.f1u1.com/" },
1403 static TestData kF2Children[] = {
1404 { "f2u2", "http://www.f2u2.com/" },
1405 { "f2u4", "http://www.f2u4.com/" },
1406 { "f2u3", "http://www.f2u3.com/" },
1407 { "f2u1", "http://www.f2u1.com/" },
1410 static TestData kOtherBookmarkChildren[] = {
1412 { "u4", "http://www.u4.com/" },
1413 { "u3", "http://www.u3.com/" },
1417 { " ls ", "http://www.ls.com/" }
1419 static TestData kF3Children[] = {
1420 { "f3u4", "http://www.f3u4.com/" },
1421 { "f3u2", "http://www.f3u2.com/" },
1422 { "f3u3", "http://www.f3u3.com/" },
1423 { "f3u1", "http://www.f3u1.com/" },
1425 static TestData kF4Children[] = {
1426 { "f4u1", "http://www.f4u1.com/" },
1427 { "f4u2", "http://www.f4u2.com/" },
1428 { "f4u3", "http://www.f4u3.com/" },
1429 { "f4u4", "http://www.f4u4.com/" },
1431 static TestData kDup1Children[] = {
1432 { "dupu1", "http://www.dupu1.com/" },
1434 static TestData kDup2Children[] = {
1435 { "dupu2", "http://www.dupu2.com/" },
1438 static TestData kMobileBookmarkChildren[] = {
1441 { "u5", "http://www.u5.com/" },
1443 static TestData kF5Children[] = {
1444 { "f5u1", "http://www.f5u1.com/" },
1445 { "f5u2", "http://www.f5u2.com/" },
1447 static TestData kF6Children[] = {
1448 { "f6u1", "http://www.f6u1.com/" },
1449 { "f6u2", "http://www.f6u2.com/" },
1452 } // anonymous namespace.
1454 ProfileSyncServiceBookmarkTestWithData::
1455 ProfileSyncServiceBookmarkTestWithData()
1456 : start_time_(base::Time::Now()) {
1459 void ProfileSyncServiceBookmarkTestWithData::PopulateFromTestData(
1460 const BookmarkNode* node,
1461 const TestData* data,
1463 int* running_count) {
1466 DCHECK(node->is_folder());
1467 for (int i = 0; i < size; ++i) {
1468 const TestData& item = data[i];
1470 const base::Time add_time =
1471 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1472 model_->AddURLWithCreationTimeAndMetaInfo(node,
1474 base::UTF8ToUTF16(item.title),
1479 model_->AddFolder(node, i, base::UTF8ToUTF16(item.title));
1485 void ProfileSyncServiceBookmarkTestWithData::CompareWithTestData(
1486 const BookmarkNode* node,
1487 const TestData* data,
1489 int* running_count) {
1492 DCHECK(node->is_folder());
1493 ASSERT_EQ(size, node->child_count());
1494 for (int i = 0; i < size; ++i) {
1495 const BookmarkNode* child_node = node->GetChild(i);
1496 const TestData& item = data[i];
1497 GURL url = GURL(item.url == NULL ? "" : item.url);
1498 BookmarkNode test_node(url);
1499 test_node.SetTitle(base::UTF8ToUTF16(item.title));
1500 EXPECT_EQ(child_node->GetTitle(), test_node.GetTitle());
1502 EXPECT_FALSE(child_node->is_folder());
1503 EXPECT_TRUE(child_node->is_url());
1504 EXPECT_EQ(child_node->url(), test_node.url());
1505 const base::Time expected_time =
1506 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1507 EXPECT_EQ(expected_time.ToInternalValue(),
1508 child_node->date_added().ToInternalValue());
1510 EXPECT_TRUE(child_node->is_folder());
1511 EXPECT_FALSE(child_node->is_url());
1517 // TODO(munjal): We should implement some way of generating random data and can
1518 // use the same seed to generate the same sequence.
1519 void ProfileSyncServiceBookmarkTestWithData::WriteTestDataToBookmarkModel() {
1520 const BookmarkNode* bookmarks_bar_node = model_->bookmark_bar_node();
1522 PopulateFromTestData(bookmarks_bar_node,
1523 kBookmarkBarChildren,
1524 arraysize(kBookmarkBarChildren),
1527 ASSERT_GE(bookmarks_bar_node->child_count(), 4);
1528 const BookmarkNode* f1_node = bookmarks_bar_node->GetChild(1);
1529 PopulateFromTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1530 const BookmarkNode* f2_node = bookmarks_bar_node->GetChild(3);
1531 PopulateFromTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1533 const BookmarkNode* other_bookmarks_node = model_->other_node();
1534 PopulateFromTestData(other_bookmarks_node,
1535 kOtherBookmarkChildren,
1536 arraysize(kOtherBookmarkChildren),
1539 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1540 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1541 PopulateFromTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1542 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1543 PopulateFromTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1544 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1545 PopulateFromTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1547 dup_node = other_bookmarks_node->GetChild(5);
1548 PopulateFromTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1551 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1552 PopulateFromTestData(mobile_bookmarks_node,
1553 kMobileBookmarkChildren,
1554 arraysize(kMobileBookmarkChildren),
1557 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1558 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1559 PopulateFromTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1560 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1561 PopulateFromTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1563 ExpectBookmarkModelMatchesTestData();
1566 void ProfileSyncServiceBookmarkTestWithData::
1567 ExpectBookmarkModelMatchesTestData() {
1568 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1570 CompareWithTestData(bookmark_bar_node,
1571 kBookmarkBarChildren,
1572 arraysize(kBookmarkBarChildren),
1575 ASSERT_GE(bookmark_bar_node->child_count(), 4);
1576 const BookmarkNode* f1_node = bookmark_bar_node->GetChild(1);
1577 CompareWithTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1578 const BookmarkNode* f2_node = bookmark_bar_node->GetChild(3);
1579 CompareWithTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1581 const BookmarkNode* other_bookmarks_node = model_->other_node();
1582 CompareWithTestData(other_bookmarks_node,
1583 kOtherBookmarkChildren,
1584 arraysize(kOtherBookmarkChildren),
1587 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1588 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1589 CompareWithTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1590 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1591 CompareWithTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1592 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1593 CompareWithTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1595 dup_node = other_bookmarks_node->GetChild(5);
1596 CompareWithTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1599 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1600 CompareWithTestData(mobile_bookmarks_node,
1601 kMobileBookmarkChildren,
1602 arraysize(kMobileBookmarkChildren),
1605 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1606 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1607 CompareWithTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1608 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1609 CompareWithTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1612 // Tests persistence of the profile sync service by unloading the
1613 // database and then reloading it from disk.
1614 TEST_F(ProfileSyncServiceBookmarkTestWithData, Persistence) {
1615 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1618 WriteTestDataToBookmarkModel();
1622 // Force both models to discard their data and reload from disk. This
1623 // simulates what would happen if the browser were to shutdown normally,
1624 // and then relaunch.
1626 UnloadBookmarkModel();
1627 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1630 ExpectBookmarkModelMatchesTestData();
1632 // With the BookmarkModel contents verified, ExpectModelMatch will
1633 // verify the contents of the sync model.
1637 // Tests the merge case when the BookmarkModel is non-empty but the
1638 // sync model is empty. This corresponds to uploading browser
1639 // bookmarks to an initially empty, new account.
1640 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptySyncModel) {
1641 // Don't start the sync service until we've populated the bookmark model.
1642 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1644 WriteTestDataToBookmarkModel();
1646 // Restart sync. This should trigger a merge step during
1647 // initialization -- we expect the browser bookmarks to be written
1648 // to the sync service during this call.
1651 // Verify that the bookmark model hasn't changed, and that the sync model
1652 // matches it exactly.
1653 ExpectBookmarkModelMatchesTestData();
1657 // Tests the merge case when the BookmarkModel is empty but the sync model is
1658 // non-empty. This corresponds (somewhat) to a clean install of the browser,
1659 // with no bookmarks, connecting to a sync account that has some bookmarks.
1660 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptyBookmarkModel) {
1661 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1664 WriteTestDataToBookmarkModel();
1668 // Force the databse to unload and write itself to disk.
1671 // Blow away the bookmark model -- it should be empty afterwards.
1672 UnloadBookmarkModel();
1673 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1674 EXPECT_EQ(model_->bookmark_bar_node()->child_count(), 0);
1675 EXPECT_EQ(model_->other_node()->child_count(), 0);
1676 EXPECT_EQ(model_->mobile_node()->child_count(), 0);
1678 // Now restart the sync service. Starting it should populate the bookmark
1679 // model -- test for consistency.
1681 ExpectBookmarkModelMatchesTestData();
1685 // Tests the merge cases when both the models are expected to be identical
1687 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeExpectedIdenticalModels) {
1688 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1690 WriteTestDataToBookmarkModel();
1693 UnloadBookmarkModel();
1695 // At this point both the bookmark model and the server should have the
1696 // exact same data and it should match the test data.
1697 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1699 ExpectBookmarkModelMatchesTestData();
1702 UnloadBookmarkModel();
1704 // Now reorder some bookmarks in the bookmark model and then merge. Make
1705 // sure we get the order of the server after merge.
1706 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1707 ExpectBookmarkModelMatchesTestData();
1708 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
1709 ASSERT_TRUE(bookmark_bar);
1710 ASSERT_GT(bookmark_bar->child_count(), 1);
1711 model_->Move(bookmark_bar->GetChild(0), bookmark_bar, 1);
1714 ExpectBookmarkModelMatchesTestData();
1717 // Tests the merge cases when both the models are expected to be identical
1719 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeModelsWithSomeExtras) {
1720 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1721 WriteTestDataToBookmarkModel();
1722 ExpectBookmarkModelMatchesTestData();
1724 // Remove some nodes and reorder some nodes.
1725 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1726 int remove_index = 2;
1727 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1728 const BookmarkNode* child_node = bookmark_bar_node->GetChild(remove_index);
1729 ASSERT_TRUE(child_node);
1730 ASSERT_TRUE(child_node->is_url());
1731 model_->Remove(bookmark_bar_node, remove_index);
1732 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1733 child_node = bookmark_bar_node->GetChild(remove_index);
1734 ASSERT_TRUE(child_node);
1735 ASSERT_TRUE(child_node->is_folder());
1736 model_->Remove(bookmark_bar_node, remove_index);
1738 const BookmarkNode* other_node = model_->other_node();
1739 ASSERT_GE(other_node->child_count(), 1);
1740 const BookmarkNode* f3_node = other_node->GetChild(0);
1741 ASSERT_TRUE(f3_node);
1742 ASSERT_TRUE(f3_node->is_folder());
1744 ASSERT_GT(f3_node->child_count(), remove_index);
1745 model_->Remove(f3_node, remove_index);
1746 ASSERT_GT(f3_node->child_count(), remove_index);
1747 model_->Remove(f3_node, remove_index);
1753 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1754 WriteTestDataToBookmarkModel();
1755 ExpectBookmarkModelMatchesTestData();
1757 // Remove some nodes and reorder some nodes.
1758 bookmark_bar_node = model_->bookmark_bar_node();
1760 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1761 child_node = bookmark_bar_node->GetChild(remove_index);
1762 ASSERT_TRUE(child_node);
1763 ASSERT_TRUE(child_node->is_url());
1764 model_->Remove(bookmark_bar_node, remove_index);
1765 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1766 child_node = bookmark_bar_node->GetChild(remove_index);
1767 ASSERT_TRUE(child_node);
1768 ASSERT_TRUE(child_node->is_folder());
1769 model_->Remove(bookmark_bar_node, remove_index);
1771 ASSERT_GE(bookmark_bar_node->child_count(), 2);
1772 model_->Move(bookmark_bar_node->GetChild(0), bookmark_bar_node, 1);
1774 other_node = model_->other_node();
1775 ASSERT_GE(other_node->child_count(), 1);
1776 f3_node = other_node->GetChild(0);
1777 ASSERT_TRUE(f3_node);
1778 ASSERT_TRUE(f3_node->is_folder());
1780 ASSERT_GT(f3_node->child_count(), remove_index);
1781 model_->Remove(f3_node, remove_index);
1782 ASSERT_GT(f3_node->child_count(), remove_index);
1783 model_->Remove(f3_node, remove_index);
1785 ASSERT_GE(other_node->child_count(), 4);
1786 model_->Move(other_node->GetChild(0), other_node, 1);
1787 model_->Move(other_node->GetChild(2), other_node, 3);
1792 // After the merge, the model should match the test data.
1793 ExpectBookmarkModelMatchesTestData();
1796 // Tests that when persisted model associations are used, things work fine.
1797 TEST_F(ProfileSyncServiceBookmarkTestWithData, ModelAssociationPersistence) {
1798 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1799 WriteTestDataToBookmarkModel();
1802 // Force sync to shut down and write itself to disk.
1804 // Now restart sync. This time it should use the persistent
1810 // Tests that when persisted model associations are used, things work fine.
1811 TEST_F(ProfileSyncServiceBookmarkTestWithData,
1812 ModelAssociationInvalidPersistence) {
1813 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1814 WriteTestDataToBookmarkModel();
1817 // Force sync to shut down and write itself to disk.
1819 // Change the bookmark model before restarting sync service to simulate
1820 // the situation where bookmark model is different from sync model and
1821 // make sure model associator correctly rebuilds associations.
1822 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1823 model_->AddURL(bookmark_bar_node, 0, base::ASCIIToUTF16("xtra"),
1824 GURL("http://www.xtra.com"));
1825 // Now restart sync. This time it will try to use the persistent
1826 // associations and realize that they are invalid and hence will rebuild
1832 TEST_F(ProfileSyncServiceBookmarkTestWithData, SortChildren) {
1833 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1836 // Write test data to bookmark model and verify that the models match.
1837 WriteTestDataToBookmarkModel();
1838 const BookmarkNode* folder_added = model_->other_node()->GetChild(0);
1839 ASSERT_TRUE(folder_added);
1840 ASSERT_TRUE(folder_added->is_folder());
1844 // Sort the other-bookmarks children and expect that the models match.
1845 model_->SortChildren(folder_added);
1849 // See what happens if we enable sync but then delete the "Sync Data"
1851 TEST_F(ProfileSyncServiceBookmarkTestWithData,
1852 RecoverAfterDeletingSyncDataDirectory) {
1853 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1856 WriteTestDataToBookmarkModel();
1860 // Nuke the sync DB and reload.
1864 // First attempt fails due to a persistence error.
1865 EXPECT_TRUE(CreatePermanentBookmarkNodes());
1866 EXPECT_FALSE(AssociateModels());
1868 // Second attempt succeeds due to the previous error resetting the native
1869 // transaction version.
1870 model_associator_.reset();
1871 EXPECT_TRUE(CreatePermanentBookmarkNodes());
1872 EXPECT_TRUE(AssociateModels());
1874 // Make sure we're back in sync. In real life, the user would need
1875 // to reauthenticate before this happens, but in the test, authentication
1877 ExpectBookmarkModelMatchesTestData();
1881 // Verify that the bookmark model is updated about whether the
1882 // associator is currently running.
1883 TEST_F(ProfileSyncServiceBookmarkTest, AssociationState) {
1884 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1886 ExtensiveChangesBookmarkModelObserver observer;
1887 model_->AddObserver(&observer);
1891 EXPECT_EQ(1, observer.get_started());
1892 EXPECT_EQ(0, observer.get_completed_count_at_started());
1893 EXPECT_EQ(1, observer.get_completed());
1895 model_->RemoveObserver(&observer);
1898 // Verify that the creation_time_us changes are applied in the local model at
1899 // association time and update time.
1900 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateDateAdded) {
1901 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1902 WriteTestDataToBookmarkModel();
1904 // Start and stop sync in order to create bookmark nodes in the sync db.
1908 // Modify the date_added field of a bookmark so it doesn't match with
1910 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1911 int remove_index = 2;
1912 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1913 const BookmarkNode* child_node = bookmark_bar_node->GetChild(remove_index);
1914 ASSERT_TRUE(child_node);
1915 EXPECT_TRUE(child_node->is_url());
1916 model_->SetDateAdded(child_node, base::Time::FromInternalValue(10));
1920 // Everything should be back in sync after model association.
1921 ExpectBookmarkModelMatchesTestData();
1924 // Now trigger a change while syncing. We add a new bookmark, sync it, then
1925 // updates it's creation time.
1926 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1927 FakeServerChange adds(&trans);
1928 const std::string kTitle = "Some site";
1929 const std::string kUrl = "http://www.whatwhat.yeah/";
1930 const int kCreationTime = 30;
1931 int64 id = adds.AddURL(kTitle, kUrl,
1932 bookmark_bar_id(), 0);
1933 adds.ApplyPendingChanges(change_processor_.get());
1934 FakeServerChange updates(&trans);
1935 updates.ModifyCreationTime(id, kCreationTime);
1936 updates.ApplyPendingChanges(change_processor_.get());
1938 const BookmarkNode* node = model_->bookmark_bar_node()->GetChild(0);
1940 EXPECT_TRUE(node->is_url());
1941 EXPECT_EQ(base::UTF8ToUTF16(kTitle), node->GetTitle());
1942 EXPECT_EQ(kUrl, node->url().possibly_invalid_spec());
1943 EXPECT_EQ(node->date_added(), base::Time::FromInternalValue(30));
1946 // Tests that changes to the sync nodes meta info gets reflected in the local
1948 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromSync) {
1949 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1950 WriteTestDataToBookmarkModel();
1953 // Create bookmark nodes containing meta info.
1954 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1955 FakeServerChange adds(&trans);
1956 BookmarkNode::MetaInfoMap folder_meta_info;
1957 folder_meta_info["folder"] = "foldervalue";
1958 int64 folder_id = adds.AddFolderWithMetaInfo(
1959 "folder title", &folder_meta_info, bookmark_bar_id(), 0);
1960 BookmarkNode::MetaInfoMap node_meta_info;
1961 node_meta_info["node"] = "nodevalue";
1962 node_meta_info["other"] = "othervalue";
1963 int64 id = adds.AddURLWithMetaInfo("node title", "http://www.foo.com",
1964 &node_meta_info, folder_id, 0);
1965 adds.ApplyPendingChanges(change_processor_.get());
1967 // Verify that the nodes are created with the correct meta info.
1968 ASSERT_LT(0, model_->bookmark_bar_node()->child_count());
1969 const BookmarkNode* folder_node = model_->bookmark_bar_node()->GetChild(0);
1970 ASSERT_TRUE(folder_node->GetMetaInfoMap());
1971 EXPECT_EQ(folder_meta_info, *folder_node->GetMetaInfoMap());
1972 ASSERT_LT(0, folder_node->child_count());
1973 const BookmarkNode* node = folder_node->GetChild(0);
1974 ASSERT_TRUE(node->GetMetaInfoMap());
1975 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
1977 // Update meta info on nodes on server
1978 FakeServerChange updates(&trans);
1979 folder_meta_info.erase("folder");
1980 updates.ModifyMetaInfo(folder_id, folder_meta_info);
1981 node_meta_info["node"] = "changednodevalue";
1982 node_meta_info.erase("other");
1983 node_meta_info["newkey"] = "newkeyvalue";
1984 updates.ModifyMetaInfo(id, node_meta_info);
1985 updates.ApplyPendingChanges(change_processor_.get());
1987 // Confirm that the updated values are reflected in the bookmark nodes.
1988 EXPECT_FALSE(folder_node->GetMetaInfoMap());
1989 ASSERT_TRUE(node->GetMetaInfoMap());
1990 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
1993 // Tests that changes to the local bookmark nodes meta info gets reflected in
1995 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromModel) {
1996 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1997 WriteTestDataToBookmarkModel();
1999 ExpectBookmarkModelMatchesTestData();
2001 const BookmarkNode* folder_node =
2002 model_->AddFolder(model_->bookmark_bar_node(), 0,
2003 base::ASCIIToUTF16("folder title"));
2004 const BookmarkNode* node = model_->AddURL(folder_node, 0,
2005 base::ASCIIToUTF16("node title"),
2006 GURL("http://www.foo.com"));
2009 // Add some meta info and verify sync model matches the changes.
2010 model_->SetNodeMetaInfo(folder_node, "folder", "foldervalue");
2011 model_->SetNodeMetaInfo(node, "node", "nodevalue");
2012 model_->SetNodeMetaInfo(node, "other", "othervalue");
2015 // Change/delete existing meta info and verify.
2016 model_->DeleteNodeMetaInfo(folder_node, "folder");
2017 model_->SetNodeMetaInfo(node, "node", "changednodevalue");
2018 model_->DeleteNodeMetaInfo(node, "other");
2019 model_->SetNodeMetaInfo(node, "newkey", "newkeyvalue");
2023 void ProfileSyncServiceBookmarkTestWithData::GetTransactionVersions(
2024 const BookmarkNode* root,
2025 BookmarkNodeVersionMap* node_versions) {
2026 node_versions->clear();
2027 std::queue<const BookmarkNode*> nodes;
2029 while (!nodes.empty()) {
2030 const BookmarkNode* n = nodes.front();
2033 int64 version = n->sync_transaction_version();
2034 EXPECT_NE(BookmarkNode::kInvalidSyncTransactionVersion, version);
2036 (*node_versions)[n->id()] = version;
2037 for (int i = 0; i < n->child_count(); ++i) {
2038 if (!CanSyncNode(n->GetChild(i)))
2040 nodes.push(n->GetChild(i));
2045 void ProfileSyncServiceBookmarkTestWithData::ExpectTransactionVersionMatch(
2046 const BookmarkNode* node,
2047 const BookmarkNodeVersionMap& version_expected) {
2048 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2050 BookmarkNodeVersionMap bnodes_versions;
2051 GetTransactionVersions(node, &bnodes_versions);
2052 for (BookmarkNodeVersionMap::const_iterator it = bnodes_versions.begin();
2053 it != bnodes_versions.end(); ++it) {
2054 syncer::ReadNode sync_node(&trans);
2055 ASSERT_TRUE(model_associator_->InitSyncNodeFromChromeId(it->first,
2057 EXPECT_EQ(sync_node.GetEntry()->GetTransactionVersion(), it->second);
2058 BookmarkNodeVersionMap::const_iterator expected_ver_it =
2059 version_expected.find(it->first);
2060 if (expected_ver_it != version_expected.end())
2061 EXPECT_EQ(expected_ver_it->second, it->second);
2065 // Test transaction versions of model and nodes are incremented after changes
2067 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateTransactionVersion) {
2068 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2070 WriteTestDataToBookmarkModel();
2071 base::MessageLoop::current()->RunUntilIdle();
2073 BookmarkNodeVersionMap initial_versions;
2075 // Verify transaction versions in sync model and bookmark model (saved as
2076 // transaction version of root node) are equal after
2077 // WriteTestDataToBookmarkModel() created bookmarks.
2079 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2080 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2081 GetTransactionVersions(model_->root_node(), &initial_versions);
2082 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2083 initial_versions[model_->root_node()->id()]);
2085 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2086 BookmarkNodeVersionMap());
2087 ExpectTransactionVersionMatch(model_->other_node(),
2088 BookmarkNodeVersionMap());
2089 ExpectTransactionVersionMatch(model_->mobile_node(),
2090 BookmarkNodeVersionMap());
2092 // Verify model version is incremented and bookmark node versions remain
2094 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
2095 model_->Remove(bookmark_bar, 0);
2096 base::MessageLoop::current()->RunUntilIdle();
2097 BookmarkNodeVersionMap new_versions;
2098 GetTransactionVersions(model_->root_node(), &new_versions);
2099 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 1,
2100 new_versions[model_->root_node()->id()]);
2101 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2102 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2103 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2105 // Verify model version and version of changed bookmark are incremented and
2106 // versions of others remain same.
2107 const BookmarkNode* changed_bookmark =
2108 model_->bookmark_bar_node()->GetChild(0);
2109 model_->SetTitle(changed_bookmark, base::ASCIIToUTF16("test"));
2110 base::MessageLoop::current()->RunUntilIdle();
2111 GetTransactionVersions(model_->root_node(), &new_versions);
2112 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 2,
2113 new_versions[model_->root_node()->id()]);
2114 EXPECT_LT(initial_versions[changed_bookmark->id()],
2115 new_versions[changed_bookmark->id()]);
2116 initial_versions.erase(changed_bookmark->id());
2117 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2118 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2119 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2122 // Test that sync persistence errors are detected and trigger a failed
2124 TEST_F(ProfileSyncServiceBookmarkTestWithData, PersistenceError) {
2125 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2127 WriteTestDataToBookmarkModel();
2128 base::MessageLoop::current()->RunUntilIdle();
2130 BookmarkNodeVersionMap initial_versions;
2132 // Verify transaction versions in sync model and bookmark model (saved as
2133 // transaction version of root node) are equal after
2134 // WriteTestDataToBookmarkModel() created bookmarks.
2136 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2137 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2138 GetTransactionVersions(model_->root_node(), &initial_versions);
2139 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2140 initial_versions[model_->root_node()->id()]);
2142 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2143 BookmarkNodeVersionMap());
2144 ExpectTransactionVersionMatch(model_->other_node(),
2145 BookmarkNodeVersionMap());
2146 ExpectTransactionVersionMatch(model_->mobile_node(),
2147 BookmarkNodeVersionMap());
2149 // Now shut down sync and artificially increment the native model's version.
2151 int64 root_version = initial_versions[model_->root_node()->id()];
2152 model_->SetNodeSyncTransactionVersion(model_->root_node(), root_version + 1);
2154 // Upon association, bookmarks should fail to associate.
2155 EXPECT_FALSE(AssociateModels());
2158 // It's possible for update/add calls from the bookmark model to be out of
2159 // order, or asynchronous. Handle that without triggering an error.
2160 TEST_F(ProfileSyncServiceBookmarkTest, UpdateThenAdd) {
2161 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2164 EXPECT_TRUE(other_bookmarks_id());
2165 EXPECT_TRUE(bookmark_bar_id());
2166 EXPECT_TRUE(mobile_bookmarks_id());
2170 // Now destroy the change processor then add a bookmark, to simulate
2171 // missing the Update call.
2172 change_processor_.reset();
2173 const BookmarkNode* node = model_->AddURL(model_->bookmark_bar_node(),
2175 base::ASCIIToUTF16("title"),
2176 GURL("http://www.url.com"));
2178 // Recreate the change processor then update that bookmark. Sync should
2179 // receive the update call and gracefully treat that as if it were an add.
2180 change_processor_.reset(new BookmarkChangeProcessor(
2181 &profile_, model_associator_.get(), &mock_error_handler_));
2182 change_processor_->Start(test_user_share_.user_share());
2183 model_->SetTitle(node, base::ASCIIToUTF16("title2"));
2186 // Then simulate the add call arriving late.
2187 change_processor_->BookmarkNodeAdded(model_, model_->bookmark_bar_node(), 0);
2193 } // namespace browser_sync