[sql] Remove _HAS_EXCEPTIONS=0 from build info.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service_bookmark_unittest.cc
blobd1493bad27a6c42c386e9620b9f4913ed3c5262d
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/internal_api/public/change_record.h"
43 #include "sync/internal_api/public/read_node.h"
44 #include "sync/internal_api/public/read_transaction.h"
45 #include "sync/internal_api/public/test/test_user_share.h"
46 #include "sync/internal_api/public/write_node.h"
47 #include "sync/internal_api/public/write_transaction.h"
48 #include "sync/internal_api/syncapi_internal.h"
49 #include "sync/syncable/mutable_entry.h"
50 #include "sync/syncable/syncable_id.h"
51 #include "sync/syncable/syncable_util.h"
52 #include "sync/syncable/syncable_write_transaction.h"
53 #include "testing/gmock/include/gmock/gmock.h"
54 #include "testing/gtest/include/gtest/gtest.h"
56 namespace browser_sync {
58 using bookmarks::BookmarkModel;
59 using bookmarks::BookmarkNode;
60 using syncer::BaseNode;
61 using testing::_;
62 using testing::InvokeWithoutArgs;
63 using testing::Mock;
64 using testing::Return;
65 using testing::StrictMock;
67 #if defined(OS_ANDROID) || defined(OS_IOS)
68 static const bool kExpectMobileBookmarks = true;
69 #else
70 static const bool kExpectMobileBookmarks = false;
71 #endif // defined(OS_ANDROID) || defined(OS_IOS)
73 namespace {
75 void MakeServerUpdate(syncer::WriteTransaction* trans,
76 syncer::WriteNode* node) {
77 syncer::syncable::ChangeEntryIDAndUpdateChildren(
78 trans->GetWrappedWriteTrans(), node->GetMutableEntryForTest(),
79 syncer::syncable::Id::CreateFromServerId(
80 base::Int64ToString(node->GetId())));
81 node->GetMutableEntryForTest()->PutBaseVersion(10);
82 node->GetMutableEntryForTest()->PutIsUnappliedUpdate(true);
85 void MakeServerUpdate(syncer::WriteTransaction* trans, int64 id) {
86 syncer::WriteNode node(trans);
87 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
88 MakeServerUpdate(trans, &node);
91 // FakeServerChange constructs a list of syncer::ChangeRecords while modifying
92 // the sync model, and can pass the ChangeRecord list to a
93 // syncer::SyncObserver (i.e., the ProfileSyncService) to test the client
94 // change-application behavior.
95 // Tests using FakeServerChange should be careful to avoid back-references,
96 // since FakeServerChange will send the edits in the order specified.
97 class FakeServerChange {
98 public:
99 explicit FakeServerChange(syncer::WriteTransaction* trans) : trans_(trans) {
102 // Pretend that the server told the syncer to add a bookmark object.
103 int64 AddWithMetaInfo(const std::string& title,
104 const std::string& url,
105 const BookmarkNode::MetaInfoMap* meta_info_map,
106 bool is_folder,
107 int64 parent_id,
108 int64 predecessor_id) {
109 syncer::ReadNode parent(trans_);
110 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
111 syncer::WriteNode node(trans_);
112 if (predecessor_id == 0) {
113 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
114 } else {
115 syncer::ReadNode predecessor(trans_);
116 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
117 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
118 EXPECT_TRUE(node.InitBookmarkByCreation(parent, &predecessor));
120 EXPECT_EQ(node.GetPredecessorId(), predecessor_id);
121 EXPECT_EQ(node.GetParentId(), parent_id);
122 node.SetIsFolder(is_folder);
123 node.SetTitle(title);
125 sync_pb::BookmarkSpecifics specifics(node.GetBookmarkSpecifics());
126 const base::Time creation_time(base::Time::Now());
127 specifics.set_creation_time_us(creation_time.ToInternalValue());
128 if (!is_folder)
129 specifics.set_url(url);
130 if (meta_info_map)
131 SetNodeMetaInfo(*meta_info_map, &specifics);
132 node.SetBookmarkSpecifics(specifics);
134 syncer::ChangeRecord record;
135 record.action = syncer::ChangeRecord::ACTION_ADD;
136 record.id = node.GetId();
137 changes_.push_back(record);
138 return node.GetId();
141 int64 Add(const std::string& title,
142 const std::string& url,
143 bool is_folder,
144 int64 parent_id,
145 int64 predecessor_id) {
146 return AddWithMetaInfo(title, url, NULL, is_folder, parent_id,
147 predecessor_id);
150 // Add a bookmark folder.
151 int64 AddFolder(const std::string& title,
152 int64 parent_id,
153 int64 predecessor_id) {
154 return Add(title, std::string(), true, parent_id, predecessor_id);
156 int64 AddFolderWithMetaInfo(const std::string& title,
157 const BookmarkNode::MetaInfoMap* meta_info_map,
158 int64 parent_id,
159 int64 predecessor_id) {
160 return AddWithMetaInfo(title, std::string(), meta_info_map, true, parent_id,
161 predecessor_id);
164 // Add a bookmark.
165 int64 AddURL(const std::string& title,
166 const std::string& url,
167 int64 parent_id,
168 int64 predecessor_id) {
169 return Add(title, url, false, parent_id, predecessor_id);
171 int64 AddURLWithMetaInfo(const std::string& title,
172 const std::string& url,
173 const BookmarkNode::MetaInfoMap* meta_info_map,
174 int64 parent_id,
175 int64 predecessor_id) {
176 return AddWithMetaInfo(title, url, meta_info_map, false, parent_id,
177 predecessor_id);
180 // Pretend that the server told the syncer to delete an object.
181 void Delete(int64 id) {
183 // Delete the sync node.
184 syncer::WriteNode node(trans_);
185 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
186 if (node.GetIsFolder())
187 EXPECT_FALSE(node.GetFirstChildId());
188 node.GetMutableEntryForTest()->PutServerIsDel(true);
189 node.Tombstone();
192 // Verify the deletion.
193 syncer::ReadNode node(trans_);
194 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL, node.InitByIdLookup(id));
197 syncer::ChangeRecord record;
198 record.action = syncer::ChangeRecord::ACTION_DELETE;
199 record.id = id;
200 // Deletions are always first in the changelist, but we can't actually do
201 // WriteNode::Remove() on the node until its children are moved. So, as
202 // a practical matter, users of FakeServerChange must move or delete
203 // children before parents. Thus, we must insert the deletion record
204 // at the front of the vector.
205 changes_.insert(changes_.begin(), record);
208 // Set a new title value, and return the old value.
209 std::string ModifyTitle(int64 id, const std::string& new_title) {
210 syncer::WriteNode node(trans_);
211 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
212 std::string old_title = node.GetTitle();
213 node.SetTitle(new_title);
214 SetModified(id);
215 return old_title;
218 // Set a new parent and predecessor value. Return the old parent id.
219 // We could return the old predecessor id, but it turns out not to be
220 // very useful for assertions.
221 int64 ModifyPosition(int64 id, int64 parent_id, int64 predecessor_id) {
222 syncer::ReadNode parent(trans_);
223 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
224 syncer::WriteNode node(trans_);
225 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
226 int64 old_parent_id = node.GetParentId();
227 if (predecessor_id == 0) {
228 EXPECT_TRUE(node.SetPosition(parent, NULL));
229 } else {
230 syncer::ReadNode predecessor(trans_);
231 EXPECT_EQ(BaseNode::INIT_OK, predecessor.InitByIdLookup(predecessor_id));
232 EXPECT_EQ(predecessor.GetParentId(), parent.GetId());
233 EXPECT_TRUE(node.SetPosition(parent, &predecessor));
235 SetModified(id);
236 return old_parent_id;
239 void ModifyCreationTime(int64 id, int64 creation_time_us) {
240 syncer::WriteNode node(trans_);
241 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
242 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
243 specifics.set_creation_time_us(creation_time_us);
244 node.SetBookmarkSpecifics(specifics);
245 SetModified(id);
248 void ModifyMetaInfo(int64 id,
249 const BookmarkNode::MetaInfoMap& meta_info_map) {
250 syncer::WriteNode node(trans_);
251 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
252 sync_pb::BookmarkSpecifics specifics = node.GetBookmarkSpecifics();
253 SetNodeMetaInfo(meta_info_map, &specifics);
254 node.SetBookmarkSpecifics(specifics);
255 SetModified(id);
258 // Pass the fake change list to |service|.
259 void ApplyPendingChanges(sync_driver::ChangeProcessor* processor) {
260 processor->ApplyChangesFromSyncModel(
261 trans_, 0, syncer::ImmutableChangeRecordList(&changes_));
264 const syncer::ChangeRecordList& changes() {
265 return changes_;
268 private:
269 // Helper function to push an ACTION_UPDATE record onto the back
270 // of the changelist.
271 void SetModified(int64 id) {
272 // Coalesce multi-property edits.
273 if (!changes_.empty() && changes_.back().id == id &&
274 changes_.back().action ==
275 syncer::ChangeRecord::ACTION_UPDATE)
276 return;
277 syncer::ChangeRecord record;
278 record.action = syncer::ChangeRecord::ACTION_UPDATE;
279 record.id = id;
280 changes_.push_back(record);
283 void SetNodeMetaInfo(const BookmarkNode::MetaInfoMap& meta_info_map,
284 sync_pb::BookmarkSpecifics* specifics) {
285 specifics->clear_meta_info();
286 // Deliberatly set MetaInfoMap entries in opposite order (compared
287 // to the implementation in BookmarkChangeProcessor) to ensure that
288 // (a) the implementation isn't sensitive to the order and
289 // (b) the original meta info isn't blindly overwritten by
290 // BookmarkChangeProcessor unless there is a real change.
291 BookmarkNode::MetaInfoMap::const_iterator it = meta_info_map.end();
292 while (it != meta_info_map.begin()) {
293 --it;
294 sync_pb::MetaInfo* meta_info = specifics->add_meta_info();
295 meta_info->set_key(it->first);
296 meta_info->set_value(it->second);
300 // The transaction on which everything happens.
301 syncer::WriteTransaction *trans_;
303 // The change list we construct.
304 syncer::ChangeRecordList changes_;
307 class ExtensiveChangesBookmarkModelObserver
308 : public bookmarks::BaseBookmarkModelObserver {
309 public:
310 ExtensiveChangesBookmarkModelObserver()
311 : started_count_(0),
312 completed_count_at_started_(0),
313 completed_count_(0) {}
315 void ExtensiveBookmarkChangesBeginning(BookmarkModel* model) override {
316 ++started_count_;
317 completed_count_at_started_ = completed_count_;
320 void ExtensiveBookmarkChangesEnded(BookmarkModel* model) override {
321 ++completed_count_;
324 void BookmarkModelChanged() override {}
326 int get_started() const {
327 return started_count_;
330 int get_completed_count_at_started() const {
331 return completed_count_at_started_;
334 int get_completed() const {
335 return completed_count_;
338 private:
339 int started_count_;
340 int completed_count_at_started_;
341 int completed_count_;
343 DISALLOW_COPY_AND_ASSIGN(ExtensiveChangesBookmarkModelObserver);
347 class ProfileSyncServiceBookmarkTest : public testing::Test {
348 protected:
349 enum LoadOption { LOAD_FROM_STORAGE, DELETE_EXISTING_STORAGE };
350 enum SaveOption { SAVE_TO_STORAGE, DONT_SAVE_TO_STORAGE };
352 ProfileSyncServiceBookmarkTest()
353 : model_(NULL),
354 local_merge_result_(syncer::BOOKMARKS),
355 syncer_merge_result_(syncer::BOOKMARKS) {}
357 virtual ~ProfileSyncServiceBookmarkTest() {
358 StopSync();
359 UnloadBookmarkModel();
362 virtual void SetUp() {
363 test_user_share_.SetUp();
366 virtual void TearDown() {
367 test_user_share_.TearDown();
370 bool CanSyncNode(const BookmarkNode* node) {
371 return model_->client()->CanSyncNode(node);
374 // Inserts a folder directly to the share.
375 // Do not use this after model association is complete.
377 // This function differs from the AddFolder() function declared elsewhere in
378 // this file in that it only affects the sync model. It would be invalid to
379 // change the sync model directly after ModelAssociation. This function can
380 // be invoked prior to model association to set up first-time sync model
381 // association scenarios.
382 int64 AddFolderToShare(syncer::WriteTransaction* trans, std::string title) {
383 EXPECT_FALSE(model_associator_);
385 // Be sure to call CreatePermanentBookmarkNodes(), otherwise this will fail.
386 syncer::ReadNode bookmark_bar(trans);
387 EXPECT_EQ(BaseNode::INIT_OK,
388 bookmark_bar.InitByTagLookupForBookmarks("bookmark_bar"));
390 syncer::WriteNode node(trans);
391 EXPECT_TRUE(node.InitBookmarkByCreation(bookmark_bar, NULL));
392 node.SetIsFolder(true);
393 node.SetTitle(title);
395 return node.GetId();
398 // Inserts a bookmark directly to the share.
399 // Do not use this after model association is complete.
401 // This function differs from the AddURL() function declared elsewhere in this
402 // file in that it only affects the sync model. It would be invalid to change
403 // the sync model directly after ModelAssociation. This function can be
404 // invoked prior to model association to set up first-time sync model
405 // association scenarios.
406 int64 AddBookmarkToShare(syncer::WriteTransaction* trans,
407 int64 parent_id,
408 const std::string& title,
409 const std::string& url) {
410 EXPECT_FALSE(model_associator_);
412 syncer::ReadNode parent(trans);
413 EXPECT_EQ(BaseNode::INIT_OK, parent.InitByIdLookup(parent_id));
415 sync_pb::BookmarkSpecifics specifics;
416 specifics.set_url(url);
417 specifics.set_title(title);
419 syncer::WriteNode node(trans);
420 EXPECT_TRUE(node.InitBookmarkByCreation(parent, NULL));
421 node.SetIsFolder(false);
422 node.SetTitle(title);
423 node.SetBookmarkSpecifics(specifics);
425 return node.GetId();
428 // Load (or re-load) the bookmark model. |load| controls use of the
429 // bookmarks file on disk. |save| controls whether the newly loaded
430 // bookmark model will write out a bookmark file as it goes.
431 void LoadBookmarkModel(LoadOption load, SaveOption save) {
432 bool delete_bookmarks = load == DELETE_EXISTING_STORAGE;
433 profile_.CreateBookmarkModel(delete_bookmarks);
434 model_ = BookmarkModelFactory::GetForProfile(&profile_);
435 bookmarks::test::WaitForBookmarkModelToLoad(model_);
436 // This noticeably speeds up the unit tests that request it.
437 if (save == DONT_SAVE_TO_STORAGE)
438 model_->ClearStore();
439 base::MessageLoop::current()->RunUntilIdle();
442 int GetSyncBookmarkCount() {
443 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
444 syncer::ReadNode node(&trans);
445 if (node.InitTypeRoot(syncer::BOOKMARKS) != syncer::BaseNode::INIT_OK)
446 return 0;
447 return node.GetTotalNodeCount();
450 // Creates the bookmark root node and the permanent nodes if they don't
451 // already exist.
452 bool CreatePermanentBookmarkNodes() {
453 bool root_exists = false;
454 syncer::ModelType type = syncer::BOOKMARKS;
456 syncer::WriteTransaction trans(FROM_HERE,
457 test_user_share_.user_share());
458 syncer::ReadNode uber_root(&trans);
459 uber_root.InitByRootLookup();
461 syncer::ReadNode root(&trans);
462 root_exists = (root.InitTypeRoot(type) == BaseNode::INIT_OK);
465 if (!root_exists) {
466 if (!syncer::TestUserShare::CreateRoot(type,
467 test_user_share_.user_share()))
468 return false;
471 const int kNumPermanentNodes = 3;
472 const std::string permanent_tags[kNumPermanentNodes] = {
473 #if defined(OS_IOS) || defined(OS_ANDROID)
474 "synced_bookmarks",
475 #endif // defined(OS_IOS) || defined(OS_ANDROID)
476 "bookmark_bar",
477 "other_bookmarks",
478 #if !defined(OS_IOS) && !defined(OS_ANDROID)
479 "synced_bookmarks",
480 #endif // !defined(OS_IOS) && !defined(OS_ANDROID)
482 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
483 syncer::ReadNode root(&trans);
484 EXPECT_EQ(BaseNode::INIT_OK, root.InitTypeRoot(type));
486 // Loop through creating permanent nodes as necessary.
487 int64 last_child_id = syncer::kInvalidId;
488 for (int i = 0; i < kNumPermanentNodes; ++i) {
489 // First check if the node already exists. This is for tests that involve
490 // persistence and set up sync more than once.
491 syncer::ReadNode lookup(&trans);
492 if (lookup.InitByTagLookupForBookmarks(permanent_tags[i]) ==
493 syncer::ReadNode::INIT_OK) {
494 last_child_id = lookup.GetId();
495 continue;
498 // If it doesn't exist, create the permanent node at the end of the
499 // ordering.
500 syncer::ReadNode predecessor_node(&trans);
501 syncer::ReadNode* predecessor = NULL;
502 if (last_child_id != syncer::kInvalidId) {
503 EXPECT_EQ(BaseNode::INIT_OK,
504 predecessor_node.InitByIdLookup(last_child_id));
505 predecessor = &predecessor_node;
507 syncer::WriteNode node(&trans);
508 if (!node.InitBookmarkByCreation(root, predecessor))
509 return false;
510 node.SetIsFolder(true);
511 node.GetMutableEntryForTest()->PutUniqueServerTag(permanent_tags[i]);
512 node.SetTitle(permanent_tags[i]);
513 node.SetExternalId(0);
514 last_child_id = node.GetId();
516 return true;
519 bool AssociateModels() {
520 DCHECK(!model_associator_);
522 // Set up model associator.
523 model_associator_.reset(new BookmarkModelAssociator(
524 BookmarkModelFactory::GetForProfile(&profile_),
525 &profile_,
526 test_user_share_.user_share(),
527 &mock_error_handler_,
528 kExpectMobileBookmarks));
530 local_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
531 syncer_merge_result_ = syncer::SyncMergeResult(syncer::BOOKMARKS);
532 int local_count_before = model_->root_node()->GetTotalNodeCount();
533 int syncer_count_before = GetSyncBookmarkCount();
535 syncer::SyncError error = model_associator_->AssociateModels(
536 &local_merge_result_,
537 &syncer_merge_result_);
538 if (error.IsSet())
539 return false;
541 base::MessageLoop::current()->RunUntilIdle();
543 // Verify the merge results were calculated properly.
544 EXPECT_EQ(local_count_before,
545 local_merge_result_.num_items_before_association());
546 EXPECT_EQ(syncer_count_before,
547 syncer_merge_result_.num_items_before_association());
548 EXPECT_EQ(local_merge_result_.num_items_after_association(),
549 local_merge_result_.num_items_before_association() +
550 local_merge_result_.num_items_added() -
551 local_merge_result_.num_items_deleted());
552 EXPECT_EQ(syncer_merge_result_.num_items_after_association(),
553 syncer_merge_result_.num_items_before_association() +
554 syncer_merge_result_.num_items_added() -
555 syncer_merge_result_.num_items_deleted());
556 EXPECT_EQ(model_->root_node()->GetTotalNodeCount(),
557 local_merge_result_.num_items_after_association());
558 EXPECT_EQ(GetSyncBookmarkCount(),
559 syncer_merge_result_.num_items_after_association());
560 return true;
563 void StartSync() {
564 test_user_share_.Reload();
566 ASSERT_TRUE(CreatePermanentBookmarkNodes());
567 ASSERT_TRUE(AssociateModels());
569 // Set up change processor.
570 change_processor_.reset(
571 new BookmarkChangeProcessor(&profile_,
572 model_associator_.get(),
573 &mock_error_handler_));
574 change_processor_->Start(test_user_share_.user_share());
577 void StopSync() {
578 change_processor_.reset();
579 if (model_associator_) {
580 syncer::SyncError error = model_associator_->DisassociateModels();
581 EXPECT_FALSE(error.IsSet());
583 model_associator_.reset();
585 base::MessageLoop::current()->RunUntilIdle();
587 // TODO(akalin): Actually close the database and flush it to disk
588 // (and make StartSync reload from disk). This would require
589 // refactoring TestUserShare.
592 void UnloadBookmarkModel() {
593 profile_.CreateBookmarkModel(false /* delete_bookmarks */);
594 model_ = NULL;
595 base::MessageLoop::current()->RunUntilIdle();
598 bool InitSyncNodeFromChromeNode(const BookmarkNode* bnode,
599 syncer::BaseNode* sync_node) {
600 return model_associator_->InitSyncNodeFromChromeId(bnode->id(),
601 sync_node);
604 void ExpectSyncerNodeMatching(syncer::BaseTransaction* trans,
605 const BookmarkNode* bnode) {
606 std::string truncated_title = base::UTF16ToUTF8(bnode->GetTitle());
607 syncer::SyncAPINameToServerName(truncated_title, &truncated_title);
608 base::TruncateUTF8ToByteSize(truncated_title, 255, &truncated_title);
609 syncer::ServerNameToSyncAPIName(truncated_title, &truncated_title);
611 syncer::ReadNode gnode(trans);
612 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnode, &gnode));
613 // Non-root node titles and parents must match.
614 if (!model_->is_permanent_node(bnode)) {
615 EXPECT_EQ(truncated_title, gnode.GetTitle());
616 EXPECT_EQ(
617 model_associator_->GetChromeNodeFromSyncId(gnode.GetParentId()),
618 bnode->parent());
620 EXPECT_EQ(bnode->is_folder(), gnode.GetIsFolder());
621 if (bnode->is_url())
622 EXPECT_EQ(bnode->url(), GURL(gnode.GetBookmarkSpecifics().url()));
624 // Check that meta info matches.
625 const BookmarkNode::MetaInfoMap* meta_info_map = bnode->GetMetaInfoMap();
626 sync_pb::BookmarkSpecifics specifics = gnode.GetBookmarkSpecifics();
627 if (!meta_info_map) {
628 EXPECT_EQ(0, specifics.meta_info_size());
629 } else {
630 EXPECT_EQ(meta_info_map->size(),
631 static_cast<size_t>(specifics.meta_info_size()));
632 for (int i = 0; i < specifics.meta_info_size(); i++) {
633 BookmarkNode::MetaInfoMap::const_iterator it =
634 meta_info_map->find(specifics.meta_info(i).key());
635 EXPECT_TRUE(it != meta_info_map->end());
636 EXPECT_EQ(it->second, specifics.meta_info(i).value());
640 // Check for position matches.
641 int browser_index = bnode->parent()->GetIndexOf(bnode);
642 if (browser_index == 0) {
643 EXPECT_EQ(gnode.GetPredecessorId(), 0);
644 } else {
645 const BookmarkNode* bprev =
646 bnode->parent()->GetChild(browser_index - 1);
647 syncer::ReadNode gprev(trans);
648 ASSERT_TRUE(InitSyncNodeFromChromeNode(bprev, &gprev));
649 EXPECT_EQ(gnode.GetPredecessorId(), gprev.GetId());
650 EXPECT_EQ(gnode.GetParentId(), gprev.GetParentId());
652 // Note: the managed node is the last child of the root_node but isn't
653 // synced; if CanSyncNode() is false then there is no next node to sync.
654 const BookmarkNode* bnext = NULL;
655 if (browser_index + 1 < bnode->parent()->child_count())
656 bnext = bnode->parent()->GetChild(browser_index + 1);
657 if (!bnext || !CanSyncNode(bnext)) {
658 EXPECT_EQ(gnode.GetSuccessorId(), 0);
659 } else {
660 syncer::ReadNode gnext(trans);
661 ASSERT_TRUE(InitSyncNodeFromChromeNode(bnext, &gnext));
662 EXPECT_EQ(gnode.GetSuccessorId(), gnext.GetId());
663 EXPECT_EQ(gnode.GetParentId(), gnext.GetParentId());
665 if (!bnode->empty())
666 EXPECT_TRUE(gnode.GetFirstChildId());
669 void ExpectSyncerNodeMatching(const BookmarkNode* bnode) {
670 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
671 ExpectSyncerNodeMatching(&trans, bnode);
674 void ExpectBrowserNodeMatching(syncer::BaseTransaction* trans,
675 int64 sync_id) {
676 EXPECT_TRUE(sync_id);
677 const BookmarkNode* bnode =
678 model_associator_->GetChromeNodeFromSyncId(sync_id);
679 ASSERT_TRUE(bnode);
680 ASSERT_TRUE(CanSyncNode(bnode));
682 int64 id = model_associator_->GetSyncIdFromChromeId(bnode->id());
683 EXPECT_EQ(id, sync_id);
684 ExpectSyncerNodeMatching(trans, bnode);
687 void ExpectBrowserNodeUnknown(int64 sync_id) {
688 EXPECT_FALSE(model_associator_->GetChromeNodeFromSyncId(sync_id));
691 void ExpectBrowserNodeKnown(int64 sync_id) {
692 EXPECT_TRUE(model_associator_->GetChromeNodeFromSyncId(sync_id));
695 void ExpectSyncerNodeKnown(const BookmarkNode* node) {
696 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
697 EXPECT_NE(sync_id, syncer::kInvalidId);
700 void ExpectSyncerNodeUnknown(const BookmarkNode* node) {
701 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
702 EXPECT_EQ(sync_id, syncer::kInvalidId);
705 void ExpectBrowserNodeTitle(int64 sync_id, const std::string& title) {
706 const BookmarkNode* bnode =
707 model_associator_->GetChromeNodeFromSyncId(sync_id);
708 ASSERT_TRUE(bnode);
709 EXPECT_EQ(bnode->GetTitle(), base::UTF8ToUTF16(title));
712 void ExpectBrowserNodeURL(int64 sync_id, const std::string& url) {
713 const BookmarkNode* bnode =
714 model_associator_->GetChromeNodeFromSyncId(sync_id);
715 ASSERT_TRUE(bnode);
716 EXPECT_EQ(GURL(url), bnode->url());
719 void ExpectBrowserNodeParent(int64 sync_id, int64 parent_sync_id) {
720 const BookmarkNode* node =
721 model_associator_->GetChromeNodeFromSyncId(sync_id);
722 ASSERT_TRUE(node);
723 const BookmarkNode* parent =
724 model_associator_->GetChromeNodeFromSyncId(parent_sync_id);
725 EXPECT_TRUE(parent);
726 EXPECT_EQ(node->parent(), parent);
729 void ExpectModelMatch(syncer::BaseTransaction* trans) {
730 const BookmarkNode* root = model_->root_node();
731 #if defined(OS_IOS) || defined(OS_ANDROID)
732 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 0);
733 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 1);
734 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 2);
735 #else
736 EXPECT_EQ(root->GetIndexOf(model_->bookmark_bar_node()), 0);
737 EXPECT_EQ(root->GetIndexOf(model_->other_node()), 1);
738 EXPECT_EQ(root->GetIndexOf(model_->mobile_node()), 2);
739 #endif // defined(OS_IOS) || defined(OS_ANDROID)
741 std::stack<int64> stack;
742 stack.push(bookmark_bar_id());
743 while (!stack.empty()) {
744 int64 id = stack.top();
745 stack.pop();
746 if (!id) continue;
748 ExpectBrowserNodeMatching(trans, id);
750 syncer::ReadNode gnode(trans);
751 ASSERT_EQ(BaseNode::INIT_OK, gnode.InitByIdLookup(id));
752 stack.push(gnode.GetSuccessorId());
753 if (gnode.GetIsFolder())
754 stack.push(gnode.GetFirstChildId());
758 void ExpectModelMatch() {
759 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
760 ExpectModelMatch(&trans);
763 int64 mobile_bookmarks_id() {
764 return
765 model_associator_->GetSyncIdFromChromeId(model_->mobile_node()->id());
768 int64 other_bookmarks_id() {
769 return
770 model_associator_->GetSyncIdFromChromeId(model_->other_node()->id());
773 int64 bookmark_bar_id() {
774 return model_associator_->GetSyncIdFromChromeId(
775 model_->bookmark_bar_node()->id());
778 private:
779 content::TestBrowserThreadBundle thread_bundle_;
781 protected:
782 TestingProfile profile_;
783 BookmarkModel* model_;
784 syncer::TestUserShare test_user_share_;
785 scoped_ptr<BookmarkChangeProcessor> change_processor_;
786 StrictMock<sync_driver::DataTypeErrorHandlerMock> mock_error_handler_;
787 scoped_ptr<BookmarkModelAssociator> model_associator_;
789 private:
790 syncer::SyncMergeResult local_merge_result_;
791 syncer::SyncMergeResult syncer_merge_result_;
794 TEST_F(ProfileSyncServiceBookmarkTest, InitialState) {
795 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
796 StartSync();
798 EXPECT_TRUE(other_bookmarks_id());
799 EXPECT_TRUE(bookmark_bar_id());
800 EXPECT_TRUE(mobile_bookmarks_id());
802 ExpectModelMatch();
805 // Populate the sync database then start model association. Sync's bookmarks
806 // should end up being copied into the native model, resulting in a successful
807 // "ExpectModelMatch()".
809 // This code has some use for verifying correctness. It's also a very useful
810 // for profiling bookmark ModelAssociation, an important part of some first-time
811 // sync scenarios. Simply increase the kNumFolders and kNumBookmarksPerFolder
812 // as desired, then run the test under a profiler to find hot spots in the model
813 // association code.
814 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociate) {
815 const int kNumBookmarksPerFolder = 10;
816 const int kNumFolders = 10;
818 CreatePermanentBookmarkNodes();
821 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
822 for (int i = 0; i < kNumFolders; ++i) {
823 int64 folder_id =
824 AddFolderToShare(&trans, base::StringPrintf("folder%05d", i));
825 for (int j = 0; j < kNumBookmarksPerFolder; ++j) {
826 AddBookmarkToShare(
827 &trans, folder_id, base::StringPrintf("bookmark%05d", j),
828 base::StringPrintf("http://www.google.com/search?q=%05d", j));
833 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
834 StartSync();
836 ExpectModelMatch();
839 // Tests bookmark association when nodes exists in the native model only.
840 // These entries should be copied to Sync directory during association process.
841 TEST_F(ProfileSyncServiceBookmarkTest,
842 InitialModelAssociateWithBookmarkModelNodes) {
843 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
844 const BookmarkNode* folder =
845 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("foobar"));
846 model_->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
847 model_->AddURL(folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
848 GURL("http://www.easypie.com/"));
849 model_->AddURL(folder, 1, base::ASCIIToUTF16("Airplanes"),
850 GURL("http://www.easyjet.com/"));
852 StartSync();
853 ExpectModelMatch();
856 // Tests bookmark association case when there is an entry in the delete journal
857 // that matches one of native bookmarks.
858 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociateWithDeleteJournal) {
859 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
860 const BookmarkNode* folder = model_->AddFolder(model_->bookmark_bar_node(), 0,
861 base::ASCIIToUTF16("foobar"));
862 const BookmarkNode* bookmark =
863 model_->AddURL(folder, 0, base::ASCIIToUTF16("Airplanes"),
864 GURL("http://www.easyjet.com/"));
866 CreatePermanentBookmarkNodes();
868 // Create entries matching the folder and the bookmark above.
869 int64 folder_id, bookmark_id;
871 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
872 folder_id = AddFolderToShare(&trans, "foobar");
873 bookmark_id = AddBookmarkToShare(&trans, folder_id, "Airplanes",
874 "http://www.easyjet.com/");
877 // Associate the bookmark sync node with the native model one and make
878 // it look like it was deleted by a server update.
880 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
881 syncer::WriteNode node(&trans);
882 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(bookmark_id));
884 node.GetMutableEntryForTest()->PutLocalExternalId(bookmark->id());
886 MakeServerUpdate(&trans, &node);
887 node.GetMutableEntryForTest()->PutServerIsDel(true);
888 node.GetMutableEntryForTest()->PutIsDel(true);
891 ASSERT_TRUE(AssociateModels());
892 ExpectModelMatch();
894 // The bookmark node should be deleted.
895 EXPECT_EQ(0, folder->child_count());
898 // Tests that the external ID is used to match the right folder amoung
899 // multiple folders with the same name during the native model traversal.
900 // Also tests that the external ID is used to match the right bookmark
901 // among multiple identical bookmarks when dealing with the delete journal.
902 TEST_F(ProfileSyncServiceBookmarkTest,
903 InitialModelAssociateVerifyExternalIdMatch) {
904 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
905 const int kNumFolders = 10;
906 const int kNumBookmarks = 10;
907 const int kFolderToIncludeBookmarks = 7;
908 const int kBookmarkToDelete = 4;
910 int64 folder_ids[kNumFolders];
911 int64 bookmark_ids[kNumBookmarks];
913 // Create native folders and bookmarks with identical names. Only
914 // one of the folders contains bookmarks and others are empty. Here is the
915 // expected tree shape:
916 // Bookmarks bar
917 // +- folder (#0)
918 // +- folder (#1)
919 // ...
920 // +- folder (#7) <-- Only this folder contains bookmarks.
921 // +- bookmark (#0)
922 // +- bookmark (#1)
923 // ...
924 // +- bookmark (#4) <-- Only this one bookmark should be removed later.
925 // ...
926 // +- bookmark (#9)
927 // ...
928 // +- folder (#9)
930 const BookmarkNode* parent_folder = nullptr;
931 for (int i = 0; i < kNumFolders; i++) {
932 const BookmarkNode* folder = model_->AddFolder(
933 model_->bookmark_bar_node(), i, base::ASCIIToUTF16("folder"));
934 folder_ids[i] = folder->id();
935 if (i == kFolderToIncludeBookmarks) {
936 parent_folder = folder;
940 for (int i = 0; i < kNumBookmarks; i++) {
941 const BookmarkNode* bookmark =
942 model_->AddURL(parent_folder, i, base::ASCIIToUTF16("bookmark"),
943 GURL("http://www.google.com/"));
944 bookmark_ids[i] = bookmark->id();
947 // Number of nodes in bookmark bar before association.
948 int total_node_count = model_->bookmark_bar_node()->GetTotalNodeCount();
950 CreatePermanentBookmarkNodes();
952 int64 sync_bookmark_id_to_delete = 0;
954 // Create sync folders matching native folders above.
955 int64 parent_id = 0;
956 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
957 // Create in reverse order because AddFolderToShare passes NULL for
958 // |predecessor| argument.
959 for (int i = kNumFolders - 1; i >= 0; i--) {
960 int64 id = AddFolderToShare(&trans, "folder");
962 // Pre-map sync folders to native folders by setting
963 // external ID. This will verify that the association algorithm picks
964 // the right ones despite all of them having identical names.
965 // More specifically this will help to avoid cloning bookmarks from
966 // a wrong folder.
967 syncer::WriteNode node(&trans);
968 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
969 node.GetMutableEntryForTest()->PutLocalExternalId(folder_ids[i]);
971 if (i == kFolderToIncludeBookmarks) {
972 parent_id = id;
976 // Create sync bookmark matching native bookmarks above in reverse order
977 // because AddBookmarkToShare passes NULL for |predecessor| argument.
978 for (int i = kNumBookmarks - 1; i >= 0; i--) {
979 int id = AddBookmarkToShare(&trans, parent_id, "bookmark",
980 "http://www.google.com/");
982 // Pre-map sync bookmarks to native bookmarks by setting
983 // external ID. This will verify that the association algorithm picks
984 // the right ones despite all of them having identical names and URLs.
985 syncer::WriteNode node(&trans);
986 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
987 node.GetMutableEntryForTest()->PutLocalExternalId(bookmark_ids[i]);
989 if (i == kBookmarkToDelete) {
990 sync_bookmark_id_to_delete = id;
995 // Make one bookmark deleted.
997 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
998 syncer::WriteNode node(&trans);
999 EXPECT_EQ(BaseNode::INIT_OK,
1000 node.InitByIdLookup(sync_bookmark_id_to_delete));
1002 MakeServerUpdate(&trans, &node);
1003 node.GetMutableEntryForTest()->PutServerIsDel(true);
1004 node.GetMutableEntryForTest()->PutIsDel(true);
1007 // Perform association.
1008 ASSERT_TRUE(AssociateModels());
1009 ExpectModelMatch();
1011 // Only one native node should have been deleted and no nodes cloned due to
1012 // matching folder names.
1013 EXPECT_EQ(kNumFolders, model_->bookmark_bar_node()->child_count());
1014 EXPECT_EQ(kNumBookmarks - 1, parent_folder->child_count());
1015 EXPECT_EQ(total_node_count - 1,
1016 model_->bookmark_bar_node()->GetTotalNodeCount());
1018 // Verify that the right bookmark got deleted and no bookmarks reordered.
1019 for (int i = 0; i < parent_folder->child_count(); i++) {
1020 int index_in_bookmark_ids = (i < kBookmarkToDelete) ? i : i + 1;
1021 EXPECT_EQ(bookmark_ids[index_in_bookmark_ids],
1022 parent_folder->GetChild(i)->id());
1026 // Verifies that the bookmark association skips sync nodes with invalid URLs.
1027 TEST_F(ProfileSyncServiceBookmarkTest, InitialModelAssociateWithInvalidUrl) {
1028 EXPECT_CALL(mock_error_handler_, CreateAndUploadError(_, _, _))
1029 .WillOnce(Return(syncer::SyncError()));
1031 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1032 // On the local side create a folder and two nodes.
1033 const BookmarkNode* folder = model_->AddFolder(model_->bookmark_bar_node(), 0,
1034 base::ASCIIToUTF16("folder"));
1035 model_->AddURL(folder, 0, base::ASCIIToUTF16("node1"),
1036 GURL("http://www.node1.com/"));
1037 model_->AddURL(folder, 1, base::ASCIIToUTF16("node2"),
1038 GURL("http://www.node2.com/"));
1040 // On the sync side create a matching folder, one matching node, one
1041 // unmatching node, and one node with an invalid URL.
1042 CreatePermanentBookmarkNodes();
1044 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1045 int64 folder_id = AddFolderToShare(&trans, "folder");
1046 // Please note that each AddBookmarkToShare inserts the node at the front
1047 // so the actual order of children in the directory will be opposite.
1048 AddBookmarkToShare(&trans, folder_id, "node2", "http://www.node2.com/");
1049 AddBookmarkToShare(&trans, folder_id, "node3", "");
1050 AddBookmarkToShare(&trans, folder_id, "node4", "http://www.node4.com/");
1053 // Perform association.
1054 StartSync();
1056 // Concatenate resulting titles of native nodes.
1057 std::string native_titles;
1058 for (int i = 0; i < folder->child_count(); i++) {
1059 if (!native_titles.empty())
1060 native_titles += ",";
1061 const BookmarkNode* child = folder->GetChild(i);
1062 native_titles += base::UTF16ToUTF8(child->GetTitle());
1065 // Expect the order of nodes to follow the sync order (see note above), the
1066 // node with the invalid URL to be skipped, and the extra native node to be
1067 // at the end.
1068 EXPECT_EQ("node4,node2,node1", native_titles);
1071 TEST_F(ProfileSyncServiceBookmarkTest, BookmarkModelOperations) {
1072 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1073 StartSync();
1075 // Test addition.
1076 const BookmarkNode* folder =
1077 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("foobar"));
1078 ExpectSyncerNodeMatching(folder);
1079 ExpectModelMatch();
1080 const BookmarkNode* folder2 =
1081 model_->AddFolder(folder, 0, base::ASCIIToUTF16("nested"));
1082 ExpectSyncerNodeMatching(folder2);
1083 ExpectModelMatch();
1084 const BookmarkNode* url1 = model_->AddURL(
1085 folder, 0, base::ASCIIToUTF16("Internets #1 Pies Site"),
1086 GURL("http://www.easypie.com/"));
1087 ExpectSyncerNodeMatching(url1);
1088 ExpectModelMatch();
1089 const BookmarkNode* url2 = model_->AddURL(
1090 folder, 1, base::ASCIIToUTF16("Airplanes"),
1091 GURL("http://www.easyjet.com/"));
1092 ExpectSyncerNodeMatching(url2);
1093 ExpectModelMatch();
1094 // Test addition.
1095 const BookmarkNode* mobile_folder =
1096 model_->AddFolder(model_->mobile_node(), 0, base::ASCIIToUTF16("pie"));
1097 ExpectSyncerNodeMatching(mobile_folder);
1098 ExpectModelMatch();
1100 // Test modification.
1101 model_->SetTitle(url2, base::ASCIIToUTF16("EasyJet"));
1102 ExpectModelMatch();
1103 model_->Move(url1, folder2, 0);
1104 ExpectModelMatch();
1105 model_->Move(folder2, model_->bookmark_bar_node(), 0);
1106 ExpectModelMatch();
1107 model_->SetTitle(folder2, base::ASCIIToUTF16("Not Nested"));
1108 ExpectModelMatch();
1109 model_->Move(folder, folder2, 0);
1110 ExpectModelMatch();
1111 model_->SetTitle(folder, base::ASCIIToUTF16("who's nested now?"));
1112 ExpectModelMatch();
1113 model_->Copy(url2, model_->bookmark_bar_node(), 0);
1114 ExpectModelMatch();
1115 model_->SetTitle(mobile_folder, base::ASCIIToUTF16("strawberry"));
1116 ExpectModelMatch();
1118 // Test deletion.
1119 // Delete a single item.
1120 model_->Remove(url2);
1121 ExpectModelMatch();
1122 // Delete an item with several children.
1123 model_->Remove(folder2);
1124 ExpectModelMatch();
1125 model_->Remove(model_->mobile_node()->GetChild(0));
1126 ExpectModelMatch();
1129 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeProcessing) {
1130 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1131 StartSync();
1133 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1135 FakeServerChange adds(&trans);
1136 int64 f1 = adds.AddFolder("Server Folder B", bookmark_bar_id(), 0);
1137 int64 f2 = adds.AddFolder("Server Folder A", bookmark_bar_id(), f1);
1138 int64 u1 = adds.AddURL("Some old site", "ftp://nifty.andrew.cmu.edu/",
1139 bookmark_bar_id(), f2);
1140 int64 u2 = adds.AddURL("Nifty", "ftp://nifty.andrew.cmu.edu/", f1, 0);
1141 // u3 is a duplicate URL
1142 int64 u3 = adds.AddURL("Nifty2", "ftp://nifty.andrew.cmu.edu/", f1, u2);
1143 // u4 is a duplicate title, different URL.
1144 adds.AddURL("Some old site", "http://slog.thestranger.com/",
1145 bookmark_bar_id(), u1);
1146 // u5 tests an empty-string title.
1147 std::string javascript_url(
1148 "javascript:(function(){var w=window.open(" \
1149 "'about:blank','gnotesWin','location=0,menubar=0," \
1150 "scrollbars=0,status=0,toolbar=0,width=300," \
1151 "height=300,resizable');});");
1152 adds.AddURL(std::string(), javascript_url, other_bookmarks_id(), 0);
1153 int64 u6 = adds.AddURL(
1154 "Sync1", "http://www.syncable.edu/", mobile_bookmarks_id(), 0);
1156 syncer::ChangeRecordList::const_iterator it;
1157 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
1158 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1159 ExpectBrowserNodeUnknown(it->id);
1161 adds.ApplyPendingChanges(change_processor_.get());
1163 // Make sure the bookmark model received all of the nodes in |adds|.
1164 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1165 ExpectBrowserNodeMatching(&trans, it->id);
1166 ExpectModelMatch(&trans);
1168 // Part two: test modifications.
1169 FakeServerChange mods(&trans);
1170 // Mess with u2, and move it into empty folder f2
1171 // TODO(ncarter): Determine if we allow ModifyURL ops or not.
1172 /* std::string u2_old_url = mods.ModifyURL(u2, "http://www.google.com"); */
1173 std::string u2_old_title = mods.ModifyTitle(u2, "The Google");
1174 int64 u2_old_parent = mods.ModifyPosition(u2, f2, 0);
1176 // Now move f1 after u2.
1177 std::string f1_old_title = mods.ModifyTitle(f1, "Server Folder C");
1178 int64 f1_old_parent = mods.ModifyPosition(f1, f2, u2);
1180 // Then add u3 after f1.
1181 int64 u3_old_parent = mods.ModifyPosition(u3, f2, f1);
1183 std::string u6_old_title = mods.ModifyTitle(u6, "Mobile Folder A");
1185 // Test that the property changes have not yet taken effect.
1186 ExpectBrowserNodeTitle(u2, u2_old_title);
1187 /* ExpectBrowserNodeURL(u2, u2_old_url); */
1188 ExpectBrowserNodeParent(u2, u2_old_parent);
1190 ExpectBrowserNodeTitle(f1, f1_old_title);
1191 ExpectBrowserNodeParent(f1, f1_old_parent);
1193 ExpectBrowserNodeParent(u3, u3_old_parent);
1195 ExpectBrowserNodeTitle(u6, u6_old_title);
1197 // Apply the changes.
1198 mods.ApplyPendingChanges(change_processor_.get());
1200 // Check for successful application.
1201 for (it = mods.changes().begin(); it != mods.changes().end(); ++it)
1202 ExpectBrowserNodeMatching(&trans, it->id);
1203 ExpectModelMatch(&trans);
1205 // Part 3: Test URL deletion.
1206 FakeServerChange dels(&trans);
1207 dels.Delete(u2);
1208 dels.Delete(u3);
1209 dels.Delete(u6);
1211 ExpectBrowserNodeKnown(u2);
1212 ExpectBrowserNodeKnown(u3);
1214 dels.ApplyPendingChanges(change_processor_.get());
1216 ExpectBrowserNodeUnknown(u2);
1217 ExpectBrowserNodeUnknown(u3);
1218 ExpectBrowserNodeUnknown(u6);
1219 ExpectModelMatch(&trans);
1222 // Tests a specific case in ApplyModelChanges where we move the
1223 // children out from under a parent, and then delete the parent
1224 // in the same changelist. The delete shows up first in the changelist,
1225 // requiring the children to be moved to a temporary location.
1226 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeRequiringFosterParent) {
1227 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1228 StartSync();
1230 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1232 // Stress the immediate children of other_node because that's where
1233 // ApplyModelChanges puts a temporary foster parent node.
1234 std::string url("http://dev.chromium.org/");
1235 FakeServerChange adds(&trans);
1236 int64 f0 = other_bookmarks_id(); // + other_node
1237 int64 f1 = adds.AddFolder("f1", f0, 0); // + f1
1238 int64 f2 = adds.AddFolder("f2", f1, 0); // + f2
1239 int64 u3 = adds.AddURL( "u3", url, f2, 0); // + u3 NOLINT
1240 int64 u4 = adds.AddURL( "u4", url, f2, u3); // + u4 NOLINT
1241 int64 u5 = adds.AddURL( "u5", url, f1, f2); // + u5 NOLINT
1242 int64 f6 = adds.AddFolder("f6", f1, u5); // + f6
1243 int64 u7 = adds.AddURL( "u7", url, f0, f1); // + u7 NOLINT
1245 syncer::ChangeRecordList::const_iterator it;
1246 // The bookmark model shouldn't yet have seen any of the nodes of |adds|.
1247 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1248 ExpectBrowserNodeUnknown(it->id);
1250 adds.ApplyPendingChanges(change_processor_.get());
1252 // Make sure the bookmark model received all of the nodes in |adds|.
1253 for (it = adds.changes().begin(); it != adds.changes().end(); ++it)
1254 ExpectBrowserNodeMatching(&trans, it->id);
1255 ExpectModelMatch(&trans);
1257 // We have to do the moves before the deletions, but FakeServerChange will
1258 // put the deletion at the front of the changelist.
1259 FakeServerChange ops(&trans);
1260 ops.ModifyPosition(f6, other_bookmarks_id(), 0);
1261 ops.ModifyPosition(u3, other_bookmarks_id(), f1); // Prev == f1 is OK here.
1262 ops.ModifyPosition(f2, other_bookmarks_id(), u7);
1263 ops.ModifyPosition(u7, f2, 0);
1264 ops.ModifyPosition(u4, other_bookmarks_id(), f2);
1265 ops.ModifyPosition(u5, f6, 0);
1266 ops.Delete(f1);
1268 ops.ApplyPendingChanges(change_processor_.get());
1270 ExpectModelMatch(&trans);
1273 // Simulate a server change record containing a valid but non-canonical URL.
1274 TEST_F(ProfileSyncServiceBookmarkTest, ServerChangeWithNonCanonicalURL) {
1275 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1276 StartSync();
1279 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1281 FakeServerChange adds(&trans);
1282 std::string url("http://dev.chromium.org");
1283 EXPECT_NE(GURL(url).spec(), url);
1284 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1286 adds.ApplyPendingChanges(change_processor_.get());
1288 EXPECT_EQ(1, model_->other_node()->child_count());
1289 ExpectModelMatch(&trans);
1292 // Now reboot the sync service, forcing a merge step.
1293 StopSync();
1294 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1295 StartSync();
1297 // There should still be just the one bookmark.
1298 EXPECT_EQ(1, model_->other_node()->child_count());
1299 ExpectModelMatch();
1302 // Simulate a server change record containing an invalid URL (per GURL).
1303 // TODO(ncarter): Disabled due to crashes. Fix bug 1677563.
1304 TEST_F(ProfileSyncServiceBookmarkTest, DISABLED_ServerChangeWithInvalidURL) {
1305 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1306 StartSync();
1308 int child_count = 0;
1310 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1312 FakeServerChange adds(&trans);
1313 std::string url("x");
1314 EXPECT_FALSE(GURL(url).is_valid());
1315 adds.AddURL("u1", url, other_bookmarks_id(), 0);
1317 adds.ApplyPendingChanges(change_processor_.get());
1319 // We're lenient about what should happen -- the model could wind up with
1320 // the node or without it; but things should be consistent, and we
1321 // shouldn't crash.
1322 child_count = model_->other_node()->child_count();
1323 EXPECT_TRUE(child_count == 0 || child_count == 1);
1324 ExpectModelMatch(&trans);
1327 // Now reboot the sync service, forcing a merge step.
1328 StopSync();
1329 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1330 StartSync();
1332 // Things ought not to have changed.
1333 EXPECT_EQ(model_->other_node()->child_count(), child_count);
1334 ExpectModelMatch();
1338 // Test strings that might pose a problem if the titles ever became used as
1339 // file names in the sync backend.
1340 TEST_F(ProfileSyncServiceBookmarkTest, CornerCaseNames) {
1341 // TODO(ncarter): Bug 1570238 explains the failure of this test.
1342 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1343 StartSync();
1345 const char* names[] = {
1346 // The empty string.
1348 // Illegal Windows filenames.
1349 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4",
1350 "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3",
1351 "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1352 // Current/parent directory markers.
1353 ".", "..", "...",
1354 // Files created automatically by the Windows shell.
1355 "Thumbs.db", ".DS_Store",
1356 // Names including Win32-illegal characters, and path separators.
1357 "foo/bar", "foo\\bar", "foo?bar", "foo:bar", "foo|bar", "foo\"bar",
1358 "foo'bar", "foo<bar", "foo>bar", "foo%bar", "foo*bar", "foo]bar",
1359 "foo[bar",
1360 // A name with title > 255 characters
1361 "012345678901234567890123456789012345678901234567890123456789012345678901"
1362 "234567890123456789012345678901234567890123456789012345678901234567890123"
1363 "456789012345678901234567890123456789012345678901234567890123456789012345"
1364 "678901234567890123456789012345678901234567890123456789012345678901234567"
1365 "890123456789"
1367 // Create both folders and bookmarks using each name.
1368 GURL url("http://www.doublemint.com");
1369 for (size_t i = 0; i < arraysize(names); ++i) {
1370 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16(names[i]));
1371 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16(names[i]), url);
1374 // Verify that the browser model matches the sync model.
1375 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1376 2*arraysize(names));
1377 ExpectModelMatch();
1379 // Restart and re-associate. Verify things still match.
1380 StopSync();
1381 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1382 StartSync();
1383 EXPECT_EQ(static_cast<size_t>(model_->other_node()->child_count()),
1384 2*arraysize(names));
1385 ExpectModelMatch();
1388 // Stress the internal representation of position by sparse numbers. We want
1389 // to repeatedly bisect the range of available positions, to force the
1390 // syncer code to renumber its ranges. Pick a number big enough so that it
1391 // would exhaust 32bits of room between items a couple of times.
1392 TEST_F(ProfileSyncServiceBookmarkTest, RepeatedMiddleInsertion) {
1393 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1394 StartSync();
1396 static const int kTimesToInsert = 256;
1398 // Create two book-end nodes to insert between.
1399 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("Alpha"));
1400 model_->AddFolder(model_->other_node(), 1, base::ASCIIToUTF16("Omega"));
1401 int count = 2;
1403 // Test insertion in first half of range by repeatedly inserting in second
1404 // position.
1405 for (int i = 0; i < kTimesToInsert; ++i) {
1406 base::string16 title =
1407 base::ASCIIToUTF16("Pre-insertion ") + base::IntToString16(i);
1408 model_->AddFolder(model_->other_node(), 1, title);
1409 count++;
1412 // Test insertion in second half of range by repeatedly inserting in
1413 // second-to-last position.
1414 for (int i = 0; i < kTimesToInsert; ++i) {
1415 base::string16 title =
1416 base::ASCIIToUTF16("Post-insertion ") + base::IntToString16(i);
1417 model_->AddFolder(model_->other_node(), count - 1, title);
1418 count++;
1421 // Verify that the browser model matches the sync model.
1422 EXPECT_EQ(model_->other_node()->child_count(), count);
1423 ExpectModelMatch();
1426 // Introduce a consistency violation into the model, and see that it
1427 // puts itself into a lame, error state.
1428 TEST_F(ProfileSyncServiceBookmarkTest, UnrecoverableErrorSuspendsService) {
1429 EXPECT_CALL(mock_error_handler_,
1430 OnSingleDataTypeUnrecoverableError(_));
1432 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1433 StartSync();
1435 // Add a node which will be the target of the consistency violation.
1436 const BookmarkNode* node =
1437 model_->AddFolder(model_->other_node(), 0, base::ASCIIToUTF16("node"));
1438 ExpectSyncerNodeMatching(node);
1440 // Now destroy the syncer node as if we were the ProfileSyncService without
1441 // updating the ProfileSyncService state. This should introduce
1442 // inconsistency between the two models.
1444 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1445 syncer::WriteNode sync_node(&trans);
1446 ASSERT_TRUE(InitSyncNodeFromChromeNode(node, &sync_node));
1447 sync_node.Tombstone();
1449 // The models don't match at this point, but the ProfileSyncService
1450 // doesn't know it yet.
1451 ExpectSyncerNodeKnown(node);
1453 // Add a child to the inconsistent node. This should cause detection of the
1454 // problem and the syncer should stop processing changes.
1455 model_->AddFolder(node, 0, base::ASCIIToUTF16("nested"));
1458 // See what happens if we run model association when there are two exact URL
1459 // duplicate bookmarks. The BookmarkModelAssociator should not fall over when
1460 // this happens.
1461 TEST_F(ProfileSyncServiceBookmarkTest, MergeDuplicates) {
1462 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1463 StartSync();
1465 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1466 GURL("http://dup.com/"));
1467 model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Dup"),
1468 GURL("http://dup.com/"));
1470 EXPECT_EQ(2, model_->other_node()->child_count());
1472 // Restart the sync service to trigger model association.
1473 StopSync();
1474 StartSync();
1476 EXPECT_EQ(2, model_->other_node()->child_count());
1477 ExpectModelMatch();
1480 TEST_F(ProfileSyncServiceBookmarkTest, ApplySyncDeletesFromJournal) {
1481 // Initialize sync model and bookmark model as:
1482 // URL 0
1483 // Folder 1
1484 // |-- URL 1
1485 // +-- Folder 2
1486 // +-- URL 2
1487 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1488 int64 u0 = 0;
1489 int64 f1 = 0;
1490 int64 u1 = 0;
1491 int64 f2 = 0;
1492 int64 u2 = 0;
1493 StartSync();
1494 int fixed_sync_bk_count = GetSyncBookmarkCount();
1496 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1497 FakeServerChange adds(&trans);
1498 u0 = adds.AddURL("URL 0", "http://plus.google.com/", bookmark_bar_id(), 0);
1499 f1 = adds.AddFolder("Folder 1", bookmark_bar_id(), u0);
1500 u1 = adds.AddURL("URL 1", "http://www.google.com/", f1, 0);
1501 f2 = adds.AddFolder("Folder 2", f1, u1);
1502 u2 = adds.AddURL("URL 2", "http://mail.google.com/", f2, 0);
1503 adds.ApplyPendingChanges(change_processor_.get());
1505 StopSync();
1507 // Reload bookmark model and disable model saving to make sync changes not
1508 // persisted.
1509 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1510 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1511 EXPECT_EQ(fixed_sync_bk_count + 5, GetSyncBookmarkCount());
1512 StartSync();
1514 // Remove all folders/bookmarks except u3 added above.
1515 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
1516 MakeServerUpdate(&trans, f1);
1517 MakeServerUpdate(&trans, u1);
1518 MakeServerUpdate(&trans, f2);
1519 MakeServerUpdate(&trans, u2);
1520 FakeServerChange dels(&trans);
1521 dels.Delete(u2);
1522 dels.Delete(f2);
1523 dels.Delete(u1);
1524 dels.Delete(f1);
1525 dels.ApplyPendingChanges(change_processor_.get());
1527 StopSync();
1528 // Bookmark bar itself and u0 remain.
1529 EXPECT_EQ(2, model_->bookmark_bar_node()->GetTotalNodeCount());
1531 // Reload bookmarks including ones deleted in sync model from storage.
1532 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1533 EXPECT_EQ(6, model_->bookmark_bar_node()->GetTotalNodeCount());
1534 // Add a bookmark under f1 when sync is off so that f1 will not be
1535 // deleted even when f1 matches delete journal because it's not empty.
1536 model_->AddURL(model_->bookmark_bar_node()->GetChild(1),
1537 0, base::UTF8ToUTF16("local"), GURL("http://www.youtube.com"));
1538 // Sync model has fixed bookmarks nodes and u3.
1539 EXPECT_EQ(fixed_sync_bk_count + 1, GetSyncBookmarkCount());
1540 StartSync();
1541 // Expect 4 bookmarks after model association because u2, f2, u1 are removed
1542 // by delete journal, f1 is not removed by delete journal because it's
1543 // not empty due to www.youtube.com added above.
1544 EXPECT_EQ(4, model_->bookmark_bar_node()->GetTotalNodeCount());
1545 EXPECT_EQ(base::UTF8ToUTF16("URL 0"),
1546 model_->bookmark_bar_node()->GetChild(0)->GetTitle());
1547 EXPECT_EQ(base::UTF8ToUTF16("Folder 1"),
1548 model_->bookmark_bar_node()->GetChild(1)->GetTitle());
1549 EXPECT_EQ(base::UTF8ToUTF16("local"),
1550 model_->bookmark_bar_node()->GetChild(1)->GetChild(0)->GetTitle());
1551 StopSync();
1553 // Verify purging of delete journals.
1554 // Delete journals for u2, f2, u1 remains because they are used in last
1555 // association.
1556 EXPECT_EQ(3u, test_user_share_.GetDeleteJournalSize());
1557 StartSync();
1558 StopSync();
1559 // Reload again and all delete journals should be gone because none is used
1560 // in last association.
1561 ASSERT_TRUE(test_user_share_.Reload());
1562 EXPECT_EQ(0u, test_user_share_.GetDeleteJournalSize());
1565 struct TestData {
1566 const char* title;
1567 const char* url;
1570 // Map from bookmark node ID to its version.
1571 typedef std::map<int64, int64> BookmarkNodeVersionMap;
1573 // TODO(ncarter): Integrate the existing TestNode/PopulateNodeFromString code
1574 // in the bookmark model unittest, to make it simpler to set up test data
1575 // here (and reduce the amount of duplication among tests), and to reduce the
1576 // duplication.
1577 class ProfileSyncServiceBookmarkTestWithData
1578 : public ProfileSyncServiceBookmarkTest {
1579 public:
1580 ProfileSyncServiceBookmarkTestWithData();
1582 protected:
1583 // Populates or compares children of the given bookmark node from/with the
1584 // given test data array with the given size. |running_count| is updated as
1585 // urls are added. It is used to set the creation date (or test the creation
1586 // date for CompareWithTestData()).
1587 void PopulateFromTestData(const BookmarkNode* node,
1588 const TestData* data,
1589 int size,
1590 int* running_count);
1591 void CompareWithTestData(const BookmarkNode* node,
1592 const TestData* data,
1593 int size,
1594 int* running_count);
1596 void ExpectBookmarkModelMatchesTestData();
1597 void WriteTestDataToBookmarkModel();
1599 // Output transaction versions of |node| and nodes under it to
1600 // |node_versions|.
1601 void GetTransactionVersions(const BookmarkNode* root,
1602 BookmarkNodeVersionMap* node_versions);
1604 // Verify transaction versions of bookmark nodes and sync nodes are equal
1605 // recursively. If node is in |version_expected|, versions should match
1606 // there, too.
1607 void ExpectTransactionVersionMatch(
1608 const BookmarkNode* node,
1609 const BookmarkNodeVersionMap& version_expected);
1611 private:
1612 const base::Time start_time_;
1614 DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceBookmarkTestWithData);
1617 namespace {
1619 // Constants for bookmark model that looks like:
1620 // |-- Bookmark bar
1621 // | |-- u2, http://www.u2.com/
1622 // | |-- f1
1623 // | | |-- f1u4, http://www.f1u4.com/
1624 // | | |-- f1u2, http://www.f1u2.com/
1625 // | | |-- f1u3, http://www.f1u3.com/
1626 // | | +-- f1u1, http://www.f1u1.com/
1627 // | |-- u1, http://www.u1.com/
1628 // | +-- f2
1629 // | |-- f2u2, http://www.f2u2.com/
1630 // | |-- f2u4, http://www.f2u4.com/
1631 // | |-- f2u3, http://www.f2u3.com/
1632 // | +-- f2u1, http://www.f2u1.com/
1633 // +-- Other bookmarks
1634 // | |-- f3
1635 // | | |-- f3u4, http://www.f3u4.com/
1636 // | | |-- f3u2, http://www.f3u2.com/
1637 // | | |-- f3u3, http://www.f3u3.com/
1638 // | | +-- f3u1, http://www.f3u1.com/
1639 // | |-- u4, http://www.u4.com/
1640 // | |-- u3, http://www.u3.com/
1641 // | --- f4
1642 // | | |-- f4u1, http://www.f4u1.com/
1643 // | | |-- f4u2, http://www.f4u2.com/
1644 // | | |-- f4u3, http://www.f4u3.com/
1645 // | | +-- f4u4, http://www.f4u4.com/
1646 // | |-- dup
1647 // | | +-- dupu1, http://www.dupu1.com/
1648 // | +-- dup
1649 // | | +-- dupu2, http://www.dupu1.com/
1650 // | +-- ls , http://www.ls.com/
1651 // |
1652 // +-- Mobile bookmarks
1653 // |-- f5
1654 // | |-- f5u1, http://www.f5u1.com/
1655 // |-- f6
1656 // | |-- f6u1, http://www.f6u1.com/
1657 // | |-- f6u2, http://www.f6u2.com/
1658 // +-- u5, http://www.u5.com/
1660 static TestData kBookmarkBarChildren[] = {
1661 { "u2", "http://www.u2.com/" },
1662 { "f1", NULL },
1663 { "u1", "http://www.u1.com/" },
1664 { "f2", NULL },
1666 static TestData kF1Children[] = {
1667 { "f1u4", "http://www.f1u4.com/" },
1668 { "f1u2", "http://www.f1u2.com/" },
1669 { "f1u3", "http://www.f1u3.com/" },
1670 { "f1u1", "http://www.f1u1.com/" },
1672 static TestData kF2Children[] = {
1673 { "f2u2", "http://www.f2u2.com/" },
1674 { "f2u4", "http://www.f2u4.com/" },
1675 { "f2u3", "http://www.f2u3.com/" },
1676 { "f2u1", "http://www.f2u1.com/" },
1679 static TestData kOtherBookmarkChildren[] = {
1680 { "f3", NULL },
1681 { "u4", "http://www.u4.com/" },
1682 { "u3", "http://www.u3.com/" },
1683 { "f4", NULL },
1684 { "dup", NULL },
1685 { "dup", NULL },
1686 { " ls ", "http://www.ls.com/" }
1688 static TestData kF3Children[] = {
1689 { "f3u4", "http://www.f3u4.com/" },
1690 { "f3u2", "http://www.f3u2.com/" },
1691 { "f3u3", "http://www.f3u3.com/" },
1692 { "f3u1", "http://www.f3u1.com/" },
1694 static TestData kF4Children[] = {
1695 { "f4u1", "http://www.f4u1.com/" },
1696 { "f4u2", "http://www.f4u2.com/" },
1697 { "f4u3", "http://www.f4u3.com/" },
1698 { "f4u4", "http://www.f4u4.com/" },
1700 static TestData kDup1Children[] = {
1701 { "dupu1", "http://www.dupu1.com/" },
1703 static TestData kDup2Children[] = {
1704 { "dupu2", "http://www.dupu2.com/" },
1707 static TestData kMobileBookmarkChildren[] = {
1708 { "f5", NULL },
1709 { "f6", NULL },
1710 { "u5", "http://www.u5.com/" },
1712 static TestData kF5Children[] = {
1713 { "f5u1", "http://www.f5u1.com/" },
1714 { "f5u2", "http://www.f5u2.com/" },
1716 static TestData kF6Children[] = {
1717 { "f6u1", "http://www.f6u1.com/" },
1718 { "f6u2", "http://www.f6u2.com/" },
1721 } // anonymous namespace.
1723 ProfileSyncServiceBookmarkTestWithData::
1724 ProfileSyncServiceBookmarkTestWithData()
1725 : start_time_(base::Time::Now()) {
1728 void ProfileSyncServiceBookmarkTestWithData::PopulateFromTestData(
1729 const BookmarkNode* node,
1730 const TestData* data,
1731 int size,
1732 int* running_count) {
1733 DCHECK(node);
1734 DCHECK(data);
1735 DCHECK(node->is_folder());
1736 for (int i = 0; i < size; ++i) {
1737 const TestData& item = data[i];
1738 if (item.url) {
1739 const base::Time add_time =
1740 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1741 model_->AddURLWithCreationTimeAndMetaInfo(node,
1743 base::UTF8ToUTF16(item.title),
1744 GURL(item.url),
1745 add_time,
1746 NULL);
1747 } else {
1748 model_->AddFolder(node, i, base::UTF8ToUTF16(item.title));
1750 (*running_count)++;
1754 void ProfileSyncServiceBookmarkTestWithData::CompareWithTestData(
1755 const BookmarkNode* node,
1756 const TestData* data,
1757 int size,
1758 int* running_count) {
1759 DCHECK(node);
1760 DCHECK(data);
1761 DCHECK(node->is_folder());
1762 ASSERT_EQ(size, node->child_count());
1763 for (int i = 0; i < size; ++i) {
1764 const BookmarkNode* child_node = node->GetChild(i);
1765 const TestData& item = data[i];
1766 GURL url = GURL(item.url == NULL ? "" : item.url);
1767 BookmarkNode test_node(url);
1768 test_node.SetTitle(base::UTF8ToUTF16(item.title));
1769 EXPECT_EQ(child_node->GetTitle(), test_node.GetTitle());
1770 if (item.url) {
1771 EXPECT_FALSE(child_node->is_folder());
1772 EXPECT_TRUE(child_node->is_url());
1773 EXPECT_EQ(child_node->url(), test_node.url());
1774 const base::Time expected_time =
1775 start_time_ + base::TimeDelta::FromMinutes(*running_count);
1776 EXPECT_EQ(expected_time.ToInternalValue(),
1777 child_node->date_added().ToInternalValue());
1778 } else {
1779 EXPECT_TRUE(child_node->is_folder());
1780 EXPECT_FALSE(child_node->is_url());
1782 (*running_count)++;
1786 // TODO(munjal): We should implement some way of generating random data and can
1787 // use the same seed to generate the same sequence.
1788 void ProfileSyncServiceBookmarkTestWithData::WriteTestDataToBookmarkModel() {
1789 const BookmarkNode* bookmarks_bar_node = model_->bookmark_bar_node();
1790 int count = 0;
1791 PopulateFromTestData(bookmarks_bar_node,
1792 kBookmarkBarChildren,
1793 arraysize(kBookmarkBarChildren),
1794 &count);
1796 ASSERT_GE(bookmarks_bar_node->child_count(), 4);
1797 const BookmarkNode* f1_node = bookmarks_bar_node->GetChild(1);
1798 PopulateFromTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1799 const BookmarkNode* f2_node = bookmarks_bar_node->GetChild(3);
1800 PopulateFromTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1802 const BookmarkNode* other_bookmarks_node = model_->other_node();
1803 PopulateFromTestData(other_bookmarks_node,
1804 kOtherBookmarkChildren,
1805 arraysize(kOtherBookmarkChildren),
1806 &count);
1808 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1809 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1810 PopulateFromTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1811 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1812 PopulateFromTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1813 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1814 PopulateFromTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1815 &count);
1816 dup_node = other_bookmarks_node->GetChild(5);
1817 PopulateFromTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1818 &count);
1820 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1821 PopulateFromTestData(mobile_bookmarks_node,
1822 kMobileBookmarkChildren,
1823 arraysize(kMobileBookmarkChildren),
1824 &count);
1826 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1827 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1828 PopulateFromTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1829 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1830 PopulateFromTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1832 ExpectBookmarkModelMatchesTestData();
1835 void ProfileSyncServiceBookmarkTestWithData::
1836 ExpectBookmarkModelMatchesTestData() {
1837 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1838 int count = 0;
1839 CompareWithTestData(bookmark_bar_node,
1840 kBookmarkBarChildren,
1841 arraysize(kBookmarkBarChildren),
1842 &count);
1844 ASSERT_GE(bookmark_bar_node->child_count(), 4);
1845 const BookmarkNode* f1_node = bookmark_bar_node->GetChild(1);
1846 CompareWithTestData(f1_node, kF1Children, arraysize(kF1Children), &count);
1847 const BookmarkNode* f2_node = bookmark_bar_node->GetChild(3);
1848 CompareWithTestData(f2_node, kF2Children, arraysize(kF2Children), &count);
1850 const BookmarkNode* other_bookmarks_node = model_->other_node();
1851 CompareWithTestData(other_bookmarks_node,
1852 kOtherBookmarkChildren,
1853 arraysize(kOtherBookmarkChildren),
1854 &count);
1856 ASSERT_GE(other_bookmarks_node->child_count(), 6);
1857 const BookmarkNode* f3_node = other_bookmarks_node->GetChild(0);
1858 CompareWithTestData(f3_node, kF3Children, arraysize(kF3Children), &count);
1859 const BookmarkNode* f4_node = other_bookmarks_node->GetChild(3);
1860 CompareWithTestData(f4_node, kF4Children, arraysize(kF4Children), &count);
1861 const BookmarkNode* dup_node = other_bookmarks_node->GetChild(4);
1862 CompareWithTestData(dup_node, kDup1Children, arraysize(kDup1Children),
1863 &count);
1864 dup_node = other_bookmarks_node->GetChild(5);
1865 CompareWithTestData(dup_node, kDup2Children, arraysize(kDup2Children),
1866 &count);
1868 const BookmarkNode* mobile_bookmarks_node = model_->mobile_node();
1869 CompareWithTestData(mobile_bookmarks_node,
1870 kMobileBookmarkChildren,
1871 arraysize(kMobileBookmarkChildren),
1872 &count);
1874 ASSERT_GE(mobile_bookmarks_node->child_count(), 3);
1875 const BookmarkNode* f5_node = mobile_bookmarks_node->GetChild(0);
1876 CompareWithTestData(f5_node, kF5Children, arraysize(kF5Children), &count);
1877 const BookmarkNode* f6_node = mobile_bookmarks_node->GetChild(1);
1878 CompareWithTestData(f6_node, kF6Children, arraysize(kF6Children), &count);
1881 // Tests persistence of the profile sync service by unloading the
1882 // database and then reloading it from disk.
1883 TEST_F(ProfileSyncServiceBookmarkTestWithData, Persistence) {
1884 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1885 StartSync();
1887 WriteTestDataToBookmarkModel();
1889 ExpectModelMatch();
1891 // Force both models to discard their data and reload from disk. This
1892 // simulates what would happen if the browser were to shutdown normally,
1893 // and then relaunch.
1894 StopSync();
1895 UnloadBookmarkModel();
1896 LoadBookmarkModel(LOAD_FROM_STORAGE, SAVE_TO_STORAGE);
1897 StartSync();
1899 ExpectBookmarkModelMatchesTestData();
1901 // With the BookmarkModel contents verified, ExpectModelMatch will
1902 // verify the contents of the sync model.
1903 ExpectModelMatch();
1906 // Tests the merge case when the BookmarkModel is non-empty but the
1907 // sync model is empty. This corresponds to uploading browser
1908 // bookmarks to an initially empty, new account.
1909 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptySyncModel) {
1910 // Don't start the sync service until we've populated the bookmark model.
1911 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1913 WriteTestDataToBookmarkModel();
1915 // Restart sync. This should trigger a merge step during
1916 // initialization -- we expect the browser bookmarks to be written
1917 // to the sync service during this call.
1918 StartSync();
1920 // Verify that the bookmark model hasn't changed, and that the sync model
1921 // matches it exactly.
1922 ExpectBookmarkModelMatchesTestData();
1923 ExpectModelMatch();
1926 // Tests the merge case when the BookmarkModel is empty but the sync model is
1927 // non-empty. This corresponds (somewhat) to a clean install of the browser,
1928 // with no bookmarks, connecting to a sync account that has some bookmarks.
1929 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeWithEmptyBookmarkModel) {
1930 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1931 StartSync();
1933 WriteTestDataToBookmarkModel();
1935 ExpectModelMatch();
1937 // Force the databse to unload and write itself to disk.
1938 StopSync();
1940 // Blow away the bookmark model -- it should be empty afterwards.
1941 UnloadBookmarkModel();
1942 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1943 EXPECT_EQ(model_->bookmark_bar_node()->child_count(), 0);
1944 EXPECT_EQ(model_->other_node()->child_count(), 0);
1945 EXPECT_EQ(model_->mobile_node()->child_count(), 0);
1947 // Now restart the sync service. Starting it should populate the bookmark
1948 // model -- test for consistency.
1949 StartSync();
1950 ExpectBookmarkModelMatchesTestData();
1951 ExpectModelMatch();
1954 // Tests the merge cases when both the models are expected to be identical
1955 // after the merge.
1956 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeExpectedIdenticalModels) {
1957 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
1958 StartSync();
1959 WriteTestDataToBookmarkModel();
1960 ExpectModelMatch();
1961 StopSync();
1962 UnloadBookmarkModel();
1964 // At this point both the bookmark model and the server should have the
1965 // exact same data and it should match the test data.
1966 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1967 StartSync();
1968 ExpectBookmarkModelMatchesTestData();
1969 ExpectModelMatch();
1970 StopSync();
1971 UnloadBookmarkModel();
1973 // Now reorder some bookmarks in the bookmark model and then merge. Make
1974 // sure we get the order of the server after merge.
1975 LoadBookmarkModel(LOAD_FROM_STORAGE, DONT_SAVE_TO_STORAGE);
1976 ExpectBookmarkModelMatchesTestData();
1977 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
1978 ASSERT_TRUE(bookmark_bar);
1979 ASSERT_GT(bookmark_bar->child_count(), 1);
1980 model_->Move(bookmark_bar->GetChild(0), bookmark_bar, 1);
1981 StartSync();
1982 ExpectModelMatch();
1983 ExpectBookmarkModelMatchesTestData();
1986 // Tests the merge cases when both the models are expected to be identical
1987 // after the merge.
1988 TEST_F(ProfileSyncServiceBookmarkTestWithData, MergeModelsWithSomeExtras) {
1989 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
1990 WriteTestDataToBookmarkModel();
1991 ExpectBookmarkModelMatchesTestData();
1993 // Remove some nodes and reorder some nodes.
1994 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
1995 int remove_index = 2;
1996 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
1997 const BookmarkNode* child_node = bookmark_bar_node->GetChild(remove_index);
1998 ASSERT_TRUE(child_node);
1999 ASSERT_TRUE(child_node->is_url());
2000 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2001 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2002 child_node = bookmark_bar_node->GetChild(remove_index);
2003 ASSERT_TRUE(child_node);
2004 ASSERT_TRUE(child_node->is_folder());
2005 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2007 const BookmarkNode* other_node = model_->other_node();
2008 ASSERT_GE(other_node->child_count(), 1);
2009 const BookmarkNode* f3_node = other_node->GetChild(0);
2010 ASSERT_TRUE(f3_node);
2011 ASSERT_TRUE(f3_node->is_folder());
2012 remove_index = 2;
2013 ASSERT_GT(f3_node->child_count(), remove_index);
2014 model_->Remove(f3_node->GetChild(remove_index));
2015 ASSERT_GT(f3_node->child_count(), remove_index);
2016 model_->Remove(f3_node->GetChild(remove_index));
2018 StartSync();
2019 ExpectModelMatch();
2020 StopSync();
2022 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2023 WriteTestDataToBookmarkModel();
2024 ExpectBookmarkModelMatchesTestData();
2026 // Remove some nodes and reorder some nodes.
2027 bookmark_bar_node = model_->bookmark_bar_node();
2028 remove_index = 0;
2029 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2030 child_node = bookmark_bar_node->GetChild(remove_index);
2031 ASSERT_TRUE(child_node);
2032 ASSERT_TRUE(child_node->is_url());
2033 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2034 ASSERT_GT(bookmark_bar_node->child_count(), remove_index);
2035 child_node = bookmark_bar_node->GetChild(remove_index);
2036 ASSERT_TRUE(child_node);
2037 ASSERT_TRUE(child_node->is_folder());
2038 model_->Remove(bookmark_bar_node->GetChild(remove_index));
2040 ASSERT_GE(bookmark_bar_node->child_count(), 2);
2041 model_->Move(bookmark_bar_node->GetChild(0), bookmark_bar_node, 1);
2043 other_node = model_->other_node();
2044 ASSERT_GE(other_node->child_count(), 1);
2045 f3_node = other_node->GetChild(0);
2046 ASSERT_TRUE(f3_node);
2047 ASSERT_TRUE(f3_node->is_folder());
2048 remove_index = 0;
2049 ASSERT_GT(f3_node->child_count(), remove_index);
2050 model_->Remove(f3_node->GetChild(remove_index));
2051 ASSERT_GT(f3_node->child_count(), remove_index);
2052 model_->Remove(f3_node->GetChild(remove_index));
2054 ASSERT_GE(other_node->child_count(), 4);
2055 model_->Move(other_node->GetChild(0), other_node, 1);
2056 model_->Move(other_node->GetChild(2), other_node, 3);
2058 StartSync();
2059 ExpectModelMatch();
2061 // After the merge, the model should match the test data.
2062 ExpectBookmarkModelMatchesTestData();
2065 // Tests the optimistic bookmark association case where some nodes are moved
2066 // and untracked by the sync before the association.
2067 TEST_F(ProfileSyncServiceBookmarkTestWithData, OptimisticMergeWithMoves) {
2068 // TODO(stanisc): crbug.com/456876: Remove this once the optimistic
2069 // association experiment has ended.
2070 base::FieldTrialList field_trial_list(new base::MockEntropyProvider());
2071 base::FieldTrialList::CreateFieldTrial("SyncOptimisticBookmarkAssociation",
2072 "Enabled");
2074 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2075 WriteTestDataToBookmarkModel();
2077 int num_bookmarks = model_->root_node()->GetTotalNodeCount();
2079 StartSync();
2080 ExpectModelMatch();
2081 StopSync();
2083 EXPECT_EQ(num_bookmarks, model_->root_node()->GetTotalNodeCount());
2085 // Move one folder into another
2086 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2087 const BookmarkNode* f1 = bookmark_bar_node->GetChild(1);
2088 ASSERT_TRUE(f1->is_folder());
2089 const BookmarkNode* f2 = bookmark_bar_node->GetChild(3);
2090 ASSERT_TRUE(f2->is_folder());
2091 model_->Move(f2, f1, 0);
2093 StartSync();
2094 ExpectModelMatch();
2095 StopSync();
2097 // Expect folders to not duplicate.
2098 EXPECT_EQ(num_bookmarks, model_->root_node()->GetTotalNodeCount());
2100 // Perform one more cycle and make sure that the number of nodes stays
2101 // the same.
2102 StartSync();
2103 ExpectModelMatch();
2104 StopSync();
2105 EXPECT_EQ(num_bookmarks, model_->root_node()->GetTotalNodeCount());
2108 // Tests that when persisted model associations are used, things work fine.
2109 TEST_F(ProfileSyncServiceBookmarkTestWithData, ModelAssociationPersistence) {
2110 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2111 WriteTestDataToBookmarkModel();
2112 StartSync();
2113 ExpectModelMatch();
2114 // Force sync to shut down and write itself to disk.
2115 StopSync();
2116 // Now restart sync. This time it should use the persistent
2117 // associations.
2118 StartSync();
2119 ExpectModelMatch();
2122 // Tests that when persisted model associations are used, things work fine.
2123 TEST_F(ProfileSyncServiceBookmarkTestWithData,
2124 ModelAssociationInvalidPersistence) {
2125 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2126 WriteTestDataToBookmarkModel();
2127 StartSync();
2128 ExpectModelMatch();
2129 // Force sync to shut down and write itself to disk.
2130 StopSync();
2131 // Change the bookmark model before restarting sync service to simulate
2132 // the situation where bookmark model is different from sync model and
2133 // make sure model associator correctly rebuilds associations.
2134 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2135 model_->AddURL(bookmark_bar_node, 0, base::ASCIIToUTF16("xtra"),
2136 GURL("http://www.xtra.com"));
2137 // Now restart sync. This time it will try to use the persistent
2138 // associations and realize that they are invalid and hence will rebuild
2139 // associations.
2140 StartSync();
2141 ExpectModelMatch();
2144 TEST_F(ProfileSyncServiceBookmarkTestWithData, SortChildren) {
2145 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2146 StartSync();
2148 // Write test data to bookmark model and verify that the models match.
2149 WriteTestDataToBookmarkModel();
2150 const BookmarkNode* folder_added = model_->other_node()->GetChild(0);
2151 ASSERT_TRUE(folder_added);
2152 ASSERT_TRUE(folder_added->is_folder());
2154 ExpectModelMatch();
2156 // Sort the other-bookmarks children and expect that the models match.
2157 model_->SortChildren(folder_added);
2158 ExpectModelMatch();
2161 // See what happens if we enable sync but then delete the "Sync Data"
2162 // folder.
2163 TEST_F(ProfileSyncServiceBookmarkTestWithData,
2164 RecoverAfterDeletingSyncDataDirectory) {
2165 LoadBookmarkModel(DELETE_EXISTING_STORAGE, SAVE_TO_STORAGE);
2166 StartSync();
2168 WriteTestDataToBookmarkModel();
2170 StopSync();
2172 // Nuke the sync DB and reload.
2173 TearDown();
2174 SetUp();
2176 // First attempt fails due to a persistence error.
2177 EXPECT_TRUE(CreatePermanentBookmarkNodes());
2178 EXPECT_FALSE(AssociateModels());
2180 // Second attempt succeeds due to the previous error resetting the native
2181 // transaction version.
2182 model_associator_.reset();
2183 EXPECT_TRUE(CreatePermanentBookmarkNodes());
2184 EXPECT_TRUE(AssociateModels());
2186 // Make sure we're back in sync. In real life, the user would need
2187 // to reauthenticate before this happens, but in the test, authentication
2188 // is sidestepped.
2189 ExpectBookmarkModelMatchesTestData();
2190 ExpectModelMatch();
2193 // Verify that the bookmark model is updated about whether the
2194 // associator is currently running.
2195 TEST_F(ProfileSyncServiceBookmarkTest, AssociationState) {
2196 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2198 ExtensiveChangesBookmarkModelObserver observer;
2199 model_->AddObserver(&observer);
2201 StartSync();
2203 EXPECT_EQ(1, observer.get_started());
2204 EXPECT_EQ(0, observer.get_completed_count_at_started());
2205 EXPECT_EQ(1, observer.get_completed());
2207 model_->RemoveObserver(&observer);
2210 // Verify that the creation_time_us changes are applied in the local model at
2211 // association time and update time.
2212 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateDateAdded) {
2213 // TODO(stanisc): crbug.com/456876: Remove this once the optimistic
2214 // association experiment has ended.
2215 base::FieldTrialList field_trial_list(new base::MockEntropyProvider());
2216 base::FieldTrialList::CreateFieldTrial("SyncOptimisticBookmarkAssociation",
2217 "Enabled");
2219 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2220 WriteTestDataToBookmarkModel();
2222 // Start and stop sync in order to create bookmark nodes in the sync db.
2223 StartSync();
2224 StopSync();
2226 // Modify the date_added field of a bookmark so it doesn't match with
2227 // the sync data.
2228 const BookmarkNode* bookmark_bar_node = model_->bookmark_bar_node();
2229 int modified_index = 2;
2230 ASSERT_GT(bookmark_bar_node->child_count(), modified_index);
2231 const BookmarkNode* child_node = bookmark_bar_node->GetChild(modified_index);
2232 ASSERT_TRUE(child_node);
2233 EXPECT_TRUE(child_node->is_url());
2234 model_->SetDateAdded(child_node, base::Time::FromInternalValue(10));
2236 StartSync();
2237 StopSync();
2239 // Verify that transaction versions are in sync between the native model
2240 // and Sync.
2242 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2243 int64 sync_version = trans.GetModelVersion(syncer::BOOKMARKS);
2244 int64 native_version = model_->root_node()->sync_transaction_version();
2245 EXPECT_EQ(native_version, sync_version);
2248 // Since the version is in sync the association above should have skipped
2249 // updating the native node above. That is expected optimization (see
2250 // crbug/464907.
2251 EXPECT_EQ(child_node->date_added(), base::Time::FromInternalValue(10));
2253 // Reset transaction version on the native model to trigger conservative
2254 // association algorithm.
2255 model_->SetNodeSyncTransactionVersion(
2256 model_->root_node(), syncer::syncable::kInvalidTransactionVersion);
2258 StartSync();
2260 // Everything should be back in sync after model association.
2261 ExpectBookmarkModelMatchesTestData();
2262 ExpectModelMatch();
2264 // Now trigger a change while syncing. We add a new bookmark, sync it, then
2265 // updates it's creation time.
2266 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2267 FakeServerChange adds(&trans);
2268 const std::string kTitle = "Some site";
2269 const std::string kUrl = "http://www.whatwhat.yeah/";
2270 const int kCreationTime = 30;
2271 int64 id = adds.AddURL(kTitle, kUrl,
2272 bookmark_bar_id(), 0);
2273 adds.ApplyPendingChanges(change_processor_.get());
2274 FakeServerChange updates(&trans);
2275 updates.ModifyCreationTime(id, kCreationTime);
2276 updates.ApplyPendingChanges(change_processor_.get());
2278 const BookmarkNode* node = model_->bookmark_bar_node()->GetChild(0);
2279 ASSERT_TRUE(node);
2280 EXPECT_TRUE(node->is_url());
2281 EXPECT_EQ(base::UTF8ToUTF16(kTitle), node->GetTitle());
2282 EXPECT_EQ(kUrl, node->url().possibly_invalid_spec());
2283 EXPECT_EQ(node->date_added(), base::Time::FromInternalValue(30));
2286 // Tests that changes to the sync nodes meta info gets reflected in the local
2287 // bookmark model.
2288 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromSync) {
2289 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2290 WriteTestDataToBookmarkModel();
2291 StartSync();
2293 // Create bookmark nodes containing meta info.
2294 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2295 FakeServerChange adds(&trans);
2296 BookmarkNode::MetaInfoMap folder_meta_info;
2297 folder_meta_info["folder"] = "foldervalue";
2298 int64 folder_id = adds.AddFolderWithMetaInfo(
2299 "folder title", &folder_meta_info, bookmark_bar_id(), 0);
2300 BookmarkNode::MetaInfoMap node_meta_info;
2301 node_meta_info["node"] = "nodevalue";
2302 node_meta_info["other"] = "othervalue";
2303 int64 id = adds.AddURLWithMetaInfo("node title", "http://www.foo.com",
2304 &node_meta_info, folder_id, 0);
2305 adds.ApplyPendingChanges(change_processor_.get());
2307 // Verify that the nodes are created with the correct meta info.
2308 ASSERT_LT(0, model_->bookmark_bar_node()->child_count());
2309 const BookmarkNode* folder_node = model_->bookmark_bar_node()->GetChild(0);
2310 ASSERT_TRUE(folder_node->GetMetaInfoMap());
2311 EXPECT_EQ(folder_meta_info, *folder_node->GetMetaInfoMap());
2312 ASSERT_LT(0, folder_node->child_count());
2313 const BookmarkNode* node = folder_node->GetChild(0);
2314 ASSERT_TRUE(node->GetMetaInfoMap());
2315 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
2317 // Update meta info on nodes on server
2318 FakeServerChange updates(&trans);
2319 folder_meta_info.erase("folder");
2320 updates.ModifyMetaInfo(folder_id, folder_meta_info);
2321 node_meta_info["node"] = "changednodevalue";
2322 node_meta_info.erase("other");
2323 node_meta_info["newkey"] = "newkeyvalue";
2324 updates.ModifyMetaInfo(id, node_meta_info);
2325 updates.ApplyPendingChanges(change_processor_.get());
2327 // Confirm that the updated values are reflected in the bookmark nodes.
2328 EXPECT_FALSE(folder_node->GetMetaInfoMap());
2329 ASSERT_TRUE(node->GetMetaInfoMap());
2330 EXPECT_EQ(node_meta_info, *node->GetMetaInfoMap());
2333 // Tests that changes to the local bookmark nodes meta info gets reflected in
2334 // the sync nodes.
2335 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateMetaInfoFromModel) {
2336 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2337 WriteTestDataToBookmarkModel();
2338 StartSync();
2339 ExpectBookmarkModelMatchesTestData();
2341 const BookmarkNode* folder_node =
2342 model_->AddFolder(model_->bookmark_bar_node(), 0,
2343 base::ASCIIToUTF16("folder title"));
2344 const BookmarkNode* node = model_->AddURL(folder_node, 0,
2345 base::ASCIIToUTF16("node title"),
2346 GURL("http://www.foo.com"));
2347 ExpectModelMatch();
2349 // Add some meta info and verify sync model matches the changes.
2350 model_->SetNodeMetaInfo(folder_node, "folder", "foldervalue");
2351 model_->SetNodeMetaInfo(node, "node", "nodevalue");
2352 model_->SetNodeMetaInfo(node, "other", "othervalue");
2353 ExpectModelMatch();
2355 // Change/delete existing meta info and verify.
2356 model_->DeleteNodeMetaInfo(folder_node, "folder");
2357 model_->SetNodeMetaInfo(node, "node", "changednodevalue");
2358 model_->DeleteNodeMetaInfo(node, "other");
2359 model_->SetNodeMetaInfo(node, "newkey", "newkeyvalue");
2360 ExpectModelMatch();
2363 // Tests that node's specifics doesn't get unnecessarily overwritten (causing
2364 // a subsequent commit) when BookmarkChangeProcessor handles a notification
2365 // (such as BookmarkMetaInfoChanged) without an actual data change.
2366 TEST_F(ProfileSyncServiceBookmarkTestWithData, MetaInfoPreservedOnNonChange) {
2367 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2368 WriteTestDataToBookmarkModel();
2369 StartSync();
2371 std::string orig_specifics;
2372 int64 sync_id;
2373 const BookmarkNode* bookmark;
2375 // Create bookmark folder node containing meta info.
2377 syncer::WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
2378 FakeServerChange adds(&trans);
2380 int64 folder_id = adds.AddFolder("folder title", bookmark_bar_id(), 0);
2382 BookmarkNode::MetaInfoMap node_meta_info;
2383 node_meta_info["one"] = "1";
2384 node_meta_info["two"] = "2";
2385 node_meta_info["three"] = "3";
2387 sync_id = adds.AddURLWithMetaInfo("node title", "http://www.foo.com/",
2388 &node_meta_info, folder_id, 0);
2390 // Verify that the node propagates to the bookmark model
2391 adds.ApplyPendingChanges(change_processor_.get());
2393 bookmark = model_->bookmark_bar_node()->GetChild(0)->GetChild(0);
2394 EXPECT_EQ(node_meta_info, *bookmark->GetMetaInfoMap());
2396 syncer::ReadNode sync_node(&trans);
2397 EXPECT_EQ(BaseNode::INIT_OK, sync_node.InitByIdLookup(sync_id));
2398 orig_specifics = sync_node.GetBookmarkSpecifics().SerializeAsString();
2401 // Force change processor to update the sync node.
2402 change_processor_->BookmarkMetaInfoChanged(model_, bookmark);
2404 // Read bookmark specifics again and verify that there is no change.
2406 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2407 syncer::ReadNode sync_node(&trans);
2408 EXPECT_EQ(BaseNode::INIT_OK, sync_node.InitByIdLookup(sync_id));
2409 std::string new_specifics =
2410 sync_node.GetBookmarkSpecifics().SerializeAsString();
2411 ASSERT_EQ(orig_specifics, new_specifics);
2415 void ProfileSyncServiceBookmarkTestWithData::GetTransactionVersions(
2416 const BookmarkNode* root,
2417 BookmarkNodeVersionMap* node_versions) {
2418 node_versions->clear();
2419 std::queue<const BookmarkNode*> nodes;
2420 nodes.push(root);
2421 while (!nodes.empty()) {
2422 const BookmarkNode* n = nodes.front();
2423 nodes.pop();
2425 int64 version = n->sync_transaction_version();
2426 EXPECT_NE(BookmarkNode::kInvalidSyncTransactionVersion, version);
2428 (*node_versions)[n->id()] = version;
2429 for (int i = 0; i < n->child_count(); ++i) {
2430 if (!CanSyncNode(n->GetChild(i)))
2431 continue;
2432 nodes.push(n->GetChild(i));
2437 void ProfileSyncServiceBookmarkTestWithData::ExpectTransactionVersionMatch(
2438 const BookmarkNode* node,
2439 const BookmarkNodeVersionMap& version_expected) {
2440 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2442 BookmarkNodeVersionMap bnodes_versions;
2443 GetTransactionVersions(node, &bnodes_versions);
2444 for (BookmarkNodeVersionMap::const_iterator it = bnodes_versions.begin();
2445 it != bnodes_versions.end(); ++it) {
2446 syncer::ReadNode sync_node(&trans);
2447 ASSERT_TRUE(model_associator_->InitSyncNodeFromChromeId(it->first,
2448 &sync_node));
2449 EXPECT_EQ(sync_node.GetEntry()->GetTransactionVersion(), it->second);
2450 BookmarkNodeVersionMap::const_iterator expected_ver_it =
2451 version_expected.find(it->first);
2452 if (expected_ver_it != version_expected.end())
2453 EXPECT_EQ(expected_ver_it->second, it->second);
2457 // Test transaction versions of model and nodes are incremented after changes
2458 // are applied.
2459 TEST_F(ProfileSyncServiceBookmarkTestWithData, UpdateTransactionVersion) {
2460 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2461 StartSync();
2462 WriteTestDataToBookmarkModel();
2463 base::MessageLoop::current()->RunUntilIdle();
2465 BookmarkNodeVersionMap initial_versions;
2467 // Verify transaction versions in sync model and bookmark model (saved as
2468 // transaction version of root node) are equal after
2469 // WriteTestDataToBookmarkModel() created bookmarks.
2471 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2472 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2473 GetTransactionVersions(model_->root_node(), &initial_versions);
2474 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2475 initial_versions[model_->root_node()->id()]);
2477 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2478 BookmarkNodeVersionMap());
2479 ExpectTransactionVersionMatch(model_->other_node(),
2480 BookmarkNodeVersionMap());
2481 ExpectTransactionVersionMatch(model_->mobile_node(),
2482 BookmarkNodeVersionMap());
2484 // Verify model version is incremented and bookmark node versions remain
2485 // the same.
2486 const BookmarkNode* bookmark_bar = model_->bookmark_bar_node();
2487 model_->Remove(bookmark_bar->GetChild(0));
2488 base::MessageLoop::current()->RunUntilIdle();
2489 BookmarkNodeVersionMap new_versions;
2490 GetTransactionVersions(model_->root_node(), &new_versions);
2491 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 1,
2492 new_versions[model_->root_node()->id()]);
2493 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2494 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2495 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2497 // Verify model version and version of changed bookmark are incremented and
2498 // versions of others remain same.
2499 const BookmarkNode* changed_bookmark =
2500 model_->bookmark_bar_node()->GetChild(0);
2501 model_->SetTitle(changed_bookmark, base::ASCIIToUTF16("test"));
2502 base::MessageLoop::current()->RunUntilIdle();
2503 GetTransactionVersions(model_->root_node(), &new_versions);
2504 EXPECT_EQ(initial_versions[model_->root_node()->id()] + 2,
2505 new_versions[model_->root_node()->id()]);
2506 EXPECT_LT(initial_versions[changed_bookmark->id()],
2507 new_versions[changed_bookmark->id()]);
2508 initial_versions.erase(changed_bookmark->id());
2509 ExpectTransactionVersionMatch(model_->bookmark_bar_node(), initial_versions);
2510 ExpectTransactionVersionMatch(model_->other_node(), initial_versions);
2511 ExpectTransactionVersionMatch(model_->mobile_node(), initial_versions);
2514 // Test that sync persistence errors are detected and trigger a failed
2515 // association.
2516 TEST_F(ProfileSyncServiceBookmarkTestWithData, PersistenceError) {
2517 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2518 StartSync();
2519 WriteTestDataToBookmarkModel();
2520 base::MessageLoop::current()->RunUntilIdle();
2522 BookmarkNodeVersionMap initial_versions;
2524 // Verify transaction versions in sync model and bookmark model (saved as
2525 // transaction version of root node) are equal after
2526 // WriteTestDataToBookmarkModel() created bookmarks.
2528 syncer::ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
2529 EXPECT_GT(trans.GetModelVersion(syncer::BOOKMARKS), 0);
2530 GetTransactionVersions(model_->root_node(), &initial_versions);
2531 EXPECT_EQ(trans.GetModelVersion(syncer::BOOKMARKS),
2532 initial_versions[model_->root_node()->id()]);
2534 ExpectTransactionVersionMatch(model_->bookmark_bar_node(),
2535 BookmarkNodeVersionMap());
2536 ExpectTransactionVersionMatch(model_->other_node(),
2537 BookmarkNodeVersionMap());
2538 ExpectTransactionVersionMatch(model_->mobile_node(),
2539 BookmarkNodeVersionMap());
2541 // Now shut down sync and artificially increment the native model's version.
2542 StopSync();
2543 int64 root_version = initial_versions[model_->root_node()->id()];
2544 model_->SetNodeSyncTransactionVersion(model_->root_node(), root_version + 1);
2546 // Upon association, bookmarks should fail to associate.
2547 EXPECT_FALSE(AssociateModels());
2550 // It's possible for update/add calls from the bookmark model to be out of
2551 // order, or asynchronous. Handle that without triggering an error.
2552 TEST_F(ProfileSyncServiceBookmarkTest, UpdateThenAdd) {
2553 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2554 StartSync();
2556 EXPECT_TRUE(other_bookmarks_id());
2557 EXPECT_TRUE(bookmark_bar_id());
2558 EXPECT_TRUE(mobile_bookmarks_id());
2560 ExpectModelMatch();
2562 // Now destroy the change processor then add a bookmark, to simulate
2563 // missing the Update call.
2564 change_processor_.reset();
2565 const BookmarkNode* node = model_->AddURL(model_->bookmark_bar_node(),
2567 base::ASCIIToUTF16("title"),
2568 GURL("http://www.url.com"));
2570 // Recreate the change processor then update that bookmark. Sync should
2571 // receive the update call and gracefully treat that as if it were an add.
2572 change_processor_.reset(new BookmarkChangeProcessor(
2573 &profile_, model_associator_.get(), &mock_error_handler_));
2574 change_processor_->Start(test_user_share_.user_share());
2575 model_->SetTitle(node, base::ASCIIToUTF16("title2"));
2576 ExpectModelMatch();
2578 // Then simulate the add call arriving late.
2579 change_processor_->BookmarkNodeAdded(model_, model_->bookmark_bar_node(), 0);
2580 ExpectModelMatch();
2583 // Verify operations on native nodes that shouldn't be propagated to Sync.
2584 TEST_F(ProfileSyncServiceBookmarkTest, TestUnsupportedNodes) {
2585 LoadBookmarkModel(DELETE_EXISTING_STORAGE, DONT_SAVE_TO_STORAGE);
2586 StartSync();
2588 // Initial number of bookmarks on the sync side.
2589 int sync_bookmark_count = GetSyncBookmarkCount();
2591 // Create a bookmark under managed_node() permanent folder.
2592 bookmarks::ManagedBookmarkService* managed_bookmark_service =
2593 ManagedBookmarkServiceFactory::GetForProfile(&profile_);
2594 const BookmarkNode* folder = managed_bookmark_service->managed_node();
2595 const BookmarkNode* node = model_->AddURL(
2596 folder, 0, base::ASCIIToUTF16("node"), GURL("http://www.node.com/"));
2598 // Verify that these changes are ignored by Sync.
2599 EXPECT_EQ(sync_bookmark_count, GetSyncBookmarkCount());
2600 int64 sync_id = model_associator_->GetSyncIdFromChromeId(node->id());
2601 EXPECT_EQ(syncer::kInvalidId, sync_id);
2603 // Verify that Sync ignores deleting this node.
2604 model_->Remove(node);
2605 EXPECT_EQ(sync_bookmark_count, GetSyncBookmarkCount());
2608 } // namespace
2610 } // namespace browser_sync