Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(171)

Side by Side Diff: chrome/browser/sync/profile_sync_service_bookmark_unittest.cc

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

Powered by Google App Engine
This is Rietveld 408576698