Use app list item shadow for app list folders.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service_bookmark_unittest.cc
blobd4db0f7e8dcb96bcf6a2a83cabeb3fe55d0ab5ed
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_write_transaction.h"
49 #include "testing/gmock/include/gmock/gmock.h"
50 #include "testing/gtest/include/gtest/gtest.h"
52 namespace browser_sync {
54 using bookmarks::BookmarkModel;
55 using bookmarks::BookmarkNode;
56 using syncer::BaseNode;
57 using testing::_;
58 using testing::InvokeWithoutArgs;
59 using testing::Mock;
60 using testing::Return;
61 using testing::StrictMock;
63 #if defined(OS_ANDROID) || defined(OS_IOS)
64 static const bool kExpectMobileBookmarks = true;
65 #else
66 static const bool kExpectMobileBookmarks = false;
67 #endif // defined(OS_ANDROID) || defined(OS_IOS)
69 namespace {
71 // FakeServerChange constructs a list of syncer::ChangeRecords while modifying
72 // the sync model, and can pass the ChangeRecord list to a
73 // syncer::SyncObserver (i.e., the ProfileSyncService) to test the client
74 // change-application behavior.
75 // Tests using FakeServerChange should be careful to avoid back-references,
76 // since FakeServerChange will send the edits in the order specified.
77 class FakeServerChange {
78 public:
79 explicit FakeServerChange(syncer::WriteTransaction* trans) : trans_(trans) {
82 // Pretend that the server told the syncer to add a bookmark object.
83 int64 AddWithMetaInfo(const std::string& title,
84 const std::string& url,
85 const BookmarkNode::MetaInfoMap* meta_info_map,
86 bool is_folder,
87 int64 parent_id,
88 int64 predecessor_id) {
89 syncer::ReadNode parent(trans_);
90 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
91 syncer::WriteNode node(trans_);
92 if (predecessor_id == 0) {
93 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
94 } else {
95 syncer::ReadNode predecessor(trans_);
96 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
97 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
98 EXPECT_TRUE(node.InitBookmarkByCreation(parent, &predecessor));
100 EXPECT_EQ(node.GetPredecessorId(), predecessor_id);
101 EXPECT_EQ(node.GetParentId(), parent_id);
102 node.SetIsFolder(is_folder);
103 node.SetTitle(title);
105 sync_pb::BookmarkSpecifics specifics(node.GetBookmarkSpecifics());
106 const base::Time creation_time(base::Time::Now());
107 specifics.set_creation_time_us(creation_time.ToInternalValue());
108 if (!is_folder)
109 specifics.set_url(url);
110 if (meta_info_map)
111 SetNodeMetaInfo(*meta_info_map, &specifics);
112 node.SetBookmarkSpecifics(specifics);
114 syncer::ChangeRecord record;
115 record.action = syncer::ChangeRecord::ACTION_ADD;
116 record.id = node.GetId();
117 changes_.push_back(record);
118 return node.GetId();
121 int64 Add(const std::string& title,
122 const std::string& url,
123 bool is_folder,
124 int64 parent_id,
125 int64 predecessor_id) {
126 return AddWithMetaInfo(title, url, NULL, is_folder, parent_id,
127 predecessor_id);
130 // Add a bookmark folder.
131 int64 AddFolder(const std::string& title,
132 int64 parent_id,
133 int64 predecessor_id) {
134 return Add(title, std::string(), true, parent_id, predecessor_id);
136 int64 AddFolderWithMetaInfo(const std::string& title,
137 const BookmarkNode::MetaInfoMap* meta_info_map,
138 int64 parent_id,
139 int64 predecessor_id) {
140 return AddWithMetaInfo(title, std::string(), meta_info_map, true, parent_id,
141 predecessor_id);
144 // Add a bookmark.
145 int64 AddURL(const std::string& title,
146 const std::string& url,
147 int64 parent_id,
148 int64 predecessor_id) {
149 return Add(title, url, false, parent_id, predecessor_id);
151 int64 AddURLWithMetaInfo(const std::string& title,
152 const std::string& url,
153 const BookmarkNode::MetaInfoMap* meta_info_map,
154 int64 parent_id,
155 int64 predecessor_id) {
156 return AddWithMetaInfo(title, url, meta_info_map, false, parent_id,
157 predecessor_id);
160 // Pretend that the server told the syncer to delete an object.
161 void Delete(int64 id) {
163 // Delete the sync node.
164 syncer::WriteNode node(trans_);
165 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
166 if (node.GetIsFolder())
167 EXPECT_FALSE(node.GetFirstChildId());
168 node.GetMutableEntryForTest()->PutServerIsDel(true);
169 node.Tombstone();
172 // Verify the deletion.
173 syncer::ReadNode node(trans_);
174 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL, node.InitByIdLookup(id));
177 syncer::ChangeRecord record;
178 record.action = syncer::ChangeRecord::ACTION_DELETE;
179 record.id = id;
180 // Deletions are always first in the changelist, but we can't actually do
181 // WriteNode::Remove() on the node until its children are moved. So, as
182 // a practical matter, users of FakeServerChange must move or delete
183 // children before parents. Thus, we must insert the deletion record
184 // at the front of the vector.
185 changes_.insert(changes_.begin(), record);
188 // Set a new title value, and return the old value.
189 std::string ModifyTitle(int64 id, const std::string& new_title) {
190 syncer::WriteNode node(trans_);
191 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
192 std::string old_title = node.GetTitle();
193 node.SetTitle(new_title);
194 SetModified(id);
195 return old_title;
198 // Set a new parent and predecessor value. Return the old parent id.
199 // We could return the old predecessor id, but it turns out not to be
200 // very useful for assertions.
201 int64 ModifyPosition(int64 id, int64 parent_id, int64 predecessor_id) {
202 syncer::ReadNode parent(trans_);
203 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
204 syncer::WriteNode node(trans_);
205 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
206 int64 old_parent_id = node.GetParentId();
207 if (predecessor_id == 0) {
208 EXPECT_TRUE(node.SetPosition(parent, NULL));
209 } else {
210 syncer::ReadNode predecessor(trans_);
211 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
212 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
213 EXPECT_TRUE(node.SetPosition(parent, &predecessor));
215 SetModified(id);
216 return old_parent_id;
219 void ModifyCreationTime(int64 id, int64 creation_time_us) {
220 syncer::WriteNode node(trans_);
221 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
222 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
223 specifics.set_creation_time_us(creation_time_us);
224 node.SetBookmarkSpecifics(specifics);
225 SetModified(id);
228 void ModifyMetaInfo(int64 id,
229 const BookmarkNode::MetaInfoMap& meta_info_map) {
230 syncer::WriteNode node(trans_);
231 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
232 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
233 SetNodeMetaInfo(meta_info_map, &specifics);
234 node.SetBookmarkSpecifics(specifics);
235 SetModified(id);
238 // Pass the fake change list to |service|.
239 void ApplyPendingChanges(sync_driver::ChangeProcessor* processor) {
240 processor->ApplyChangesFromSyncModel(
241 trans_, 0, syncer::ImmutableChangeRecordList(&changes_));
244 const syncer::ChangeRecordList& changes() {
245 return changes_;
248 private:
249 // Helper function to push an ACTION_UPDATE record onto the back
250 // of the changelist.
251 void SetModified(int64 id) {
252 // Coalesce multi-property edits.
253 if (!changes_.empty() && changes_.back().id == id &&
254 changes_.back().action ==
255 syncer::ChangeRecord::ACTION_UPDATE)
256 return;
257 syncer::ChangeRecord record;
258 record.action = syncer::ChangeRecord::ACTION_UPDATE;
259 record.id = id;
260 changes_.push_back(record);
263 void SetNodeMetaInfo(const BookmarkNode::MetaInfoMap& meta_info_map,
264 sync_pb::BookmarkSpecifics* specifics) {
265 specifics->clear_meta_info();
266 // Deliberatly set MetaInfoMap entries in opposite order (compared
267 // to the implementation in BookmarkChangeProcessor) to ensure that
268 // (a) the implementation isn't sensitive to the order and
269 // (b) the original meta info isn't blindly overwritten by
270 // BookmarkChangeProcessor unless there is a real change.
271 BookmarkNode::MetaInfoMap::const_iterator it = meta_info_map.end();
272 while (it != meta_info_map.begin()) {
273 --it;
274 sync_pb::MetaInfo* meta_info = specifics->add_meta_info();
275 meta_info->set_key(it->first);
276 meta_info->set_value(it->second);
280 // The transaction on which everything happens.
281 syncer::WriteTransaction *trans_;
283 // The change list we construct.
284 syncer::ChangeRecordList changes_;
287 class ExtensiveChangesBookmarkModelObserver
288 : public bookmarks::BaseBookmarkModelObserver {
289 public:
290 ExtensiveChangesBookmarkModelObserver()
291 : started_count_(0),
292 completed_count_at_started_(0),
293 completed_count_(0) {}
295 void ExtensiveBookmarkChangesBeginning(BookmarkModel* model) override {
296 ++started_count_;
297 completed_count_at_started_ = completed_count_;
300 void ExtensiveBookmarkChangesEnded(BookmarkModel* model) override {
301 ++completed_count_;
304 void BookmarkModelChanged() override {}
306 int get_started() const {
307 return started_count_;
310 int get_completed_count_at_started() const {
311 return completed_count_at_started_;
314 int get_completed() const {
315 return completed_count_;
318 private:
319 int started_count_;
320 int completed_count_at_started_;
321 int completed_count_;
323 DISALLOW_COPY_AND_ASSIGN(ExtensiveChangesBookmarkModelObserver);
327 class ProfileSyncServiceBookmarkTest : public testing::Test {
328 protected:
329 enum LoadOption { LOAD_FROM_STORAGE, DELETE_EXISTING_STORAGE };
330 enum SaveOption { SAVE_TO_STORAGE, DONT_SAVE_TO_STORAGE };
332 ProfileSyncServiceBookmarkTest()
333 : model_(NULL),
334 local_merge_result_(syncer::BOOKMARKS),
335 syncer_merge_result_(syncer::BOOKMARKS) {}
337 virtual ~ProfileSyncServiceBookmarkTest() {
338 StopSync();
339 UnloadBookmarkModel();
342 virtual void SetUp() {
343 test_user_share_.SetUp();
346 virtual void TearDown() {
347 test_user_share_.TearDown();
350 bool CanSyncNode(const BookmarkNode* node) {
351 return model_->client()->CanSyncNode(node);
354 // Inserts a folder directly to the share.
355 // Do not use this after model association is complete.
357 // This function differs from the AddFolder() function declared elsewhere in
358 // this file in that it only affects the sync model. It would be invalid to
359 // change the sync model directly after ModelAssociation. This function can
360 // be invoked prior to model association to set up first-time sync model
361 // association scenarios.
362 int64 AddFolderToShare(syncer::WriteTransaction* trans, std::string title) {
363 EXPECT_FALSE(model_associator_);
365 // Be sure to call CreatePermanentBookmarkNodes(), otherwise this will fail.
366 syncer::ReadNode bookmark_bar(trans);
367 EXPECT_EQ(BaseNode::INIT_OK,
368 bookmark_bar.InitByTagLookupForBookmarks("bookmark_bar"));
370 syncer::WriteNode node(trans);
371 EXPECT_TRUE(node.InitBookmarkByCreation(bookmark_bar, NULL));
372 node.SetIsFolder(true);
373 node.SetTitle(title);
375 return node.GetId();
378 // Inserts a bookmark directly to the share.
379 // Do not use this after model association is complete.
381 // This function differs from the AddURL() function declared elsewhere in this
382 // file in that it only affects the sync model. It would be invalid to change
383 // the sync model directly after ModelAssociation. This function can be
384 // invoked prior to model association to set up first-time sync model
385 // association scenarios.
386 int64 AddBookmarkToShare(syncer::WriteTransaction* trans,
387 int64 parent_id,
388 const std::string& title,
389 const std::string& url) {
390 EXPECT_FALSE(model_associator_);
392 syncer::ReadNode parent(trans);
393 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
395 sync_pb::BookmarkSpecifics specifics;
396 specifics.set_url(url);
397 specifics.set_title(title);
399 syncer::WriteNode node(trans);
400 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
401 node.SetIsFolder(false);
402 node.SetTitle(title);
403 node.SetBookmarkSpecifics(specifics);
405 return node.GetId();
408 // Load (or re-load) the bookmark model. |load| controls use of the
409 // bookmarks file on disk. |save| controls whether the newly loaded
410 // bookmark model will write out a bookmark file as it goes.
411 void LoadBookmarkModel(LoadOption load, SaveOption save) {
412 bool delete_bookmarks = load == DELETE_EXISTING_STORAGE;
413 profile_.CreateBookmarkModel(delete_bookmarks);
414 model_ = BookmarkModelFactory::GetForProfile(&profile_);
415 bookmarks::test::WaitForBookmarkModelToLoad(model_);
416 // This noticeably speeds up the unit tests that request it.
417 if (save == DONT_SAVE_TO_STORAGE)
418 model_->ClearStore();
419 base::MessageLoop::current()->RunUntilIdle();
422 int GetSyncBookmarkCount() {
423 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
424 syncer::ReadNode node(&trans);
425 if (node.InitTypeRoot(syncer::BOOKMARKS) != syncer::BaseNode::INIT_OK)
426 return 0;
427 return node.GetTotalNodeCount();
430 // Creates the bookmark root node and the permanent nodes if they don't
431 // already exist.
432 bool CreatePermanentBookmarkNodes() {
433 bool root_exists = false;
434 syncer::ModelType type = syncer::BOOKMARKS;
436 syncer::WriteTransaction trans(FROM_HERE,
437 test_user_share_.user_share());
438 syncer::ReadNode uber_root(&trans);
439 uber_root.InitByRootLookup();
441 syncer::ReadNode root(&trans);
442 root_exists = (root.InitTypeRoot(type) == BaseNode::INIT_OK);
445 if (!root_exists) {
446 if (!syncer::TestUserShare::CreateRoot(type,
447 test_user_share_.user_share()))
448 return false;
451 const int kNumPermanentNodes = 3;
452 const std::string permanent_tags[kNumPermanentNodes] = {
453 #if defined(OS_IOS)
454 "synced_bookmarks",
455 #endif
456 "bookmark_bar",
457 "other_bookmarks",
458 #if !defined(OS_IOS)
459 "synced_bookmarks",
460 #endif
462 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
463 syncer::ReadNode root(&trans);
464 EXPECT_EQ(BaseNode::INIT_OK, root.InitTypeRoot(type));
466 // Loop through creating permanent nodes as necessary.
467 int64 last_child_id = syncer::kInvalidId;
468 for (int i = 0; i < kNumPermanentNodes; ++i) {
469 // First check if the node already exists. This is for tests that involve
470 // persistence and set up sync more than once.
471 syncer::ReadNode lookup(&trans);
472 if (lookup.InitByTagLookupForBookmarks(permanent_tags[i]) ==
473 syncer::ReadNode::INIT_OK) {
474 last_child_id = lookup.GetId();
475 continue;
478 // If it doesn't exist, create the permanent node at the end of the
479 // ordering.
480 syncer::ReadNode predecessor_node(&trans);
481 syncer::ReadNode* predecessor = NULL;
482 if (last_child_id != syncer::kInvalidId) {
483 EXPECT_EQ(BaseNode::INIT_OK,
484 predecessor_node.InitByIdLookup(last_child_id));
485 predecessor = &predecessor_node;
487 syncer::WriteNode node(&trans);
488 if (!node.InitBookmarkByCreation(root, predecessor))
489 return false;
490 node.SetIsFolder(true);
491 node.GetMutableEntryForTest()->PutUniqueServerTag(permanent_tags[i]);
492 node.SetTitle(permanent_tags[i]);
493 node.SetExternalId(0);
494 last_child_id = node.GetId();
496 return true;
499 bool AssociateModels() {
500 DCHECK(!model_associator_);
502 // Set up model associator.
503 model_associator_.reset(new BookmarkModelAssociator(
504 BookmarkModelFactory::GetForProfile(&profile_),
505 &profile_,
506 test_user_share_.user_share(),
507 &mock_error_handler_,
508 kExpectMobileBookmarks));
510 local_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
511 syncer_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
512 int local_count_before = model_->root_node()->GetTotalNodeCount();
513 int syncer_count_before = GetSyncBookmarkCount();
515 syncer::SyncError error = model_associator_->AssociateModels(
516 &local_merge_result_,
517 &syncer_merge_result_);
518 if (error.IsSet())
519 return false;
521 base::MessageLoop::current()->RunUntilIdle();
523 // Verify the merge results were calculated properly.
524 EXPECT_EQ(local_count_before,
525 local_merge_result_.num_items_before_association());
526 EXPECT_EQ(syncer_count_before,
527 syncer_merge_result_.num_items_before_association());
528 EXPECT_EQ(local_merge_result_.num_items_after_association(),
529 local_merge_result_.num_items_before_association() +
530 local_merge_result_.num_items_added() -
531 local_merge_result_.num_items_deleted());
532 EXPECT_EQ(syncer_merge_result_.num_items_after_association(),
533 syncer_merge_result_.num_items_before_association() +
534 syncer_merge_result_.num_items_added() -
535 syncer_merge_result_.num_items_deleted());
536 EXPECT_EQ(model_->root_node()->GetTotalNodeCount(),
537 local_merge_result_.num_items_after_association());
538 EXPECT_EQ(GetSyncBookmarkCount(),
539 syncer_merge_result_.num_items_after_association());
540 return true;
543 void StartSync() {
544 test_user_share_.Reload();
546 ASSERT_TRUE(CreatePermanentBookmarkNodes());
547 ASSERT_TRUE(AssociateModels());
549 // Set up change processor.
550 change_processor_.reset(
551 new BookmarkChangeProcessor(&profile_,
552 model_associator_.get(),
553 &mock_error_handler_));
554 change_processor_->Start(test_user_share_.user_share());
557 void StopSync() {
558 change_processor_.reset();
559 if (model_associator_) {
560 syncer::SyncError error = model_associator_->DisassociateModels();
561 EXPECT_FALSE(error.IsSet());
563 model_associator_.reset();
565 base::MessageLoop::current()->RunUntilIdle();
567 // TODO(akalin): Actually close the database and flush it to disk
568 // (and make StartSync reload from disk). This would require
569 // refactoring TestUserShare.
572 void UnloadBookmarkModel() {
573 profile_.CreateBookmarkModel(false /* delete_bookmarks */);
574 model_ = NULL;
575 base::MessageLoop::current()->RunUntilIdle();
578 bool InitSyncNodeFromChromeNode(const BookmarkNode* bnode,
579 syncer::BaseNode* sync_node) {
580 return model_associator_->InitSyncNodeFromChromeId(bnode->id(),
581 sync_node);
584 void ExpectSyncerNodeMatching(syncer::BaseTransaction* trans,
585 const BookmarkNode* bnode) {
586 std::string truncated_title = base::UTF16ToUTF8(bnode->GetTitle());
587 syncer::SyncAPINameToServerName(truncated_title, &truncated_title);
588 base::TruncateUTF8ToByteSize(truncated_title, 255, &truncated_title);
589 syncer::ServerNameToSyncAPIName(truncated_title, &truncated_title);
591 syncer::ReadNode gnode(trans);
592 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnode, &gnode));
593 // Non-root node titles and parents must match.
594 if (!model_->is_permanent_node(bnode)) {
595 EXPECT_EQ(truncated_title, gnode.GetTitle());
596 EXPECT_EQ(
597 model_associator_->GetChromeNodeFromSyncId(gnode.GetParentId()),
598 bnode->parent());
600 EXPECT_EQ(bnode->is_folder(), gnode.GetIsFolder());
601 if (bnode->is_url())
602 EXPECT_EQ(bnode->url(), GURL(gnode.GetBookmarkSpecifics().url()));
604 // Check that meta info matches.
605 const BookmarkNode::MetaInfoMap* meta_info_map = bnode->GetMetaInfoMap();
606 sync_pb::BookmarkSpecifics specifics = gnode.GetBookmarkSpecifics();
607 if (!meta_info_map) {
608 EXPECT_EQ(0, specifics.meta_info_size());
609 } else {
610 EXPECT_EQ(meta_info_map->size(),
611 static_cast<size_t>(specifics.meta_info_size()));
612 for (int i = 0; i < specifics.meta_info_size(); i++) {
613 BookmarkNode::MetaInfoMap::const_iterator it =
614 meta_info_map->find(specifics.meta_info(i).key());
615 EXPECT_TRUE(it != meta_info_map->end());
616 EXPECT_EQ(it->second, specifics.meta_info(i).value());
620 // Check for position matches.
621 int browser_index = bnode->parent()->GetIndexOf(bnode);
622 if (browser_index == 0) {
623 EXPECT_EQ(gnode.GetPredecessorId(), 0);
624 } else {
625 const BookmarkNode* bprev =
626 bnode->parent()->GetChild(browser_index - 1);
627 syncer::ReadNode gprev(trans);
628 ASSERT_TRUE(InitSyncNodeFromChromeNode(bprev, &gprev));
629 EXPECT_EQ(gnode.GetPredecessorId(), gprev.GetId());
630 EXPECT_EQ(gnode.GetParentId(), gprev.GetParentId());
632 // Note: the managed node is the last child of the root_node but isn't
633 // synced; if CanSyncNode() is false then there is no next node to sync.
634 const BookmarkNode* bnext = NULL;
635 if (browser_index + 1 < bnode->parent()->child_count())
636 bnext = bnode->parent()->GetChild(browser_index + 1);
637 if (!bnext || !CanSyncNode(bnext)) {
638 EXPECT_EQ(gnode.GetSuccessorId(), 0);
639 } else {
640 syncer::ReadNode gnext(trans);
641 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnext, &gnext));
642 EXPECT_EQ(gnode.GetSuccessorId(), gnext.GetId());
643 EXPECT_EQ(gnode.GetParentId(), gnext.GetParentId());
645 if (!bnode->empty())
646 EXPECT_TRUE(gnode.GetFirstChildId());
649 void ExpectSyncerNodeMatching(const BookmarkNode* bnode) {
650 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
651 ExpectSyncerNodeMatching(&trans, bnode);
654 void ExpectBrowserNodeMatching(syncer::BaseTransaction* trans,
655 int64 sync_id) {
656 EXPECT_TRUE(sync_id);
657 const BookmarkNode* bnode =
658 model_associator_->GetChromeNodeFromSyncId(sync_id);
659 ASSERT_TRUE(bnode);
660 ASSERT_TRUE(CanSyncNode(bnode));
662 int64 id = model_associator_->GetSyncIdFromChromeId(bnode->id());
663 EXPECT_EQ(id, sync_id);
664 ExpectSyncerNodeMatching(trans, bnode);
667 void ExpectBrowserNodeUnknown(int64 sync_id) {
668 EXPECT_FALSE(model_associator_->GetChromeNodeFromSyncId(sync_id));
671 void ExpectBrowserNodeKnown(int64 sync_id) {
672 EXPECT_TRUE(model_associator_->GetChromeNodeFromSyncId(sync_id));
675 void ExpectSyncerNodeKnown(const BookmarkNode* node) {
676 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
677 EXPECT_NE(sync_id, syncer::kInvalidId);
680 void ExpectSyncerNodeUnknown(const BookmarkNode* node) {
681 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
682 EXPECT_EQ(sync_id, syncer::kInvalidId);
685 void ExpectBrowserNodeTitle(int64 sync_id, const std::string& title) {
686 const BookmarkNode* bnode =
687 model_associator_->GetChromeNodeFromSyncId(sync_id);
688 ASSERT_TRUE(bnode);
689 EXPECT_EQ(bnode->GetTitle(), base::UTF8ToUTF16(title));
692 void ExpectBrowserNodeURL(int64 sync_id, const std::string& url) {
693 const BookmarkNode* bnode =
694 model_associator_->GetChromeNodeFromSyncId(sync_id);
695 ASSERT_TRUE(bnode);
696 EXPECT_EQ(GURL(url), bnode->url());
699 void ExpectBrowserNodeParent(int64 sync_id, int64 parent_sync_id) {
700 const BookmarkNode* node =
701 model_associator_->GetChromeNodeFromSyncId(sync_id);
702 ASSERT_TRUE(node);
703 const BookmarkNode* parent =
704 model_associator_->GetChromeNodeFromSyncId(parent_sync_id);
705 EXPECT_TRUE(parent);
706 EXPECT_EQ(node->parent(), parent);
709 void ExpectModelMatch(syncer::BaseTransaction* trans) {
710 const BookmarkNode* root = model_->root_node();
711 #if defined(OS_IOS)
712 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 0);
713 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 1);
714 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 2);
715 #else
716 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 0);
717 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 1);
718 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 2);
719 #endif
721 std::stack<int64> stack;
722 stack.push(bookmark_bar_id());
723 while (!stack.empty()) {
724 int64 id = stack.top();
725 stack.pop();
726 if (!id) continue;
728 ExpectBrowserNodeMatching(trans, id);
730 syncer::ReadNode gnode(trans);
731 ASSERT_EQ(BaseNode::INIT_OK, gnode.InitByIdLookup(id));
732 stack.push(gnode.GetSuccessorId());
733 if (gnode.GetIsFolder())
734 stack.push(gnode.GetFirstChildId());
738 void ExpectModelMatch() {
739 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
740 ExpectModelMatch(&trans);
743 int64 mobile_bookmarks_id() {
744 return
745 model_associator_->GetSyncIdFromChromeId(model_->mobile_node()->id());
748 int64 other_bookmarks_id() {
749 return
750 model_associator_->GetSyncIdFromChromeId(model_->other_node()->id());
753 int64 bookmark_bar_id() {
754 return model_associator_->GetSyncIdFromChromeId(
755 model_->bookmark_bar_node()->id());
758 private:
759 content::TestBrowserThreadBundle thread_bundle_;
761 protected:
762 TestingProfile profile_;
763 BookmarkModel* model_;
764 syncer::TestUserShare test_user_share_;
765 scoped_ptr<BookmarkChangeProcessor> change_processor_;
766 StrictMock<sync_driver::DataTypeErrorHandlerMock> mock_error_handler_;
767 scoped_ptr<BookmarkModelAssociator> model_associator_;
769 private:
770 syncer::SyncMergeResult local_merge_result_;
771 syncer::SyncMergeResult syncer_merge_result_;
774 TEST_F(ProfileSyncServiceBookmarkTest, InitialState) {
775 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
776 StartSync();
778 EXPECT_TRUE(other_bookmarks_id());
779 EXPECT_TRUE(bookmark_bar_id());
780 EXPECT_TRUE(mobile_bookmarks_id());
782 ExpectModelMatch();
785 // Populate the sync database then start model association. Sync's bookmarks
786 // should end up being copied into the native model, resulting in a successful
787 // "ExpectModelMatch()".
789 // This code has some use for verifying correctness. It's also a very useful
790 // for profiling bookmark ModelAssociation, an important part of some first-time
791 // sync scenarios. Simply increase the kNumFolders and kNumBookmarksPerFolder
792 // as desired, then run the test under a profiler to find hot spots in the model
793 // association code.
794 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociate) {
795 const int kNumBookmarksPerFolder = 10;
796 const int kNumFolders = 10;
798 CreatePermanentBookmarkNodes();
801 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
802 for (int i = 0; i < kNumFolders; ++i) {
803 int64 folder_id =
804 AddFolderToShare(&trans, base::StringPrintf("folder%05d", i));
805 for (int j = 0; j < kNumBookmarksPerFolder; ++j) {
806 AddBookmarkToShare(
807 &trans, folder_id, base::StringPrintf("bookmark%05d", j),
808 base::StringPrintf("http://www.google.com/search?q=%05d", j));
813 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
814 StartSync();
816 ExpectModelMatch();
819 // Tests bookmark association when nodes exists in the native model only.
820 // These entries should be copied to Sync directory during association process.
821 TEST_F(ProfileSyncServiceBookmarkTest,
822 InitialModelAssociateWithBookmarkModelNodes) {
823 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
824 const BookmarkNode* folder =
825 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("foobar"));
826 model_->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
827 model_->AddURL(folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
828 GURL("http://www.easypie.com/"));
829 model_->AddURL(folder, 1, base::ASCIIToUTF16("Airplanes"),
830 GURL("http://www.easyjet.com/"));
832 StartSync();
833 ExpectModelMatch();
836 // Tests bookmark association case when there is an entry in the delete journal
837 // that matches one of native bookmarks.
838 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociateWithDeleteJournal) {
839 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
840 const BookmarkNode* folder = model_->AddFolder(model_->bookmark_bar_node(), 0,
841 base::ASCIIToUTF16("foobar"));
842 const BookmarkNode* bookmark =
843 model_->AddURL(folder, 0, base::ASCIIToUTF16("Airplanes"),
844 GURL("http://www.easyjet.com/"));
846 CreatePermanentBookmarkNodes();
848 // Create entries matching the folder and the bookmark above.
849 int64 folder_id, bookmark_id;
851 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
852 folder_id = AddFolderToShare(&trans, "foobar");
853 bookmark_id = AddBookmarkToShare(&trans, folder_id, "Airplanes",
854 "http://www.easyjet.com/");
857 // Associate the bookmark sync node with the native model one and make
858 // it deleted.
860 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
861 syncer::WriteNode node(&trans);
862 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(bookmark_id));
864 node.GetMutableEntryForTest()->PutLocalExternalId(bookmark->id());
865 node.GetMutableEntryForTest()->PutServerIsDel(true);
866 node.GetMutableEntryForTest()->PutIsDel(true);
869 ASSERT_TRUE(AssociateModels());
870 ExpectModelMatch();
872 // The bookmark node should be deleted.
873 EXPECT_EQ(0, folder->child_count());
876 // Tests that the external ID is used to match the right folder amoung
877 // multiple folders with the same name during the native model traversal.
878 // Also tests that the external ID is used to match the right bookmark
879 // among multiple identical bookmarks when dealing with the delete journal.
880 TEST_F(ProfileSyncServiceBookmarkTest,
881 InitialModelAssociateVerifyExternalIdMatch) {
882 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
883 const int kNumFolders = 10;
884 const int kNumBookmarks = 10;
885 const int kFolderToIncludeBookmarks = 7;
886 const int kBookmarkToDelete = 4;
888 int64 folder_ids[kNumFolders];
889 int64 bookmark_ids[kNumBookmarks];
891 // Create native folders and bookmarks with identical names. Only
892 // one of the folders contains bookmarks and others are empty. Here is the
893 // expected tree shape:
894 // Bookmarks bar
895 // +- folder (#0)
896 // +- folder (#1)
897 // ...
898 // +- folder (#7) <-- Only this folder contains bookmarks.
899 // +- bookmark (#0)
900 // +- bookmark (#1)
901 // ...
902 // +- bookmark (#4) <-- Only this one bookmark should be removed later.
903 // ...
904 // +- bookmark (#9)
905 // ...
906 // +- folder (#9)
908 const BookmarkNode* parent_folder = nullptr;
909 for (int i = 0; i < kNumFolders; i++) {
910 const BookmarkNode* folder = model_->AddFolder(
911 model_->bookmark_bar_node(), i, base::ASCIIToUTF16("folder"));
912 folder_ids[i] = folder->id();
913 if (i == kFolderToIncludeBookmarks) {
914 parent_folder = folder;
918 for (int i = 0; i < kNumBookmarks; i++) {
919 const BookmarkNode* bookmark =
920 model_->AddURL(parent_folder, i, base::ASCIIToUTF16("bookmark"),
921 GURL("http://www.google.com/"));
922 bookmark_ids[i] = bookmark->id();
925 // Number of nodes in bookmark bar before association.
926 int total_node_count = model_->bookmark_bar_node()->GetTotalNodeCount();
928 CreatePermanentBookmarkNodes();
930 int64 sync_bookmark_id_to_delete = 0;
932 // Create sync folders matching native folders above.
933 int64 parent_id = 0;
934 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
935 // Create in reverse order because AddFolderToShare passes NULL for
936 // |predecessor| argument.
937 for (int i = kNumFolders - 1; i >= 0; i--) {
938 int64 id = AddFolderToShare(&trans, "folder");
940 // Pre-map sync folders to native folders by setting
941 // external ID. This will verify that the association algorithm picks
942 // the right ones despite all of them having identical names.
943 // More specifically this will help to avoid cloning bookmarks from
944 // a wrong folder.
945 syncer::WriteNode node(&trans);
946 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
947 node.GetMutableEntryForTest()->PutLocalExternalId(folder_ids[i]);
949 if (i == kFolderToIncludeBookmarks) {
950 parent_id = id;
954 // Create sync bookmark matching native bookmarks above in reverse order
955 // because AddBookmarkToShare passes NULL for |predecessor| argument.
956 for (int i = kNumBookmarks - 1; i >= 0; i--) {
957 int id = AddBookmarkToShare(&trans, parent_id, "bookmark",
958 "http://www.google.com/");
960 // Pre-map sync bookmarks to native bookmarks by setting
961 // external ID. This will verify that the association algorithm picks
962 // the right ones despite all of them having identical names and URLs.
963 syncer::WriteNode node(&trans);
964 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
965 node.GetMutableEntryForTest()->PutLocalExternalId(bookmark_ids[i]);
967 if (i == kBookmarkToDelete) {
968 sync_bookmark_id_to_delete = id;
973 // Make one bookmark deleted.
975 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
976 syncer::WriteNode node(&trans);
977 EXPECT_EQ(BaseNode::INIT_OK,
978 node.InitByIdLookup(sync_bookmark_id_to_delete));
980 node.GetMutableEntryForTest()->PutServerIsDel(true);
981 node.GetMutableEntryForTest()->PutIsDel(true);
984 // Perform association.
985 ASSERT_TRUE(AssociateModels());
986 ExpectModelMatch();
988 // Only one native node should have been deleted and no nodes cloned due to
989 // matching folder names.
990 EXPECT_EQ(kNumFolders, model_->bookmark_bar_node()->child_count());
991 EXPECT_EQ(kNumBookmarks - 1, parent_folder->child_count());
992 EXPECT_EQ(total_node_count - 1,
993 model_->bookmark_bar_node()->GetTotalNodeCount());
995 // Verify that the right bookmark got deleted and no bookmarks reordered.
996 for (int i = 0; i < parent_folder->child_count(); i++) {
997 int index_in_bookmark_ids = (i < kBookmarkToDelete) ? i : i + 1;
998 EXPECT_EQ(bookmark_ids[index_in_bookmark_ids],
999 parent_folder->GetChild(i)->id());
1003 // Verifies that the bookmark association skips sync nodes with invalid URLs.
1004 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociateWithInvalidUrl) {
1005 EXPECT_CALL(mock_error_handler_, CreateAndUploadError(_, _, _))
1006 .WillOnce(Return(syncer::SyncError()));
1008 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1009 // On the local side create a folder and two nodes.
1010 const BookmarkNode* folder = model_->AddFolder(model_->bookmark_bar_node(), 0,
1011 base::ASCIIToUTF16("folder"));
1012 model_->AddURL(folder, 0, base::ASCIIToUTF16("node1"),
1013 GURL("http://www.node1.com/"));
1014 model_->AddURL(folder, 1, base::ASCIIToUTF16("node2"),
1015 GURL("http://www.node2.com/"));
1017 // On the sync side create a matching folder, one matching node, one
1018 // unmatching node, and one node with an invalid URL.
1019 CreatePermanentBookmarkNodes();
1021 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1022 int64 folder_id = AddFolderToShare(&trans, "folder");
1023 // Please note that each AddBookmarkToShare inserts the node at the front
1024 // so the actual order of children in the directory will be opposite.
1025 AddBookmarkToShare(&trans, folder_id, "node2", "http://www.node2.com/");
1026 AddBookmarkToShare(&trans, folder_id, "node3", "");
1027 AddBookmarkToShare(&trans, folder_id, "node4", "http://www.node4.com/");
1030 // Perform association.
1031 StartSync();
1033 // Concatenate resulting titles of native nodes.
1034 std::string native_titles;
1035 for (int i = 0; i < folder->child_count(); i++) {
1036 if (!native_titles.empty())
1037 native_titles += ",";
1038 const BookmarkNode* child = folder->GetChild(i);
1039 native_titles += base::UTF16ToUTF8(child->GetTitle());
1042 // Expect the order of nodes to follow the sync order (see note above), the
1043 // node with the invalid URL to be skipped, and the extra native node to be
1044 // at the end.
1045 EXPECT_EQ("node4,node2,node1", native_titles);
1048 TEST_F(ProfileSyncServiceBookmarkTest, BookmarkModelOperations) {
1049 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1050 StartSync();
1052 // Test addition.
1053 const BookmarkNode* folder =
1054 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("foobar"));
1055 ExpectSyncerNodeMatching(folder);
1056 ExpectModelMatch();
1057 const BookmarkNode* folder2 =
1058 model_->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
1059 ExpectSyncerNodeMatching(folder2);
1060 ExpectModelMatch();
1061 const BookmarkNode* url1 = model_->AddURL(
1062 folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
1063 GURL("http://www.easypie.com/"));
1064 ExpectSyncerNodeMatching(url1);
1065 ExpectModelMatch();
1066 const BookmarkNode* url2 = model_->AddURL(
1067 folder, 1, base::ASCIIToUTF16("Airplanes"),
1068 GURL("http://www.easyjet.com/"));
1069 ExpectSyncerNodeMatching(url2);
1070 ExpectModelMatch();
1071 // Test addition.
1072 const BookmarkNode* mobile_folder =
1073 model_->AddFolder(model_->mobile_node(), 0, base::ASCIIToUTF16("pie"));
1074 ExpectSyncerNodeMatching(mobile_folder);
1075 ExpectModelMatch();
1077 // Test modification.
1078 model_->SetTitle(url2, base::ASCIIToUTF16("EasyJet"));
1079 ExpectModelMatch();
1080 model_->Move(url1, folder2, 0);
1081 ExpectModelMatch();
1082 model_->Move(folder2, model_->bookmark_bar_node(), 0);
1083 ExpectModelMatch();
1084 model_->SetTitle(folder2, base::ASCIIToUTF16("Not Nested"));
1085 ExpectModelMatch();
1086 model_->Move(folder, folder2, 0);
1087 ExpectModelMatch();
1088 model_->SetTitle(folder, base::ASCIIToUTF16("who's nested now?"));
1089 ExpectModelMatch();
1090 model_->Copy(url2, model_->bookmark_bar_node(), 0);
1091 ExpectModelMatch();
1092 model_->SetTitle(mobile_folder, base::ASCIIToUTF16("strawberry"));
1093 ExpectModelMatch();
1095 // Test deletion.
1096 // Delete a single item.
1097 model_->Remove(url2);
1098 ExpectModelMatch();
1099 // Delete an item with several children.
1100 model_->Remove(folder2);
1101 ExpectModelMatch();
1102 model_->Remove(model_->mobile_node()->GetChild(0));
1103 ExpectModelMatch();
1106 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeProcessing) {
1107 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1108 StartSync();
1110 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1112 FakeServerChange adds(&trans);
1113 int64 f1 = adds.AddFolder("Server Folder B", bookmark_bar_id(), 0);
1114 int64 f2 = adds.AddFolder("Server Folder A", bookmark_bar_id(), f1);
1115 int64 u1 = adds.AddURL("Some old site", "ftp://nifty.andrew.cmu.edu/",
1116 bookmark_bar_id(), f2);
1117 int64 u2 = adds.AddURL("Nifty", "ftp://nifty.andrew.cmu.edu/", f1, 0);
1118 // u3 is a duplicate URL
1119 int64 u3 = adds.AddURL("Nifty2", "ftp://nifty.andrew.cmu.edu/", f1, u2);
1120 // u4 is a duplicate title, different URL.
1121 adds.AddURL("Some old site", "http://slog.thestranger.com/",
1122 bookmark_bar_id(), u1);
1123 // u5 tests an empty-string title.
1124 std::string javascript_url(
1125 "javascript:(function(){var w=window.open(" \
1126 "'about:blank','gnotesWin','location=0,menubar=0," \
1127 "scrollbars=0,status=0,toolbar=0,width=300," \
1128 "height=300,resizable');});");
1129 adds.AddURL(std::string(), javascript_url, other_bookmarks_id(), 0);
1130 int64 u6 = adds.AddURL(
1131 "Sync1", "http://www.syncable.edu/", mobile_bookmarks_id(), 0);
1133 syncer::ChangeRecordList::const_iterator it;
1134 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
1135 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1136 ExpectBrowserNodeUnknown(it->id);
1138 adds.ApplyPendingChanges(change_processor_.get());
1140 // Make sure the bookmark model received all of the nodes in |adds|.
1141 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1142 ExpectBrowserNodeMatching(&trans, it->id);
1143 ExpectModelMatch(&trans);
1145 // Part two: test modifications.
1146 FakeServerChange mods(&trans);
1147 // Mess with u2, and move it into empty folder f2
1148 // TODO(ncarter): Determine if we allow ModifyURL ops or not.
1149 /* std::string u2_old_url = mods.ModifyURL(u2, "http://www.google.com"); */
1150 std::string u2_old_title = mods.ModifyTitle(u2, "The Google");
1151 int64 u2_old_parent = mods.ModifyPosition(u2, f2, 0);
1153 // Now move f1 after u2.
1154 std::string f1_old_title = mods.ModifyTitle(f1, "Server Folder C");
1155 int64 f1_old_parent = mods.ModifyPosition(f1, f2, u2);
1157 // Then add u3 after f1.
1158 int64 u3_old_parent = mods.ModifyPosition(u3, f2, f1);
1160 std::string u6_old_title = mods.ModifyTitle(u6, "Mobile Folder A");
1162 // Test that the property changes have not yet taken effect.
1163 ExpectBrowserNodeTitle(u2, u2_old_title);
1164 /* ExpectBrowserNodeURL(u2, u2_old_url); */
1165 ExpectBrowserNodeParent(u2, u2_old_parent);
1167 ExpectBrowserNodeTitle(f1, f1_old_title);
1168 ExpectBrowserNodeParent(f1, f1_old_parent);
1170 ExpectBrowserNodeParent(u3, u3_old_parent);
1172 ExpectBrowserNodeTitle(u6, u6_old_title);
1174 // Apply the changes.
1175 mods.ApplyPendingChanges(change_processor_.get());
1177 // Check for successful application.
1178 for (it = mods.changes().begin(); it != mods.changes().end(); ++it)
1179 ExpectBrowserNodeMatching(&trans, it->id);
1180 ExpectModelMatch(&trans);
1182 // Part 3: Test URL deletion.
1183 FakeServerChange dels(&trans);
1184 dels.Delete(u2);
1185 dels.Delete(u3);
1186 dels.Delete(u6);
1188 ExpectBrowserNodeKnown(u2);
1189 ExpectBrowserNodeKnown(u3);
1191 dels.ApplyPendingChanges(change_processor_.get());
1193 ExpectBrowserNodeUnknown(u2);
1194 ExpectBrowserNodeUnknown(u3);
1195 ExpectBrowserNodeUnknown(u6);
1196 ExpectModelMatch(&trans);
1199 // Tests a specific case in ApplyModelChanges where we move the
1200 // children out from under a parent, and then delete the parent
1201 // in the same changelist. The delete shows up first in the changelist,
1202 // requiring the children to be moved to a temporary location.
1203 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeRequiringFosterParent) {
1204 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1205 StartSync();
1207 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1209 // Stress the immediate children of other_node because that's where
1210 // ApplyModelChanges puts a temporary foster parent node.
1211 std::string url("http://dev.chromium.org/");
1212 FakeServerChange adds(&trans);
1213 int64 f0 = other_bookmarks_id(); // + other_node
1214 int64 f1 = adds.AddFolder("f1", f0, 0); // + f1
1215 int64 f2 = adds.AddFolder("f2", f1, 0); // + f2
1216 int64 u3 = adds.AddURL( "u3", url, f2, 0); // + u3 NOLINT
1217 int64 u4 = adds.AddURL( "u4", url, f2, u3); // + u4 NOLINT
1218 int64 u5 = adds.AddURL( "u5", url, f1, f2); // + u5 NOLINT
1219 int64 f6 = adds.AddFolder("f6", f1, u5); // + f6
1220 int64 u7 = adds.AddURL( "u7", url, f0, f1); // + u7 NOLINT
1222 syncer::ChangeRecordList::const_iterator it;
1223 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
1224 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1225 ExpectBrowserNodeUnknown(it->id);
1227 adds.ApplyPendingChanges(change_processor_.get());
1229 // Make sure the bookmark model received all of the nodes in |adds|.
1230 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1231 ExpectBrowserNodeMatching(&trans, it->id);
1232 ExpectModelMatch(&trans);
1234 // We have to do the moves before the deletions, but FakeServerChange will
1235 // put the deletion at the front of the changelist.
1236 FakeServerChange ops(&trans);
1237 ops.ModifyPosition(f6, other_bookmarks_id(), 0);
1238 ops.ModifyPosition(u3, other_bookmarks_id(), f1); // Prev == f1 is OK here.
1239 ops.ModifyPosition(f2, other_bookmarks_id(), u7);
1240 ops.ModifyPosition(u7, f2, 0);
1241 ops.ModifyPosition(u4, other_bookmarks_id(), f2);
1242 ops.ModifyPosition(u5, f6, 0);
1243 ops.Delete(f1);
1245 ops.ApplyPendingChanges(change_processor_.get());
1247 ExpectModelMatch(&trans);
1250 // Simulate a server change record containing a valid but non-canonical URL.
1251 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeWithNonCanonicalURL) {
1252 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1253 StartSync();
1256 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1258 FakeServerChange adds(&trans);
1259 std::string url("http://dev.chromium.org");
1260 EXPECT_NE(GURL(url).spec(), url);
1261 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1263 adds.ApplyPendingChanges(change_processor_.get());
1265 EXPECT_EQ(1, model_->other_node()->child_count());
1266 ExpectModelMatch(&trans);
1269 // Now reboot the sync service, forcing a merge step.
1270 StopSync();
1271 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1272 StartSync();
1274 // There should still be just the one bookmark.
1275 EXPECT_EQ(1, model_->other_node()->child_count());
1276 ExpectModelMatch();
1279 // Simulate a server change record containing an invalid URL (per GURL).
1280 // TODO(ncarter): Disabled due to crashes. Fix bug 1677563.
1281 TEST_F(ProfileSyncServiceBookmarkTest, DISABLED_ServerChangeWithInvalidURL) {
1282 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1283 StartSync();
1285 int child_count = 0;
1287 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1289 FakeServerChange adds(&trans);
1290 std::string url("x");
1291 EXPECT_FALSE(GURL(url).is_valid());
1292 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1294 adds.ApplyPendingChanges(change_processor_.get());
1296 // We're lenient about what should happen -- the model could wind up with
1297 // the node or without it; but things should be consistent, and we
1298 // shouldn't crash.
1299 child_count = model_->other_node()->child_count();
1300 EXPECT_TRUE(child_count == 0 || child_count == 1);
1301 ExpectModelMatch(&trans);
1304 // Now reboot the sync service, forcing a merge step.
1305 StopSync();
1306 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1307 StartSync();
1309 // Things ought not to have changed.
1310 EXPECT_EQ(model_->other_node()->child_count(), child_count);
1311 ExpectModelMatch();
1315 // Test strings that might pose a problem if the titles ever became used as
1316 // file names in the sync backend.
1317 TEST_F(ProfileSyncServiceBookmarkTest, CornerCaseNames) {
1318 // TODO(ncarter): Bug 1570238 explains the failure of this test.
1319 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1320 StartSync();
1322 const char* names[] = {
1323 // The empty string.
1325 // Illegal Windows filenames.
1326 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4",
1327 "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3",
1328 "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1329 // Current/parent directory markers.
1330 ".", "..", "...",
1331 // Files created automatically by the Windows shell.
1332 "Thumbs.db", ".DS_Store",
1333 // Names including Win32-illegal characters, and path separators.
1334 "foo/bar", "foo\\bar", "foo?bar", "foo:bar", "foo|bar", "foo\"bar",
1335 "foo'bar", "foo<bar", "foo>bar", "foo%bar", "foo*bar", "foo]bar",
1336 "foo[bar",
1337 // A name with title > 255 characters
1338 "012345678901234567890123456789012345678901234567890123456789012345678901"
1339 "234567890123456789012345678901234567890123456789012345678901234567890123"
1340 "456789012345678901234567890123456789012345678901234567890123456789012345"
1341 "678901234567890123456789012345678901234567890123456789012345678901234567"
1342 "890123456789"
1344 // Create both folders and bookmarks using each name.
1345 GURL url("http://www.doublemint.com");
1346 for (size_t i = 0; i < arraysize(names); ++i) {
1347 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16(names[i]));
1348 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16(names[i]), url);
1351 // Verify that the browser model matches the sync model.
1352 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1353 2*arraysize(names));
1354 ExpectModelMatch();
1356 // Restart and re-associate. Verify things still match.
1357 StopSync();
1358 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1359 StartSync();
1360 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1361 2*arraysize(names));
1362 ExpectModelMatch();
1365 // Stress the internal representation of position by sparse numbers. We want
1366 // to repeatedly bisect the range of available positions, to force the
1367 // syncer code to renumber its ranges. Pick a number big enough so that it
1368 // would exhaust 32bits of room between items a couple of times.
1369 TEST_F(ProfileSyncServiceBookmarkTest, RepeatedMiddleInsertion) {
1370 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1371 StartSync();
1373 static const int kTimesToInsert = 256;
1375 // Create two book-end nodes to insert between.
1376 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("Alpha"));
1377 model_->AddFolder(model_->other_node(), 1, base::ASCIIToUTF16("Omega"));
1378 int count = 2;
1380 // Test insertion in first half of range by repeatedly inserting in second
1381 // position.
1382 for (int i = 0; i < kTimesToInsert; ++i) {
1383 base::string16 title =
1384 base::ASCIIToUTF16("Pre-insertion ") + base::IntToString16(i);
1385 model_->AddFolder(model_->other_node(), 1, title);
1386 count++;
1389 // Test insertion in second half of range by repeatedly inserting in
1390 // second-to-last position.
1391 for (int i = 0; i < kTimesToInsert; ++i) {
1392 base::string16 title =
1393 base::ASCIIToUTF16("Post-insertion ") + base::IntToString16(i);
1394 model_->AddFolder(model_->other_node(), count - 1, title);
1395 count++;
1398 // Verify that the browser model matches the sync model.
1399 EXPECT_EQ(model_->other_node()->child_count(), count);
1400 ExpectModelMatch();
1403 // Introduce a consistency violation into the model, and see that it
1404 // puts itself into a lame, error state.
1405 TEST_F(ProfileSyncServiceBookmarkTest, UnrecoverableErrorSuspendsService) {
1406 EXPECT_CALL(mock_error_handler_,
1407 OnSingleDataTypeUnrecoverableError(_));
1409 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1410 StartSync();
1412 // Add a node which will be the target of the consistency violation.
1413 const BookmarkNode* node =
1414 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("node"));
1415 ExpectSyncerNodeMatching(node);
1417 // Now destroy the syncer node as if we were the ProfileSyncService without
1418 // updating the ProfileSyncService state. This should introduce
1419 // inconsistency between the two models.
1421 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1422 syncer::WriteNode sync_node(&trans);
1423 ASSERT_TRUE(InitSyncNodeFromChromeNode(node, &sync_node));
1424 sync_node.Tombstone();
1426 // The models don't match at this point, but the ProfileSyncService
1427 // doesn't know it yet.
1428 ExpectSyncerNodeKnown(node);
1430 // Add a child to the inconsistent node. This should cause detection of the
1431 // problem and the syncer should stop processing changes.
1432 model_->AddFolder(node, 0, base::ASCIIToUTF16("nested"));
1435 // See what happens if we run model association when there are two exact URL
1436 // duplicate bookmarks. The BookmarkModelAssociator should not fall over when
1437 // this happens.
1438 TEST_F(ProfileSyncServiceBookmarkTest, MergeDuplicates) {
1439 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1440 StartSync();
1442 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1443 GURL("http://dup.com/"));
1444 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1445 GURL("http://dup.com/"));
1447 EXPECT_EQ(2, model_->other_node()->child_count());
1449 // Restart the sync service to trigger model association.
1450 StopSync();
1451 StartSync();
1453 EXPECT_EQ(2, model_->other_node()->child_count());
1454 ExpectModelMatch();
1457 TEST_F(ProfileSyncServiceBookmarkTest, ApplySyncDeletesFromJournal) {
1458 // Initialize sync model and bookmark model as:
1459 // URL 0
1460 // Folder 1
1461 // |-- URL 1
1462 // +-- Folder 2
1463 // +-- URL 2
1464 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1465 int64 u0 = 0;
1466 int64 f1 = 0;
1467 int64 u1 = 0;
1468 int64 f2 = 0;
1469 int64 u2 = 0;
1470 StartSync();
1471 int fixed_sync_bk_count = GetSyncBookmarkCount();
1473 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1474 FakeServerChange adds(&trans);
1475 u0 = adds.AddURL("URL 0", "http://plus.google.com/", bookmark_bar_id(), 0);
1476 f1 = adds.AddFolder("Folder 1", bookmark_bar_id(), u0);
1477 u1 = adds.AddURL("URL 1", "http://www.google.com/", f1, 0);
1478 f2 = adds.AddFolder("Folder 2", f1, u1);
1479 u2 = adds.AddURL("URL 2", "http://mail.google.com/", f2, 0);
1480 adds.ApplyPendingChanges(change_processor_.get());
1482 StopSync();
1484 // Reload bookmark model and disable model saving to make sync changes not
1485 // persisted.
1486 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1487 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1488 EXPECT_EQ(fixed_sync_bk_count + 5, GetSyncBookmarkCount());
1489 StartSync();
1491 // Remove all folders/bookmarks except u3 added above.
1492 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1493 FakeServerChange dels(&trans);
1494 dels.Delete(u2);
1495 dels.Delete(f2);
1496 dels.Delete(u1);
1497 dels.Delete(f1);
1498 dels.ApplyPendingChanges(change_processor_.get());
1500 StopSync();
1501 // Bookmark bar itself and u0 remain.
1502 EXPECT_EQ(2, model_->bookmark_bar_node()->GetTotalNodeCount());
1504 // Reload bookmarks including ones deleted in sync model from storage.
1505 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1506 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1507 // Add a bookmark under f1 when sync is off so that f1 will not be
1508 // deleted even when f1 matches delete journal because it's not empty.
1509 model_->AddURL(model_->bookmark_bar_node()->GetChild(1),
1510 0, base::UTF8ToUTF16("local"), GURL("http://www.youtube.com"));
1511 // Sync model has fixed bookmarks nodes and u3.
1512 EXPECT_EQ(fixed_sync_bk_count + 1, GetSyncBookmarkCount());
1513 StartSync();
1514 // Expect 4 bookmarks after model association because u2, f2, u1 are removed
1515 // by delete journal, f1 is not removed by delete journal because it's
1516 // not empty due to www.youtube.com added above.
1517 EXPECT_EQ(4, model_->bookmark_bar_node()->GetTotalNodeCount());
1518 EXPECT_EQ(base::UTF8ToUTF16("URL 0"),
1519 model_->bookmark_bar_node()->GetChild(0)->GetTitle());
1520 EXPECT_EQ(base::UTF8ToUTF16("Folder 1"),
1521 model_->bookmark_bar_node()->GetChild(1)->GetTitle());
1522 EXPECT_EQ(base::UTF8ToUTF16("local"),
1523 model_->bookmark_bar_node()->GetChild(1)->GetChild(0)->GetTitle());
1524 StopSync();
1526 // Verify purging of delete journals.
1527 // Delete journals for u2, f2, u1 remains because they are used in last
1528 // association.
1529 EXPECT_EQ(3u, test_user_share_.GetDeleteJournalSize());
1530 StartSync();
1531 StopSync();
1532 // Reload again and all delete journals should be gone because none is used
1533 // in last association.
1534 ASSERT_TRUE(test_user_share_.Reload());
1535 EXPECT_EQ(0u, test_user_share_.GetDeleteJournalSize());
1538 struct TestData {
1539 const char* title;
1540 const char* url;
1543 // Map from bookmark node ID to its version.
1544 typedef std::map<int64, int64> BookmarkNodeVersionMap;
1546 // TODO(ncarter): Integrate the existing TestNode/PopulateNodeFromString code
1547 // in the bookmark model unittest, to make it simpler to set up test data
1548 // here (and reduce the amount of duplication among tests), and to reduce the
1549 // duplication.
1550 class ProfileSyncServiceBookmarkTestWithData
1551 : public ProfileSyncServiceBookmarkTest {
1552 public:
1553 ProfileSyncServiceBookmarkTestWithData();
1555 protected:
1556 // Populates or compares children of the given bookmark node from/with the
1557 // given test data array with the given size. |running_count| is updated as
1558 // urls are added. It is used to set the creation date (or test the creation
1559 // date for CompareWithTestData()).
1560 void PopulateFromTestData(const BookmarkNode* node,
1561 const TestData* data,
1562 int size,
1563 int* running_count);
1564 void CompareWithTestData(const BookmarkNode* node,
1565 const TestData* data,
1566 int size,
1567 int* running_count);
1569 void ExpectBookmarkModelMatchesTestData();
1570 void WriteTestDataToBookmarkModel();
1572 // Output transaction versions of |node| and nodes under it to
1573 // |node_versions|.
1574 void GetTransactionVersions(const BookmarkNode* root,
1575 BookmarkNodeVersionMap* node_versions);
1577 // Verify transaction versions of bookmark nodes and sync nodes are equal
1578 // recursively. If node is in |version_expected|, versions should match
1579 // there, too.
1580 void ExpectTransactionVersionMatch(
1581 const BookmarkNode* node,
1582 const BookmarkNodeVersionMap& version_expected);
1584 private:
1585 const base::Time start_time_;
1587 DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceBookmarkTestWithData);
1590 namespace {
1592 // Constants for bookmark model that looks like:
1593 // |-- Bookmark bar
1594 // | |-- u2, http://www.u2.com/
1595 // | |-- f1
1596 // | | |-- f1u4, http://www.f1u4.com/
1597 // | | |-- f1u2, http://www.f1u2.com/
1598 // | | |-- f1u3, http://www.f1u3.com/
1599 // | | +-- f1u1, http://www.f1u1.com/
1600 // | |-- u1, http://www.u1.com/
1601 // | +-- f2
1602 // | |-- f2u2, http://www.f2u2.com/
1603 // | |-- f2u4, http://www.f2u4.com/
1604 // | |-- f2u3, http://www.f2u3.com/
1605 // | +-- f2u1, http://www.f2u1.com/
1606 // +-- Other bookmarks
1607 // | |-- f3
1608 // | | |-- f3u4, http://www.f3u4.com/
1609 // | | |-- f3u2, http://www.f3u2.com/
1610 // | | |-- f3u3, http://www.f3u3.com/
1611 // | | +-- f3u1, http://www.f3u1.com/
1612 // | |-- u4, http://www.u4.com/
1613 // | |-- u3, http://www.u3.com/
1614 // | --- f4
1615 // | | |-- f4u1, http://www.f4u1.com/
1616 // | | |-- f4u2, http://www.f4u2.com/
1617 // | | |-- f4u3, http://www.f4u3.com/
1618 // | | +-- f4u4, http://www.f4u4.com/
1619 // | |-- dup
1620 // | | +-- dupu1, http://www.dupu1.com/
1621 // | +-- dup
1622 // | | +-- dupu2, http://www.dupu1.com/
1623 // | +-- ls , http://www.ls.com/
1624 // |
1625 // +-- Mobile bookmarks
1626 // |-- f5
1627 // | |-- f5u1, http://www.f5u1.com/
1628 // |-- f6
1629 // | |-- f6u1, http://www.f6u1.com/
1630 // | |-- f6u2, http://www.f6u2.com/
1631 // +-- u5, http://www.u5.com/
1633 static TestData kBookmarkBarChildren[] = {
1634 { "u2", "http://www.u2.com/" },
1635 { "f1", NULL },
1636 { "u1", "http://www.u1.com/" },
1637 { "f2", NULL },
1639 static TestData kF1Children[] = {
1640 { "f1u4", "http://www.f1u4.com/" },
1641 { "f1u2", "http://www.f1u2.com/" },
1642 { "f1u3", "http://www.f1u3.com/" },
1643 { "f1u1", "http://www.f1u1.com/" },
1645 static TestData kF2Children[] = {
1646 { "f2u2", "http://www.f2u2.com/" },
1647 { "f2u4", "http://www.f2u4.com/" },
1648 { "f2u3", "http://www.f2u3.com/" },
1649 { "f2u1", "http://www.f2u1.com/" },
1652 static TestData kOtherBookmarkChildren[] = {
1653 { "f3", NULL },
1654 { "u4", "http://www.u4.com/" },
1655 { "u3", "http://www.u3.com/" },
1656 { "f4", NULL },
1657 { "dup", NULL },
1658 { "dup", NULL },
1659 { " ls ", "http://www.ls.com/" }
1661 static TestData kF3Children[] = {
1662 { "f3u4", "http://www.f3u4.com/" },
1663 { "f3u2", "http://www.f3u2.com/" },
1664 { "f3u3", "http://www.f3u3.com/" },
1665 { "f3u1", "http://www.f3u1.com/" },
1667 static TestData kF4Children[] = {
1668 { "f4u1", "http://www.f4u1.com/" },
1669 { "f4u2", "http://www.f4u2.com/" },
1670 { "f4u3", "http://www.f4u3.com/" },
1671 { "f4u4", "http://www.f4u4.com/" },
1673 static TestData kDup1Children[] = {
1674 { "dupu1", "http://www.dupu1.com/" },
1676 static TestData kDup2Children[] = {
1677 { "dupu2", "http://www.dupu2.com/" },
1680 static TestData kMobileBookmarkChildren[] = {
1681 { "f5", NULL },
1682 { "f6", NULL },
1683 { "u5", "http://www.u5.com/" },
1685 static TestData kF5Children[] = {
1686 { "f5u1", "http://www.f5u1.com/" },
1687 { "f5u2", "http://www.f5u2.com/" },
1689 static TestData kF6Children[] = {
1690 { "f6u1", "http://www.f6u1.com/" },
1691 { "f6u2", "http://www.f6u2.com/" },
1694 } // anonymous namespace.
1696 ProfileSyncServiceBookmarkTestWithData::
1697 ProfileSyncServiceBookmarkTestWithData()
1698 : start_time_(base::Time::Now()) {
1701 void ProfileSyncServiceBookmarkTestWithData::PopulateFromTestData(
1702 const BookmarkNode* node,
1703 const TestData* data,
1704 int size,
1705 int* running_count) {
1706 DCHECK(node);
1707 DCHECK(data);
1708 DCHECK(node->is_folder());
1709 for (int i = 0; i < size; ++i) {
1710 const TestData& item = data[i];
1711 if (item.url) {
1712 const base::Time add_time =
1713 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1714 model_->AddURLWithCreationTimeAndMetaInfo(node,
1716 base::UTF8ToUTF16(item.title),
1717 GURL(item.url),
1718 add_time,
1719 NULL);
1720 } else {
1721 model_->AddFolder(node, i, base::UTF8ToUTF16(item.title));
1723 (*running_count)++;
1727 void ProfileSyncServiceBookmarkTestWithData::CompareWithTestData(
1728 const BookmarkNode* node,
1729 const TestData* data,
1730 int size,
1731 int* running_count) {
1732 DCHECK(node);
1733 DCHECK(data);
1734 DCHECK(node->is_folder());
1735 ASSERT_EQ(size, node->child_count());
1736 for (int i = 0; i < size; ++i) {
1737 const BookmarkNode* child_node = node->GetChild(i);
1738 const TestData& item = data[i];
1739 GURL url = GURL(item.url == NULL ? "" : item.url);
1740 BookmarkNode test_node(url);
1741 test_node.SetTitle(base::UTF8ToUTF16(item.title));
1742 EXPECT_EQ(child_node->GetTitle(), test_node.GetTitle());
1743 if (item.url) {
1744 EXPECT_FALSE(child_node->is_folder());
1745 EXPECT_TRUE(child_node->is_url());
1746 EXPECT_EQ(child_node->url(), test_node.url());
1747 const base::Time expected_time =
1748 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1749 EXPECT_EQ(expected_time.ToInternalValue(),
1750 child_node->date_added().ToInternalValue());
1751 } else {
1752 EXPECT_TRUE(child_node->is_folder());
1753 EXPECT_FALSE(child_node->is_url());
1755 (*running_count)++;
1759 // TODO(munjal): We should implement some way of generating random data and can
1760 // use the same seed to generate the same sequence.
1761 void ProfileSyncServiceBookmarkTestWithData::WriteTestDataToBookmarkModel() {
1762 const BookmarkNode* bookmarks_bar_node = model_->bookmark_bar_node();
1763 int count = 0;
1764 PopulateFromTestData(bookmarks_bar_node,
1765 kBookmarkBarChildren,
1766 arraysize(kBookmarkBarChildren),
1767 &count);
1769 ASSERT_GE(bookmarks_bar_node->child_count(), 4);
1770 const BookmarkNode* f1_node = bookmarks_bar_node->GetChild(1);
1771 PopulateFromTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1772 const BookmarkNode* f2_node = bookmarks_bar_node->GetChild(3);
1773 PopulateFromTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1775 const BookmarkNode* other_bookmarks_node = model_->other_node();
1776 PopulateFromTestData(other_bookmarks_node,
1777 kOtherBookmarkChildren,
1778 arraysize(kOtherBookmarkChildren),
1779 &count);
1781 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1782 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1783 PopulateFromTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1784 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1785 PopulateFromTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1786 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1787 PopulateFromTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1788 &count);
1789 dup_node = other_bookmarks_node->GetChild(5);
1790 PopulateFromTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1791 &count);
1793 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1794 PopulateFromTestData(mobile_bookmarks_node,
1795 kMobileBookmarkChildren,
1796 arraysize(kMobileBookmarkChildren),
1797 &count);
1799 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1800 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1801 PopulateFromTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1802 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1803 PopulateFromTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1805 ExpectBookmarkModelMatchesTestData();
1808 void ProfileSyncServiceBookmarkTestWithData::
1809 ExpectBookmarkModelMatchesTestData() {
1810 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1811 int count = 0;
1812 CompareWithTestData(bookmark_bar_node,
1813 kBookmarkBarChildren,
1814 arraysize(kBookmarkBarChildren),
1815 &count);
1817 ASSERT_GE(bookmark_bar_node->child_count(), 4);
1818 const BookmarkNode* f1_node = bookmark_bar_node->GetChild(1);
1819 CompareWithTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1820 const BookmarkNode* f2_node = bookmark_bar_node->GetChild(3);
1821 CompareWithTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1823 const BookmarkNode* other_bookmarks_node = model_->other_node();
1824 CompareWithTestData(other_bookmarks_node,
1825 kOtherBookmarkChildren,
1826 arraysize(kOtherBookmarkChildren),
1827 &count);
1829 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1830 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1831 CompareWithTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1832 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1833 CompareWithTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1834 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1835 CompareWithTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1836 &count);
1837 dup_node = other_bookmarks_node->GetChild(5);
1838 CompareWithTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1839 &count);
1841 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1842 CompareWithTestData(mobile_bookmarks_node,
1843 kMobileBookmarkChildren,
1844 arraysize(kMobileBookmarkChildren),
1845 &count);
1847 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1848 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1849 CompareWithTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1850 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1851 CompareWithTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1854 // Tests persistence of the profile sync service by unloading the
1855 // database and then reloading it from disk.
1856 TEST_F(ProfileSyncServiceBookmarkTestWithData, Persistence) {
1857 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1858 StartSync();
1860 WriteTestDataToBookmarkModel();
1862 ExpectModelMatch();
1864 // Force both models to discard their data and reload from disk. This
1865 // simulates what would happen if the browser were to shutdown normally,
1866 // and then relaunch.
1867 StopSync();
1868 UnloadBookmarkModel();
1869 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1870 StartSync();
1872 ExpectBookmarkModelMatchesTestData();
1874 // With the BookmarkModel contents verified, ExpectModelMatch will
1875 // verify the contents of the sync model.
1876 ExpectModelMatch();
1879 // Tests the merge case when the BookmarkModel is non-empty but the
1880 // sync model is empty. This corresponds to uploading browser
1881 // bookmarks to an initially empty, new account.
1882 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptySyncModel) {
1883 // Don't start the sync service until we've populated the bookmark model.
1884 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1886 WriteTestDataToBookmarkModel();
1888 // Restart sync. This should trigger a merge step during
1889 // initialization -- we expect the browser bookmarks to be written
1890 // to the sync service during this call.
1891 StartSync();
1893 // Verify that the bookmark model hasn't changed, and that the sync model
1894 // matches it exactly.
1895 ExpectBookmarkModelMatchesTestData();
1896 ExpectModelMatch();
1899 // Tests the merge case when the BookmarkModel is empty but the sync model is
1900 // non-empty. This corresponds (somewhat) to a clean install of the browser,
1901 // with no bookmarks, connecting to a sync account that has some bookmarks.
1902 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptyBookmarkModel) {
1903 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1904 StartSync();
1906 WriteTestDataToBookmarkModel();
1908 ExpectModelMatch();
1910 // Force the databse to unload and write itself to disk.
1911 StopSync();
1913 // Blow away the bookmark model -- it should be empty afterwards.
1914 UnloadBookmarkModel();
1915 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1916 EXPECT_EQ(model_->bookmark_bar_node()->child_count(), 0);
1917 EXPECT_EQ(model_->other_node()->child_count(), 0);
1918 EXPECT_EQ(model_->mobile_node()->child_count(), 0);
1920 // Now restart the sync service. Starting it should populate the bookmark
1921 // model -- test for consistency.
1922 StartSync();
1923 ExpectBookmarkModelMatchesTestData();
1924 ExpectModelMatch();
1927 // Tests the merge cases when both the models are expected to be identical
1928 // after the merge.
1929 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeExpectedIdenticalModels) {
1930 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1931 StartSync();
1932 WriteTestDataToBookmarkModel();
1933 ExpectModelMatch();
1934 StopSync();
1935 UnloadBookmarkModel();
1937 // At this point both the bookmark model and the server should have the
1938 // exact same data and it should match the test data.
1939 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1940 StartSync();
1941 ExpectBookmarkModelMatchesTestData();
1942 ExpectModelMatch();
1943 StopSync();
1944 UnloadBookmarkModel();
1946 // Now reorder some bookmarks in the bookmark model and then merge. Make
1947 // sure we get the order of the server after merge.
1948 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1949 ExpectBookmarkModelMatchesTestData();
1950 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
1951 ASSERT_TRUE(bookmark_bar);
1952 ASSERT_GT(bookmark_bar->child_count(), 1);
1953 model_->Move(bookmark_bar->GetChild(0), bookmark_bar, 1);
1954 StartSync();
1955 ExpectModelMatch();
1956 ExpectBookmarkModelMatchesTestData();
1959 // Tests the merge cases when both the models are expected to be identical
1960 // after the merge.
1961 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeModelsWithSomeExtras) {
1962 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1963 WriteTestDataToBookmarkModel();
1964 ExpectBookmarkModelMatchesTestData();
1966 // Remove some nodes and reorder some nodes.
1967 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1968 int remove_index = 2;
1969 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1970 const BookmarkNode* child_node = bookmark_bar_node->GetChild(remove_index);
1971 ASSERT_TRUE(child_node);
1972 ASSERT_TRUE(child_node->is_url());
1973 model_->Remove(bookmark_bar_node->GetChild(remove_index));
1974 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1975 child_node = bookmark_bar_node->GetChild(remove_index);
1976 ASSERT_TRUE(child_node);
1977 ASSERT_TRUE(child_node->is_folder());
1978 model_->Remove(bookmark_bar_node->GetChild(remove_index));
1980 const BookmarkNode* other_node = model_->other_node();
1981 ASSERT_GE(other_node->child_count(), 1);
1982 const BookmarkNode* f3_node = other_node->GetChild(0);
1983 ASSERT_TRUE(f3_node);
1984 ASSERT_TRUE(f3_node->is_folder());
1985 remove_index = 2;
1986 ASSERT_GT(f3_node->child_count(), remove_index);
1987 model_->Remove(f3_node->GetChild(remove_index));
1988 ASSERT_GT(f3_node->child_count(), remove_index);
1989 model_->Remove(f3_node->GetChild(remove_index));
1991 StartSync();
1992 ExpectModelMatch();
1993 StopSync();
1995 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1996 WriteTestDataToBookmarkModel();
1997 ExpectBookmarkModelMatchesTestData();
1999 // Remove some nodes and reorder some nodes.
2000 bookmark_bar_node = model_->bookmark_bar_node();
2001 remove_index = 0;
2002 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2003 child_node = bookmark_bar_node->GetChild(remove_index);
2004 ASSERT_TRUE(child_node);
2005 ASSERT_TRUE(child_node->is_url());
2006 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2007 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2008 child_node = bookmark_bar_node->GetChild(remove_index);
2009 ASSERT_TRUE(child_node);
2010 ASSERT_TRUE(child_node->is_folder());
2011 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2013 ASSERT_GE(bookmark_bar_node->child_count(), 2);
2014 model_->Move(bookmark_bar_node->GetChild(0), bookmark_bar_node, 1);
2016 other_node = model_->other_node();
2017 ASSERT_GE(other_node->child_count(), 1);
2018 f3_node = other_node->GetChild(0);
2019 ASSERT_TRUE(f3_node);
2020 ASSERT_TRUE(f3_node->is_folder());
2021 remove_index = 0;
2022 ASSERT_GT(f3_node->child_count(), remove_index);
2023 model_->Remove(f3_node->GetChild(remove_index));
2024 ASSERT_GT(f3_node->child_count(), remove_index);
2025 model_->Remove(f3_node->GetChild(remove_index));
2027 ASSERT_GE(other_node->child_count(), 4);
2028 model_->Move(other_node->GetChild(0), other_node, 1);
2029 model_->Move(other_node->GetChild(2), other_node, 3);
2031 StartSync();
2032 ExpectModelMatch();
2034 // After the merge, the model should match the test data.
2035 ExpectBookmarkModelMatchesTestData();
2038 // Tests that when persisted model associations are used, things work fine.
2039 TEST_F(ProfileSyncServiceBookmarkTestWithData, ModelAssociationPersistence) {
2040 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2041 WriteTestDataToBookmarkModel();
2042 StartSync();
2043 ExpectModelMatch();
2044 // Force sync to shut down and write itself to disk.
2045 StopSync();
2046 // Now restart sync. This time it should use the persistent
2047 // associations.
2048 StartSync();
2049 ExpectModelMatch();
2052 // Tests that when persisted model associations are used, things work fine.
2053 TEST_F(ProfileSyncServiceBookmarkTestWithData,
2054 ModelAssociationInvalidPersistence) {
2055 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2056 WriteTestDataToBookmarkModel();
2057 StartSync();
2058 ExpectModelMatch();
2059 // Force sync to shut down and write itself to disk.
2060 StopSync();
2061 // Change the bookmark model before restarting sync service to simulate
2062 // the situation where bookmark model is different from sync model and
2063 // make sure model associator correctly rebuilds associations.
2064 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2065 model_->AddURL(bookmark_bar_node, 0, base::ASCIIToUTF16("xtra"),
2066 GURL("http://www.xtra.com"));
2067 // Now restart sync. This time it will try to use the persistent
2068 // associations and realize that they are invalid and hence will rebuild
2069 // associations.
2070 StartSync();
2071 ExpectModelMatch();
2074 TEST_F(ProfileSyncServiceBookmarkTestWithData, SortChildren) {
2075 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2076 StartSync();
2078 // Write test data to bookmark model and verify that the models match.
2079 WriteTestDataToBookmarkModel();
2080 const BookmarkNode* folder_added = model_->other_node()->GetChild(0);
2081 ASSERT_TRUE(folder_added);
2082 ASSERT_TRUE(folder_added->is_folder());
2084 ExpectModelMatch();
2086 // Sort the other-bookmarks children and expect that the models match.
2087 model_->SortChildren(folder_added);
2088 ExpectModelMatch();
2091 // See what happens if we enable sync but then delete the "Sync Data"
2092 // folder.
2093 TEST_F(ProfileSyncServiceBookmarkTestWithData,
2094 RecoverAfterDeletingSyncDataDirectory) {
2095 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
2096 StartSync();
2098 WriteTestDataToBookmarkModel();
2100 StopSync();
2102 // Nuke the sync DB and reload.
2103 TearDown();
2104 SetUp();
2106 // First attempt fails due to a persistence error.
2107 EXPECT_TRUE(CreatePermanentBookmarkNodes());
2108 EXPECT_FALSE(AssociateModels());
2110 // Second attempt succeeds due to the previous error resetting the native
2111 // transaction version.
2112 model_associator_.reset();
2113 EXPECT_TRUE(CreatePermanentBookmarkNodes());
2114 EXPECT_TRUE(AssociateModels());
2116 // Make sure we're back in sync. In real life, the user would need
2117 // to reauthenticate before this happens, but in the test, authentication
2118 // is sidestepped.
2119 ExpectBookmarkModelMatchesTestData();
2120 ExpectModelMatch();
2123 // Verify that the bookmark model is updated about whether the
2124 // associator is currently running.
2125 TEST_F(ProfileSyncServiceBookmarkTest, AssociationState) {
2126 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2128 ExtensiveChangesBookmarkModelObserver observer;
2129 model_->AddObserver(&observer);
2131 StartSync();
2133 EXPECT_EQ(1, observer.get_started());
2134 EXPECT_EQ(0, observer.get_completed_count_at_started());
2135 EXPECT_EQ(1, observer.get_completed());
2137 model_->RemoveObserver(&observer);
2140 // Verify that the creation_time_us changes are applied in the local model at
2141 // association time and update time.
2142 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateDateAdded) {
2143 // TODO(stanisc): crbug.com/456876: Remove this once the optimistic
2144 // association experiment has ended.
2145 base::FieldTrialList field_trial_list(new base::MockEntropyProvider());
2146 base::FieldTrialList::CreateFieldTrial("SyncOptimisticBookmarkAssociation",
2147 "Enabled");
2149 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2150 WriteTestDataToBookmarkModel();
2152 // Start and stop sync in order to create bookmark nodes in the sync db.
2153 StartSync();
2154 StopSync();
2156 // Modify the date_added field of a bookmark so it doesn't match with
2157 // the sync data.
2158 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2159 int modified_index = 2;
2160 ASSERT_GT(bookmark_bar_node->child_count(), modified_index);
2161 const BookmarkNode* child_node = bookmark_bar_node->GetChild(modified_index);
2162 ASSERT_TRUE(child_node);
2163 EXPECT_TRUE(child_node->is_url());
2164 model_->SetDateAdded(child_node, base::Time::FromInternalValue(10));
2166 StartSync();
2167 StopSync();
2169 // Verify that transaction versions are in sync between the native model
2170 // and Sync.
2172 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2173 int64 sync_version = trans.GetModelVersion(syncer::BOOKMARKS);
2174 int64 native_version = model_->root_node()->sync_transaction_version();
2175 EXPECT_EQ(native_version, sync_version);
2178 // Since the version is in sync the association above should have skipped
2179 // updating the native node above. That is expected optimization (see
2180 // crbug/464907.
2181 EXPECT_EQ(child_node->date_added(), base::Time::FromInternalValue(10));
2183 // Reset transaction version on the native model to trigger conservative
2184 // association algorithm.
2185 model_->SetNodeSyncTransactionVersion(
2186 model_->root_node(), syncer::syncable::kInvalidTransactionVersion);
2188 StartSync();
2190 // Everything should be back in sync after model association.
2191 ExpectBookmarkModelMatchesTestData();
2192 ExpectModelMatch();
2194 // Now trigger a change while syncing. We add a new bookmark, sync it, then
2195 // updates it's creation time.
2196 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2197 FakeServerChange adds(&trans);
2198 const std::string kTitle = "Some site";
2199 const std::string kUrl = "http://www.whatwhat.yeah/";
2200 const int kCreationTime = 30;
2201 int64 id = adds.AddURL(kTitle, kUrl,
2202 bookmark_bar_id(), 0);
2203 adds.ApplyPendingChanges(change_processor_.get());
2204 FakeServerChange updates(&trans);
2205 updates.ModifyCreationTime(id, kCreationTime);
2206 updates.ApplyPendingChanges(change_processor_.get());
2208 const BookmarkNode* node = model_->bookmark_bar_node()->GetChild(0);
2209 ASSERT_TRUE(node);
2210 EXPECT_TRUE(node->is_url());
2211 EXPECT_EQ(base::UTF8ToUTF16(kTitle), node->GetTitle());
2212 EXPECT_EQ(kUrl, node->url().possibly_invalid_spec());
2213 EXPECT_EQ(node->date_added(), base::Time::FromInternalValue(30));
2216 // Tests that changes to the sync nodes meta info gets reflected in the local
2217 // bookmark model.
2218 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromSync) {
2219 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2220 WriteTestDataToBookmarkModel();
2221 StartSync();
2223 // Create bookmark nodes containing meta info.
2224 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2225 FakeServerChange adds(&trans);
2226 BookmarkNode::MetaInfoMap folder_meta_info;
2227 folder_meta_info["folder"] = "foldervalue";
2228 int64 folder_id = adds.AddFolderWithMetaInfo(
2229 "folder title", &folder_meta_info, bookmark_bar_id(), 0);
2230 BookmarkNode::MetaInfoMap node_meta_info;
2231 node_meta_info["node"] = "nodevalue";
2232 node_meta_info["other"] = "othervalue";
2233 int64 id = adds.AddURLWithMetaInfo("node title", "http://www.foo.com",
2234 &node_meta_info, folder_id, 0);
2235 adds.ApplyPendingChanges(change_processor_.get());
2237 // Verify that the nodes are created with the correct meta info.
2238 ASSERT_LT(0, model_->bookmark_bar_node()->child_count());
2239 const BookmarkNode* folder_node = model_->bookmark_bar_node()->GetChild(0);
2240 ASSERT_TRUE(folder_node->GetMetaInfoMap());
2241 EXPECT_EQ(folder_meta_info, *folder_node->GetMetaInfoMap());
2242 ASSERT_LT(0, folder_node->child_count());
2243 const BookmarkNode* node = folder_node->GetChild(0);
2244 ASSERT_TRUE(node->GetMetaInfoMap());
2245 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
2247 // Update meta info on nodes on server
2248 FakeServerChange updates(&trans);
2249 folder_meta_info.erase("folder");
2250 updates.ModifyMetaInfo(folder_id, folder_meta_info);
2251 node_meta_info["node"] = "changednodevalue";
2252 node_meta_info.erase("other");
2253 node_meta_info["newkey"] = "newkeyvalue";
2254 updates.ModifyMetaInfo(id, node_meta_info);
2255 updates.ApplyPendingChanges(change_processor_.get());
2257 // Confirm that the updated values are reflected in the bookmark nodes.
2258 EXPECT_FALSE(folder_node->GetMetaInfoMap());
2259 ASSERT_TRUE(node->GetMetaInfoMap());
2260 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
2263 // Tests that changes to the local bookmark nodes meta info gets reflected in
2264 // the sync nodes.
2265 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromModel) {
2266 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2267 WriteTestDataToBookmarkModel();
2268 StartSync();
2269 ExpectBookmarkModelMatchesTestData();
2271 const BookmarkNode* folder_node =
2272 model_->AddFolder(model_->bookmark_bar_node(), 0,
2273 base::ASCIIToUTF16("folder title"));
2274 const BookmarkNode* node = model_->AddURL(folder_node, 0,
2275 base::ASCIIToUTF16("node title"),
2276 GURL("http://www.foo.com"));
2277 ExpectModelMatch();
2279 // Add some meta info and verify sync model matches the changes.
2280 model_->SetNodeMetaInfo(folder_node, "folder", "foldervalue");
2281 model_->SetNodeMetaInfo(node, "node", "nodevalue");
2282 model_->SetNodeMetaInfo(node, "other", "othervalue");
2283 ExpectModelMatch();
2285 // Change/delete existing meta info and verify.
2286 model_->DeleteNodeMetaInfo(folder_node, "folder");
2287 model_->SetNodeMetaInfo(node, "node", "changednodevalue");
2288 model_->DeleteNodeMetaInfo(node, "other");
2289 model_->SetNodeMetaInfo(node, "newkey", "newkeyvalue");
2290 ExpectModelMatch();
2293 // Tests that node's specifics doesn't get unnecessarily overwritten (causing
2294 // a subsequent commit) when BookmarkChangeProcessor handles a notification
2295 // (such as BookmarkMetaInfoChanged) without an actual data change.
2296 TEST_F(ProfileSyncServiceBookmarkTestWithData, MetaInfoPreservedOnNonChange) {
2297 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2298 WriteTestDataToBookmarkModel();
2299 StartSync();
2301 std::string orig_specifics;
2302 int64 sync_id;
2303 const BookmarkNode* bookmark;
2305 // Create bookmark folder node containing meta info.
2307 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2308 FakeServerChange adds(&trans);
2310 int64 folder_id = adds.AddFolder("folder title", bookmark_bar_id(), 0);
2312 BookmarkNode::MetaInfoMap node_meta_info;
2313 node_meta_info["one"] = "1";
2314 node_meta_info["two"] = "2";
2315 node_meta_info["three"] = "3";
2317 sync_id = adds.AddURLWithMetaInfo("node title", "http://www.foo.com/",
2318 &node_meta_info, folder_id, 0);
2320 // Verify that the node propagates to the bookmark model
2321 adds.ApplyPendingChanges(change_processor_.get());
2323 bookmark = model_->bookmark_bar_node()->GetChild(0)->GetChild(0);
2324 EXPECT_EQ(node_meta_info, *bookmark->GetMetaInfoMap());
2326 syncer::ReadNode sync_node(&trans);
2327 EXPECT_EQ(BaseNode::INIT_OK, sync_node.InitByIdLookup(sync_id));
2328 orig_specifics = sync_node.GetBookmarkSpecifics().SerializeAsString();
2331 // Force change processor to update the sync node.
2332 change_processor_->BookmarkMetaInfoChanged(model_, bookmark);
2334 // Read bookmark specifics again and verify that there is no change.
2336 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2337 syncer::ReadNode sync_node(&trans);
2338 EXPECT_EQ(BaseNode::INIT_OK, sync_node.InitByIdLookup(sync_id));
2339 std::string new_specifics =
2340 sync_node.GetBookmarkSpecifics().SerializeAsString();
2341 ASSERT_EQ(orig_specifics, new_specifics);
2345 void ProfileSyncServiceBookmarkTestWithData::GetTransactionVersions(
2346 const BookmarkNode* root,
2347 BookmarkNodeVersionMap* node_versions) {
2348 node_versions->clear();
2349 std::queue<const BookmarkNode*> nodes;
2350 nodes.push(root);
2351 while (!nodes.empty()) {
2352 const BookmarkNode* n = nodes.front();
2353 nodes.pop();
2355 int64 version = n->sync_transaction_version();
2356 EXPECT_NE(BookmarkNode::kInvalidSyncTransactionVersion, version);
2358 (*node_versions)[n->id()] = version;
2359 for (int i = 0; i < n->child_count(); ++i) {
2360 if (!CanSyncNode(n->GetChild(i)))
2361 continue;
2362 nodes.push(n->GetChild(i));
2367 void ProfileSyncServiceBookmarkTestWithData::ExpectTransactionVersionMatch(
2368 const BookmarkNode* node,
2369 const BookmarkNodeVersionMap& version_expected) {
2370 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2372 BookmarkNodeVersionMap bnodes_versions;
2373 GetTransactionVersions(node, &bnodes_versions);
2374 for (BookmarkNodeVersionMap::const_iterator it = bnodes_versions.begin();
2375 it != bnodes_versions.end(); ++it) {
2376 syncer::ReadNode sync_node(&trans);
2377 ASSERT_TRUE(model_associator_->InitSyncNodeFromChromeId(it->first,
2378 &sync_node));
2379 EXPECT_EQ(sync_node.GetEntry()->GetTransactionVersion(), it->second);
2380 BookmarkNodeVersionMap::const_iterator expected_ver_it =
2381 version_expected.find(it->first);
2382 if (expected_ver_it != version_expected.end())
2383 EXPECT_EQ(expected_ver_it->second, it->second);
2387 // Test transaction versions of model and nodes are incremented after changes
2388 // are applied.
2389 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateTransactionVersion) {
2390 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2391 StartSync();
2392 WriteTestDataToBookmarkModel();
2393 base::MessageLoop::current()->RunUntilIdle();
2395 BookmarkNodeVersionMap initial_versions;
2397 // Verify transaction versions in sync model and bookmark model (saved as
2398 // transaction version of root node) are equal after
2399 // WriteTestDataToBookmarkModel() created bookmarks.
2401 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2402 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2403 GetTransactionVersions(model_->root_node(), &initial_versions);
2404 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2405 initial_versions[model_->root_node()->id()]);
2407 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2408 BookmarkNodeVersionMap());
2409 ExpectTransactionVersionMatch(model_->other_node(),
2410 BookmarkNodeVersionMap());
2411 ExpectTransactionVersionMatch(model_->mobile_node(),
2412 BookmarkNodeVersionMap());
2414 // Verify model version is incremented and bookmark node versions remain
2415 // the same.
2416 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
2417 model_->Remove(bookmark_bar->GetChild(0));
2418 base::MessageLoop::current()->RunUntilIdle();
2419 BookmarkNodeVersionMap new_versions;
2420 GetTransactionVersions(model_->root_node(), &new_versions);
2421 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 1,
2422 new_versions[model_->root_node()->id()]);
2423 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2424 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2425 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2427 // Verify model version and version of changed bookmark are incremented and
2428 // versions of others remain same.
2429 const BookmarkNode* changed_bookmark =
2430 model_->bookmark_bar_node()->GetChild(0);
2431 model_->SetTitle(changed_bookmark, base::ASCIIToUTF16("test"));
2432 base::MessageLoop::current()->RunUntilIdle();
2433 GetTransactionVersions(model_->root_node(), &new_versions);
2434 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 2,
2435 new_versions[model_->root_node()->id()]);
2436 EXPECT_LT(initial_versions[changed_bookmark->id()],
2437 new_versions[changed_bookmark->id()]);
2438 initial_versions.erase(changed_bookmark->id());
2439 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2440 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2441 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2444 // Test that sync persistence errors are detected and trigger a failed
2445 // association.
2446 TEST_F(ProfileSyncServiceBookmarkTestWithData, PersistenceError) {
2447 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2448 StartSync();
2449 WriteTestDataToBookmarkModel();
2450 base::MessageLoop::current()->RunUntilIdle();
2452 BookmarkNodeVersionMap initial_versions;
2454 // Verify transaction versions in sync model and bookmark model (saved as
2455 // transaction version of root node) are equal after
2456 // WriteTestDataToBookmarkModel() created bookmarks.
2458 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2459 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2460 GetTransactionVersions(model_->root_node(), &initial_versions);
2461 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2462 initial_versions[model_->root_node()->id()]);
2464 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2465 BookmarkNodeVersionMap());
2466 ExpectTransactionVersionMatch(model_->other_node(),
2467 BookmarkNodeVersionMap());
2468 ExpectTransactionVersionMatch(model_->mobile_node(),
2469 BookmarkNodeVersionMap());
2471 // Now shut down sync and artificially increment the native model's version.
2472 StopSync();
2473 int64 root_version = initial_versions[model_->root_node()->id()];
2474 model_->SetNodeSyncTransactionVersion(model_->root_node(), root_version + 1);
2476 // Upon association, bookmarks should fail to associate.
2477 EXPECT_FALSE(AssociateModels());
2480 // It's possible for update/add calls from the bookmark model to be out of
2481 // order, or asynchronous. Handle that without triggering an error.
2482 TEST_F(ProfileSyncServiceBookmarkTest, UpdateThenAdd) {
2483 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2484 StartSync();
2486 EXPECT_TRUE(other_bookmarks_id());
2487 EXPECT_TRUE(bookmark_bar_id());
2488 EXPECT_TRUE(mobile_bookmarks_id());
2490 ExpectModelMatch();
2492 // Now destroy the change processor then add a bookmark, to simulate
2493 // missing the Update call.
2494 change_processor_.reset();
2495 const BookmarkNode* node = model_->AddURL(model_->bookmark_bar_node(),
2497 base::ASCIIToUTF16("title"),
2498 GURL("http://www.url.com"));
2500 // Recreate the change processor then update that bookmark. Sync should
2501 // receive the update call and gracefully treat that as if it were an add.
2502 change_processor_.reset(new BookmarkChangeProcessor(
2503 &profile_, model_associator_.get(), &mock_error_handler_));
2504 change_processor_->Start(test_user_share_.user_share());
2505 model_->SetTitle(node, base::ASCIIToUTF16("title2"));
2506 ExpectModelMatch();
2508 // Then simulate the add call arriving late.
2509 change_processor_->BookmarkNodeAdded(model_, model_->bookmark_bar_node(), 0);
2510 ExpectModelMatch();
2513 } // namespace
2515 } // namespace browser_sync