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