Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / sync / test / integration / bookmarks_helper.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 #include "chrome/browser/sync/test/integration/bookmarks_helper.h"
6
7 #include "base/bind.h"
8 #include "base/compiler_specific.h"
9 #include "base/files/file_util.h"
10 #include "base/path_service.h"
11 #include "base/rand_util.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/synchronization/waitable_event.h"
17 #include "base/task/cancelable_task_tracker.h"
18 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
19 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
20 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
21 #include "chrome/browser/favicon/favicon_service.h"
22 #include "chrome/browser/favicon/favicon_service_factory.h"
23 #include "chrome/browser/history/history_db_task.h"
24 #include "chrome/browser/history/history_service.h"
25 #include "chrome/browser/history/history_service_factory.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/sync/glue/bookmark_change_processor.h"
28 #include "chrome/browser/sync/test/integration/multi_client_status_change_checker.h"
29 #include "chrome/browser/sync/test/integration/profile_sync_service_harness.h"
30 #include "chrome/browser/sync/test/integration/sync_datatype_helper.h"
31 #include "chrome/browser/sync/test/integration/sync_test.h"
32 #include "chrome/common/chrome_paths.h"
33 #include "components/bookmarks/browser/bookmark_client.h"
34 #include "components/bookmarks/browser/bookmark_model.h"
35 #include "components/bookmarks/browser/bookmark_model_observer.h"
36 #include "components/bookmarks/browser/bookmark_utils.h"
37 #include "components/favicon_base/favicon_util.h"
38 #include "components/history/core/browser/history_types.h"
39 #include "content/public/test/test_utils.h"
40 #include "testing/gtest/include/gtest/gtest.h"
41 #include "third_party/skia/include/core/SkBitmap.h"
42 #include "ui/base/models/tree_node_iterator.h"
43 #include "ui/gfx/image/image_skia.h"
44
45 namespace {
46
47 // History task which runs all pending tasks on the history thread and
48 // signals when the tasks have completed.
49 class HistoryEmptyTask : public history::HistoryDBTask {
50  public:
51   explicit HistoryEmptyTask(base::WaitableEvent* done) : done_(done) {}
52
53   bool RunOnDBThread(history::HistoryBackend* backend,
54                      history::HistoryDatabase* db) override {
55     content::RunAllPendingInMessageLoop();
56     done_->Signal();
57     return true;
58   }
59
60   void DoneRunOnMainThread() override {}
61
62  private:
63   ~HistoryEmptyTask() override {}
64
65   base::WaitableEvent* done_;
66 };
67
68 // Helper class used to wait for changes to take effect on the favicon of a
69 // particular bookmark node in a particular bookmark model.
70 class FaviconChangeObserver : public BookmarkModelObserver {
71  public:
72   FaviconChangeObserver(BookmarkModel* model, const BookmarkNode* node)
73       : model_(model),
74         node_(node),
75         wait_for_load_(false) {
76     model->AddObserver(this);
77   }
78   ~FaviconChangeObserver() override { model_->RemoveObserver(this); }
79   void WaitForGetFavicon() {
80     wait_for_load_ = true;
81     content::RunMessageLoop();
82     ASSERT_TRUE(node_->is_favicon_loaded());
83     ASSERT_FALSE(model_->GetFavicon(node_).IsEmpty());
84   }
85   void WaitForSetFavicon() {
86     wait_for_load_ = false;
87     content::RunMessageLoop();
88   }
89   void BookmarkModelLoaded(BookmarkModel* model, bool ids_reassigned) override {
90   }
91   void BookmarkNodeMoved(BookmarkModel* model,
92                          const BookmarkNode* old_parent,
93                          int old_index,
94                          const BookmarkNode* new_parent,
95                          int new_index) override {}
96   void BookmarkNodeAdded(BookmarkModel* model,
97                          const BookmarkNode* parent,
98                          int index) override {}
99   void BookmarkNodeRemoved(BookmarkModel* model,
100                            const BookmarkNode* parent,
101                            int old_index,
102                            const BookmarkNode* node,
103                            const std::set<GURL>& removed_urls) override {}
104   void BookmarkAllUserNodesRemoved(
105       BookmarkModel* model,
106       const std::set<GURL>& removed_urls) override {}
107
108   void BookmarkNodeChanged(BookmarkModel* model,
109                            const BookmarkNode* node) override {
110     if (model == model_ && node == node_)
111       model->GetFavicon(node);
112   }
113   void BookmarkNodeChildrenReordered(BookmarkModel* model,
114                                      const BookmarkNode* node) override {}
115   void BookmarkNodeFaviconChanged(BookmarkModel* model,
116                                   const BookmarkNode* node) override {
117     if (model == model_ && node == node_) {
118       if (!wait_for_load_ || (wait_for_load_ && node->is_favicon_loaded()))
119         base::MessageLoopForUI::current()->Quit();
120     }
121   }
122
123  private:
124   BookmarkModel* model_;
125   const BookmarkNode* node_;
126   bool wait_for_load_;
127   DISALLOW_COPY_AND_ASSIGN(FaviconChangeObserver);
128 };
129
130 // A collection of URLs for which we have added favicons. Since loading a
131 // favicon is an asynchronous operation and doesn't necessarily invoke a
132 // callback, this collection is used to determine if we must wait for a URL's
133 // favicon to load or not.
134 std::set<GURL>* urls_with_favicons_ = NULL;
135
136 // Returns the number of nodes of node type |node_type| in |model| whose
137 // titles match the string |title|.
138 int CountNodesWithTitlesMatching(BookmarkModel* model,
139                                  BookmarkNode::Type node_type,
140                                  const base::string16& title) {
141   ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
142   // Walk through the model tree looking for bookmark nodes of node type
143   // |node_type| whose titles match |title|.
144   int count = 0;
145   while (iterator.has_next()) {
146     const BookmarkNode* node = iterator.Next();
147     if ((node->type() == node_type) && (node->GetTitle() == title))
148       ++count;
149   }
150   return count;
151 }
152
153 // Checks if the favicon data in |bitmap_a| and |bitmap_b| are equivalent.
154 // Returns true if they match.
155 bool FaviconRawBitmapsMatch(const SkBitmap& bitmap_a,
156                             const SkBitmap& bitmap_b) {
157   if (bitmap_a.getSize() == 0U && bitmap_b.getSize() == 0U)
158     return true;
159   if ((bitmap_a.getSize() != bitmap_b.getSize()) ||
160       (bitmap_a.width() != bitmap_b.width()) ||
161       (bitmap_a.height() != bitmap_b.height())) {
162     LOG(ERROR) << "Favicon size mismatch: " << bitmap_a.getSize() << " ("
163                << bitmap_a.width() << "x" << bitmap_a.height() << ") vs. "
164                << bitmap_b.getSize() << " (" << bitmap_b.width() << "x"
165                << bitmap_b.height() << ")";
166     return false;
167   }
168   SkAutoLockPixels bitmap_lock_a(bitmap_a);
169   SkAutoLockPixels bitmap_lock_b(bitmap_b);
170   void* node_pixel_addr_a = bitmap_a.getPixels();
171   EXPECT_TRUE(node_pixel_addr_a);
172   void* node_pixel_addr_b = bitmap_b.getPixels();
173   EXPECT_TRUE(node_pixel_addr_b);
174   if (memcmp(node_pixel_addr_a, node_pixel_addr_b, bitmap_a.getSize()) !=  0) {
175     LOG(ERROR) << "Favicon bitmap mismatch";
176     return false;
177   } else {
178     return true;
179   }
180 }
181
182 // Represents a favicon image and the icon URL associated with it.
183 struct FaviconData {
184   FaviconData() {
185   }
186
187   FaviconData(const gfx::Image& favicon_image,
188               const GURL& favicon_url)
189       : image(favicon_image),
190         icon_url(favicon_url) {
191   }
192
193   ~FaviconData() {
194   }
195
196   gfx::Image image;
197   GURL icon_url;
198 };
199
200 // Gets the favicon and icon URL associated with |node| in |model|.
201 FaviconData GetFaviconData(BookmarkModel* model,
202                            const BookmarkNode* node) {
203   // If a favicon wasn't explicitly set for a particular URL, simply return its
204   // blank favicon.
205   if (!urls_with_favicons_ ||
206       urls_with_favicons_->find(node->url()) == urls_with_favicons_->end()) {
207     return FaviconData();
208   }
209   // If a favicon was explicitly set, we may need to wait for it to be loaded
210   // via BookmarkModel::GetFavicon(), which is an asynchronous operation.
211   if (!node->is_favicon_loaded()) {
212     FaviconChangeObserver observer(model, node);
213     model->GetFavicon(node);
214     observer.WaitForGetFavicon();
215   }
216   EXPECT_TRUE(node->is_favicon_loaded());
217   EXPECT_FALSE(model->GetFavicon(node).IsEmpty());
218   return FaviconData(model->GetFavicon(node), node->icon_url());
219 }
220
221 // Sets the favicon for |profile| and |node|. |profile| may be
222 // |test()->verifier()|.
223 void SetFaviconImpl(Profile* profile,
224                     const BookmarkNode* node,
225                     const GURL& icon_url,
226                     const gfx::Image& image,
227                     bookmarks_helper::FaviconSource favicon_source) {
228     BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile);
229
230     FaviconChangeObserver observer(model, node);
231     FaviconService* favicon_service =
232         FaviconServiceFactory::GetForProfile(profile,
233                                              Profile::EXPLICIT_ACCESS);
234     if (favicon_source == bookmarks_helper::FROM_UI) {
235       favicon_service->SetFavicons(
236           node->url(), icon_url, favicon_base::FAVICON, image);
237     } else {
238       browser_sync::BookmarkChangeProcessor::ApplyBookmarkFavicon(
239           node, profile, icon_url, image.As1xPNGBytes());
240     }
241
242     // Wait for the favicon for |node| to be invalidated.
243     observer.WaitForSetFavicon();
244     // Wait for the BookmarkModel to fetch the updated favicon and for the new
245     // favicon to be sent to BookmarkChangeProcessor.
246     GetFaviconData(model, node);
247 }
248
249 // Wait for all currently scheduled tasks on the history thread for all
250 // profiles to complete and any notifications sent to the UI thread to have
251 // finished processing.
252 void WaitForHistoryToProcessPendingTasks() {
253   // Skip waiting for history to complete for tests without favicons.
254   if (!urls_with_favicons_)
255     return;
256
257   std::vector<Profile*> profiles_which_need_to_wait;
258   if (sync_datatype_helper::test()->use_verifier())
259     profiles_which_need_to_wait.push_back(
260         sync_datatype_helper::test()->verifier());
261   for (int i = 0; i < sync_datatype_helper::test()->num_clients(); ++i)
262     profiles_which_need_to_wait.push_back(
263         sync_datatype_helper::test()->GetProfile(i));
264
265   for (size_t i = 0; i < profiles_which_need_to_wait.size(); ++i) {
266     Profile* profile = profiles_which_need_to_wait[i];
267     HistoryService* history_service =
268         HistoryServiceFactory::GetForProfileWithoutCreating(profile);
269     base::WaitableEvent done(false, false);
270     base::CancelableTaskTracker task_tracker;
271     history_service->ScheduleDBTask(
272         scoped_ptr<history::HistoryDBTask>(
273             new HistoryEmptyTask(&done)),
274         &task_tracker);
275     done.Wait();
276   }
277   // Wait such that any notifications broadcast from one of the history threads
278   // to the UI thread are processed.
279   content::RunAllPendingInMessageLoop();
280 }
281
282 // Checks if the favicon in |node_a| from |model_a| matches that of |node_b|
283 // from |model_b|. Returns true if they match.
284 bool FaviconsMatch(BookmarkModel* model_a,
285                    BookmarkModel* model_b,
286                    const BookmarkNode* node_a,
287                    const BookmarkNode* node_b) {
288   FaviconData favicon_data_a = GetFaviconData(model_a, node_a);
289   FaviconData favicon_data_b = GetFaviconData(model_b, node_b);
290
291   if (favicon_data_a.icon_url != favicon_data_b.icon_url)
292     return false;
293
294   gfx::Image image_a = favicon_data_a.image;
295   gfx::Image image_b = favicon_data_b.image;
296
297   if (image_a.IsEmpty() && image_b.IsEmpty())
298     return true;  // Two empty images are equivalent.
299
300   if (image_a.IsEmpty() != image_b.IsEmpty())
301     return false;
302
303   // Compare only the 1x bitmaps as only those are synced.
304   SkBitmap bitmap_a = image_a.AsImageSkia().GetRepresentation(
305       1.0f).sk_bitmap();
306   SkBitmap bitmap_b = image_b.AsImageSkia().GetRepresentation(
307       1.0f).sk_bitmap();
308   return FaviconRawBitmapsMatch(bitmap_a, bitmap_b);
309 }
310
311 // Does a deep comparison of BookmarkNode fields in |model_a| and |model_b|.
312 // Returns true if they are all equal.
313 bool NodesMatch(const BookmarkNode* node_a, const BookmarkNode* node_b) {
314   if (node_a == NULL || node_b == NULL)
315     return node_a == node_b;
316   if (node_a->is_folder() != node_b->is_folder()) {
317     LOG(ERROR) << "Cannot compare folder with bookmark";
318     return false;
319   }
320   if (node_a->GetTitle() != node_b->GetTitle()) {
321     LOG(ERROR) << "Title mismatch: " << node_a->GetTitle() << " vs. "
322                << node_b->GetTitle();
323     return false;
324   }
325   if (node_a->url() != node_b->url()) {
326     LOG(ERROR) << "URL mismatch: " << node_a->url() << " vs. "
327                << node_b->url();
328     return false;
329   }
330   if (node_a->parent()->GetIndexOf(node_a) !=
331       node_b->parent()->GetIndexOf(node_b)) {
332     LOG(ERROR) << "Index mismatch: "
333                << node_a->parent()->GetIndexOf(node_a) << " vs. "
334                << node_b->parent()->GetIndexOf(node_b);
335     return false;
336   }
337   return true;
338 }
339
340 // Helper for BookmarkModelsMatch.
341 bool NodeCantBeSynced(bookmarks::BookmarkClient* client,
342                       const BookmarkNode* node) {
343   // Return true to skip a node.
344   return !client->CanSyncNode(node);
345 }
346
347 // Checks if the hierarchies in |model_a| and |model_b| are equivalent in
348 // terms of the data model and favicon. Returns true if they both match.
349 // Note: Some peripheral fields like creation times are allowed to mismatch.
350 bool BookmarkModelsMatch(BookmarkModel* model_a, BookmarkModel* model_b) {
351   bool ret_val = true;
352   ui::TreeNodeIterator<const BookmarkNode> iterator_a(
353       model_a->root_node(), base::Bind(&NodeCantBeSynced, model_a->client()));
354   ui::TreeNodeIterator<const BookmarkNode> iterator_b(
355       model_b->root_node(), base::Bind(&NodeCantBeSynced, model_b->client()));
356   while (iterator_a.has_next()) {
357     const BookmarkNode* node_a = iterator_a.Next();
358     if (!iterator_b.has_next()) {
359       LOG(ERROR) << "Models do not match.";
360       return false;
361     }
362     const BookmarkNode* node_b = iterator_b.Next();
363     ret_val = ret_val && NodesMatch(node_a, node_b);
364     if (node_a->is_folder() || node_b->is_folder())
365       continue;
366     ret_val = ret_val && FaviconsMatch(model_a, model_b, node_a, node_b);
367   }
368   ret_val = ret_val && (!iterator_b.has_next());
369   return ret_val;
370 }
371
372 // Finds the node in the verifier bookmark model that corresponds to
373 // |foreign_node| in |foreign_model| and stores its address in |result|.
374 void FindNodeInVerifier(BookmarkModel* foreign_model,
375                         const BookmarkNode* foreign_node,
376                         const BookmarkNode** result) {
377   // Climb the tree.
378   std::stack<int> path;
379   const BookmarkNode* walker = foreign_node;
380   while (walker != foreign_model->root_node()) {
381     path.push(walker->parent()->GetIndexOf(walker));
382     walker = walker->parent();
383   }
384
385   // Swing over to the other tree.
386   walker = bookmarks_helper::GetVerifierBookmarkModel()->root_node();
387
388   // Climb down.
389   while (!path.empty()) {
390     ASSERT_TRUE(walker->is_folder());
391     ASSERT_LT(path.top(), walker->child_count());
392     walker = walker->GetChild(path.top());
393     path.pop();
394   }
395
396   ASSERT_TRUE(NodesMatch(foreign_node, walker));
397   *result = walker;
398 }
399
400 }  // namespace
401
402
403 namespace bookmarks_helper {
404
405 BookmarkModel* GetBookmarkModel(int index) {
406   return BookmarkModelFactory::GetForProfile(
407       sync_datatype_helper::test()->GetProfile(index));
408 }
409
410 const BookmarkNode* GetBookmarkBarNode(int index) {
411   return GetBookmarkModel(index)->bookmark_bar_node();
412 }
413
414 const BookmarkNode* GetOtherNode(int index) {
415   return GetBookmarkModel(index)->other_node();
416 }
417
418 const BookmarkNode* GetSyncedBookmarksNode(int index) {
419   return GetBookmarkModel(index)->mobile_node();
420 }
421
422 const BookmarkNode* GetManagedNode(int index) {
423   return ChromeBookmarkClientFactory::GetForProfile(
424       sync_datatype_helper::test()->GetProfile(index))->managed_node();
425 }
426
427 BookmarkModel* GetVerifierBookmarkModel() {
428   return BookmarkModelFactory::GetForProfile(
429       sync_datatype_helper::test()->verifier());
430 }
431
432 const BookmarkNode* AddURL(int profile,
433                            const std::string& title,
434                            const GURL& url) {
435   return AddURL(profile, GetBookmarkBarNode(profile), 0, title,  url);
436 }
437
438 const BookmarkNode* AddURL(int profile,
439                            int index,
440                            const std::string& title,
441                            const GURL& url) {
442   return AddURL(profile, GetBookmarkBarNode(profile), index, title, url);
443 }
444
445 const BookmarkNode* AddURL(int profile,
446                            const BookmarkNode* parent,
447                            int index,
448                            const std::string& title,
449                            const GURL& url) {
450   BookmarkModel* model = GetBookmarkModel(profile);
451   if (bookmarks::GetBookmarkNodeByID(model, parent->id()) != parent) {
452     LOG(ERROR) << "Node " << parent->GetTitle() << " does not belong to "
453                << "Profile " << profile;
454     return NULL;
455   }
456   const BookmarkNode* result =
457       model->AddURL(parent, index, base::UTF8ToUTF16(title), url);
458   if (!result) {
459     LOG(ERROR) << "Could not add bookmark " << title << " to Profile "
460                << profile;
461     return NULL;
462   }
463   if (sync_datatype_helper::test()->use_verifier()) {
464     const BookmarkNode* v_parent = NULL;
465     FindNodeInVerifier(model, parent, &v_parent);
466     const BookmarkNode* v_node = GetVerifierBookmarkModel()->AddURL(
467         v_parent, index, base::UTF8ToUTF16(title), url);
468     if (!v_node) {
469       LOG(ERROR) << "Could not add bookmark " << title << " to the verifier";
470       return NULL;
471     }
472     EXPECT_TRUE(NodesMatch(v_node, result));
473   }
474   return result;
475 }
476
477 const BookmarkNode* AddFolder(int profile,
478                               const std::string& title) {
479   return AddFolder(profile, GetBookmarkBarNode(profile), 0, title);
480 }
481
482 const BookmarkNode* AddFolder(int profile,
483                               int index,
484                               const std::string& title) {
485   return AddFolder(profile, GetBookmarkBarNode(profile), index, title);
486 }
487
488 const BookmarkNode* AddFolder(int profile,
489                               const BookmarkNode* parent,
490                               int index,
491                               const std::string& title) {
492   BookmarkModel* model = GetBookmarkModel(profile);
493   if (bookmarks::GetBookmarkNodeByID(model, parent->id()) != parent) {
494     LOG(ERROR) << "Node " << parent->GetTitle() << " does not belong to "
495                << "Profile " << profile;
496     return NULL;
497   }
498   const BookmarkNode* result =
499       model->AddFolder(parent, index, base::UTF8ToUTF16(title));
500   EXPECT_TRUE(result);
501   if (!result) {
502     LOG(ERROR) << "Could not add folder " << title << " to Profile "
503                << profile;
504     return NULL;
505   }
506   if (sync_datatype_helper::test()->use_verifier()) {
507     const BookmarkNode* v_parent = NULL;
508     FindNodeInVerifier(model, parent, &v_parent);
509     const BookmarkNode* v_node = GetVerifierBookmarkModel()->AddFolder(
510         v_parent, index, base::UTF8ToUTF16(title));
511     if (!v_node) {
512       LOG(ERROR) << "Could not add folder " << title << " to the verifier";
513       return NULL;
514     }
515     EXPECT_TRUE(NodesMatch(v_node, result));
516   }
517   return result;
518 }
519
520 void SetTitle(int profile,
521               const BookmarkNode* node,
522               const std::string& new_title) {
523   BookmarkModel* model = GetBookmarkModel(profile);
524   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, node->id()), node)
525       << "Node " << node->GetTitle() << " does not belong to "
526       << "Profile " << profile;
527   if (sync_datatype_helper::test()->use_verifier()) {
528     const BookmarkNode* v_node = NULL;
529     FindNodeInVerifier(model, node, &v_node);
530     GetVerifierBookmarkModel()->SetTitle(v_node, base::UTF8ToUTF16(new_title));
531   }
532   model->SetTitle(node, base::UTF8ToUTF16(new_title));
533 }
534
535 void SetFavicon(int profile,
536                 const BookmarkNode* node,
537                 const GURL& icon_url,
538                 const gfx::Image& image,
539                 FaviconSource favicon_source) {
540   BookmarkModel* model = GetBookmarkModel(profile);
541   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, node->id()), node)
542       << "Node " << node->GetTitle() << " does not belong to "
543       << "Profile " << profile;
544   ASSERT_EQ(BookmarkNode::URL, node->type()) << "Node " << node->GetTitle()
545                                              << " must be a url.";
546   if (urls_with_favicons_ == NULL)
547     urls_with_favicons_ = new std::set<GURL>();
548   urls_with_favicons_->insert(node->url());
549   if (sync_datatype_helper::test()->use_verifier()) {
550     const BookmarkNode* v_node = NULL;
551     FindNodeInVerifier(model, node, &v_node);
552     SetFaviconImpl(sync_datatype_helper::test()->verifier(),
553                    v_node,
554                    icon_url,
555                    image,
556                    favicon_source);
557   }
558   SetFaviconImpl(sync_datatype_helper::test()->GetProfile(profile),
559                  node,
560                  icon_url,
561                  image,
562                  favicon_source);
563 }
564
565 const BookmarkNode* SetURL(int profile,
566                            const BookmarkNode* node,
567                            const GURL& new_url) {
568   BookmarkModel* model = GetBookmarkModel(profile);
569   if (bookmarks::GetBookmarkNodeByID(model, node->id()) != node) {
570     LOG(ERROR) << "Node " << node->GetTitle() << " does not belong to "
571                << "Profile " << profile;
572     return NULL;
573   }
574   if (sync_datatype_helper::test()->use_verifier()) {
575     const BookmarkNode* v_node = NULL;
576     FindNodeInVerifier(model, node, &v_node);
577     if (v_node->is_url())
578       GetVerifierBookmarkModel()->SetURL(v_node, new_url);
579   }
580   if (node->is_url())
581     model->SetURL(node, new_url);
582   return node;
583 }
584
585 void Move(int profile,
586           const BookmarkNode* node,
587           const BookmarkNode* new_parent,
588           int index) {
589   BookmarkModel* model = GetBookmarkModel(profile);
590   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, node->id()), node)
591       << "Node " << node->GetTitle() << " does not belong to "
592       << "Profile " << profile;
593   if (sync_datatype_helper::test()->use_verifier()) {
594     const BookmarkNode* v_new_parent = NULL;
595     const BookmarkNode* v_node = NULL;
596     FindNodeInVerifier(model, new_parent, &v_new_parent);
597     FindNodeInVerifier(model, node, &v_node);
598     GetVerifierBookmarkModel()->Move(v_node, v_new_parent, index);
599   }
600   model->Move(node, new_parent, index);
601 }
602
603 void Remove(int profile, const BookmarkNode* parent, int index) {
604   BookmarkModel* model = GetBookmarkModel(profile);
605   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, parent->id()), parent)
606       << "Node " << parent->GetTitle() << " does not belong to "
607       << "Profile " << profile;
608   if (sync_datatype_helper::test()->use_verifier()) {
609     const BookmarkNode* v_parent = NULL;
610     FindNodeInVerifier(model, parent, &v_parent);
611     ASSERT_TRUE(NodesMatch(parent->GetChild(index), v_parent->GetChild(index)));
612     GetVerifierBookmarkModel()->Remove(v_parent, index);
613   }
614   model->Remove(parent, index);
615 }
616
617 void RemoveAll(int profile) {
618   if (sync_datatype_helper::test()->use_verifier()) {
619     const BookmarkNode* root_node = GetVerifierBookmarkModel()->root_node();
620     for (int i = 0; i < root_node->child_count(); ++i) {
621       const BookmarkNode* permanent_node = root_node->GetChild(i);
622       for (int j = permanent_node->child_count() - 1; j >= 0; --j) {
623         GetVerifierBookmarkModel()->Remove(permanent_node, j);
624       }
625     }
626   }
627   GetBookmarkModel(profile)->RemoveAllUserBookmarks();
628 }
629
630 void SortChildren(int profile, const BookmarkNode* parent) {
631   BookmarkModel* model = GetBookmarkModel(profile);
632   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, parent->id()), parent)
633       << "Node " << parent->GetTitle() << " does not belong to "
634       << "Profile " << profile;
635   if (sync_datatype_helper::test()->use_verifier()) {
636     const BookmarkNode* v_parent = NULL;
637     FindNodeInVerifier(model, parent, &v_parent);
638     GetVerifierBookmarkModel()->SortChildren(v_parent);
639   }
640   model->SortChildren(parent);
641 }
642
643 void ReverseChildOrder(int profile, const BookmarkNode* parent) {
644   ASSERT_EQ(
645       bookmarks::GetBookmarkNodeByID(GetBookmarkModel(profile), parent->id()),
646       parent)
647       << "Node " << parent->GetTitle() << " does not belong to "
648       << "Profile " << profile;
649   int child_count = parent->child_count();
650   if (child_count <= 0)
651     return;
652   for (int index = 0; index < child_count; ++index) {
653     Move(profile, parent->GetChild(index), parent, child_count - index);
654   }
655 }
656
657 bool ModelMatchesVerifier(int profile) {
658   if (!sync_datatype_helper::test()->use_verifier()) {
659     LOG(ERROR) << "Illegal to call ModelMatchesVerifier() after "
660                << "DisableVerifier(). Use ModelsMatch() instead.";
661     return false;
662   }
663   return BookmarkModelsMatch(GetVerifierBookmarkModel(),
664                              GetBookmarkModel(profile));
665 }
666
667 bool AllModelsMatchVerifier() {
668   // Ensure that all tasks have finished processing on the history thread
669   // and that any notifications the history thread may have sent have been
670   // processed before comparing models.
671   WaitForHistoryToProcessPendingTasks();
672
673   for (int i = 0; i < sync_datatype_helper::test()->num_clients(); ++i) {
674     if (!ModelMatchesVerifier(i)) {
675       LOG(ERROR) << "Model " << i << " does not match the verifier.";
676       return false;
677     }
678   }
679   return true;
680 }
681
682 bool ModelsMatch(int profile_a, int profile_b) {
683   return BookmarkModelsMatch(GetBookmarkModel(profile_a),
684                              GetBookmarkModel(profile_b));
685 }
686
687 bool AllModelsMatch() {
688   // Ensure that all tasks have finished processing on the history thread
689   // and that any notifications the history thread may have sent have been
690   // processed before comparing models.
691   WaitForHistoryToProcessPendingTasks();
692
693   for (int i = 1; i < sync_datatype_helper::test()->num_clients(); ++i) {
694     if (!ModelsMatch(0, i)) {
695       LOG(ERROR) << "Model " << i << " does not match Model 0.";
696       return false;
697     }
698   }
699   return true;
700 }
701
702 namespace {
703
704 // Helper class used in the implementation of AwaitAllModelsMatch.
705 class AllModelsMatchChecker : public MultiClientStatusChangeChecker {
706  public:
707   AllModelsMatchChecker();
708   ~AllModelsMatchChecker() override;
709
710   bool IsExitConditionSatisfied() override;
711   std::string GetDebugMessage() const override;
712 };
713
714 AllModelsMatchChecker::AllModelsMatchChecker()
715     : MultiClientStatusChangeChecker(
716         sync_datatype_helper::test()->GetSyncServices()) {}
717
718 AllModelsMatchChecker::~AllModelsMatchChecker() {}
719
720 bool AllModelsMatchChecker::IsExitConditionSatisfied() {
721   return AllModelsMatch();
722 }
723
724 std::string AllModelsMatchChecker::GetDebugMessage() const {
725   return "Waiting for matching models";
726 }
727
728 }  //  namespace
729
730 bool AwaitAllModelsMatch() {
731   AllModelsMatchChecker checker;
732   checker.Wait();
733   return !checker.TimedOut();
734 }
735
736
737 bool ContainsDuplicateBookmarks(int profile) {
738   ui::TreeNodeIterator<const BookmarkNode> iterator(
739       GetBookmarkModel(profile)->root_node());
740   while (iterator.has_next()) {
741     const BookmarkNode* node = iterator.Next();
742     if (node->is_folder())
743       continue;
744     std::vector<const BookmarkNode*> nodes;
745     GetBookmarkModel(profile)->GetNodesByURL(node->url(), &nodes);
746     EXPECT_TRUE(nodes.size() >= 1);
747     for (std::vector<const BookmarkNode*>::const_iterator it = nodes.begin();
748          it != nodes.end(); ++it) {
749       if (node->id() != (*it)->id() &&
750           node->parent() == (*it)->parent() &&
751           node->GetTitle() == (*it)->GetTitle()){
752         return true;
753       }
754     }
755   }
756   return false;
757 }
758
759 bool HasNodeWithURL(int profile, const GURL& url) {
760   std::vector<const BookmarkNode*> nodes;
761   GetBookmarkModel(profile)->GetNodesByURL(url, &nodes);
762   return !nodes.empty();
763 }
764
765 const BookmarkNode* GetUniqueNodeByURL(int profile, const GURL& url) {
766   std::vector<const BookmarkNode*> nodes;
767   GetBookmarkModel(profile)->GetNodesByURL(url, &nodes);
768   EXPECT_EQ(1U, nodes.size());
769   if (nodes.empty())
770     return NULL;
771   return nodes[0];
772 }
773
774 int CountBookmarksWithTitlesMatching(int profile, const std::string& title) {
775   return CountNodesWithTitlesMatching(GetBookmarkModel(profile),
776                                       BookmarkNode::URL,
777                                       base::UTF8ToUTF16(title));
778 }
779
780 int CountFoldersWithTitlesMatching(int profile, const std::string& title) {
781   return CountNodesWithTitlesMatching(GetBookmarkModel(profile),
782                                       BookmarkNode::FOLDER,
783                                       base::UTF8ToUTF16(title));
784 }
785
786 gfx::Image CreateFavicon(SkColor color) {
787   const int dip_width = 16;
788   const int dip_height = 16;
789   std::vector<float> favicon_scales = favicon_base::GetFaviconScales();
790   gfx::ImageSkia favicon;
791   for (size_t i = 0; i < favicon_scales.size(); ++i) {
792     float scale = favicon_scales[i];
793     int pixel_width = dip_width * scale;
794     int pixel_height = dip_height * scale;
795     SkBitmap bmp;
796     bmp.allocN32Pixels(pixel_width, pixel_height);
797     bmp.eraseColor(color);
798     favicon.AddRepresentation(gfx::ImageSkiaRep(bmp, scale));
799   }
800   return gfx::Image(favicon);
801 }
802
803 gfx::Image Create1xFaviconFromPNGFile(const std::string& path) {
804   const char* kPNGExtension = ".png";
805   if (!EndsWith(path, kPNGExtension, false))
806     return gfx::Image();
807
808   base::FilePath full_path;
809   if (!PathService::Get(chrome::DIR_TEST_DATA, &full_path))
810     return gfx::Image();
811
812   full_path = full_path.AppendASCII("sync").AppendASCII(path);
813   std::string contents;
814   base::ReadFileToString(full_path, &contents);
815   return gfx::Image::CreateFrom1xPNGBytes(
816       base::RefCountedString::TakeString(&contents));
817 }
818
819 std::string IndexedURL(int i) {
820   return base::StringPrintf("http://www.host.ext:1234/path/filename/%d", i);
821 }
822
823 std::string IndexedURLTitle(int i) {
824   return base::StringPrintf("URL Title %d", i);
825 }
826
827 std::string IndexedFolderName(int i) {
828   return base::StringPrintf("Folder Name %d", i);
829 }
830
831 std::string IndexedSubfolderName(int i) {
832   return base::StringPrintf("Subfolder Name %d", i);
833 }
834
835 std::string IndexedSubsubfolderName(int i) {
836   return base::StringPrintf("Subsubfolder Name %d", i);
837 }
838
839 }  // namespace bookmarks_helper