Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / sync / syncable / syncable_unittest.cc
1 // Copyright 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 <string>
6
7 #include "base/basictypes.h"
8 #include "base/compiler_specific.h"
9 #include "base/files/file_path.h"
10 #include "base/files/file_util.h"
11 #include "base/files/scoped_temp_dir.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/stl_util.h"
17 #include "base/synchronization/condition_variable.h"
18 #include "base/test/values_test_util.h"
19 #include "base/threading/platform_thread.h"
20 #include "base/values.h"
21 #include "sync/protocol/bookmark_specifics.pb.h"
22 #include "sync/syncable/directory_backing_store.h"
23 #include "sync/syncable/directory_change_delegate.h"
24 #include "sync/syncable/directory_unittest.h"
25 #include "sync/syncable/in_memory_directory_backing_store.h"
26 #include "sync/syncable/metahandle_set.h"
27 #include "sync/syncable/mutable_entry.h"
28 #include "sync/syncable/on_disk_directory_backing_store.h"
29 #include "sync/syncable/syncable_proto_util.h"
30 #include "sync/syncable/syncable_read_transaction.h"
31 #include "sync/syncable/syncable_util.h"
32 #include "sync/syncable/syncable_write_transaction.h"
33 #include "sync/test/engine/test_id_factory.h"
34 #include "sync/test/engine/test_syncable_utils.h"
35 #include "sync/test/fake_encryptor.h"
36 #include "sync/test/null_directory_change_delegate.h"
37 #include "sync/test/null_transaction_observer.h"
38 #include "sync/util/test_unrecoverable_error_handler.h"
39 #include "testing/gtest/include/gtest/gtest.h"
40
41 namespace syncer {
42 namespace syncable {
43
44 using base::ExpectDictBooleanValue;
45 using base::ExpectDictStringValue;
46
47 // An OnDiskDirectoryBackingStore that can be set to always fail SaveChanges.
48 class TestBackingStore : public OnDiskDirectoryBackingStore {
49  public:
50   TestBackingStore(const std::string& dir_name,
51                    const base::FilePath& backing_filepath);
52
53   ~TestBackingStore() override;
54
55   bool SaveChanges(const Directory::SaveChangesSnapshot& snapshot) override;
56
57    void StartFailingSaveChanges() {
58      fail_save_changes_ = true;
59    }
60
61  private:
62    bool fail_save_changes_;
63 };
64
65 TestBackingStore::TestBackingStore(const std::string& dir_name,
66                                    const base::FilePath& backing_filepath)
67   : OnDiskDirectoryBackingStore(dir_name, backing_filepath),
68     fail_save_changes_(false) {
69 }
70
71 TestBackingStore::~TestBackingStore() { }
72
73 bool TestBackingStore::SaveChanges(
74     const Directory::SaveChangesSnapshot& snapshot){
75   if (fail_save_changes_) {
76     return false;
77   } else {
78     return OnDiskDirectoryBackingStore::SaveChanges(snapshot);
79   }
80 }
81
82 // A directory whose Save() function can be set to always fail.
83 class TestDirectory : public Directory {
84  public:
85   // A factory function used to work around some initialization order issues.
86   static TestDirectory* Create(
87       Encryptor *encryptor,
88       UnrecoverableErrorHandler *handler,
89       const std::string& dir_name,
90       const base::FilePath& backing_filepath);
91
92   ~TestDirectory() override;
93
94   void StartFailingSaveChanges() {
95     backing_store_->StartFailingSaveChanges();
96   }
97
98  private:
99   TestDirectory(Encryptor* encryptor,
100                 UnrecoverableErrorHandler* handler,
101                 TestBackingStore* backing_store);
102
103   TestBackingStore* backing_store_;
104 };
105
106 TestDirectory* TestDirectory::Create(
107     Encryptor *encryptor,
108     UnrecoverableErrorHandler *handler,
109     const std::string& dir_name,
110     const base::FilePath& backing_filepath) {
111   TestBackingStore* backing_store =
112       new TestBackingStore(dir_name, backing_filepath);
113   return new TestDirectory(encryptor, handler, backing_store);
114 }
115
116 TestDirectory::TestDirectory(Encryptor* encryptor,
117                              UnrecoverableErrorHandler* handler,
118                              TestBackingStore* backing_store)
119     : Directory(backing_store, handler, NULL, NULL, NULL),
120       backing_store_(backing_store) {
121 }
122
123 TestDirectory::~TestDirectory() { }
124
125 TEST(OnDiskSyncableDirectory, FailInitialWrite) {
126   base::MessageLoop message_loop;
127   FakeEncryptor encryptor;
128   TestUnrecoverableErrorHandler handler;
129   base::ScopedTempDir temp_dir;
130   ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
131   base::FilePath file_path = temp_dir.path().Append(
132       FILE_PATH_LITERAL("Test.sqlite3"));
133   std::string name = "user@x.com";
134   NullDirectoryChangeDelegate delegate;
135
136   scoped_ptr<TestDirectory> test_dir(
137       TestDirectory::Create(&encryptor, &handler, name, file_path));
138
139   test_dir->StartFailingSaveChanges();
140   ASSERT_EQ(FAILED_INITIAL_WRITE, test_dir->Open(name, &delegate,
141                                                  NullTransactionObserver()));
142 }
143
144 // A variant of SyncableDirectoryTest that uses a real sqlite database.
145 class OnDiskSyncableDirectoryTest : public SyncableDirectoryTest {
146  protected:
147   // SetUp() is called before each test case is run.
148   // The sqlite3 DB is deleted before each test is run.
149   virtual void SetUp() {
150     SyncableDirectoryTest::SetUp();
151     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
152     file_path_ = temp_dir_.path().Append(
153         FILE_PATH_LITERAL("Test.sqlite3"));
154     base::DeleteFile(file_path_, true);
155     CreateDirectory();
156   }
157
158   virtual void TearDown() {
159     // This also closes file handles.
160     dir()->SaveChanges();
161     dir().reset();
162     base::DeleteFile(file_path_, true);
163     SyncableDirectoryTest::TearDown();
164   }
165
166   // Creates a new directory.  Deletes the old directory, if it exists.
167   void CreateDirectory() {
168     test_directory_ = TestDirectory::Create(
169         encryptor(), unrecoverable_error_handler(), kDirectoryName, file_path_);
170     dir().reset(test_directory_);
171     ASSERT_TRUE(dir().get());
172     ASSERT_EQ(OPENED,
173               dir()->Open(kDirectoryName,
174                           directory_change_delegate(),
175                           NullTransactionObserver()));
176     ASSERT_TRUE(dir()->good());
177   }
178
179   void SaveAndReloadDir() {
180     dir()->SaveChanges();
181     CreateDirectory();
182   }
183
184   void StartFailingSaveChanges() {
185     test_directory_->StartFailingSaveChanges();
186   }
187
188   TestDirectory *test_directory_;  // mirrors scoped_ptr<Directory> dir_
189   base::ScopedTempDir temp_dir_;
190   base::FilePath file_path_;
191 };
192
193 sync_pb::DataTypeContext BuildContext(ModelType type) {
194   sync_pb::DataTypeContext context;
195   context.set_context("context");
196   context.set_data_type_id(GetSpecificsFieldNumberFromModelType(type));
197   return context;
198 }
199
200 TEST_F(OnDiskSyncableDirectoryTest, TestPurgeEntriesWithTypeIn) {
201   sync_pb::EntitySpecifics bookmark_specs;
202   sync_pb::EntitySpecifics autofill_specs;
203   sync_pb::EntitySpecifics preference_specs;
204   AddDefaultFieldValue(BOOKMARKS, &bookmark_specs);
205   AddDefaultFieldValue(PREFERENCES, &preference_specs);
206   AddDefaultFieldValue(AUTOFILL, &autofill_specs);
207
208   ModelTypeSet types_to_purge(PREFERENCES, AUTOFILL);
209
210   dir()->SetDownloadProgress(BOOKMARKS, BuildProgress(BOOKMARKS));
211   dir()->SetDownloadProgress(PREFERENCES, BuildProgress(PREFERENCES));
212   dir()->SetDownloadProgress(AUTOFILL, BuildProgress(AUTOFILL));
213
214   TestIdFactory id_factory;
215   // Create some items for each type.
216   {
217     WriteTransaction trans(FROM_HERE, UNITTEST, dir().get());
218
219     dir()->SetDataTypeContext(&trans, BOOKMARKS, BuildContext(BOOKMARKS));
220     dir()->SetDataTypeContext(&trans, PREFERENCES, BuildContext(PREFERENCES));
221     dir()->SetDataTypeContext(&trans, AUTOFILL, BuildContext(AUTOFILL));
222
223     // Make it look like these types have completed initial sync.
224     CreateTypeRoot(&trans, dir().get(), BOOKMARKS);
225     CreateTypeRoot(&trans, dir().get(), PREFERENCES);
226     CreateTypeRoot(&trans, dir().get(), AUTOFILL);
227
228     // Add more nodes for this type.  Technically, they should be placed under
229     // the proper type root nodes but the assertions in this test won't notice
230     // if their parent isn't quite right.
231     MutableEntry item1(&trans, CREATE, BOOKMARKS, trans.root_id(), "Item");
232     ASSERT_TRUE(item1.good());
233     item1.PutServerSpecifics(bookmark_specs);
234     item1.PutIsUnsynced(true);
235
236     MutableEntry item2(&trans, CREATE_NEW_UPDATE_ITEM,
237                        id_factory.NewServerId());
238     ASSERT_TRUE(item2.good());
239     item2.PutServerSpecifics(bookmark_specs);
240     item2.PutIsUnappliedUpdate(true);
241
242     MutableEntry item3(&trans, CREATE, PREFERENCES,
243                        trans.root_id(), "Item");
244     ASSERT_TRUE(item3.good());
245     item3.PutSpecifics(preference_specs);
246     item3.PutServerSpecifics(preference_specs);
247     item3.PutIsUnsynced(true);
248
249     MutableEntry item4(&trans, CREATE_NEW_UPDATE_ITEM,
250                        id_factory.NewServerId());
251     ASSERT_TRUE(item4.good());
252     item4.PutServerSpecifics(preference_specs);
253     item4.PutIsUnappliedUpdate(true);
254
255     MutableEntry item5(&trans, CREATE, AUTOFILL,
256                        trans.root_id(), "Item");
257     ASSERT_TRUE(item5.good());
258     item5.PutSpecifics(autofill_specs);
259     item5.PutServerSpecifics(autofill_specs);
260     item5.PutIsUnsynced(true);
261
262     MutableEntry item6(&trans, CREATE_NEW_UPDATE_ITEM,
263       id_factory.NewServerId());
264     ASSERT_TRUE(item6.good());
265     item6.PutServerSpecifics(autofill_specs);
266     item6.PutIsUnappliedUpdate(true);
267   }
268
269   dir()->SaveChanges();
270   {
271     ReadTransaction trans(FROM_HERE, dir().get());
272     MetahandleSet all_set;
273     GetAllMetaHandles(&trans, &all_set);
274     ASSERT_EQ(10U, all_set.size());
275   }
276
277   dir()->PurgeEntriesWithTypeIn(types_to_purge, ModelTypeSet(), ModelTypeSet());
278
279   // We first query the in-memory data, and then reload the directory (without
280   // saving) to verify that disk does not still have the data.
281   CheckPurgeEntriesWithTypeInSucceeded(types_to_purge, true);
282   SaveAndReloadDir();
283   CheckPurgeEntriesWithTypeInSucceeded(types_to_purge, false);
284 }
285
286 TEST_F(OnDiskSyncableDirectoryTest, TestShareInfo) {
287   dir()->set_store_birthday("Jan 31st");
288   const char* const bag_of_chips_array = "\0bag of chips";
289   const std::string bag_of_chips_string =
290       std::string(bag_of_chips_array, sizeof(bag_of_chips_array));
291   dir()->set_bag_of_chips(bag_of_chips_string);
292   {
293     ReadTransaction trans(FROM_HERE, dir().get());
294     EXPECT_EQ("Jan 31st", dir()->store_birthday());
295     EXPECT_EQ(bag_of_chips_string, dir()->bag_of_chips());
296   }
297   dir()->set_store_birthday("April 10th");
298   const char* const bag_of_chips2_array = "\0bag of chips2";
299   const std::string bag_of_chips2_string =
300       std::string(bag_of_chips2_array, sizeof(bag_of_chips2_array));
301   dir()->set_bag_of_chips(bag_of_chips2_string);
302   dir()->SaveChanges();
303   {
304     ReadTransaction trans(FROM_HERE, dir().get());
305     EXPECT_EQ("April 10th", dir()->store_birthday());
306     EXPECT_EQ(bag_of_chips2_string, dir()->bag_of_chips());
307   }
308   const char* const bag_of_chips3_array = "\0bag of chips3";
309   const std::string bag_of_chips3_string =
310       std::string(bag_of_chips3_array, sizeof(bag_of_chips3_array));
311   dir()->set_bag_of_chips(bag_of_chips3_string);
312   // Restore the directory from disk.  Make sure that nothing's changed.
313   SaveAndReloadDir();
314   {
315     ReadTransaction trans(FROM_HERE, dir().get());
316     EXPECT_EQ("April 10th", dir()->store_birthday());
317     EXPECT_EQ(bag_of_chips3_string, dir()->bag_of_chips());
318   }
319 }
320
321 TEST_F(OnDiskSyncableDirectoryTest,
322        TestSimpleFieldsPreservedDuringSaveChanges) {
323   Id update_id = TestIdFactory::FromNumber(1);
324   Id create_id;
325   EntryKernel create_pre_save, update_pre_save;
326   EntryKernel create_post_save, update_post_save;
327   std::string create_name =  "Create";
328
329   {
330     WriteTransaction trans(FROM_HERE, UNITTEST, dir().get());
331     MutableEntry create(
332         &trans, CREATE, BOOKMARKS, trans.root_id(), create_name);
333     MutableEntry update(&trans, CREATE_NEW_UPDATE_ITEM, update_id);
334     create.PutIsUnsynced(true);
335     update.PutIsUnappliedUpdate(true);
336     sync_pb::EntitySpecifics specifics;
337     specifics.mutable_bookmark()->set_favicon("PNG");
338     specifics.mutable_bookmark()->set_url("http://nowhere");
339     create.PutSpecifics(specifics);
340     update.PutServerSpecifics(specifics);
341     create_pre_save = create.GetKernelCopy();
342     update_pre_save = update.GetKernelCopy();
343     create_id = create.GetId();
344   }
345
346   dir()->SaveChanges();
347   dir().reset(
348       new Directory(new OnDiskDirectoryBackingStore(kDirectoryName, file_path_),
349                     unrecoverable_error_handler(),
350                     NULL,
351                     NULL,
352                     NULL));
353
354   ASSERT_TRUE(dir().get());
355   ASSERT_EQ(OPENED,
356             dir()->Open(kDirectoryName,
357                         directory_change_delegate(),
358                         NullTransactionObserver()));
359   ASSERT_TRUE(dir()->good());
360
361   {
362     ReadTransaction trans(FROM_HERE, dir().get());
363     Entry create(&trans, GET_BY_ID, create_id);
364     EXPECT_EQ(1, CountEntriesWithName(&trans, trans.root_id(), create_name));
365     Entry update(&trans, GET_BY_ID, update_id);
366     create_post_save = create.GetKernelCopy();
367     update_post_save = update.GetKernelCopy();
368   }
369   int i = BEGIN_FIELDS;
370   for ( ; i < INT64_FIELDS_END ; ++i) {
371     EXPECT_EQ(create_pre_save.ref((Int64Field)i) +
372                   (i == TRANSACTION_VERSION ? 1 : 0),
373               create_post_save.ref((Int64Field)i))
374               << "int64 field #" << i << " changed during save/load";
375     EXPECT_EQ(update_pre_save.ref((Int64Field)i),
376               update_post_save.ref((Int64Field)i))
377         << "int64 field #" << i << " changed during save/load";
378   }
379   for ( ; i < TIME_FIELDS_END ; ++i) {
380     EXPECT_EQ(create_pre_save.ref((TimeField)i),
381               create_post_save.ref((TimeField)i))
382               << "time field #" << i << " changed during save/load";
383     EXPECT_EQ(update_pre_save.ref((TimeField)i),
384               update_post_save.ref((TimeField)i))
385               << "time field #" << i << " changed during save/load";
386   }
387   for ( ; i < ID_FIELDS_END ; ++i) {
388     EXPECT_EQ(create_pre_save.ref((IdField)i),
389               create_post_save.ref((IdField)i))
390               << "id field #" << i << " changed during save/load";
391     EXPECT_EQ(update_pre_save.ref((IdField)i),
392               update_pre_save.ref((IdField)i))
393               << "id field #" << i << " changed during save/load";
394   }
395   for ( ; i < BIT_FIELDS_END ; ++i) {
396     EXPECT_EQ(create_pre_save.ref((BitField)i),
397               create_post_save.ref((BitField)i))
398               << "Bit field #" << i << " changed during save/load";
399     EXPECT_EQ(update_pre_save.ref((BitField)i),
400               update_post_save.ref((BitField)i))
401               << "Bit field #" << i << " changed during save/load";
402   }
403   for ( ; i < STRING_FIELDS_END ; ++i) {
404     EXPECT_EQ(create_pre_save.ref((StringField)i),
405               create_post_save.ref((StringField)i))
406               << "String field #" << i << " changed during save/load";
407     EXPECT_EQ(update_pre_save.ref((StringField)i),
408               update_post_save.ref((StringField)i))
409               << "String field #" << i << " changed during save/load";
410   }
411   for ( ; i < PROTO_FIELDS_END; ++i) {
412     EXPECT_EQ(create_pre_save.ref((ProtoField)i).SerializeAsString(),
413               create_post_save.ref((ProtoField)i).SerializeAsString())
414               << "Blob field #" << i << " changed during save/load";
415     EXPECT_EQ(update_pre_save.ref((ProtoField)i).SerializeAsString(),
416               update_post_save.ref((ProtoField)i).SerializeAsString())
417               << "Blob field #" << i << " changed during save/load";
418   }
419   for ( ; i < UNIQUE_POSITION_FIELDS_END; ++i) {
420     EXPECT_TRUE(create_pre_save.ref((UniquePositionField)i).Equals(
421         create_post_save.ref((UniquePositionField)i)))
422         << "Position field #" << i << " changed during save/load";
423     EXPECT_TRUE(update_pre_save.ref((UniquePositionField)i).Equals(
424         update_post_save.ref((UniquePositionField)i)))
425         << "Position field #" << i << " changed during save/load";
426   }
427 }
428
429 TEST_F(OnDiskSyncableDirectoryTest, TestSaveChangesFailure) {
430   int64 handle1 = 0;
431   // Set up an item using a regular, saveable directory.
432   {
433     WriteTransaction trans(FROM_HERE, UNITTEST, dir().get());
434
435     MutableEntry e1(&trans, CREATE, BOOKMARKS, trans.root_id(), "aguilera");
436     ASSERT_TRUE(e1.good());
437     EXPECT_TRUE(e1.GetKernelCopy().is_dirty());
438     handle1 = e1.GetMetahandle();
439     e1.PutBaseVersion(1);
440     e1.PutIsDir(true);
441     e1.PutId(TestIdFactory::FromNumber(101));
442     EXPECT_TRUE(e1.GetKernelCopy().is_dirty());
443     EXPECT_TRUE(IsInDirtyMetahandles(handle1));
444   }
445   ASSERT_TRUE(dir()->SaveChanges());
446
447   // Make sure the item is no longer dirty after saving,
448   // and make a modification.
449   {
450     WriteTransaction trans(FROM_HERE, UNITTEST, dir().get());
451
452     MutableEntry aguilera(&trans, GET_BY_HANDLE, handle1);
453     ASSERT_TRUE(aguilera.good());
454     EXPECT_FALSE(aguilera.GetKernelCopy().is_dirty());
455     EXPECT_EQ(aguilera.GetNonUniqueName(), "aguilera");
456     aguilera.PutNonUniqueName("overwritten");
457     EXPECT_TRUE(aguilera.GetKernelCopy().is_dirty());
458     EXPECT_TRUE(IsInDirtyMetahandles(handle1));
459   }
460   ASSERT_TRUE(dir()->SaveChanges());
461
462   // Now do some operations when SaveChanges() will fail.
463   StartFailingSaveChanges();
464   ASSERT_TRUE(dir()->good());
465
466   int64 handle2 = 0;
467   {
468     WriteTransaction trans(FROM_HERE, UNITTEST, dir().get());
469
470     MutableEntry aguilera(&trans, GET_BY_HANDLE, handle1);
471     ASSERT_TRUE(aguilera.good());
472     EXPECT_FALSE(aguilera.GetKernelCopy().is_dirty());
473     EXPECT_EQ(aguilera.GetNonUniqueName(), "overwritten");
474     EXPECT_FALSE(aguilera.GetKernelCopy().is_dirty());
475     EXPECT_FALSE(IsInDirtyMetahandles(handle1));
476     aguilera.PutNonUniqueName("christina");
477     EXPECT_TRUE(aguilera.GetKernelCopy().is_dirty());
478     EXPECT_TRUE(IsInDirtyMetahandles(handle1));
479
480     // New item.
481     MutableEntry kids_on_block(
482         &trans, CREATE, BOOKMARKS, trans.root_id(), "kids");
483     ASSERT_TRUE(kids_on_block.good());
484     handle2 = kids_on_block.GetMetahandle();
485     kids_on_block.PutBaseVersion(1);
486     kids_on_block.PutIsDir(true);
487     kids_on_block.PutId(TestIdFactory::FromNumber(102));
488     EXPECT_TRUE(kids_on_block.GetKernelCopy().is_dirty());
489     EXPECT_TRUE(IsInDirtyMetahandles(handle2));
490   }
491
492   // We are using an unsaveable directory, so this can't succeed.  However,
493   // the HandleSaveChangesFailure code path should have been triggered.
494   ASSERT_FALSE(dir()->SaveChanges());
495
496   // Make sure things were rolled back and the world is as it was before call.
497   {
498     ReadTransaction trans(FROM_HERE, dir().get());
499     Entry e1(&trans, GET_BY_HANDLE, handle1);
500     ASSERT_TRUE(e1.good());
501     EntryKernel aguilera = e1.GetKernelCopy();
502     Entry kids(&trans, GET_BY_HANDLE, handle2);
503     ASSERT_TRUE(kids.good());
504     EXPECT_TRUE(kids.GetKernelCopy().is_dirty());
505     EXPECT_TRUE(IsInDirtyMetahandles(handle2));
506     EXPECT_TRUE(aguilera.is_dirty());
507     EXPECT_TRUE(IsInDirtyMetahandles(handle1));
508   }
509 }
510
511 TEST_F(OnDiskSyncableDirectoryTest, TestSaveChangesFailureWithPurge) {
512   int64 handle1 = 0;
513   // Set up an item and progress marker using a regular, saveable directory.
514   dir()->SetDownloadProgress(BOOKMARKS, BuildProgress(BOOKMARKS));
515   {
516     WriteTransaction trans(FROM_HERE, UNITTEST, dir().get());
517
518     MutableEntry e1(&trans, CREATE, BOOKMARKS, trans.root_id(), "aguilera");
519     ASSERT_TRUE(e1.good());
520     EXPECT_TRUE(e1.GetKernelCopy().is_dirty());
521     handle1 = e1.GetMetahandle();
522     e1.PutBaseVersion(1);
523     e1.PutIsDir(true);
524     e1.PutId(TestIdFactory::FromNumber(101));
525     sync_pb::EntitySpecifics bookmark_specs;
526     AddDefaultFieldValue(BOOKMARKS, &bookmark_specs);
527     e1.PutSpecifics(bookmark_specs);
528     e1.PutServerSpecifics(bookmark_specs);
529     e1.PutId(TestIdFactory::FromNumber(101));
530     EXPECT_TRUE(e1.GetKernelCopy().is_dirty());
531     EXPECT_TRUE(IsInDirtyMetahandles(handle1));
532   }
533   ASSERT_TRUE(dir()->SaveChanges());
534
535   // Now do some operations while SaveChanges() is set to fail.
536   StartFailingSaveChanges();
537   ASSERT_TRUE(dir()->good());
538
539   ModelTypeSet set(BOOKMARKS);
540   dir()->PurgeEntriesWithTypeIn(set, ModelTypeSet(), ModelTypeSet());
541   EXPECT_TRUE(IsInMetahandlesToPurge(handle1));
542   ASSERT_FALSE(dir()->SaveChanges());
543   EXPECT_TRUE(IsInMetahandlesToPurge(handle1));
544 }
545
546 class SyncableDirectoryManagement : public testing::Test {
547  public:
548   virtual void SetUp() {
549     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
550   }
551
552   virtual void TearDown() {
553   }
554  protected:
555   base::MessageLoop message_loop_;
556   base::ScopedTempDir temp_dir_;
557   FakeEncryptor encryptor_;
558   TestUnrecoverableErrorHandler handler_;
559   NullDirectoryChangeDelegate delegate_;
560 };
561
562 TEST_F(SyncableDirectoryManagement, TestFileRelease) {
563   base::FilePath path =
564       temp_dir_.path().Append(Directory::kSyncDatabaseFilename);
565
566   Directory dir(new OnDiskDirectoryBackingStore("ScopeTest", path),
567                 &handler_,
568                 NULL,
569                 NULL,
570                 NULL);
571   DirOpenResult result =
572       dir.Open("ScopeTest", &delegate_, NullTransactionObserver());
573   ASSERT_EQ(result, OPENED);
574   dir.Close();
575
576   // Closing the directory should have released the backing database file.
577   ASSERT_TRUE(base::DeleteFile(path, true));
578 }
579
580 class SyncableClientTagTest : public SyncableDirectoryTest {
581  public:
582   static const int kBaseVersion = 1;
583   const char* test_name_;
584   const char* test_tag_;
585
586   SyncableClientTagTest() : test_name_("test_name"), test_tag_("dietcoke") {}
587
588   bool CreateWithDefaultTag(Id id, bool deleted) {
589     WriteTransaction wtrans(FROM_HERE, UNITTEST, dir().get());
590     MutableEntry me(&wtrans, CREATE, PREFERENCES,
591                     wtrans.root_id(), test_name_);
592     CHECK(me.good());
593     me.PutId(id);
594     if (id.ServerKnows()) {
595       me.PutBaseVersion(kBaseVersion);
596     }
597     me.PutIsUnsynced(true);
598     me.PutIsDel(deleted);
599     me.PutIsDir(false);
600     return me.PutUniqueClientTag(test_tag_);
601   }
602
603   // Verify an entry exists with the default tag.
604   void VerifyTag(Id id, bool deleted) {
605     // Should still be present and valid in the client tag index.
606     ReadTransaction trans(FROM_HERE, dir().get());
607     Entry me(&trans, GET_BY_CLIENT_TAG, test_tag_);
608     CHECK(me.good());
609     EXPECT_EQ(me.GetId(), id);
610     EXPECT_EQ(me.GetUniqueClientTag(), test_tag_);
611     EXPECT_EQ(me.GetIsDel(), deleted);
612
613     // We only sync deleted items that the server knew about.
614     if (me.GetId().ServerKnows() || !me.GetIsDel()) {
615       EXPECT_EQ(me.GetIsUnsynced(), true);
616     }
617   }
618
619  protected:
620   TestIdFactory factory_;
621 };
622
623 TEST_F(SyncableClientTagTest, TestClientTagClear) {
624   Id server_id = factory_.NewServerId();
625   EXPECT_TRUE(CreateWithDefaultTag(server_id, false));
626   {
627     WriteTransaction trans(FROM_HERE, UNITTEST, dir().get());
628     MutableEntry me(&trans, GET_BY_CLIENT_TAG, test_tag_);
629     EXPECT_TRUE(me.good());
630     me.PutUniqueClientTag(std::string());
631   }
632   {
633     ReadTransaction trans(FROM_HERE, dir().get());
634     Entry by_tag(&trans, GET_BY_CLIENT_TAG, test_tag_);
635     EXPECT_FALSE(by_tag.good());
636
637     Entry by_id(&trans, GET_BY_ID, server_id);
638     EXPECT_TRUE(by_id.good());
639     EXPECT_TRUE(by_id.GetUniqueClientTag().empty());
640   }
641 }
642
643 TEST_F(SyncableClientTagTest, TestClientTagIndexServerId) {
644   Id server_id = factory_.NewServerId();
645   EXPECT_TRUE(CreateWithDefaultTag(server_id, false));
646   VerifyTag(server_id, false);
647 }
648
649 TEST_F(SyncableClientTagTest, TestClientTagIndexClientId) {
650   Id client_id = factory_.NewLocalId();
651   EXPECT_TRUE(CreateWithDefaultTag(client_id, false));
652   VerifyTag(client_id, false);
653 }
654
655 TEST_F(SyncableClientTagTest, TestDeletedClientTagIndexClientId) {
656   Id client_id = factory_.NewLocalId();
657   EXPECT_TRUE(CreateWithDefaultTag(client_id, true));
658   VerifyTag(client_id, true);
659 }
660
661 TEST_F(SyncableClientTagTest, TestDeletedClientTagIndexServerId) {
662   Id server_id = factory_.NewServerId();
663   EXPECT_TRUE(CreateWithDefaultTag(server_id, true));
664   VerifyTag(server_id, true);
665 }
666
667 TEST_F(SyncableClientTagTest, TestClientTagIndexDuplicateServer) {
668   EXPECT_TRUE(CreateWithDefaultTag(factory_.NewServerId(), true));
669   EXPECT_FALSE(CreateWithDefaultTag(factory_.NewServerId(), true));
670   EXPECT_FALSE(CreateWithDefaultTag(factory_.NewServerId(), false));
671   EXPECT_FALSE(CreateWithDefaultTag(factory_.NewLocalId(), false));
672   EXPECT_FALSE(CreateWithDefaultTag(factory_.NewLocalId(), true));
673 }
674
675 }  // namespace syncable
676 }  // namespace syncer