Add new certificateProvider extension API.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service_bookmark_unittest.cc
blob390891723dc641d3439282e09717c8aec2e12a29
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/bookmarks/managed_bookmark_service_factory.h"
30 #include "chrome/browser/sync/glue/bookmark_change_processor.h"
31 #include "chrome/browser/sync/glue/bookmark_model_associator.h"
32 #include "chrome/common/chrome_switches.h"
33 #include "chrome/test/base/testing_profile.h"
34 #include "components/bookmarks/browser/base_bookmark_model_observer.h"
35 #include "components/bookmarks/browser/bookmark_model.h"
36 #include "components/bookmarks/managed/managed_bookmark_service.h"
37 #include "components/bookmarks/test/bookmark_test_helpers.h"
38 #include "components/sync_driver/data_type_error_handler.h"
39 #include "components/sync_driver/data_type_error_handler_mock.h"
40 #include "content/public/test/test_browser_thread_bundle.h"
41 #include "sync/api/sync_error.h"
42 #include "sync/api/sync_merge_result.h"
43 #include "sync/internal_api/public/change_record.h"
44 #include "sync/internal_api/public/read_node.h"
45 #include "sync/internal_api/public/read_transaction.h"
46 #include "sync/internal_api/public/test/test_user_share.h"
47 #include "sync/internal_api/public/write_node.h"
48 #include "sync/internal_api/public/write_transaction.h"
49 #include "sync/internal_api/syncapi_internal.h"
50 #include "sync/syncable/mutable_entry.h"
51 #include "sync/syncable/syncable_id.h"
52 #include "sync/syncable/syncable_util.h"
53 #include "sync/syncable/syncable_write_transaction.h"
54 #include "testing/gmock/include/gmock/gmock.h"
55 #include "testing/gtest/include/gtest/gtest.h"
57 namespace browser_sync {
59 using bookmarks::BookmarkModel;
60 using bookmarks::BookmarkNode;
61 using syncer::BaseNode;
62 using testing::_;
63 using testing::InvokeWithoutArgs;
64 using testing::Mock;
65 using testing::Return;
66 using testing::StrictMock;
68 #if defined(OS_ANDROID) || defined(OS_IOS)
69 static const bool kExpectMobileBookmarks = true;
70 #else
71 static const bool kExpectMobileBookmarks = false;
72 #endif // defined(OS_ANDROID) || defined(OS_IOS)
74 namespace {
76 void MakeServerUpdate(syncer::WriteTransaction* trans,
77 syncer::WriteNode* node) {
78 syncer::syncable::ChangeEntryIDAndUpdateChildren(
79 trans->GetWrappedWriteTrans(), node->GetMutableEntryForTest(),
80 syncer::syncable::Id::CreateFromServerId(
81 base::Int64ToString(node->GetId())));
82 node->GetMutableEntryForTest()->PutBaseVersion(10);
83 node->GetMutableEntryForTest()->PutIsUnappliedUpdate(true);
86 void MakeServerUpdate(syncer::WriteTransaction* trans, int64 id) {
87 syncer::WriteNode node(trans);
88 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
89 MakeServerUpdate(trans, &node);
92 // FakeServerChange constructs a list of syncer::ChangeRecords while modifying
93 // the sync model, and can pass the ChangeRecord list to a
94 // syncer::SyncObserver (i.e., the ProfileSyncService) to test the client
95 // change-application behavior.
96 // Tests using FakeServerChange should be careful to avoid back-references,
97 // since FakeServerChange will send the edits in the order specified.
98 class FakeServerChange {
99 public:
100 explicit FakeServerChange(syncer::WriteTransaction* trans) : trans_(trans) {
103 // Pretend that the server told the syncer to add a bookmark object.
104 int64 AddWithMetaInfo(const std::string& title,
105 const std::string& url,
106 const BookmarkNode::MetaInfoMap* meta_info_map,
107 bool is_folder,
108 int64 parent_id,
109 int64 predecessor_id) {
110 syncer::ReadNode parent(trans_);
111 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
112 syncer::WriteNode node(trans_);
113 if (predecessor_id == 0) {
114 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
115 } else {
116 syncer::ReadNode predecessor(trans_);
117 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
118 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
119 EXPECT_TRUE(node.InitBookmarkByCreation(parent, &predecessor));
121 EXPECT_EQ(node.GetPredecessorId(), predecessor_id);
122 EXPECT_EQ(node.GetParentId(), parent_id);
123 node.SetIsFolder(is_folder);
124 node.SetTitle(title);
126 sync_pb::BookmarkSpecifics specifics(node.GetBookmarkSpecifics());
127 const base::Time creation_time(base::Time::Now());
128 specifics.set_creation_time_us(creation_time.ToInternalValue());
129 if (!is_folder)
130 specifics.set_url(url);
131 if (meta_info_map)
132 SetNodeMetaInfo(*meta_info_map, &specifics);
133 node.SetBookmarkSpecifics(specifics);
135 syncer::ChangeRecord record;
136 record.action = syncer::ChangeRecord::ACTION_ADD;
137 record.id = node.GetId();
138 changes_.push_back(record);
139 return node.GetId();
142 int64 Add(const std::string& title,
143 const std::string& url,
144 bool is_folder,
145 int64 parent_id,
146 int64 predecessor_id) {
147 return AddWithMetaInfo(title, url, NULL, is_folder, parent_id,
148 predecessor_id);
151 // Add a bookmark folder.
152 int64 AddFolder(const std::string& title,
153 int64 parent_id,
154 int64 predecessor_id) {
155 return Add(title, std::string(), true, parent_id, predecessor_id);
157 int64 AddFolderWithMetaInfo(const std::string& title,
158 const BookmarkNode::MetaInfoMap* meta_info_map,
159 int64 parent_id,
160 int64 predecessor_id) {
161 return AddWithMetaInfo(title, std::string(), meta_info_map, true, parent_id,
162 predecessor_id);
165 // Add a bookmark.
166 int64 AddURL(const std::string& title,
167 const std::string& url,
168 int64 parent_id,
169 int64 predecessor_id) {
170 return Add(title, url, false, parent_id, predecessor_id);
172 int64 AddURLWithMetaInfo(const std::string& title,
173 const std::string& url,
174 const BookmarkNode::MetaInfoMap* meta_info_map,
175 int64 parent_id,
176 int64 predecessor_id) {
177 return AddWithMetaInfo(title, url, meta_info_map, false, parent_id,
178 predecessor_id);
181 // Pretend that the server told the syncer to delete an object.
182 void Delete(int64 id) {
184 // Delete the sync node.
185 syncer::WriteNode node(trans_);
186 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
187 if (node.GetIsFolder())
188 EXPECT_FALSE(node.GetFirstChildId());
189 node.GetMutableEntryForTest()->PutServerIsDel(true);
190 node.Tombstone();
193 // Verify the deletion.
194 syncer::ReadNode node(trans_);
195 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL, node.InitByIdLookup(id));
198 syncer::ChangeRecord record;
199 record.action = syncer::ChangeRecord::ACTION_DELETE;
200 record.id = id;
201 // Deletions are always first in the changelist, but we can't actually do
202 // WriteNode::Remove() on the node until its children are moved. So, as
203 // a practical matter, users of FakeServerChange must move or delete
204 // children before parents. Thus, we must insert the deletion record
205 // at the front of the vector.
206 changes_.insert(changes_.begin(), record);
209 // Set a new title value, and return the old value.
210 std::string ModifyTitle(int64 id, const std::string& new_title) {
211 syncer::WriteNode node(trans_);
212 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
213 std::string old_title = node.GetTitle();
214 node.SetTitle(new_title);
215 SetModified(id);
216 return old_title;
219 // Set a new parent and predecessor value. Return the old parent id.
220 // We could return the old predecessor id, but it turns out not to be
221 // very useful for assertions.
222 int64 ModifyPosition(int64 id, int64 parent_id, int64 predecessor_id) {
223 syncer::ReadNode parent(trans_);
224 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
225 syncer::WriteNode node(trans_);
226 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
227 int64 old_parent_id = node.GetParentId();
228 if (predecessor_id == 0) {
229 EXPECT_TRUE(node.SetPosition(parent, NULL));
230 } else {
231 syncer::ReadNode predecessor(trans_);
232 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
233 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
234 EXPECT_TRUE(node.SetPosition(parent, &predecessor));
236 SetModified(id);
237 return old_parent_id;
240 void ModifyCreationTime(int64 id, int64 creation_time_us) {
241 syncer::WriteNode node(trans_);
242 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
243 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
244 specifics.set_creation_time_us(creation_time_us);
245 node.SetBookmarkSpecifics(specifics);
246 SetModified(id);
249 void ModifyMetaInfo(int64 id,
250 const BookmarkNode::MetaInfoMap& meta_info_map) {
251 syncer::WriteNode node(trans_);
252 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
253 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
254 SetNodeMetaInfo(meta_info_map, &specifics);
255 node.SetBookmarkSpecifics(specifics);
256 SetModified(id);
259 // Pass the fake change list to |service|.
260 void ApplyPendingChanges(sync_driver::ChangeProcessor* processor) {
261 processor->ApplyChangesFromSyncModel(
262 trans_, 0, syncer::ImmutableChangeRecordList(&changes_));
265 const syncer::ChangeRecordList& changes() {
266 return changes_;
269 private:
270 // Helper function to push an ACTION_UPDATE record onto the back
271 // of the changelist.
272 void SetModified(int64 id) {
273 // Coalesce multi-property edits.
274 if (!changes_.empty() && changes_.back().id == id &&
275 changes_.back().action ==
276 syncer::ChangeRecord::ACTION_UPDATE)
277 return;
278 syncer::ChangeRecord record;
279 record.action = syncer::ChangeRecord::ACTION_UPDATE;
280 record.id = id;
281 changes_.push_back(record);
284 void SetNodeMetaInfo(const BookmarkNode::MetaInfoMap& meta_info_map,
285 sync_pb::BookmarkSpecifics* specifics) {
286 specifics->clear_meta_info();
287 // Deliberatly set MetaInfoMap entries in opposite order (compared
288 // to the implementation in BookmarkChangeProcessor) to ensure that
289 // (a) the implementation isn't sensitive to the order and
290 // (b) the original meta info isn't blindly overwritten by
291 // BookmarkChangeProcessor unless there is a real change.
292 BookmarkNode::MetaInfoMap::const_iterator it = meta_info_map.end();
293 while (it != meta_info_map.begin()) {
294 --it;
295 sync_pb::MetaInfo* meta_info = specifics->add_meta_info();
296 meta_info->set_key(it->first);
297 meta_info->set_value(it->second);
301 // The transaction on which everything happens.
302 syncer::WriteTransaction *trans_;
304 // The change list we construct.
305 syncer::ChangeRecordList changes_;
308 class ExtensiveChangesBookmarkModelObserver
309 : public bookmarks::BaseBookmarkModelObserver {
310 public:
311 ExtensiveChangesBookmarkModelObserver()
312 : started_count_(0),
313 completed_count_at_started_(0),
314 completed_count_(0) {}
316 void ExtensiveBookmarkChangesBeginning(BookmarkModel* model) override {
317 ++started_count_;
318 completed_count_at_started_ = completed_count_;
321 void ExtensiveBookmarkChangesEnded(BookmarkModel* model) override {
322 ++completed_count_;
325 void BookmarkModelChanged() override {}
327 int get_started() const {
328 return started_count_;
331 int get_completed_count_at_started() const {
332 return completed_count_at_started_;
335 int get_completed() const {
336 return completed_count_;
339 private:
340 int started_count_;
341 int completed_count_at_started_;
342 int completed_count_;
344 DISALLOW_COPY_AND_ASSIGN(ExtensiveChangesBookmarkModelObserver);
348 class ProfileSyncServiceBookmarkTest : public testing::Test {
349 protected:
350 enum LoadOption { LOAD_FROM_STORAGE, DELETE_EXISTING_STORAGE };
351 enum SaveOption { SAVE_TO_STORAGE, DONT_SAVE_TO_STORAGE };
353 ProfileSyncServiceBookmarkTest()
354 : model_(NULL),
355 local_merge_result_(syncer::BOOKMARKS),
356 syncer_merge_result_(syncer::BOOKMARKS) {}
358 virtual ~ProfileSyncServiceBookmarkTest() {
359 StopSync();
360 UnloadBookmarkModel();
363 virtual void SetUp() {
364 test_user_share_.SetUp();
367 virtual void TearDown() {
368 test_user_share_.TearDown();
371 bool CanSyncNode(const BookmarkNode* node) {
372 return model_->client()->CanSyncNode(node);
375 // Inserts a folder directly to the share.
376 // Do not use this after model association is complete.
378 // This function differs from the AddFolder() function declared elsewhere in
379 // this file in that it only affects the sync model. It would be invalid to
380 // change the sync model directly after ModelAssociation. This function can
381 // be invoked prior to model association to set up first-time sync model
382 // association scenarios.
383 int64 AddFolderToShare(syncer::WriteTransaction* trans, std::string title) {
384 EXPECT_FALSE(model_associator_);
386 // Be sure to call CreatePermanentBookmarkNodes(), otherwise this will fail.
387 syncer::ReadNode bookmark_bar(trans);
388 EXPECT_EQ(BaseNode::INIT_OK,
389 bookmark_bar.InitByTagLookupForBookmarks("bookmark_bar"));
391 syncer::WriteNode node(trans);
392 EXPECT_TRUE(node.InitBookmarkByCreation(bookmark_bar, NULL));
393 node.SetIsFolder(true);
394 node.SetTitle(title);
396 return node.GetId();
399 // Inserts a bookmark directly to the share.
400 // Do not use this after model association is complete.
402 // This function differs from the AddURL() function declared elsewhere in this
403 // file in that it only affects the sync model. It would be invalid to change
404 // the sync model directly after ModelAssociation. This function can be
405 // invoked prior to model association to set up first-time sync model
406 // association scenarios.
407 int64 AddBookmarkToShare(syncer::WriteTransaction* trans,
408 int64 parent_id,
409 const std::string& title,
410 const std::string& url) {
411 EXPECT_FALSE(model_associator_);
413 syncer::ReadNode parent(trans);
414 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
416 sync_pb::BookmarkSpecifics specifics;
417 specifics.set_url(url);
418 specifics.set_title(title);
420 syncer::WriteNode node(trans);
421 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
422 node.SetIsFolder(false);
423 node.SetTitle(title);
424 node.SetBookmarkSpecifics(specifics);
426 return node.GetId();
429 // Load (or re-load) the bookmark model. |load| controls use of the
430 // bookmarks file on disk. |save| controls whether the newly loaded
431 // bookmark model will write out a bookmark file as it goes.
432 void LoadBookmarkModel(LoadOption load, SaveOption save) {
433 bool delete_bookmarks = load == DELETE_EXISTING_STORAGE;
434 profile_.CreateBookmarkModel(delete_bookmarks);
435 model_ = BookmarkModelFactory::GetForProfile(&profile_);
436 bookmarks::test::WaitForBookmarkModelToLoad(model_);
437 // This noticeably speeds up the unit tests that request it.
438 if (save == DONT_SAVE_TO_STORAGE)
439 model_->ClearStore();
440 base::MessageLoop::current()->RunUntilIdle();
443 int GetSyncBookmarkCount() {
444 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
445 syncer::ReadNode node(&trans);
446 if (node.InitTypeRoot(syncer::BOOKMARKS) != syncer::BaseNode::INIT_OK)
447 return 0;
448 return node.GetTotalNodeCount();
451 // Creates the bookmark root node and the permanent nodes if they don't
452 // already exist.
453 bool CreatePermanentBookmarkNodes() {
454 bool root_exists = false;
455 syncer::ModelType type = syncer::BOOKMARKS;
457 syncer::WriteTransaction trans(FROM_HERE,
458 test_user_share_.user_share());
459 syncer::ReadNode uber_root(&trans);
460 uber_root.InitByRootLookup();
462 syncer::ReadNode root(&trans);
463 root_exists = (root.InitTypeRoot(type) == BaseNode::INIT_OK);
466 if (!root_exists) {
467 if (!syncer::TestUserShare::CreateRoot(type,
468 test_user_share_.user_share()))
469 return false;
472 const int kNumPermanentNodes = 3;
473 const std::string permanent_tags[kNumPermanentNodes] = {
474 #if defined(OS_IOS) || defined(OS_ANDROID)
475 "synced_bookmarks",
476 #endif // defined(OS_IOS) || defined(OS_ANDROID)
477 "bookmark_bar",
478 "other_bookmarks",
479 #if !defined(OS_IOS) && !defined(OS_ANDROID)
480 "synced_bookmarks",
481 #endif // !defined(OS_IOS) && !defined(OS_ANDROID)
483 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
484 syncer::ReadNode root(&trans);
485 EXPECT_EQ(BaseNode::INIT_OK, root.InitTypeRoot(type));
487 // Loop through creating permanent nodes as necessary.
488 int64 last_child_id = syncer::kInvalidId;
489 for (int i = 0; i < kNumPermanentNodes; ++i) {
490 // First check if the node already exists. This is for tests that involve
491 // persistence and set up sync more than once.
492 syncer::ReadNode lookup(&trans);
493 if (lookup.InitByTagLookupForBookmarks(permanent_tags[i]) ==
494 syncer::ReadNode::INIT_OK) {
495 last_child_id = lookup.GetId();
496 continue;
499 // If it doesn't exist, create the permanent node at the end of the
500 // ordering.
501 syncer::ReadNode predecessor_node(&trans);
502 syncer::ReadNode* predecessor = NULL;
503 if (last_child_id != syncer::kInvalidId) {
504 EXPECT_EQ(BaseNode::INIT_OK,
505 predecessor_node.InitByIdLookup(last_child_id));
506 predecessor = &predecessor_node;
508 syncer::WriteNode node(&trans);
509 if (!node.InitBookmarkByCreation(root, predecessor))
510 return false;
511 node.SetIsFolder(true);
512 node.GetMutableEntryForTest()->PutUniqueServerTag(permanent_tags[i]);
513 node.SetTitle(permanent_tags[i]);
514 node.SetExternalId(0);
515 last_child_id = node.GetId();
517 return true;
520 bool AssociateModels() {
521 DCHECK(!model_associator_);
523 // Set up model associator.
524 model_associator_.reset(new BookmarkModelAssociator(
525 BookmarkModelFactory::GetForProfile(&profile_),
526 &profile_,
527 test_user_share_.user_share(),
528 &mock_error_handler_,
529 kExpectMobileBookmarks));
531 local_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
532 syncer_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
533 int local_count_before = model_->root_node()->GetTotalNodeCount();
534 int syncer_count_before = GetSyncBookmarkCount();
536 syncer::SyncError error = model_associator_->AssociateModels(
537 &local_merge_result_,
538 &syncer_merge_result_);
539 if (error.IsSet())
540 return false;
542 base::MessageLoop::current()->RunUntilIdle();
544 // Verify the merge results were calculated properly.
545 EXPECT_EQ(local_count_before,
546 local_merge_result_.num_items_before_association());
547 EXPECT_EQ(syncer_count_before,
548 syncer_merge_result_.num_items_before_association());
549 EXPECT_EQ(local_merge_result_.num_items_after_association(),
550 local_merge_result_.num_items_before_association() +
551 local_merge_result_.num_items_added() -
552 local_merge_result_.num_items_deleted());
553 EXPECT_EQ(syncer_merge_result_.num_items_after_association(),
554 syncer_merge_result_.num_items_before_association() +
555 syncer_merge_result_.num_items_added() -
556 syncer_merge_result_.num_items_deleted());
557 EXPECT_EQ(model_->root_node()->GetTotalNodeCount(),
558 local_merge_result_.num_items_after_association());
559 EXPECT_EQ(GetSyncBookmarkCount(),
560 syncer_merge_result_.num_items_after_association());
561 return true;
564 void StartSync() {
565 test_user_share_.Reload();
567 ASSERT_TRUE(CreatePermanentBookmarkNodes());
568 ASSERT_TRUE(AssociateModels());
570 // Set up change processor.
571 change_processor_.reset(
572 new BookmarkChangeProcessor(&profile_,
573 model_associator_.get(),
574 &mock_error_handler_));
575 change_processor_->Start(test_user_share_.user_share());
578 void StopSync() {
579 change_processor_.reset();
580 if (model_associator_) {
581 syncer::SyncError error = model_associator_->DisassociateModels();
582 EXPECT_FALSE(error.IsSet());
584 model_associator_.reset();
586 base::MessageLoop::current()->RunUntilIdle();
588 // TODO(akalin): Actually close the database and flush it to disk
589 // (and make StartSync reload from disk). This would require
590 // refactoring TestUserShare.
593 void UnloadBookmarkModel() {
594 profile_.CreateBookmarkModel(false /* delete_bookmarks */);
595 model_ = NULL;
596 base::MessageLoop::current()->RunUntilIdle();
599 bool InitSyncNodeFromChromeNode(const BookmarkNode* bnode,
600 syncer::BaseNode* sync_node) {
601 return model_associator_->InitSyncNodeFromChromeId(bnode->id(),
602 sync_node);
605 void ExpectSyncerNodeMatching(syncer::BaseTransaction* trans,
606 const BookmarkNode* bnode) {
607 std::string truncated_title = base::UTF16ToUTF8(bnode->GetTitle());
608 syncer::SyncAPINameToServerName(truncated_title, &truncated_title);
609 base::TruncateUTF8ToByteSize(truncated_title, 255, &truncated_title);
610 syncer::ServerNameToSyncAPIName(truncated_title, &truncated_title);
612 syncer::ReadNode gnode(trans);
613 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnode, &gnode));
614 // Non-root node titles and parents must match.
615 if (!model_->is_permanent_node(bnode)) {
616 EXPECT_EQ(truncated_title, gnode.GetTitle());
617 EXPECT_EQ(
618 model_associator_->GetChromeNodeFromSyncId(gnode.GetParentId()),
619 bnode->parent());
621 EXPECT_EQ(bnode->is_folder(), gnode.GetIsFolder());
622 if (bnode->is_url())
623 EXPECT_EQ(bnode->url(), GURL(gnode.GetBookmarkSpecifics().url()));
625 // Check that meta info matches.
626 const BookmarkNode::MetaInfoMap* meta_info_map = bnode->GetMetaInfoMap();
627 sync_pb::BookmarkSpecifics specifics = gnode.GetBookmarkSpecifics();
628 if (!meta_info_map) {
629 EXPECT_EQ(0, specifics.meta_info_size());
630 } else {
631 EXPECT_EQ(meta_info_map->size(),
632 static_cast<size_t>(specifics.meta_info_size()));
633 for (int i = 0; i < specifics.meta_info_size(); i++) {
634 BookmarkNode::MetaInfoMap::const_iterator it =
635 meta_info_map->find(specifics.meta_info(i).key());
636 EXPECT_TRUE(it != meta_info_map->end());
637 EXPECT_EQ(it->second, specifics.meta_info(i).value());
641 // Check for position matches.
642 int browser_index = bnode->parent()->GetIndexOf(bnode);
643 if (browser_index == 0) {
644 EXPECT_EQ(gnode.GetPredecessorId(), 0);
645 } else {
646 const BookmarkNode* bprev =
647 bnode->parent()->GetChild(browser_index - 1);
648 syncer::ReadNode gprev(trans);
649 ASSERT_TRUE(InitSyncNodeFromChromeNode(bprev, &gprev));
650 EXPECT_EQ(gnode.GetPredecessorId(), gprev.GetId());
651 EXPECT_EQ(gnode.GetParentId(), gprev.GetParentId());
653 // Note: the managed node is the last child of the root_node but isn't
654 // synced; if CanSyncNode() is false then there is no next node to sync.
655 const BookmarkNode* bnext = NULL;
656 if (browser_index + 1 < bnode->parent()->child_count())
657 bnext = bnode->parent()->GetChild(browser_index + 1);
658 if (!bnext || !CanSyncNode(bnext)) {
659 EXPECT_EQ(gnode.GetSuccessorId(), 0);
660 } else {
661 syncer::ReadNode gnext(trans);
662 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnext, &gnext));
663 EXPECT_EQ(gnode.GetSuccessorId(), gnext.GetId());
664 EXPECT_EQ(gnode.GetParentId(), gnext.GetParentId());
666 if (!bnode->empty())
667 EXPECT_TRUE(gnode.GetFirstChildId());
670 void ExpectSyncerNodeMatching(const BookmarkNode* bnode) {
671 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
672 ExpectSyncerNodeMatching(&trans, bnode);
675 void ExpectBrowserNodeMatching(syncer::BaseTransaction* trans,
676 int64 sync_id) {
677 EXPECT_TRUE(sync_id);
678 const BookmarkNode* bnode =
679 model_associator_->GetChromeNodeFromSyncId(sync_id);
680 ASSERT_TRUE(bnode);
681 ASSERT_TRUE(CanSyncNode(bnode));
683 int64 id = model_associator_->GetSyncIdFromChromeId(bnode->id());
684 EXPECT_EQ(id, sync_id);
685 ExpectSyncerNodeMatching(trans, bnode);
688 void ExpectBrowserNodeUnknown(int64 sync_id) {
689 EXPECT_FALSE(model_associator_->GetChromeNodeFromSyncId(sync_id));
692 void ExpectBrowserNodeKnown(int64 sync_id) {
693 EXPECT_TRUE(model_associator_->GetChromeNodeFromSyncId(sync_id));
696 void ExpectSyncerNodeKnown(const BookmarkNode* node) {
697 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
698 EXPECT_NE(sync_id, syncer::kInvalidId);
701 void ExpectSyncerNodeUnknown(const BookmarkNode* node) {
702 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
703 EXPECT_EQ(sync_id, syncer::kInvalidId);
706 void ExpectBrowserNodeTitle(int64 sync_id, const std::string& title) {
707 const BookmarkNode* bnode =
708 model_associator_->GetChromeNodeFromSyncId(sync_id);
709 ASSERT_TRUE(bnode);
710 EXPECT_EQ(bnode->GetTitle(), base::UTF8ToUTF16(title));
713 void ExpectBrowserNodeURL(int64 sync_id, const std::string& url) {
714 const BookmarkNode* bnode =
715 model_associator_->GetChromeNodeFromSyncId(sync_id);
716 ASSERT_TRUE(bnode);
717 EXPECT_EQ(GURL(url), bnode->url());
720 void ExpectBrowserNodeParent(int64 sync_id, int64 parent_sync_id) {
721 const BookmarkNode* node =
722 model_associator_->GetChromeNodeFromSyncId(sync_id);
723 ASSERT_TRUE(node);
724 const BookmarkNode* parent =
725 model_associator_->GetChromeNodeFromSyncId(parent_sync_id);
726 EXPECT_TRUE(parent);
727 EXPECT_EQ(node->parent(), parent);
730 void ExpectModelMatch(syncer::BaseTransaction* trans) {
731 const BookmarkNode* root = model_->root_node();
732 #if defined(OS_IOS) || defined(OS_ANDROID)
733 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 0);
734 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 1);
735 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 2);
736 #else
737 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 0);
738 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 1);
739 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 2);
740 #endif // defined(OS_IOS) || defined(OS_ANDROID)
742 std::stack<int64> stack;
743 stack.push(bookmark_bar_id());
744 while (!stack.empty()) {
745 int64 id = stack.top();
746 stack.pop();
747 if (!id) continue;
749 ExpectBrowserNodeMatching(trans, id);
751 syncer::ReadNode gnode(trans);
752 ASSERT_EQ(BaseNode::INIT_OK, gnode.InitByIdLookup(id));
753 stack.push(gnode.GetSuccessorId());
754 if (gnode.GetIsFolder())
755 stack.push(gnode.GetFirstChildId());
759 void ExpectModelMatch() {
760 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
761 ExpectModelMatch(&trans);
764 int64 mobile_bookmarks_id() {
765 return
766 model_associator_->GetSyncIdFromChromeId(model_->mobile_node()->id());
769 int64 other_bookmarks_id() {
770 return
771 model_associator_->GetSyncIdFromChromeId(model_->other_node()->id());
774 int64 bookmark_bar_id() {
775 return model_associator_->GetSyncIdFromChromeId(
776 model_->bookmark_bar_node()->id());
779 private:
780 content::TestBrowserThreadBundle thread_bundle_;
782 protected:
783 TestingProfile profile_;
784 BookmarkModel* model_;
785 syncer::TestUserShare test_user_share_;
786 scoped_ptr<BookmarkChangeProcessor> change_processor_;
787 StrictMock<sync_driver::DataTypeErrorHandlerMock> mock_error_handler_;
788 scoped_ptr<BookmarkModelAssociator> model_associator_;
790 private:
791 syncer::SyncMergeResult local_merge_result_;
792 syncer::SyncMergeResult syncer_merge_result_;
795 TEST_F(ProfileSyncServiceBookmarkTest, InitialState) {
796 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
797 StartSync();
799 EXPECT_TRUE(other_bookmarks_id());
800 EXPECT_TRUE(bookmark_bar_id());
801 EXPECT_TRUE(mobile_bookmarks_id());
803 ExpectModelMatch();
806 // Populate the sync database then start model association. Sync's bookmarks
807 // should end up being copied into the native model, resulting in a successful
808 // "ExpectModelMatch()".
810 // This code has some use for verifying correctness. It's also a very useful
811 // for profiling bookmark ModelAssociation, an important part of some first-time
812 // sync scenarios. Simply increase the kNumFolders and kNumBookmarksPerFolder
813 // as desired, then run the test under a profiler to find hot spots in the model
814 // association code.
815 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociate) {
816 const int kNumBookmarksPerFolder = 10;
817 const int kNumFolders = 10;
819 CreatePermanentBookmarkNodes();
822 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
823 for (int i = 0; i < kNumFolders; ++i) {
824 int64 folder_id =
825 AddFolderToShare(&trans, base::StringPrintf("folder%05d", i));
826 for (int j = 0; j < kNumBookmarksPerFolder; ++j) {
827 AddBookmarkToShare(
828 &trans, folder_id, base::StringPrintf("bookmark%05d", j),
829 base::StringPrintf("http://www.google.com/search?q=%05d", j));
834 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
835 StartSync();
837 ExpectModelMatch();
840 // Tests bookmark association when nodes exists in the native model only.
841 // These entries should be copied to Sync directory during association process.
842 TEST_F(ProfileSyncServiceBookmarkTest,
843 InitialModelAssociateWithBookmarkModelNodes) {
844 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
845 const BookmarkNode* folder =
846 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("foobar"));
847 model_->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
848 model_->AddURL(folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
849 GURL("http://www.easypie.com/"));
850 model_->AddURL(folder, 1, base::ASCIIToUTF16("Airplanes"),
851 GURL("http://www.easyjet.com/"));
853 StartSync();
854 ExpectModelMatch();
857 // Tests bookmark association case when there is an entry in the delete journal
858 // that matches one of native bookmarks.
859 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociateWithDeleteJournal) {
860 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
861 const BookmarkNode* folder = model_->AddFolder(model_->bookmark_bar_node(), 0,
862 base::ASCIIToUTF16("foobar"));
863 const BookmarkNode* bookmark =
864 model_->AddURL(folder, 0, base::ASCIIToUTF16("Airplanes"),
865 GURL("http://www.easyjet.com/"));
867 CreatePermanentBookmarkNodes();
869 // Create entries matching the folder and the bookmark above.
870 int64 folder_id, bookmark_id;
872 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
873 folder_id = AddFolderToShare(&trans, "foobar");
874 bookmark_id = AddBookmarkToShare(&trans, folder_id, "Airplanes",
875 "http://www.easyjet.com/");
878 // Associate the bookmark sync node with the native model one and make
879 // it look like it was deleted by a server update.
881 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
882 syncer::WriteNode node(&trans);
883 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(bookmark_id));
885 node.GetMutableEntryForTest()->PutLocalExternalId(bookmark->id());
887 MakeServerUpdate(&trans, &node);
888 node.GetMutableEntryForTest()->PutServerIsDel(true);
889 node.GetMutableEntryForTest()->PutIsDel(true);
892 ASSERT_TRUE(AssociateModels());
893 ExpectModelMatch();
895 // The bookmark node should be deleted.
896 EXPECT_EQ(0, folder->child_count());
899 // Tests that the external ID is used to match the right folder amoung
900 // multiple folders with the same name during the native model traversal.
901 // Also tests that the external ID is used to match the right bookmark
902 // among multiple identical bookmarks when dealing with the delete journal.
903 TEST_F(ProfileSyncServiceBookmarkTest,
904 InitialModelAssociateVerifyExternalIdMatch) {
905 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
906 const int kNumFolders = 10;
907 const int kNumBookmarks = 10;
908 const int kFolderToIncludeBookmarks = 7;
909 const int kBookmarkToDelete = 4;
911 int64 folder_ids[kNumFolders];
912 int64 bookmark_ids[kNumBookmarks];
914 // Create native folders and bookmarks with identical names. Only
915 // one of the folders contains bookmarks and others are empty. Here is the
916 // expected tree shape:
917 // Bookmarks bar
918 // +- folder (#0)
919 // +- folder (#1)
920 // ...
921 // +- folder (#7) <-- Only this folder contains bookmarks.
922 // +- bookmark (#0)
923 // +- bookmark (#1)
924 // ...
925 // +- bookmark (#4) <-- Only this one bookmark should be removed later.
926 // ...
927 // +- bookmark (#9)
928 // ...
929 // +- folder (#9)
931 const BookmarkNode* parent_folder = nullptr;
932 for (int i = 0; i < kNumFolders; i++) {
933 const BookmarkNode* folder = model_->AddFolder(
934 model_->bookmark_bar_node(), i, base::ASCIIToUTF16("folder"));
935 folder_ids[i] = folder->id();
936 if (i == kFolderToIncludeBookmarks) {
937 parent_folder = folder;
941 for (int i = 0; i < kNumBookmarks; i++) {
942 const BookmarkNode* bookmark =
943 model_->AddURL(parent_folder, i, base::ASCIIToUTF16("bookmark"),
944 GURL("http://www.google.com/"));
945 bookmark_ids[i] = bookmark->id();
948 // Number of nodes in bookmark bar before association.
949 int total_node_count = model_->bookmark_bar_node()->GetTotalNodeCount();
951 CreatePermanentBookmarkNodes();
953 int64 sync_bookmark_id_to_delete = 0;
955 // Create sync folders matching native folders above.
956 int64 parent_id = 0;
957 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
958 // Create in reverse order because AddFolderToShare passes NULL for
959 // |predecessor| argument.
960 for (int i = kNumFolders - 1; i >= 0; i--) {
961 int64 id = AddFolderToShare(&trans, "folder");
963 // Pre-map sync folders to native folders by setting
964 // external ID. This will verify that the association algorithm picks
965 // the right ones despite all of them having identical names.
966 // More specifically this will help to avoid cloning bookmarks from
967 // a wrong folder.
968 syncer::WriteNode node(&trans);
969 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
970 node.GetMutableEntryForTest()->PutLocalExternalId(folder_ids[i]);
972 if (i == kFolderToIncludeBookmarks) {
973 parent_id = id;
977 // Create sync bookmark matching native bookmarks above in reverse order
978 // because AddBookmarkToShare passes NULL for |predecessor| argument.
979 for (int i = kNumBookmarks - 1; i >= 0; i--) {
980 int id = AddBookmarkToShare(&trans, parent_id, "bookmark",
981 "http://www.google.com/");
983 // Pre-map sync bookmarks to native bookmarks by setting
984 // external ID. This will verify that the association algorithm picks
985 // the right ones despite all of them having identical names and URLs.
986 syncer::WriteNode node(&trans);
987 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
988 node.GetMutableEntryForTest()->PutLocalExternalId(bookmark_ids[i]);
990 if (i == kBookmarkToDelete) {
991 sync_bookmark_id_to_delete = id;
996 // Make one bookmark deleted.
998 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
999 syncer::WriteNode node(&trans);
1000 EXPECT_EQ(BaseNode::INIT_OK,
1001 node.InitByIdLookup(sync_bookmark_id_to_delete));
1003 MakeServerUpdate(&trans, &node);
1004 node.GetMutableEntryForTest()->PutServerIsDel(true);
1005 node.GetMutableEntryForTest()->PutIsDel(true);
1008 // Perform association.
1009 ASSERT_TRUE(AssociateModels());
1010 ExpectModelMatch();
1012 // Only one native node should have been deleted and no nodes cloned due to
1013 // matching folder names.
1014 EXPECT_EQ(kNumFolders, model_->bookmark_bar_node()->child_count());
1015 EXPECT_EQ(kNumBookmarks - 1, parent_folder->child_count());
1016 EXPECT_EQ(total_node_count - 1,
1017 model_->bookmark_bar_node()->GetTotalNodeCount());
1019 // Verify that the right bookmark got deleted and no bookmarks reordered.
1020 for (int i = 0; i < parent_folder->child_count(); i++) {
1021 int index_in_bookmark_ids = (i < kBookmarkToDelete) ? i : i + 1;
1022 EXPECT_EQ(bookmark_ids[index_in_bookmark_ids],
1023 parent_folder->GetChild(i)->id());
1027 // Verifies that the bookmark association skips sync nodes with invalid URLs.
1028 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociateWithInvalidUrl) {
1029 EXPECT_CALL(mock_error_handler_, CreateAndUploadError(_, _, _))
1030 .WillOnce(Return(syncer::SyncError()));
1032 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1033 // On the local side create a folder and two nodes.
1034 const BookmarkNode* folder = model_->AddFolder(model_->bookmark_bar_node(), 0,
1035 base::ASCIIToUTF16("folder"));
1036 model_->AddURL(folder, 0, base::ASCIIToUTF16("node1"),
1037 GURL("http://www.node1.com/"));
1038 model_->AddURL(folder, 1, base::ASCIIToUTF16("node2"),
1039 GURL("http://www.node2.com/"));
1041 // On the sync side create a matching folder, one matching node, one
1042 // unmatching node, and one node with an invalid URL.
1043 CreatePermanentBookmarkNodes();
1045 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1046 int64 folder_id = AddFolderToShare(&trans, "folder");
1047 // Please note that each AddBookmarkToShare inserts the node at the front
1048 // so the actual order of children in the directory will be opposite.
1049 AddBookmarkToShare(&trans, folder_id, "node2", "http://www.node2.com/");
1050 AddBookmarkToShare(&trans, folder_id, "node3", "");
1051 AddBookmarkToShare(&trans, folder_id, "node4", "http://www.node4.com/");
1054 // Perform association.
1055 StartSync();
1057 // Concatenate resulting titles of native nodes.
1058 std::string native_titles;
1059 for (int i = 0; i < folder->child_count(); i++) {
1060 if (!native_titles.empty())
1061 native_titles += ",";
1062 const BookmarkNode* child = folder->GetChild(i);
1063 native_titles += base::UTF16ToUTF8(child->GetTitle());
1066 // Expect the order of nodes to follow the sync order (see note above), the
1067 // node with the invalid URL to be skipped, and the extra native node to be
1068 // at the end.
1069 EXPECT_EQ("node4,node2,node1", native_titles);
1072 TEST_F(ProfileSyncServiceBookmarkTest, BookmarkModelOperations) {
1073 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1074 StartSync();
1076 // Test addition.
1077 const BookmarkNode* folder =
1078 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("foobar"));
1079 ExpectSyncerNodeMatching(folder);
1080 ExpectModelMatch();
1081 const BookmarkNode* folder2 =
1082 model_->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
1083 ExpectSyncerNodeMatching(folder2);
1084 ExpectModelMatch();
1085 const BookmarkNode* url1 = model_->AddURL(
1086 folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
1087 GURL("http://www.easypie.com/"));
1088 ExpectSyncerNodeMatching(url1);
1089 ExpectModelMatch();
1090 const BookmarkNode* url2 = model_->AddURL(
1091 folder, 1, base::ASCIIToUTF16("Airplanes"),
1092 GURL("http://www.easyjet.com/"));
1093 ExpectSyncerNodeMatching(url2);
1094 ExpectModelMatch();
1095 // Test addition.
1096 const BookmarkNode* mobile_folder =
1097 model_->AddFolder(model_->mobile_node(), 0, base::ASCIIToUTF16("pie"));
1098 ExpectSyncerNodeMatching(mobile_folder);
1099 ExpectModelMatch();
1101 // Test modification.
1102 model_->SetTitle(url2, base::ASCIIToUTF16("EasyJet"));
1103 ExpectModelMatch();
1104 model_->Move(url1, folder2, 0);
1105 ExpectModelMatch();
1106 model_->Move(folder2, model_->bookmark_bar_node(), 0);
1107 ExpectModelMatch();
1108 model_->SetTitle(folder2, base::ASCIIToUTF16("Not Nested"));
1109 ExpectModelMatch();
1110 model_->Move(folder, folder2, 0);
1111 ExpectModelMatch();
1112 model_->SetTitle(folder, base::ASCIIToUTF16("who's nested now?"));
1113 ExpectModelMatch();
1114 model_->Copy(url2, model_->bookmark_bar_node(), 0);
1115 ExpectModelMatch();
1116 model_->SetTitle(mobile_folder, base::ASCIIToUTF16("strawberry"));
1117 ExpectModelMatch();
1119 // Test deletion.
1120 // Delete a single item.
1121 model_->Remove(url2);
1122 ExpectModelMatch();
1123 // Delete an item with several children.
1124 model_->Remove(folder2);
1125 ExpectModelMatch();
1126 model_->Remove(model_->mobile_node()->GetChild(0));
1127 ExpectModelMatch();
1130 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeProcessing) {
1131 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1132 StartSync();
1134 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1136 FakeServerChange adds(&trans);
1137 int64 f1 = adds.AddFolder("Server Folder B", bookmark_bar_id(), 0);
1138 int64 f2 = adds.AddFolder("Server Folder A", bookmark_bar_id(), f1);
1139 int64 u1 = adds.AddURL("Some old site", "ftp://nifty.andrew.cmu.edu/",
1140 bookmark_bar_id(), f2);
1141 int64 u2 = adds.AddURL("Nifty", "ftp://nifty.andrew.cmu.edu/", f1, 0);
1142 // u3 is a duplicate URL
1143 int64 u3 = adds.AddURL("Nifty2", "ftp://nifty.andrew.cmu.edu/", f1, u2);
1144 // u4 is a duplicate title, different URL.
1145 adds.AddURL("Some old site", "http://slog.thestranger.com/",
1146 bookmark_bar_id(), u1);
1147 // u5 tests an empty-string title.
1148 std::string javascript_url(
1149 "javascript:(function(){var w=window.open(" \
1150 "'about:blank','gnotesWin','location=0,menubar=0," \
1151 "scrollbars=0,status=0,toolbar=0,width=300," \
1152 "height=300,resizable');});");
1153 adds.AddURL(std::string(), javascript_url, other_bookmarks_id(), 0);
1154 int64 u6 = adds.AddURL(
1155 "Sync1", "http://www.syncable.edu/", mobile_bookmarks_id(), 0);
1157 syncer::ChangeRecordList::const_iterator it;
1158 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
1159 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1160 ExpectBrowserNodeUnknown(it->id);
1162 adds.ApplyPendingChanges(change_processor_.get());
1164 // Make sure the bookmark model received all of the nodes in |adds|.
1165 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1166 ExpectBrowserNodeMatching(&trans, it->id);
1167 ExpectModelMatch(&trans);
1169 // Part two: test modifications.
1170 FakeServerChange mods(&trans);
1171 // Mess with u2, and move it into empty folder f2
1172 // TODO(ncarter): Determine if we allow ModifyURL ops or not.
1173 /* std::string u2_old_url = mods.ModifyURL(u2, "http://www.google.com"); */
1174 std::string u2_old_title = mods.ModifyTitle(u2, "The Google");
1175 int64 u2_old_parent = mods.ModifyPosition(u2, f2, 0);
1177 // Now move f1 after u2.
1178 std::string f1_old_title = mods.ModifyTitle(f1, "Server Folder C");
1179 int64 f1_old_parent = mods.ModifyPosition(f1, f2, u2);
1181 // Then add u3 after f1.
1182 int64 u3_old_parent = mods.ModifyPosition(u3, f2, f1);
1184 std::string u6_old_title = mods.ModifyTitle(u6, "Mobile Folder A");
1186 // Test that the property changes have not yet taken effect.
1187 ExpectBrowserNodeTitle(u2, u2_old_title);
1188 /* ExpectBrowserNodeURL(u2, u2_old_url); */
1189 ExpectBrowserNodeParent(u2, u2_old_parent);
1191 ExpectBrowserNodeTitle(f1, f1_old_title);
1192 ExpectBrowserNodeParent(f1, f1_old_parent);
1194 ExpectBrowserNodeParent(u3, u3_old_parent);
1196 ExpectBrowserNodeTitle(u6, u6_old_title);
1198 // Apply the changes.
1199 mods.ApplyPendingChanges(change_processor_.get());
1201 // Check for successful application.
1202 for (it = mods.changes().begin(); it != mods.changes().end(); ++it)
1203 ExpectBrowserNodeMatching(&trans, it->id);
1204 ExpectModelMatch(&trans);
1206 // Part 3: Test URL deletion.
1207 FakeServerChange dels(&trans);
1208 dels.Delete(u2);
1209 dels.Delete(u3);
1210 dels.Delete(u6);
1212 ExpectBrowserNodeKnown(u2);
1213 ExpectBrowserNodeKnown(u3);
1215 dels.ApplyPendingChanges(change_processor_.get());
1217 ExpectBrowserNodeUnknown(u2);
1218 ExpectBrowserNodeUnknown(u3);
1219 ExpectBrowserNodeUnknown(u6);
1220 ExpectModelMatch(&trans);
1223 // Tests a specific case in ApplyModelChanges where we move the
1224 // children out from under a parent, and then delete the parent
1225 // in the same changelist. The delete shows up first in the changelist,
1226 // requiring the children to be moved to a temporary location.
1227 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeRequiringFosterParent) {
1228 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1229 StartSync();
1231 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1233 // Stress the immediate children of other_node because that's where
1234 // ApplyModelChanges puts a temporary foster parent node.
1235 std::string url("http://dev.chromium.org/");
1236 FakeServerChange adds(&trans);
1237 int64 f0 = other_bookmarks_id(); // + other_node
1238 int64 f1 = adds.AddFolder("f1", f0, 0); // + f1
1239 int64 f2 = adds.AddFolder("f2", f1, 0); // + f2
1240 int64 u3 = adds.AddURL( "u3", url, f2, 0); // + u3 NOLINT
1241 int64 u4 = adds.AddURL( "u4", url, f2, u3); // + u4 NOLINT
1242 int64 u5 = adds.AddURL( "u5", url, f1, f2); // + u5 NOLINT
1243 int64 f6 = adds.AddFolder("f6", f1, u5); // + f6
1244 int64 u7 = adds.AddURL( "u7", url, f0, f1); // + u7 NOLINT
1246 syncer::ChangeRecordList::const_iterator it;
1247 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
1248 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1249 ExpectBrowserNodeUnknown(it->id);
1251 adds.ApplyPendingChanges(change_processor_.get());
1253 // Make sure the bookmark model received all of the nodes in |adds|.
1254 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1255 ExpectBrowserNodeMatching(&trans, it->id);
1256 ExpectModelMatch(&trans);
1258 // We have to do the moves before the deletions, but FakeServerChange will
1259 // put the deletion at the front of the changelist.
1260 FakeServerChange ops(&trans);
1261 ops.ModifyPosition(f6, other_bookmarks_id(), 0);
1262 ops.ModifyPosition(u3, other_bookmarks_id(), f1); // Prev == f1 is OK here.
1263 ops.ModifyPosition(f2, other_bookmarks_id(), u7);
1264 ops.ModifyPosition(u7, f2, 0);
1265 ops.ModifyPosition(u4, other_bookmarks_id(), f2);
1266 ops.ModifyPosition(u5, f6, 0);
1267 ops.Delete(f1);
1269 ops.ApplyPendingChanges(change_processor_.get());
1271 ExpectModelMatch(&trans);
1274 // Simulate a server change record containing a valid but non-canonical URL.
1275 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeWithNonCanonicalURL) {
1276 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1277 StartSync();
1280 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1282 FakeServerChange adds(&trans);
1283 std::string url("http://dev.chromium.org");
1284 EXPECT_NE(GURL(url).spec(), url);
1285 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1287 adds.ApplyPendingChanges(change_processor_.get());
1289 EXPECT_EQ(1, model_->other_node()->child_count());
1290 ExpectModelMatch(&trans);
1293 // Now reboot the sync service, forcing a merge step.
1294 StopSync();
1295 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1296 StartSync();
1298 // There should still be just the one bookmark.
1299 EXPECT_EQ(1, model_->other_node()->child_count());
1300 ExpectModelMatch();
1303 // Simulate a server change record containing an invalid URL (per GURL).
1304 // TODO(ncarter): Disabled due to crashes. Fix bug 1677563.
1305 TEST_F(ProfileSyncServiceBookmarkTest, DISABLED_ServerChangeWithInvalidURL) {
1306 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1307 StartSync();
1309 int child_count = 0;
1311 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1313 FakeServerChange adds(&trans);
1314 std::string url("x");
1315 EXPECT_FALSE(GURL(url).is_valid());
1316 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1318 adds.ApplyPendingChanges(change_processor_.get());
1320 // We're lenient about what should happen -- the model could wind up with
1321 // the node or without it; but things should be consistent, and we
1322 // shouldn't crash.
1323 child_count = model_->other_node()->child_count();
1324 EXPECT_TRUE(child_count == 0 || child_count == 1);
1325 ExpectModelMatch(&trans);
1328 // Now reboot the sync service, forcing a merge step.
1329 StopSync();
1330 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1331 StartSync();
1333 // Things ought not to have changed.
1334 EXPECT_EQ(model_->other_node()->child_count(), child_count);
1335 ExpectModelMatch();
1339 // Test strings that might pose a problem if the titles ever became used as
1340 // file names in the sync backend.
1341 TEST_F(ProfileSyncServiceBookmarkTest, CornerCaseNames) {
1342 // TODO(ncarter): Bug 1570238 explains the failure of this test.
1343 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1344 StartSync();
1346 const char* names[] = {
1347 // The empty string.
1349 // Illegal Windows filenames.
1350 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4",
1351 "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3",
1352 "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1353 // Current/parent directory markers.
1354 ".", "..", "...",
1355 // Files created automatically by the Windows shell.
1356 "Thumbs.db", ".DS_Store",
1357 // Names including Win32-illegal characters, and path separators.
1358 "foo/bar", "foo\\bar", "foo?bar", "foo:bar", "foo|bar", "foo\"bar",
1359 "foo'bar", "foo<bar", "foo>bar", "foo%bar", "foo*bar", "foo]bar",
1360 "foo[bar",
1361 // A name with title > 255 characters
1362 "012345678901234567890123456789012345678901234567890123456789012345678901"
1363 "234567890123456789012345678901234567890123456789012345678901234567890123"
1364 "456789012345678901234567890123456789012345678901234567890123456789012345"
1365 "678901234567890123456789012345678901234567890123456789012345678901234567"
1366 "890123456789"
1368 // Create both folders and bookmarks using each name.
1369 GURL url("http://www.doublemint.com");
1370 for (size_t i = 0; i < arraysize(names); ++i) {
1371 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16(names[i]));
1372 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16(names[i]), url);
1375 // Verify that the browser model matches the sync model.
1376 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1377 2*arraysize(names));
1378 ExpectModelMatch();
1380 // Restart and re-associate. Verify things still match.
1381 StopSync();
1382 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1383 StartSync();
1384 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1385 2*arraysize(names));
1386 ExpectModelMatch();
1389 // Stress the internal representation of position by sparse numbers. We want
1390 // to repeatedly bisect the range of available positions, to force the
1391 // syncer code to renumber its ranges. Pick a number big enough so that it
1392 // would exhaust 32bits of room between items a couple of times.
1393 TEST_F(ProfileSyncServiceBookmarkTest, RepeatedMiddleInsertion) {
1394 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1395 StartSync();
1397 static const int kTimesToInsert = 256;
1399 // Create two book-end nodes to insert between.
1400 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("Alpha"));
1401 model_->AddFolder(model_->other_node(), 1, base::ASCIIToUTF16("Omega"));
1402 int count = 2;
1404 // Test insertion in first half of range by repeatedly inserting in second
1405 // position.
1406 for (int i = 0; i < kTimesToInsert; ++i) {
1407 base::string16 title =
1408 base::ASCIIToUTF16("Pre-insertion ") + base::IntToString16(i);
1409 model_->AddFolder(model_->other_node(), 1, title);
1410 count++;
1413 // Test insertion in second half of range by repeatedly inserting in
1414 // second-to-last position.
1415 for (int i = 0; i < kTimesToInsert; ++i) {
1416 base::string16 title =
1417 base::ASCIIToUTF16("Post-insertion ") + base::IntToString16(i);
1418 model_->AddFolder(model_->other_node(), count - 1, title);
1419 count++;
1422 // Verify that the browser model matches the sync model.
1423 EXPECT_EQ(model_->other_node()->child_count(), count);
1424 ExpectModelMatch();
1427 // Introduce a consistency violation into the model, and see that it
1428 // puts itself into a lame, error state.
1429 TEST_F(ProfileSyncServiceBookmarkTest, UnrecoverableErrorSuspendsService) {
1430 EXPECT_CALL(mock_error_handler_,
1431 OnSingleDataTypeUnrecoverableError(_));
1433 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1434 StartSync();
1436 // Add a node which will be the target of the consistency violation.
1437 const BookmarkNode* node =
1438 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("node"));
1439 ExpectSyncerNodeMatching(node);
1441 // Now destroy the syncer node as if we were the ProfileSyncService without
1442 // updating the ProfileSyncService state. This should introduce
1443 // inconsistency between the two models.
1445 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1446 syncer::WriteNode sync_node(&trans);
1447 ASSERT_TRUE(InitSyncNodeFromChromeNode(node, &sync_node));
1448 sync_node.Tombstone();
1450 // The models don't match at this point, but the ProfileSyncService
1451 // doesn't know it yet.
1452 ExpectSyncerNodeKnown(node);
1454 // Add a child to the inconsistent node. This should cause detection of the
1455 // problem and the syncer should stop processing changes.
1456 model_->AddFolder(node, 0, base::ASCIIToUTF16("nested"));
1459 // See what happens if we run model association when there are two exact URL
1460 // duplicate bookmarks. The BookmarkModelAssociator should not fall over when
1461 // this happens.
1462 TEST_F(ProfileSyncServiceBookmarkTest, MergeDuplicates) {
1463 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1464 StartSync();
1466 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1467 GURL("http://dup.com/"));
1468 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1469 GURL("http://dup.com/"));
1471 EXPECT_EQ(2, model_->other_node()->child_count());
1473 // Restart the sync service to trigger model association.
1474 StopSync();
1475 StartSync();
1477 EXPECT_EQ(2, model_->other_node()->child_count());
1478 ExpectModelMatch();
1481 TEST_F(ProfileSyncServiceBookmarkTest, ApplySyncDeletesFromJournal) {
1482 // Initialize sync model and bookmark model as:
1483 // URL 0
1484 // Folder 1
1485 // |-- URL 1
1486 // +-- Folder 2
1487 // +-- URL 2
1488 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1489 int64 u0 = 0;
1490 int64 f1 = 0;
1491 int64 u1 = 0;
1492 int64 f2 = 0;
1493 int64 u2 = 0;
1494 StartSync();
1495 int fixed_sync_bk_count = GetSyncBookmarkCount();
1497 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1498 FakeServerChange adds(&trans);
1499 u0 = adds.AddURL("URL 0", "http://plus.google.com/", bookmark_bar_id(), 0);
1500 f1 = adds.AddFolder("Folder 1", bookmark_bar_id(), u0);
1501 u1 = adds.AddURL("URL 1", "http://www.google.com/", f1, 0);
1502 f2 = adds.AddFolder("Folder 2", f1, u1);
1503 u2 = adds.AddURL("URL 2", "http://mail.google.com/", f2, 0);
1504 adds.ApplyPendingChanges(change_processor_.get());
1506 StopSync();
1508 // Reload bookmark model and disable model saving to make sync changes not
1509 // persisted.
1510 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1511 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1512 EXPECT_EQ(fixed_sync_bk_count + 5, GetSyncBookmarkCount());
1513 StartSync();
1515 // Remove all folders/bookmarks except u3 added above.
1516 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1517 MakeServerUpdate(&trans, f1);
1518 MakeServerUpdate(&trans, u1);
1519 MakeServerUpdate(&trans, f2);
1520 MakeServerUpdate(&trans, u2);
1521 FakeServerChange dels(&trans);
1522 dels.Delete(u2);
1523 dels.Delete(f2);
1524 dels.Delete(u1);
1525 dels.Delete(f1);
1526 dels.ApplyPendingChanges(change_processor_.get());
1528 StopSync();
1529 // Bookmark bar itself and u0 remain.
1530 EXPECT_EQ(2, model_->bookmark_bar_node()->GetTotalNodeCount());
1532 // Reload bookmarks including ones deleted in sync model from storage.
1533 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1534 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1535 // Add a bookmark under f1 when sync is off so that f1 will not be
1536 // deleted even when f1 matches delete journal because it's not empty.
1537 model_->AddURL(model_->bookmark_bar_node()->GetChild(1),
1538 0, base::UTF8ToUTF16("local"), GURL("http://www.youtube.com"));
1539 // Sync model has fixed bookmarks nodes and u3.
1540 EXPECT_EQ(fixed_sync_bk_count + 1, GetSyncBookmarkCount());
1541 StartSync();
1542 // Expect 4 bookmarks after model association because u2, f2, u1 are removed
1543 // by delete journal, f1 is not removed by delete journal because it's
1544 // not empty due to www.youtube.com added above.
1545 EXPECT_EQ(4, model_->bookmark_bar_node()->GetTotalNodeCount());
1546 EXPECT_EQ(base::UTF8ToUTF16("URL 0"),
1547 model_->bookmark_bar_node()->GetChild(0)->GetTitle());
1548 EXPECT_EQ(base::UTF8ToUTF16("Folder 1"),
1549 model_->bookmark_bar_node()->GetChild(1)->GetTitle());
1550 EXPECT_EQ(base::UTF8ToUTF16("local"),
1551 model_->bookmark_bar_node()->GetChild(1)->GetChild(0)->GetTitle());
1552 StopSync();
1554 // Verify purging of delete journals.
1555 // Delete journals for u2, f2, u1 remains because they are used in last
1556 // association.
1557 EXPECT_EQ(3u, test_user_share_.GetDeleteJournalSize());
1558 StartSync();
1559 StopSync();
1560 // Reload again and all delete journals should be gone because none is used
1561 // in last association.
1562 ASSERT_TRUE(test_user_share_.Reload());
1563 EXPECT_EQ(0u, test_user_share_.GetDeleteJournalSize());
1566 struct TestData {
1567 const char* title;
1568 const char* url;
1571 // Map from bookmark node ID to its version.
1572 typedef std::map<int64, int64> BookmarkNodeVersionMap;
1574 // TODO(ncarter): Integrate the existing TestNode/PopulateNodeFromString code
1575 // in the bookmark model unittest, to make it simpler to set up test data
1576 // here (and reduce the amount of duplication among tests), and to reduce the
1577 // duplication.
1578 class ProfileSyncServiceBookmarkTestWithData
1579 : public ProfileSyncServiceBookmarkTest {
1580 public:
1581 ProfileSyncServiceBookmarkTestWithData();
1583 protected:
1584 // Populates or compares children of the given bookmark node from/with the
1585 // given test data array with the given size. |running_count| is updated as
1586 // urls are added. It is used to set the creation date (or test the creation
1587 // date for CompareWithTestData()).
1588 void PopulateFromTestData(const BookmarkNode* node,
1589 const TestData* data,
1590 int size,
1591 int* running_count);
1592 void CompareWithTestData(const BookmarkNode* node,
1593 const TestData* data,
1594 int size,
1595 int* running_count);
1597 void ExpectBookmarkModelMatchesTestData();
1598 void WriteTestDataToBookmarkModel();
1600 // Output transaction versions of |node| and nodes under it to
1601 // |node_versions|.
1602 void GetTransactionVersions(const BookmarkNode* root,
1603 BookmarkNodeVersionMap* node_versions);
1605 // Verify transaction versions of bookmark nodes and sync nodes are equal
1606 // recursively. If node is in |version_expected|, versions should match
1607 // there, too.
1608 void ExpectTransactionVersionMatch(
1609 const BookmarkNode* node,
1610 const BookmarkNodeVersionMap& version_expected);
1612 private:
1613 const base::Time start_time_;
1615 DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceBookmarkTestWithData);
1618 namespace {
1620 // Constants for bookmark model that looks like:
1621 // |-- Bookmark bar
1622 // | |-- u2, http://www.u2.com/
1623 // | |-- f1
1624 // | | |-- f1u4, http://www.f1u4.com/
1625 // | | |-- f1u2, http://www.f1u2.com/
1626 // | | |-- f1u3, http://www.f1u3.com/
1627 // | | +-- f1u1, http://www.f1u1.com/
1628 // | |-- u1, http://www.u1.com/
1629 // | +-- f2
1630 // | |-- f2u2, http://www.f2u2.com/
1631 // | |-- f2u4, http://www.f2u4.com/
1632 // | |-- f2u3, http://www.f2u3.com/
1633 // | +-- f2u1, http://www.f2u1.com/
1634 // +-- Other bookmarks
1635 // | |-- f3
1636 // | | |-- f3u4, http://www.f3u4.com/
1637 // | | |-- f3u2, http://www.f3u2.com/
1638 // | | |-- f3u3, http://www.f3u3.com/
1639 // | | +-- f3u1, http://www.f3u1.com/
1640 // | |-- u4, http://www.u4.com/
1641 // | |-- u3, http://www.u3.com/
1642 // | --- f4
1643 // | | |-- f4u1, http://www.f4u1.com/
1644 // | | |-- f4u2, http://www.f4u2.com/
1645 // | | |-- f4u3, http://www.f4u3.com/
1646 // | | +-- f4u4, http://www.f4u4.com/
1647 // | |-- dup
1648 // | | +-- dupu1, http://www.dupu1.com/
1649 // | +-- dup
1650 // | | +-- dupu2, http://www.dupu1.com/
1651 // | +-- ls , http://www.ls.com/
1652 // |
1653 // +-- Mobile bookmarks
1654 // |-- f5
1655 // | |-- f5u1, http://www.f5u1.com/
1656 // |-- f6
1657 // | |-- f6u1, http://www.f6u1.com/
1658 // | |-- f6u2, http://www.f6u2.com/
1659 // +-- u5, http://www.u5.com/
1661 static TestData kBookmarkBarChildren[] = {
1662 { "u2", "http://www.u2.com/" },
1663 { "f1", NULL },
1664 { "u1", "http://www.u1.com/" },
1665 { "f2", NULL },
1667 static TestData kF1Children[] = {
1668 { "f1u4", "http://www.f1u4.com/" },
1669 { "f1u2", "http://www.f1u2.com/" },
1670 { "f1u3", "http://www.f1u3.com/" },
1671 { "f1u1", "http://www.f1u1.com/" },
1673 static TestData kF2Children[] = {
1674 { "f2u2", "http://www.f2u2.com/" },
1675 { "f2u4", "http://www.f2u4.com/" },
1676 { "f2u3", "http://www.f2u3.com/" },
1677 { "f2u1", "http://www.f2u1.com/" },
1680 static TestData kOtherBookmarkChildren[] = {
1681 { "f3", NULL },
1682 { "u4", "http://www.u4.com/" },
1683 { "u3", "http://www.u3.com/" },
1684 { "f4", NULL },
1685 { "dup", NULL },
1686 { "dup", NULL },
1687 { " ls ", "http://www.ls.com/" }
1689 static TestData kF3Children[] = {
1690 { "f3u4", "http://www.f3u4.com/" },
1691 { "f3u2", "http://www.f3u2.com/" },
1692 { "f3u3", "http://www.f3u3.com/" },
1693 { "f3u1", "http://www.f3u1.com/" },
1695 static TestData kF4Children[] = {
1696 { "f4u1", "http://www.f4u1.com/" },
1697 { "f4u2", "http://www.f4u2.com/" },
1698 { "f4u3", "http://www.f4u3.com/" },
1699 { "f4u4", "http://www.f4u4.com/" },
1701 static TestData kDup1Children[] = {
1702 { "dupu1", "http://www.dupu1.com/" },
1704 static TestData kDup2Children[] = {
1705 { "dupu2", "http://www.dupu2.com/" },
1708 static TestData kMobileBookmarkChildren[] = {
1709 { "f5", NULL },
1710 { "f6", NULL },
1711 { "u5", "http://www.u5.com/" },
1713 static TestData kF5Children[] = {
1714 { "f5u1", "http://www.f5u1.com/" },
1715 { "f5u2", "http://www.f5u2.com/" },
1717 static TestData kF6Children[] = {
1718 { "f6u1", "http://www.f6u1.com/" },
1719 { "f6u2", "http://www.f6u2.com/" },
1722 } // anonymous namespace.
1724 ProfileSyncServiceBookmarkTestWithData::
1725 ProfileSyncServiceBookmarkTestWithData()
1726 : start_time_(base::Time::Now()) {
1729 void ProfileSyncServiceBookmarkTestWithData::PopulateFromTestData(
1730 const BookmarkNode* node,
1731 const TestData* data,
1732 int size,
1733 int* running_count) {
1734 DCHECK(node);
1735 DCHECK(data);
1736 DCHECK(node->is_folder());
1737 for (int i = 0; i < size; ++i) {
1738 const TestData& item = data[i];
1739 if (item.url) {
1740 const base::Time add_time =
1741 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1742 model_->AddURLWithCreationTimeAndMetaInfo(node,
1744 base::UTF8ToUTF16(item.title),
1745 GURL(item.url),
1746 add_time,
1747 NULL);
1748 } else {
1749 model_->AddFolder(node, i, base::UTF8ToUTF16(item.title));
1751 (*running_count)++;
1755 void ProfileSyncServiceBookmarkTestWithData::CompareWithTestData(
1756 const BookmarkNode* node,
1757 const TestData* data,
1758 int size,
1759 int* running_count) {
1760 DCHECK(node);
1761 DCHECK(data);
1762 DCHECK(node->is_folder());
1763 ASSERT_EQ(size, node->child_count());
1764 for (int i = 0; i < size; ++i) {
1765 const BookmarkNode* child_node = node->GetChild(i);
1766 const TestData& item = data[i];
1767 GURL url = GURL(item.url == NULL ? "" : item.url);
1768 BookmarkNode test_node(url);
1769 test_node.SetTitle(base::UTF8ToUTF16(item.title));
1770 EXPECT_EQ(child_node->GetTitle(), test_node.GetTitle());
1771 if (item.url) {
1772 EXPECT_FALSE(child_node->is_folder());
1773 EXPECT_TRUE(child_node->is_url());
1774 EXPECT_EQ(child_node->url(), test_node.url());
1775 const base::Time expected_time =
1776 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1777 EXPECT_EQ(expected_time.ToInternalValue(),
1778 child_node->date_added().ToInternalValue());
1779 } else {
1780 EXPECT_TRUE(child_node->is_folder());
1781 EXPECT_FALSE(child_node->is_url());
1783 (*running_count)++;
1787 // TODO(munjal): We should implement some way of generating random data and can
1788 // use the same seed to generate the same sequence.
1789 void ProfileSyncServiceBookmarkTestWithData::WriteTestDataToBookmarkModel() {
1790 const BookmarkNode* bookmarks_bar_node = model_->bookmark_bar_node();
1791 int count = 0;
1792 PopulateFromTestData(bookmarks_bar_node,
1793 kBookmarkBarChildren,
1794 arraysize(kBookmarkBarChildren),
1795 &count);
1797 ASSERT_GE(bookmarks_bar_node->child_count(), 4);
1798 const BookmarkNode* f1_node = bookmarks_bar_node->GetChild(1);
1799 PopulateFromTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1800 const BookmarkNode* f2_node = bookmarks_bar_node->GetChild(3);
1801 PopulateFromTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1803 const BookmarkNode* other_bookmarks_node = model_->other_node();
1804 PopulateFromTestData(other_bookmarks_node,
1805 kOtherBookmarkChildren,
1806 arraysize(kOtherBookmarkChildren),
1807 &count);
1809 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1810 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1811 PopulateFromTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1812 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1813 PopulateFromTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1814 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1815 PopulateFromTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1816 &count);
1817 dup_node = other_bookmarks_node->GetChild(5);
1818 PopulateFromTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1819 &count);
1821 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1822 PopulateFromTestData(mobile_bookmarks_node,
1823 kMobileBookmarkChildren,
1824 arraysize(kMobileBookmarkChildren),
1825 &count);
1827 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1828 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1829 PopulateFromTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1830 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1831 PopulateFromTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1833 ExpectBookmarkModelMatchesTestData();
1836 void ProfileSyncServiceBookmarkTestWithData::
1837 ExpectBookmarkModelMatchesTestData() {
1838 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1839 int count = 0;
1840 CompareWithTestData(bookmark_bar_node,
1841 kBookmarkBarChildren,
1842 arraysize(kBookmarkBarChildren),
1843 &count);
1845 ASSERT_GE(bookmark_bar_node->child_count(), 4);
1846 const BookmarkNode* f1_node = bookmark_bar_node->GetChild(1);
1847 CompareWithTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1848 const BookmarkNode* f2_node = bookmark_bar_node->GetChild(3);
1849 CompareWithTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1851 const BookmarkNode* other_bookmarks_node = model_->other_node();
1852 CompareWithTestData(other_bookmarks_node,
1853 kOtherBookmarkChildren,
1854 arraysize(kOtherBookmarkChildren),
1855 &count);
1857 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1858 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1859 CompareWithTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1860 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1861 CompareWithTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1862 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1863 CompareWithTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1864 &count);
1865 dup_node = other_bookmarks_node->GetChild(5);
1866 CompareWithTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1867 &count);
1869 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1870 CompareWithTestData(mobile_bookmarks_node,
1871 kMobileBookmarkChildren,
1872 arraysize(kMobileBookmarkChildren),
1873 &count);
1875 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1876 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1877 CompareWithTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1878 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1879 CompareWithTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1882 // Tests persistence of the profile sync service by unloading the
1883 // database and then reloading it from disk.
1884 TEST_F(ProfileSyncServiceBookmarkTestWithData, Persistence) {
1885 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1886 StartSync();
1888 WriteTestDataToBookmarkModel();
1890 ExpectModelMatch();
1892 // Force both models to discard their data and reload from disk. This
1893 // simulates what would happen if the browser were to shutdown normally,
1894 // and then relaunch.
1895 StopSync();
1896 UnloadBookmarkModel();
1897 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1898 StartSync();
1900 ExpectBookmarkModelMatchesTestData();
1902 // With the BookmarkModel contents verified, ExpectModelMatch will
1903 // verify the contents of the sync model.
1904 ExpectModelMatch();
1907 // Tests the merge case when the BookmarkModel is non-empty but the
1908 // sync model is empty. This corresponds to uploading browser
1909 // bookmarks to an initially empty, new account.
1910 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptySyncModel) {
1911 // Don't start the sync service until we've populated the bookmark model.
1912 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1914 WriteTestDataToBookmarkModel();
1916 // Restart sync. This should trigger a merge step during
1917 // initialization -- we expect the browser bookmarks to be written
1918 // to the sync service during this call.
1919 StartSync();
1921 // Verify that the bookmark model hasn't changed, and that the sync model
1922 // matches it exactly.
1923 ExpectBookmarkModelMatchesTestData();
1924 ExpectModelMatch();
1927 // Tests the merge case when the BookmarkModel is empty but the sync model is
1928 // non-empty. This corresponds (somewhat) to a clean install of the browser,
1929 // with no bookmarks, connecting to a sync account that has some bookmarks.
1930 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptyBookmarkModel) {
1931 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1932 StartSync();
1934 WriteTestDataToBookmarkModel();
1936 ExpectModelMatch();
1938 // Force the databse to unload and write itself to disk.
1939 StopSync();
1941 // Blow away the bookmark model -- it should be empty afterwards.
1942 UnloadBookmarkModel();
1943 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1944 EXPECT_EQ(model_->bookmark_bar_node()->child_count(), 0);
1945 EXPECT_EQ(model_->other_node()->child_count(), 0);
1946 EXPECT_EQ(model_->mobile_node()->child_count(), 0);
1948 // Now restart the sync service. Starting it should populate the bookmark
1949 // model -- test for consistency.
1950 StartSync();
1951 ExpectBookmarkModelMatchesTestData();
1952 ExpectModelMatch();
1955 // Tests the merge cases when both the models are expected to be identical
1956 // after the merge.
1957 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeExpectedIdenticalModels) {
1958 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1959 StartSync();
1960 WriteTestDataToBookmarkModel();
1961 ExpectModelMatch();
1962 StopSync();
1963 UnloadBookmarkModel();
1965 // At this point both the bookmark model and the server should have the
1966 // exact same data and it should match the test data.
1967 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1968 StartSync();
1969 ExpectBookmarkModelMatchesTestData();
1970 ExpectModelMatch();
1971 StopSync();
1972 UnloadBookmarkModel();
1974 // Now reorder some bookmarks in the bookmark model and then merge. Make
1975 // sure we get the order of the server after merge.
1976 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1977 ExpectBookmarkModelMatchesTestData();
1978 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
1979 ASSERT_TRUE(bookmark_bar);
1980 ASSERT_GT(bookmark_bar->child_count(), 1);
1981 model_->Move(bookmark_bar->GetChild(0), bookmark_bar, 1);
1982 StartSync();
1983 ExpectModelMatch();
1984 ExpectBookmarkModelMatchesTestData();
1987 // Tests the merge cases when both the models are expected to be identical
1988 // after the merge.
1989 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeModelsWithSomeExtras) {
1990 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1991 WriteTestDataToBookmarkModel();
1992 ExpectBookmarkModelMatchesTestData();
1994 // Remove some nodes and reorder some nodes.
1995 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1996 int remove_index = 2;
1997 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1998 const BookmarkNode* child_node = bookmark_bar_node->GetChild(remove_index);
1999 ASSERT_TRUE(child_node);
2000 ASSERT_TRUE(child_node->is_url());
2001 model_->Remove(bookmark_bar_node->GetChild(remove_index));
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_folder());
2006 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2008 const BookmarkNode* other_node = model_->other_node();
2009 ASSERT_GE(other_node->child_count(), 1);
2010 const BookmarkNode* f3_node = other_node->GetChild(0);
2011 ASSERT_TRUE(f3_node);
2012 ASSERT_TRUE(f3_node->is_folder());
2013 remove_index = 2;
2014 ASSERT_GT(f3_node->child_count(), remove_index);
2015 model_->Remove(f3_node->GetChild(remove_index));
2016 ASSERT_GT(f3_node->child_count(), remove_index);
2017 model_->Remove(f3_node->GetChild(remove_index));
2019 StartSync();
2020 ExpectModelMatch();
2021 StopSync();
2023 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2024 WriteTestDataToBookmarkModel();
2025 ExpectBookmarkModelMatchesTestData();
2027 // Remove some nodes and reorder some nodes.
2028 bookmark_bar_node = model_->bookmark_bar_node();
2029 remove_index = 0;
2030 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2031 child_node = bookmark_bar_node->GetChild(remove_index);
2032 ASSERT_TRUE(child_node);
2033 ASSERT_TRUE(child_node->is_url());
2034 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2035 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2036 child_node = bookmark_bar_node->GetChild(remove_index);
2037 ASSERT_TRUE(child_node);
2038 ASSERT_TRUE(child_node->is_folder());
2039 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2041 ASSERT_GE(bookmark_bar_node->child_count(), 2);
2042 model_->Move(bookmark_bar_node->GetChild(0), bookmark_bar_node, 1);
2044 other_node = model_->other_node();
2045 ASSERT_GE(other_node->child_count(), 1);
2046 f3_node = other_node->GetChild(0);
2047 ASSERT_TRUE(f3_node);
2048 ASSERT_TRUE(f3_node->is_folder());
2049 remove_index = 0;
2050 ASSERT_GT(f3_node->child_count(), remove_index);
2051 model_->Remove(f3_node->GetChild(remove_index));
2052 ASSERT_GT(f3_node->child_count(), remove_index);
2053 model_->Remove(f3_node->GetChild(remove_index));
2055 ASSERT_GE(other_node->child_count(), 4);
2056 model_->Move(other_node->GetChild(0), other_node, 1);
2057 model_->Move(other_node->GetChild(2), other_node, 3);
2059 StartSync();
2060 ExpectModelMatch();
2062 // After the merge, the model should match the test data.
2063 ExpectBookmarkModelMatchesTestData();
2066 // Tests the optimistic bookmark association case where some nodes are moved
2067 // and untracked by the sync before the association.
2068 TEST_F(ProfileSyncServiceBookmarkTestWithData, OptimisticMergeWithMoves) {
2069 // TODO(stanisc): crbug.com/456876: Remove this once the optimistic
2070 // association experiment has ended.
2071 base::FieldTrialList field_trial_list(new base::MockEntropyProvider());
2072 base::FieldTrialList::CreateFieldTrial("SyncOptimisticBookmarkAssociation",
2073 "Enabled");
2075 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2076 WriteTestDataToBookmarkModel();
2078 int num_bookmarks = model_->root_node()->GetTotalNodeCount();
2080 StartSync();
2081 ExpectModelMatch();
2082 StopSync();
2084 EXPECT_EQ(num_bookmarks, model_->root_node()->GetTotalNodeCount());
2086 // Move one folder into mobile bookmarks
2087 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2088 const BookmarkNode* f1 = bookmark_bar_node->GetChild(1);
2089 ASSERT_TRUE(f1->is_folder());
2090 model_->Move(f1, model_->mobile_node(), 0);
2092 StartSync();
2093 ExpectModelMatch();
2094 StopSync();
2096 // Expect folders to not duplicate.
2097 EXPECT_EQ(num_bookmarks, model_->root_node()->GetTotalNodeCount());
2099 // Perform one more cycle and make sure that the number of nodes stays
2100 // the same.
2101 StartSync();
2102 ExpectModelMatch();
2103 StopSync();
2104 EXPECT_EQ(num_bookmarks, model_->root_node()->GetTotalNodeCount());
2107 // Tests that when persisted model associations are used, things work fine.
2108 TEST_F(ProfileSyncServiceBookmarkTestWithData, ModelAssociationPersistence) {
2109 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2110 WriteTestDataToBookmarkModel();
2111 StartSync();
2112 ExpectModelMatch();
2113 // Force sync to shut down and write itself to disk.
2114 StopSync();
2115 // Now restart sync. This time it should use the persistent
2116 // associations.
2117 StartSync();
2118 ExpectModelMatch();
2121 // Tests that when persisted model associations are used, things work fine.
2122 TEST_F(ProfileSyncServiceBookmarkTestWithData,
2123 ModelAssociationInvalidPersistence) {
2124 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2125 WriteTestDataToBookmarkModel();
2126 StartSync();
2127 ExpectModelMatch();
2128 // Force sync to shut down and write itself to disk.
2129 StopSync();
2130 // Change the bookmark model before restarting sync service to simulate
2131 // the situation where bookmark model is different from sync model and
2132 // make sure model associator correctly rebuilds associations.
2133 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2134 model_->AddURL(bookmark_bar_node, 0, base::ASCIIToUTF16("xtra"),
2135 GURL("http://www.xtra.com"));
2136 // Now restart sync. This time it will try to use the persistent
2137 // associations and realize that they are invalid and hence will rebuild
2138 // associations.
2139 StartSync();
2140 ExpectModelMatch();
2143 TEST_F(ProfileSyncServiceBookmarkTestWithData, SortChildren) {
2144 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2145 StartSync();
2147 // Write test data to bookmark model and verify that the models match.
2148 WriteTestDataToBookmarkModel();
2149 const BookmarkNode* folder_added = model_->other_node()->GetChild(0);
2150 ASSERT_TRUE(folder_added);
2151 ASSERT_TRUE(folder_added->is_folder());
2153 ExpectModelMatch();
2155 // Sort the other-bookmarks children and expect that the models match.
2156 model_->SortChildren(folder_added);
2157 ExpectModelMatch();
2160 // See what happens if we enable sync but then delete the "Sync Data"
2161 // folder.
2162 TEST_F(ProfileSyncServiceBookmarkTestWithData,
2163 RecoverAfterDeletingSyncDataDirectory) {
2164 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
2165 StartSync();
2167 WriteTestDataToBookmarkModel();
2169 StopSync();
2171 // Nuke the sync DB and reload.
2172 TearDown();
2173 SetUp();
2175 // First attempt fails due to a persistence error.
2176 EXPECT_TRUE(CreatePermanentBookmarkNodes());
2177 EXPECT_FALSE(AssociateModels());
2179 // Second attempt succeeds due to the previous error resetting the native
2180 // transaction version.
2181 model_associator_.reset();
2182 EXPECT_TRUE(CreatePermanentBookmarkNodes());
2183 EXPECT_TRUE(AssociateModels());
2185 // Make sure we're back in sync. In real life, the user would need
2186 // to reauthenticate before this happens, but in the test, authentication
2187 // is sidestepped.
2188 ExpectBookmarkModelMatchesTestData();
2189 ExpectModelMatch();
2192 // Verify that the bookmark model is updated about whether the
2193 // associator is currently running.
2194 TEST_F(ProfileSyncServiceBookmarkTest, AssociationState) {
2195 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2197 ExtensiveChangesBookmarkModelObserver observer;
2198 model_->AddObserver(&observer);
2200 StartSync();
2202 EXPECT_EQ(1, observer.get_started());
2203 EXPECT_EQ(0, observer.get_completed_count_at_started());
2204 EXPECT_EQ(1, observer.get_completed());
2206 model_->RemoveObserver(&observer);
2209 // Verify that the creation_time_us changes are applied in the local model at
2210 // association time and update time.
2211 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateDateAdded) {
2212 // TODO(stanisc): crbug.com/456876: Remove this once the optimistic
2213 // association experiment has ended.
2214 base::FieldTrialList field_trial_list(new base::MockEntropyProvider());
2215 base::FieldTrialList::CreateFieldTrial("SyncOptimisticBookmarkAssociation",
2216 "Enabled");
2218 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2219 WriteTestDataToBookmarkModel();
2221 // Start and stop sync in order to create bookmark nodes in the sync db.
2222 StartSync();
2223 StopSync();
2225 // Modify the date_added field of a bookmark so it doesn't match with
2226 // the sync data.
2227 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2228 int modified_index = 2;
2229 ASSERT_GT(bookmark_bar_node->child_count(), modified_index);
2230 const BookmarkNode* child_node = bookmark_bar_node->GetChild(modified_index);
2231 ASSERT_TRUE(child_node);
2232 EXPECT_TRUE(child_node->is_url());
2233 model_->SetDateAdded(child_node, base::Time::FromInternalValue(10));
2235 StartSync();
2236 StopSync();
2238 // Verify that transaction versions are in sync between the native model
2239 // and Sync.
2241 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2242 int64 sync_version = trans.GetModelVersion(syncer::BOOKMARKS);
2243 int64 native_version = model_->root_node()->sync_transaction_version();
2244 EXPECT_EQ(native_version, sync_version);
2247 // Since the version is in sync the association above should have skipped
2248 // updating the native node above. That is expected optimization (see
2249 // crbug/464907.
2250 EXPECT_EQ(child_node->date_added(), base::Time::FromInternalValue(10));
2252 // Reset transaction version on the native model to trigger conservative
2253 // association algorithm.
2254 model_->SetNodeSyncTransactionVersion(
2255 model_->root_node(), syncer::syncable::kInvalidTransactionVersion);
2257 StartSync();
2259 // Everything should be back in sync after model association.
2260 ExpectBookmarkModelMatchesTestData();
2261 ExpectModelMatch();
2263 // Now trigger a change while syncing. We add a new bookmark, sync it, then
2264 // updates it's creation time.
2265 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2266 FakeServerChange adds(&trans);
2267 const std::string kTitle = "Some site";
2268 const std::string kUrl = "http://www.whatwhat.yeah/";
2269 const int kCreationTime = 30;
2270 int64 id = adds.AddURL(kTitle, kUrl,
2271 bookmark_bar_id(), 0);
2272 adds.ApplyPendingChanges(change_processor_.get());
2273 FakeServerChange updates(&trans);
2274 updates.ModifyCreationTime(id, kCreationTime);
2275 updates.ApplyPendingChanges(change_processor_.get());
2277 const BookmarkNode* node = model_->bookmark_bar_node()->GetChild(0);
2278 ASSERT_TRUE(node);
2279 EXPECT_TRUE(node->is_url());
2280 EXPECT_EQ(base::UTF8ToUTF16(kTitle), node->GetTitle());
2281 EXPECT_EQ(kUrl, node->url().possibly_invalid_spec());
2282 EXPECT_EQ(node->date_added(), base::Time::FromInternalValue(30));
2285 // Tests that changes to the sync nodes meta info gets reflected in the local
2286 // bookmark model.
2287 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromSync) {
2288 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2289 WriteTestDataToBookmarkModel();
2290 StartSync();
2292 // Create bookmark nodes containing meta info.
2293 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2294 FakeServerChange adds(&trans);
2295 BookmarkNode::MetaInfoMap folder_meta_info;
2296 folder_meta_info["folder"] = "foldervalue";
2297 int64 folder_id = adds.AddFolderWithMetaInfo(
2298 "folder title", &folder_meta_info, bookmark_bar_id(), 0);
2299 BookmarkNode::MetaInfoMap node_meta_info;
2300 node_meta_info["node"] = "nodevalue";
2301 node_meta_info["other"] = "othervalue";
2302 int64 id = adds.AddURLWithMetaInfo("node title", "http://www.foo.com",
2303 &node_meta_info, folder_id, 0);
2304 adds.ApplyPendingChanges(change_processor_.get());
2306 // Verify that the nodes are created with the correct meta info.
2307 ASSERT_LT(0, model_->bookmark_bar_node()->child_count());
2308 const BookmarkNode* folder_node = model_->bookmark_bar_node()->GetChild(0);
2309 ASSERT_TRUE(folder_node->GetMetaInfoMap());
2310 EXPECT_EQ(folder_meta_info, *folder_node->GetMetaInfoMap());
2311 ASSERT_LT(0, folder_node->child_count());
2312 const BookmarkNode* node = folder_node->GetChild(0);
2313 ASSERT_TRUE(node->GetMetaInfoMap());
2314 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
2316 // Update meta info on nodes on server
2317 FakeServerChange updates(&trans);
2318 folder_meta_info.erase("folder");
2319 updates.ModifyMetaInfo(folder_id, folder_meta_info);
2320 node_meta_info["node"] = "changednodevalue";
2321 node_meta_info.erase("other");
2322 node_meta_info["newkey"] = "newkeyvalue";
2323 updates.ModifyMetaInfo(id, node_meta_info);
2324 updates.ApplyPendingChanges(change_processor_.get());
2326 // Confirm that the updated values are reflected in the bookmark nodes.
2327 EXPECT_FALSE(folder_node->GetMetaInfoMap());
2328 ASSERT_TRUE(node->GetMetaInfoMap());
2329 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
2332 // Tests that changes to the local bookmark nodes meta info gets reflected in
2333 // the sync nodes.
2334 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromModel) {
2335 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2336 WriteTestDataToBookmarkModel();
2337 StartSync();
2338 ExpectBookmarkModelMatchesTestData();
2340 const BookmarkNode* folder_node =
2341 model_->AddFolder(model_->bookmark_bar_node(), 0,
2342 base::ASCIIToUTF16("folder title"));
2343 const BookmarkNode* node = model_->AddURL(folder_node, 0,
2344 base::ASCIIToUTF16("node title"),
2345 GURL("http://www.foo.com"));
2346 ExpectModelMatch();
2348 // Add some meta info and verify sync model matches the changes.
2349 model_->SetNodeMetaInfo(folder_node, "folder", "foldervalue");
2350 model_->SetNodeMetaInfo(node, "node", "nodevalue");
2351 model_->SetNodeMetaInfo(node, "other", "othervalue");
2352 ExpectModelMatch();
2354 // Change/delete existing meta info and verify.
2355 model_->DeleteNodeMetaInfo(folder_node, "folder");
2356 model_->SetNodeMetaInfo(node, "node", "changednodevalue");
2357 model_->DeleteNodeMetaInfo(node, "other");
2358 model_->SetNodeMetaInfo(node, "newkey", "newkeyvalue");
2359 ExpectModelMatch();
2362 // Tests that node's specifics doesn't get unnecessarily overwritten (causing
2363 // a subsequent commit) when BookmarkChangeProcessor handles a notification
2364 // (such as BookmarkMetaInfoChanged) without an actual data change.
2365 TEST_F(ProfileSyncServiceBookmarkTestWithData, MetaInfoPreservedOnNonChange) {
2366 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2367 WriteTestDataToBookmarkModel();
2368 StartSync();
2370 std::string orig_specifics;
2371 int64 sync_id;
2372 const BookmarkNode* bookmark;
2374 // Create bookmark folder node containing meta info.
2376 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2377 FakeServerChange adds(&trans);
2379 int64 folder_id = adds.AddFolder("folder title", bookmark_bar_id(), 0);
2381 BookmarkNode::MetaInfoMap node_meta_info;
2382 node_meta_info["one"] = "1";
2383 node_meta_info["two"] = "2";
2384 node_meta_info["three"] = "3";
2386 sync_id = adds.AddURLWithMetaInfo("node title", "http://www.foo.com/",
2387 &node_meta_info, folder_id, 0);
2389 // Verify that the node propagates to the bookmark model
2390 adds.ApplyPendingChanges(change_processor_.get());
2392 bookmark = model_->bookmark_bar_node()->GetChild(0)->GetChild(0);
2393 EXPECT_EQ(node_meta_info, *bookmark->GetMetaInfoMap());
2395 syncer::ReadNode sync_node(&trans);
2396 EXPECT_EQ(BaseNode::INIT_OK, sync_node.InitByIdLookup(sync_id));
2397 orig_specifics = sync_node.GetBookmarkSpecifics().SerializeAsString();
2400 // Force change processor to update the sync node.
2401 change_processor_->BookmarkMetaInfoChanged(model_, bookmark);
2403 // Read bookmark specifics again and verify that there is no change.
2405 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2406 syncer::ReadNode sync_node(&trans);
2407 EXPECT_EQ(BaseNode::INIT_OK, sync_node.InitByIdLookup(sync_id));
2408 std::string new_specifics =
2409 sync_node.GetBookmarkSpecifics().SerializeAsString();
2410 ASSERT_EQ(orig_specifics, new_specifics);
2414 void ProfileSyncServiceBookmarkTestWithData::GetTransactionVersions(
2415 const BookmarkNode* root,
2416 BookmarkNodeVersionMap* node_versions) {
2417 node_versions->clear();
2418 std::queue<const BookmarkNode*> nodes;
2419 nodes.push(root);
2420 while (!nodes.empty()) {
2421 const BookmarkNode* n = nodes.front();
2422 nodes.pop();
2424 int64 version = n->sync_transaction_version();
2425 EXPECT_NE(BookmarkNode::kInvalidSyncTransactionVersion, version);
2427 (*node_versions)[n->id()] = version;
2428 for (int i = 0; i < n->child_count(); ++i) {
2429 if (!CanSyncNode(n->GetChild(i)))
2430 continue;
2431 nodes.push(n->GetChild(i));
2436 void ProfileSyncServiceBookmarkTestWithData::ExpectTransactionVersionMatch(
2437 const BookmarkNode* node,
2438 const BookmarkNodeVersionMap& version_expected) {
2439 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2441 BookmarkNodeVersionMap bnodes_versions;
2442 GetTransactionVersions(node, &bnodes_versions);
2443 for (BookmarkNodeVersionMap::const_iterator it = bnodes_versions.begin();
2444 it != bnodes_versions.end(); ++it) {
2445 syncer::ReadNode sync_node(&trans);
2446 ASSERT_TRUE(model_associator_->InitSyncNodeFromChromeId(it->first,
2447 &sync_node));
2448 EXPECT_EQ(sync_node.GetEntry()->GetTransactionVersion(), it->second);
2449 BookmarkNodeVersionMap::const_iterator expected_ver_it =
2450 version_expected.find(it->first);
2451 if (expected_ver_it != version_expected.end())
2452 EXPECT_EQ(expected_ver_it->second, it->second);
2456 // Test transaction versions of model and nodes are incremented after changes
2457 // are applied.
2458 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateTransactionVersion) {
2459 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2460 StartSync();
2461 WriteTestDataToBookmarkModel();
2462 base::MessageLoop::current()->RunUntilIdle();
2464 BookmarkNodeVersionMap initial_versions;
2466 // Verify transaction versions in sync model and bookmark model (saved as
2467 // transaction version of root node) are equal after
2468 // WriteTestDataToBookmarkModel() created bookmarks.
2470 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2471 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2472 GetTransactionVersions(model_->root_node(), &initial_versions);
2473 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2474 initial_versions[model_->root_node()->id()]);
2476 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2477 BookmarkNodeVersionMap());
2478 ExpectTransactionVersionMatch(model_->other_node(),
2479 BookmarkNodeVersionMap());
2480 ExpectTransactionVersionMatch(model_->mobile_node(),
2481 BookmarkNodeVersionMap());
2483 // Verify model version is incremented and bookmark node versions remain
2484 // the same.
2485 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
2486 model_->Remove(bookmark_bar->GetChild(0));
2487 base::MessageLoop::current()->RunUntilIdle();
2488 BookmarkNodeVersionMap new_versions;
2489 GetTransactionVersions(model_->root_node(), &new_versions);
2490 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 1,
2491 new_versions[model_->root_node()->id()]);
2492 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2493 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2494 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2496 // Verify model version and version of changed bookmark are incremented and
2497 // versions of others remain same.
2498 const BookmarkNode* changed_bookmark =
2499 model_->bookmark_bar_node()->GetChild(0);
2500 model_->SetTitle(changed_bookmark, base::ASCIIToUTF16("test"));
2501 base::MessageLoop::current()->RunUntilIdle();
2502 GetTransactionVersions(model_->root_node(), &new_versions);
2503 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 2,
2504 new_versions[model_->root_node()->id()]);
2505 EXPECT_LT(initial_versions[changed_bookmark->id()],
2506 new_versions[changed_bookmark->id()]);
2507 initial_versions.erase(changed_bookmark->id());
2508 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2509 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2510 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2513 // Test that sync persistence errors are detected and trigger a failed
2514 // association.
2515 TEST_F(ProfileSyncServiceBookmarkTestWithData, PersistenceError) {
2516 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2517 StartSync();
2518 WriteTestDataToBookmarkModel();
2519 base::MessageLoop::current()->RunUntilIdle();
2521 BookmarkNodeVersionMap initial_versions;
2523 // Verify transaction versions in sync model and bookmark model (saved as
2524 // transaction version of root node) are equal after
2525 // WriteTestDataToBookmarkModel() created bookmarks.
2527 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2528 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2529 GetTransactionVersions(model_->root_node(), &initial_versions);
2530 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2531 initial_versions[model_->root_node()->id()]);
2533 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2534 BookmarkNodeVersionMap());
2535 ExpectTransactionVersionMatch(model_->other_node(),
2536 BookmarkNodeVersionMap());
2537 ExpectTransactionVersionMatch(model_->mobile_node(),
2538 BookmarkNodeVersionMap());
2540 // Now shut down sync and artificially increment the native model's version.
2541 StopSync();
2542 int64 root_version = initial_versions[model_->root_node()->id()];
2543 model_->SetNodeSyncTransactionVersion(model_->root_node(), root_version + 1);
2545 // Upon association, bookmarks should fail to associate.
2546 EXPECT_FALSE(AssociateModels());
2549 // It's possible for update/add calls from the bookmark model to be out of
2550 // order, or asynchronous. Handle that without triggering an error.
2551 TEST_F(ProfileSyncServiceBookmarkTest, UpdateThenAdd) {
2552 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2553 StartSync();
2555 EXPECT_TRUE(other_bookmarks_id());
2556 EXPECT_TRUE(bookmark_bar_id());
2557 EXPECT_TRUE(mobile_bookmarks_id());
2559 ExpectModelMatch();
2561 // Now destroy the change processor then add a bookmark, to simulate
2562 // missing the Update call.
2563 change_processor_.reset();
2564 const BookmarkNode* node = model_->AddURL(model_->bookmark_bar_node(),
2566 base::ASCIIToUTF16("title"),
2567 GURL("http://www.url.com"));
2569 // Recreate the change processor then update that bookmark. Sync should
2570 // receive the update call and gracefully treat that as if it were an add.
2571 change_processor_.reset(new BookmarkChangeProcessor(
2572 &profile_, model_associator_.get(), &mock_error_handler_));
2573 change_processor_->Start(test_user_share_.user_share());
2574 model_->SetTitle(node, base::ASCIIToUTF16("title2"));
2575 ExpectModelMatch();
2577 // Then simulate the add call arriving late.
2578 change_processor_->BookmarkNodeAdded(model_, model_->bookmark_bar_node(), 0);
2579 ExpectModelMatch();
2582 // Verify operations on native nodes that shouldn't be propagated to Sync.
2583 TEST_F(ProfileSyncServiceBookmarkTest, TestUnsupportedNodes) {
2584 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2585 StartSync();
2587 // Initial number of bookmarks on the sync side.
2588 int sync_bookmark_count = GetSyncBookmarkCount();
2590 // Create a bookmark under managed_node() permanent folder.
2591 bookmarks::ManagedBookmarkService* managed_bookmark_service =
2592 ManagedBookmarkServiceFactory::GetForProfile(&profile_);
2593 const BookmarkNode* folder = managed_bookmark_service->managed_node();
2594 const BookmarkNode* node = model_->AddURL(
2595 folder, 0, base::ASCIIToUTF16("node"), GURL("http://www.node.com/"));
2597 // Verify that these changes are ignored by Sync.
2598 EXPECT_EQ(sync_bookmark_count, GetSyncBookmarkCount());
2599 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
2600 EXPECT_EQ(syncer::kInvalidId, sync_id);
2602 // Verify that Sync ignores deleting this node.
2603 model_->Remove(node);
2604 EXPECT_EQ(sync_bookmark_count, GetSyncBookmarkCount());
2607 } // namespace
2609 } // namespace browser_sync