Upstream version 9.38.198.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/compiler_specific.h"
8 #include "base/file_util.h"
9 #include "base/path_service.h"
10 #include "base/rand_util.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/synchronization/waitable_event.h"
16 #include "base/task/cancelable_task_tracker.h"
17 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
18 #include "chrome/browser/favicon/favicon_service.h"
19 #include "chrome/browser/favicon/favicon_service_factory.h"
20 #include "chrome/browser/history/history_db_task.h"
21 #include "chrome/browser/history/history_service_factory.h"
22 #include "chrome/browser/history/history_types.h"
23 #include "chrome/browser/profiles/profile.h"
24 #include "chrome/browser/sync/glue/bookmark_change_processor.h"
25 #include "chrome/browser/sync/test/integration/multi_client_status_change_checker.h"
26 #include "chrome/browser/sync/test/integration/profile_sync_service_harness.h"
27 #include "chrome/browser/sync/test/integration/sync_datatype_helper.h"
28 #include "chrome/browser/sync/test/integration/sync_test.h"
29 #include "chrome/common/chrome_paths.h"
30 #include "chrome/test/base/ui_test_utils.h"
31 #include "components/bookmarks/browser/bookmark_model.h"
32 #include "components/bookmarks/browser/bookmark_model_observer.h"
33 #include "components/bookmarks/browser/bookmark_utils.h"
34 #include "components/favicon_base/favicon_util.h"
35 #include "testing/gtest/include/gtest/gtest.h"
36 #include "third_party/skia/include/core/SkBitmap.h"
37 #include "ui/base/models/tree_node_iterator.h"
38 #include "ui/gfx/image/image_skia.h"
39
40 namespace {
41
42 // History task which runs all pending tasks on the history thread and
43 // signals when the tasks have completed.
44 class HistoryEmptyTask : public history::HistoryDBTask {
45  public:
46   explicit HistoryEmptyTask(base::WaitableEvent* done) : done_(done) {}
47
48   virtual bool RunOnDBThread(history::HistoryBackend* backend,
49                              history::HistoryDatabase* db) OVERRIDE {
50     content::RunAllPendingInMessageLoop();
51     done_->Signal();
52     return true;
53   }
54
55   virtual void DoneRunOnMainThread() OVERRIDE {}
56
57  private:
58   virtual ~HistoryEmptyTask() {}
59
60   base::WaitableEvent* done_;
61 };
62
63 // Helper class used to wait for changes to take effect on the favicon of a
64 // particular bookmark node in a particular bookmark model.
65 class FaviconChangeObserver : public BookmarkModelObserver {
66  public:
67   FaviconChangeObserver(BookmarkModel* model, const BookmarkNode* node)
68       : model_(model),
69         node_(node),
70         wait_for_load_(false) {
71     model->AddObserver(this);
72   }
73   virtual ~FaviconChangeObserver() {
74     model_->RemoveObserver(this);
75   }
76   void WaitForGetFavicon() {
77     wait_for_load_ = true;
78     content::RunMessageLoop();
79     ASSERT_TRUE(node_->is_favicon_loaded());
80     ASSERT_FALSE(model_->GetFavicon(node_).IsEmpty());
81   }
82   void WaitForSetFavicon() {
83     wait_for_load_ = false;
84     content::RunMessageLoop();
85   }
86   virtual void BookmarkModelLoaded(BookmarkModel* model,
87                                    bool ids_reassigned) OVERRIDE {}
88   virtual void BookmarkNodeMoved(BookmarkModel* model,
89                                  const BookmarkNode* old_parent,
90                                  int old_index,
91                                  const BookmarkNode* new_parent,
92                                  int new_index) OVERRIDE {}
93   virtual void BookmarkNodeAdded(BookmarkModel* model,
94                                  const BookmarkNode* parent,
95                                  int index) OVERRIDE {}
96   virtual void BookmarkNodeRemoved(
97       BookmarkModel* model,
98       const BookmarkNode* parent,
99       int old_index,
100       const BookmarkNode* node,
101       const std::set<GURL>& removed_urls) OVERRIDE {}
102   virtual void BookmarkAllUserNodesRemoved(
103       BookmarkModel* model,
104       const std::set<GURL>& removed_urls) OVERRIDE {}
105
106   virtual void BookmarkNodeChanged(BookmarkModel* model,
107                                    const BookmarkNode* node) OVERRIDE {
108     if (model == model_ && node == node_)
109       model->GetFavicon(node);
110   }
111   virtual void BookmarkNodeChildrenReordered(
112       BookmarkModel* model,
113       const BookmarkNode* node) OVERRIDE {}
114   virtual void BookmarkNodeFaviconChanged(
115       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 // Checks if the hierarchies in |model_a| and |model_b| are equivalent in
341 // terms of the data model and favicon. Returns true if they both match.
342 // Note: Some peripheral fields like creation times are allowed to mismatch.
343 bool BookmarkModelsMatch(BookmarkModel* model_a, BookmarkModel* model_b) {
344   bool ret_val = true;
345   ui::TreeNodeIterator<const BookmarkNode> iterator_a(model_a->root_node());
346   ui::TreeNodeIterator<const BookmarkNode> iterator_b(model_b->root_node());
347   while (iterator_a.has_next()) {
348     const BookmarkNode* node_a = iterator_a.Next();
349     if (!iterator_b.has_next()) {
350       LOG(ERROR) << "Models do not match.";
351       return false;
352     }
353     const BookmarkNode* node_b = iterator_b.Next();
354     ret_val = ret_val && NodesMatch(node_a, node_b);
355     if (node_a->is_folder() || node_b->is_folder())
356       continue;
357     ret_val = ret_val && FaviconsMatch(model_a, model_b, node_a, node_b);
358   }
359   ret_val = ret_val && (!iterator_b.has_next());
360   return ret_val;
361 }
362
363 // Finds the node in the verifier bookmark model that corresponds to
364 // |foreign_node| in |foreign_model| and stores its address in |result|.
365 void FindNodeInVerifier(BookmarkModel* foreign_model,
366                         const BookmarkNode* foreign_node,
367                         const BookmarkNode** result) {
368   // Climb the tree.
369   std::stack<int> path;
370   const BookmarkNode* walker = foreign_node;
371   while (walker != foreign_model->root_node()) {
372     path.push(walker->parent()->GetIndexOf(walker));
373     walker = walker->parent();
374   }
375
376   // Swing over to the other tree.
377   walker = bookmarks_helper::GetVerifierBookmarkModel()->root_node();
378
379   // Climb down.
380   while (!path.empty()) {
381     ASSERT_TRUE(walker->is_folder());
382     ASSERT_LT(path.top(), walker->child_count());
383     walker = walker->GetChild(path.top());
384     path.pop();
385   }
386
387   ASSERT_TRUE(NodesMatch(foreign_node, walker));
388   *result = walker;
389 }
390
391 }  // namespace
392
393
394 namespace bookmarks_helper {
395
396 BookmarkModel* GetBookmarkModel(int index) {
397   return BookmarkModelFactory::GetForProfile(
398       sync_datatype_helper::test()->GetProfile(index));
399 }
400
401 const BookmarkNode* GetBookmarkBarNode(int index) {
402   return GetBookmarkModel(index)->bookmark_bar_node();
403 }
404
405 const BookmarkNode* GetOtherNode(int index) {
406   return GetBookmarkModel(index)->other_node();
407 }
408
409 const BookmarkNode* GetSyncedBookmarksNode(int index) {
410   return GetBookmarkModel(index)->mobile_node();
411 }
412
413 BookmarkModel* GetVerifierBookmarkModel() {
414   return BookmarkModelFactory::GetForProfile(
415       sync_datatype_helper::test()->verifier());
416 }
417
418 const BookmarkNode* AddURL(int profile,
419                            const std::string& title,
420                            const GURL& url) {
421   return AddURL(profile, GetBookmarkBarNode(profile), 0, title,  url);
422 }
423
424 const BookmarkNode* AddURL(int profile,
425                            int index,
426                            const std::string& title,
427                            const GURL& url) {
428   return AddURL(profile, GetBookmarkBarNode(profile), index, title, url);
429 }
430
431 const BookmarkNode* AddURL(int profile,
432                            const BookmarkNode* parent,
433                            int index,
434                            const std::string& title,
435                            const GURL& url) {
436   BookmarkModel* model = GetBookmarkModel(profile);
437   if (bookmarks::GetBookmarkNodeByID(model, parent->id()) != parent) {
438     LOG(ERROR) << "Node " << parent->GetTitle() << " does not belong to "
439                << "Profile " << profile;
440     return NULL;
441   }
442   const BookmarkNode* result =
443       model->AddURL(parent, index, base::UTF8ToUTF16(title), url);
444   if (!result) {
445     LOG(ERROR) << "Could not add bookmark " << title << " to Profile "
446                << profile;
447     return NULL;
448   }
449   if (sync_datatype_helper::test()->use_verifier()) {
450     const BookmarkNode* v_parent = NULL;
451     FindNodeInVerifier(model, parent, &v_parent);
452     const BookmarkNode* v_node = GetVerifierBookmarkModel()->AddURL(
453         v_parent, index, base::UTF8ToUTF16(title), url);
454     if (!v_node) {
455       LOG(ERROR) << "Could not add bookmark " << title << " to the verifier";
456       return NULL;
457     }
458     EXPECT_TRUE(NodesMatch(v_node, result));
459   }
460   return result;
461 }
462
463 const BookmarkNode* AddFolder(int profile,
464                               const std::string& title) {
465   return AddFolder(profile, GetBookmarkBarNode(profile), 0, title);
466 }
467
468 const BookmarkNode* AddFolder(int profile,
469                               int index,
470                               const std::string& title) {
471   return AddFolder(profile, GetBookmarkBarNode(profile), index, title);
472 }
473
474 const BookmarkNode* AddFolder(int profile,
475                               const BookmarkNode* parent,
476                               int index,
477                               const std::string& title) {
478   BookmarkModel* model = GetBookmarkModel(profile);
479   if (bookmarks::GetBookmarkNodeByID(model, parent->id()) != parent) {
480     LOG(ERROR) << "Node " << parent->GetTitle() << " does not belong to "
481                << "Profile " << profile;
482     return NULL;
483   }
484   const BookmarkNode* result =
485       model->AddFolder(parent, index, base::UTF8ToUTF16(title));
486   EXPECT_TRUE(result);
487   if (!result) {
488     LOG(ERROR) << "Could not add folder " << title << " to Profile "
489                << profile;
490     return NULL;
491   }
492   if (sync_datatype_helper::test()->use_verifier()) {
493     const BookmarkNode* v_parent = NULL;
494     FindNodeInVerifier(model, parent, &v_parent);
495     const BookmarkNode* v_node = GetVerifierBookmarkModel()->AddFolder(
496         v_parent, index, base::UTF8ToUTF16(title));
497     if (!v_node) {
498       LOG(ERROR) << "Could not add folder " << title << " to the verifier";
499       return NULL;
500     }
501     EXPECT_TRUE(NodesMatch(v_node, result));
502   }
503   return result;
504 }
505
506 void SetTitle(int profile,
507               const BookmarkNode* node,
508               const std::string& new_title) {
509   BookmarkModel* model = GetBookmarkModel(profile);
510   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, node->id()), node)
511       << "Node " << node->GetTitle() << " does not belong to "
512       << "Profile " << profile;
513   if (sync_datatype_helper::test()->use_verifier()) {
514     const BookmarkNode* v_node = NULL;
515     FindNodeInVerifier(model, node, &v_node);
516     GetVerifierBookmarkModel()->SetTitle(v_node, base::UTF8ToUTF16(new_title));
517   }
518   model->SetTitle(node, base::UTF8ToUTF16(new_title));
519 }
520
521 void SetFavicon(int profile,
522                 const BookmarkNode* node,
523                 const GURL& icon_url,
524                 const gfx::Image& image,
525                 FaviconSource favicon_source) {
526   BookmarkModel* model = GetBookmarkModel(profile);
527   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, node->id()), node)
528       << "Node " << node->GetTitle() << " does not belong to "
529       << "Profile " << profile;
530   ASSERT_EQ(BookmarkNode::URL, node->type()) << "Node " << node->GetTitle()
531                                              << " must be a url.";
532   if (urls_with_favicons_ == NULL)
533     urls_with_favicons_ = new std::set<GURL>();
534   urls_with_favicons_->insert(node->url());
535   if (sync_datatype_helper::test()->use_verifier()) {
536     const BookmarkNode* v_node = NULL;
537     FindNodeInVerifier(model, node, &v_node);
538     SetFaviconImpl(sync_datatype_helper::test()->verifier(),
539                    v_node,
540                    icon_url,
541                    image,
542                    favicon_source);
543   }
544   SetFaviconImpl(sync_datatype_helper::test()->GetProfile(profile),
545                  node,
546                  icon_url,
547                  image,
548                  favicon_source);
549 }
550
551 const BookmarkNode* SetURL(int profile,
552                            const BookmarkNode* node,
553                            const GURL& new_url) {
554   BookmarkModel* model = GetBookmarkModel(profile);
555   if (bookmarks::GetBookmarkNodeByID(model, node->id()) != node) {
556     LOG(ERROR) << "Node " << node->GetTitle() << " does not belong to "
557                << "Profile " << profile;
558     return NULL;
559   }
560   if (sync_datatype_helper::test()->use_verifier()) {
561     const BookmarkNode* v_node = NULL;
562     FindNodeInVerifier(model, node, &v_node);
563     if (v_node->is_url())
564       GetVerifierBookmarkModel()->SetURL(v_node, new_url);
565   }
566   if (node->is_url())
567     model->SetURL(node, new_url);
568   return node;
569 }
570
571 void Move(int profile,
572           const BookmarkNode* node,
573           const BookmarkNode* new_parent,
574           int index) {
575   BookmarkModel* model = GetBookmarkModel(profile);
576   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, node->id()), node)
577       << "Node " << node->GetTitle() << " does not belong to "
578       << "Profile " << profile;
579   if (sync_datatype_helper::test()->use_verifier()) {
580     const BookmarkNode* v_new_parent = NULL;
581     const BookmarkNode* v_node = NULL;
582     FindNodeInVerifier(model, new_parent, &v_new_parent);
583     FindNodeInVerifier(model, node, &v_node);
584     GetVerifierBookmarkModel()->Move(v_node, v_new_parent, index);
585   }
586   model->Move(node, new_parent, index);
587 }
588
589 void Remove(int profile, const BookmarkNode* parent, int index) {
590   BookmarkModel* model = GetBookmarkModel(profile);
591   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, parent->id()), parent)
592       << "Node " << parent->GetTitle() << " does not belong to "
593       << "Profile " << profile;
594   if (sync_datatype_helper::test()->use_verifier()) {
595     const BookmarkNode* v_parent = NULL;
596     FindNodeInVerifier(model, parent, &v_parent);
597     ASSERT_TRUE(NodesMatch(parent->GetChild(index), v_parent->GetChild(index)));
598     GetVerifierBookmarkModel()->Remove(v_parent, index);
599   }
600   model->Remove(parent, index);
601 }
602
603 void RemoveAll(int profile) {
604   if (sync_datatype_helper::test()->use_verifier()) {
605     const BookmarkNode* root_node = GetVerifierBookmarkModel()->root_node();
606     for (int i = 0; i < root_node->child_count(); ++i) {
607       const BookmarkNode* permanent_node = root_node->GetChild(i);
608       for (int j = permanent_node->child_count() - 1; j >= 0; --j) {
609         GetVerifierBookmarkModel()->Remove(permanent_node, j);
610       }
611     }
612   }
613   GetBookmarkModel(profile)->RemoveAllUserBookmarks();
614 }
615
616 void SortChildren(int profile, const BookmarkNode* parent) {
617   BookmarkModel* model = GetBookmarkModel(profile);
618   ASSERT_EQ(bookmarks::GetBookmarkNodeByID(model, parent->id()), parent)
619       << "Node " << parent->GetTitle() << " does not belong to "
620       << "Profile " << profile;
621   if (sync_datatype_helper::test()->use_verifier()) {
622     const BookmarkNode* v_parent = NULL;
623     FindNodeInVerifier(model, parent, &v_parent);
624     GetVerifierBookmarkModel()->SortChildren(v_parent);
625   }
626   model->SortChildren(parent);
627 }
628
629 void ReverseChildOrder(int profile, const BookmarkNode* parent) {
630   ASSERT_EQ(
631       bookmarks::GetBookmarkNodeByID(GetBookmarkModel(profile), parent->id()),
632       parent)
633       << "Node " << parent->GetTitle() << " does not belong to "
634       << "Profile " << profile;
635   int child_count = parent->child_count();
636   if (child_count <= 0)
637     return;
638   for (int index = 0; index < child_count; ++index) {
639     Move(profile, parent->GetChild(index), parent, child_count - index);
640   }
641 }
642
643 bool ModelMatchesVerifier(int profile) {
644   if (!sync_datatype_helper::test()->use_verifier()) {
645     LOG(ERROR) << "Illegal to call ModelMatchesVerifier() after "
646                << "DisableVerifier(). Use ModelsMatch() instead.";
647     return false;
648   }
649   return BookmarkModelsMatch(GetVerifierBookmarkModel(),
650                              GetBookmarkModel(profile));
651 }
652
653 bool AllModelsMatchVerifier() {
654   // Ensure that all tasks have finished processing on the history thread
655   // and that any notifications the history thread may have sent have been
656   // processed before comparing models.
657   WaitForHistoryToProcessPendingTasks();
658
659   for (int i = 0; i < sync_datatype_helper::test()->num_clients(); ++i) {
660     if (!ModelMatchesVerifier(i)) {
661       LOG(ERROR) << "Model " << i << " does not match the verifier.";
662       return false;
663     }
664   }
665   return true;
666 }
667
668 bool ModelsMatch(int profile_a, int profile_b) {
669   return BookmarkModelsMatch(GetBookmarkModel(profile_a),
670                              GetBookmarkModel(profile_b));
671 }
672
673 bool AllModelsMatch() {
674   // Ensure that all tasks have finished processing on the history thread
675   // and that any notifications the history thread may have sent have been
676   // processed before comparing models.
677   WaitForHistoryToProcessPendingTasks();
678
679   for (int i = 1; i < sync_datatype_helper::test()->num_clients(); ++i) {
680     if (!ModelsMatch(0, i)) {
681       LOG(ERROR) << "Model " << i << " does not match Model 0.";
682       return false;
683     }
684   }
685   return true;
686 }
687
688 namespace {
689
690 // Helper class used in the implementation of AwaitAllModelsMatch.
691 class AllModelsMatchChecker : public MultiClientStatusChangeChecker {
692  public:
693   AllModelsMatchChecker();
694   virtual ~AllModelsMatchChecker();
695
696   virtual bool IsExitConditionSatisfied() OVERRIDE;
697   virtual std::string GetDebugMessage() const OVERRIDE;
698 };
699
700 AllModelsMatchChecker::AllModelsMatchChecker()
701     : MultiClientStatusChangeChecker(
702         sync_datatype_helper::test()->GetSyncServices()) {}
703
704 AllModelsMatchChecker::~AllModelsMatchChecker() {}
705
706 bool AllModelsMatchChecker::IsExitConditionSatisfied() {
707   return AllModelsMatch();
708 }
709
710 std::string AllModelsMatchChecker::GetDebugMessage() const {
711   return "Waiting for matching models";
712 }
713
714 }  //  namespace
715
716 bool AwaitAllModelsMatch() {
717   AllModelsMatchChecker checker;
718   checker.Wait();
719   return !checker.TimedOut();
720 }
721
722
723 bool ContainsDuplicateBookmarks(int profile) {
724   ui::TreeNodeIterator<const BookmarkNode> iterator(
725       GetBookmarkModel(profile)->root_node());
726   while (iterator.has_next()) {
727     const BookmarkNode* node = iterator.Next();
728     if (node->is_folder())
729       continue;
730     std::vector<const BookmarkNode*> nodes;
731     GetBookmarkModel(profile)->GetNodesByURL(node->url(), &nodes);
732     EXPECT_TRUE(nodes.size() >= 1);
733     for (std::vector<const BookmarkNode*>::const_iterator it = nodes.begin();
734          it != nodes.end(); ++it) {
735       if (node->id() != (*it)->id() &&
736           node->parent() == (*it)->parent() &&
737           node->GetTitle() == (*it)->GetTitle()){
738         return true;
739       }
740     }
741   }
742   return false;
743 }
744
745 bool HasNodeWithURL(int profile, const GURL& url) {
746   std::vector<const BookmarkNode*> nodes;
747   GetBookmarkModel(profile)->GetNodesByURL(url, &nodes);
748   return !nodes.empty();
749 }
750
751 const BookmarkNode* GetUniqueNodeByURL(int profile, const GURL& url) {
752   std::vector<const BookmarkNode*> nodes;
753   GetBookmarkModel(profile)->GetNodesByURL(url, &nodes);
754   EXPECT_EQ(1U, nodes.size());
755   if (nodes.empty())
756     return NULL;
757   return nodes[0];
758 }
759
760 int CountBookmarksWithTitlesMatching(int profile, const std::string& title) {
761   return CountNodesWithTitlesMatching(GetBookmarkModel(profile),
762                                       BookmarkNode::URL,
763                                       base::UTF8ToUTF16(title));
764 }
765
766 int CountFoldersWithTitlesMatching(int profile, const std::string& title) {
767   return CountNodesWithTitlesMatching(GetBookmarkModel(profile),
768                                       BookmarkNode::FOLDER,
769                                       base::UTF8ToUTF16(title));
770 }
771
772 gfx::Image CreateFavicon(SkColor color) {
773   const int dip_width = 16;
774   const int dip_height = 16;
775   std::vector<float> favicon_scales = favicon_base::GetFaviconScales();
776   gfx::ImageSkia favicon;
777   for (size_t i = 0; i < favicon_scales.size(); ++i) {
778     float scale = favicon_scales[i];
779     int pixel_width = dip_width * scale;
780     int pixel_height = dip_height * scale;
781     SkBitmap bmp;
782     bmp.allocN32Pixels(pixel_width, pixel_height);
783     bmp.eraseColor(color);
784     favicon.AddRepresentation(gfx::ImageSkiaRep(bmp, scale));
785   }
786   return gfx::Image(favicon);
787 }
788
789 gfx::Image Create1xFaviconFromPNGFile(const std::string& path) {
790   const char* kPNGExtension = ".png";
791   if (!EndsWith(path, kPNGExtension, false))
792     return gfx::Image();
793
794   base::FilePath full_path;
795   if (!PathService::Get(chrome::DIR_TEST_DATA, &full_path))
796     return gfx::Image();
797
798   full_path = full_path.AppendASCII("sync").AppendASCII(path);
799   std::string contents;
800   base::ReadFileToString(full_path, &contents);
801   return gfx::Image::CreateFrom1xPNGBytes(
802       base::RefCountedString::TakeString(&contents));
803 }
804
805 std::string IndexedURL(int i) {
806   return base::StringPrintf("http://www.host.ext:1234/path/filename/%d", i);
807 }
808
809 std::string IndexedURLTitle(int i) {
810   return base::StringPrintf("URL Title %d", i);
811 }
812
813 std::string IndexedFolderName(int i) {
814   return base::StringPrintf("Folder Name %d", i);
815 }
816
817 std::string IndexedSubfolderName(int i) {
818   return base::StringPrintf("Subfolder Name %d", i);
819 }
820
821 std::string IndexedSubsubfolderName(int i) {
822   return base::StringPrintf("Subsubfolder Name %d", i);
823 }
824
825 }  // namespace bookmarks_helper