Roll src/third_party/WebKit f36d5e0:68b67cd (svn 193299:193303)
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl_unittest.cc
blobdaedba2ae73530aa5f0a4829471a07b48f5b71a9
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.
5 // Unit tests for the SyncApi. Note that a lot of the underlying
6 // functionality is provided by the Syncable layer, which has its own
7 // unit tests. We'll test SyncApi specific things in this harness.
9 #include <cstddef>
10 #include <map>
12 #include "base/basictypes.h"
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/files/scoped_temp_dir.h"
16 #include "base/format_macros.h"
17 #include "base/location.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/run_loop.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/test/values_test_util.h"
24 #include "base/values.h"
25 #include "google_apis/gaia/gaia_constants.h"
26 #include "sync/engine/sync_scheduler.h"
27 #include "sync/internal_api/public/base/attachment_id_proto.h"
28 #include "sync/internal_api/public/base/cancelation_signal.h"
29 #include "sync/internal_api/public/base/model_type_test_util.h"
30 #include "sync/internal_api/public/change_record.h"
31 #include "sync/internal_api/public/engine/model_safe_worker.h"
32 #include "sync/internal_api/public/engine/polling_constants.h"
33 #include "sync/internal_api/public/events/protocol_event.h"
34 #include "sync/internal_api/public/http_post_provider_factory.h"
35 #include "sync/internal_api/public/http_post_provider_interface.h"
36 #include "sync/internal_api/public/read_node.h"
37 #include "sync/internal_api/public/read_transaction.h"
38 #include "sync/internal_api/public/test/test_entry_factory.h"
39 #include "sync/internal_api/public/test/test_internal_components_factory.h"
40 #include "sync/internal_api/public/test/test_user_share.h"
41 #include "sync/internal_api/public/write_node.h"
42 #include "sync/internal_api/public/write_transaction.h"
43 #include "sync/internal_api/sync_encryption_handler_impl.h"
44 #include "sync/internal_api/sync_manager_impl.h"
45 #include "sync/internal_api/syncapi_internal.h"
46 #include "sync/js/js_backend.h"
47 #include "sync/js/js_event_handler.h"
48 #include "sync/js/js_test_util.h"
49 #include "sync/protocol/bookmark_specifics.pb.h"
50 #include "sync/protocol/encryption.pb.h"
51 #include "sync/protocol/extension_specifics.pb.h"
52 #include "sync/protocol/password_specifics.pb.h"
53 #include "sync/protocol/preference_specifics.pb.h"
54 #include "sync/protocol/proto_value_conversions.h"
55 #include "sync/protocol/sync.pb.h"
56 #include "sync/sessions/sync_session.h"
57 #include "sync/syncable/directory.h"
58 #include "sync/syncable/entry.h"
59 #include "sync/syncable/mutable_entry.h"
60 #include "sync/syncable/nigori_util.h"
61 #include "sync/syncable/syncable_id.h"
62 #include "sync/syncable/syncable_read_transaction.h"
63 #include "sync/syncable/syncable_util.h"
64 #include "sync/syncable/syncable_write_transaction.h"
65 #include "sync/test/callback_counter.h"
66 #include "sync/test/engine/fake_model_worker.h"
67 #include "sync/test/engine/fake_sync_scheduler.h"
68 #include "sync/test/engine/test_id_factory.h"
69 #include "sync/test/fake_encryptor.h"
70 #include "sync/util/cryptographer.h"
71 #include "sync/util/extensions_activity.h"
72 #include "sync/util/test_unrecoverable_error_handler.h"
73 #include "sync/util/time.h"
74 #include "testing/gmock/include/gmock/gmock.h"
75 #include "testing/gtest/include/gtest/gtest.h"
76 #include "url/gurl.h"
78 using base::ExpectDictStringValue;
79 using testing::_;
80 using testing::DoAll;
81 using testing::InSequence;
82 using testing::Return;
83 using testing::SaveArg;
84 using testing::StrictMock;
86 namespace syncer {
88 using sessions::SyncSessionSnapshot;
89 using syncable::GET_BY_HANDLE;
90 using syncable::IS_DEL;
91 using syncable::IS_UNSYNCED;
92 using syncable::NON_UNIQUE_NAME;
93 using syncable::SPECIFICS;
94 using syncable::kEncryptedString;
96 namespace {
98 // Makes a child node under the type root folder. Returns the id of the
99 // newly-created node.
100 int64 MakeNode(UserShare* share,
101 ModelType model_type,
102 const std::string& client_tag) {
103 WriteTransaction trans(FROM_HERE, share);
104 WriteNode node(&trans);
105 WriteNode::InitUniqueByCreationResult result =
106 node.InitUniqueByCreation(model_type, client_tag);
107 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
108 node.SetIsFolder(false);
109 return node.GetId();
112 // Makes a non-folder child of the root node. Returns the id of the
113 // newly-created node.
114 int64 MakeNodeWithRoot(UserShare* share,
115 ModelType model_type,
116 const std::string& client_tag) {
117 WriteTransaction trans(FROM_HERE, share);
118 ReadNode root_node(&trans);
119 root_node.InitByRootLookup();
120 WriteNode node(&trans);
121 WriteNode::InitUniqueByCreationResult result =
122 node.InitUniqueByCreation(model_type, root_node, client_tag);
123 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
124 node.SetIsFolder(false);
125 return node.GetId();
128 // Makes a folder child of a non-root node. Returns the id of the
129 // newly-created node.
130 int64 MakeFolderWithParent(UserShare* share,
131 ModelType model_type,
132 int64 parent_id,
133 BaseNode* predecessor) {
134 WriteTransaction trans(FROM_HERE, share);
135 ReadNode parent_node(&trans);
136 EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
137 WriteNode node(&trans);
138 EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
139 node.SetIsFolder(true);
140 return node.GetId();
143 int64 MakeBookmarkWithParent(UserShare* share,
144 int64 parent_id,
145 BaseNode* predecessor) {
146 WriteTransaction trans(FROM_HERE, share);
147 ReadNode parent_node(&trans);
148 EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
149 WriteNode node(&trans);
150 EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
151 return node.GetId();
154 // Creates the "synced" root node for a particular datatype. We use the syncable
155 // methods here so that the syncer treats these nodes as if they were already
156 // received from the server.
157 int64 MakeTypeRoot(UserShare* share, ModelType model_type) {
158 sync_pb::EntitySpecifics specifics;
159 AddDefaultFieldValue(model_type, &specifics);
160 syncable::WriteTransaction trans(
161 FROM_HERE, syncable::UNITTEST, share->directory.get());
162 // Attempt to lookup by nigori tag.
163 std::string type_tag = ModelTypeToRootTag(model_type);
164 syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag);
165 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
166 node_id);
167 EXPECT_TRUE(entry.good());
168 entry.PutBaseVersion(1);
169 entry.PutServerVersion(1);
170 entry.PutIsUnappliedUpdate(false);
171 entry.PutParentId(syncable::Id::GetRoot());
172 entry.PutServerParentId(syncable::Id::GetRoot());
173 entry.PutServerIsDir(true);
174 entry.PutIsDir(true);
175 entry.PutServerSpecifics(specifics);
176 entry.PutUniqueServerTag(type_tag);
177 entry.PutNonUniqueName(type_tag);
178 entry.PutIsDel(false);
179 entry.PutSpecifics(specifics);
180 return entry.GetMetahandle();
183 // Simulates creating a "synced" node as a child of the root datatype node.
184 int64 MakeServerNode(UserShare* share, ModelType model_type,
185 const std::string& client_tag,
186 const std::string& hashed_tag,
187 const sync_pb::EntitySpecifics& specifics) {
188 syncable::WriteTransaction trans(
189 FROM_HERE, syncable::UNITTEST, share->directory.get());
190 syncable::Entry root_entry(&trans, syncable::GET_TYPE_ROOT, model_type);
191 EXPECT_TRUE(root_entry.good());
192 syncable::Id root_id = root_entry.GetId();
193 syncable::Id node_id = syncable::Id::CreateFromServerId(client_tag);
194 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
195 node_id);
196 EXPECT_TRUE(entry.good());
197 entry.PutBaseVersion(1);
198 entry.PutServerVersion(1);
199 entry.PutIsUnappliedUpdate(false);
200 entry.PutServerParentId(root_id);
201 entry.PutParentId(root_id);
202 entry.PutServerIsDir(false);
203 entry.PutIsDir(false);
204 entry.PutServerSpecifics(specifics);
205 entry.PutNonUniqueName(client_tag);
206 entry.PutUniqueClientTag(hashed_tag);
207 entry.PutIsDel(false);
208 entry.PutSpecifics(specifics);
209 return entry.GetMetahandle();
212 } // namespace
214 class SyncApiTest : public testing::Test {
215 public:
216 void SetUp() override { test_user_share_.SetUp(); }
218 void TearDown() override { test_user_share_.TearDown(); }
220 protected:
221 // Create an entry with the given |model_type|, |client_tag| and
222 // |attachment_metadata|.
223 void CreateEntryWithAttachmentMetadata(
224 const ModelType& model_type,
225 const std::string& client_tag,
226 const sync_pb::AttachmentMetadata& attachment_metadata);
228 // Attempts to load the entry specified by |model_type| and |client_tag| and
229 // returns the lookup result code.
230 BaseNode::InitByLookupResult LookupEntryByClientTag(
231 const ModelType& model_type,
232 const std::string& client_tag);
234 // Replace the entry specified by |model_type| and |client_tag| with a
235 // tombstone.
236 void ReplaceWithTombstone(const ModelType& model_type,
237 const std::string& client_tag);
239 // Save changes to the Directory, destroy it then reload it.
240 bool ReloadDir();
242 UserShare* user_share();
243 syncable::Directory* dir();
244 SyncEncryptionHandler* encryption_handler();
246 private:
247 base::MessageLoop message_loop_;
248 TestUserShare test_user_share_;
251 UserShare* SyncApiTest::user_share() {
252 return test_user_share_.user_share();
255 syncable::Directory* SyncApiTest::dir() {
256 return test_user_share_.user_share()->directory.get();
259 SyncEncryptionHandler* SyncApiTest::encryption_handler() {
260 return test_user_share_.encryption_handler();
263 bool SyncApiTest::ReloadDir() {
264 return test_user_share_.Reload();
267 void SyncApiTest::CreateEntryWithAttachmentMetadata(
268 const ModelType& model_type,
269 const std::string& client_tag,
270 const sync_pb::AttachmentMetadata& attachment_metadata) {
271 syncer::WriteTransaction trans(FROM_HERE, user_share());
272 syncer::ReadNode root_node(&trans);
273 root_node.InitByRootLookup();
274 syncer::WriteNode node(&trans);
275 ASSERT_EQ(node.InitUniqueByCreation(model_type, root_node, client_tag),
276 syncer::WriteNode::INIT_SUCCESS);
277 node.SetAttachmentMetadata(attachment_metadata);
280 BaseNode::InitByLookupResult SyncApiTest::LookupEntryByClientTag(
281 const ModelType& model_type,
282 const std::string& client_tag) {
283 syncer::ReadTransaction trans(FROM_HERE, user_share());
284 syncer::ReadNode node(&trans);
285 return node.InitByClientTagLookup(model_type, client_tag);
288 void SyncApiTest::ReplaceWithTombstone(const ModelType& model_type,
289 const std::string& client_tag) {
290 syncer::WriteTransaction trans(FROM_HERE, user_share());
291 syncer::WriteNode node(&trans);
292 ASSERT_EQ(node.InitByClientTagLookup(model_type, client_tag),
293 syncer::WriteNode::INIT_OK);
294 node.Tombstone();
297 TEST_F(SyncApiTest, SanityCheckTest) {
299 ReadTransaction trans(FROM_HERE, user_share());
300 EXPECT_TRUE(trans.GetWrappedTrans());
303 WriteTransaction trans(FROM_HERE, user_share());
304 EXPECT_TRUE(trans.GetWrappedTrans());
307 // No entries but root should exist
308 ReadTransaction trans(FROM_HERE, user_share());
309 ReadNode node(&trans);
310 // Metahandle 1 can be root, sanity check 2
311 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByIdLookup(2));
315 TEST_F(SyncApiTest, BasicTagWrite) {
317 ReadTransaction trans(FROM_HERE, user_share());
318 ReadNode root_node(&trans);
319 root_node.InitByRootLookup();
320 EXPECT_EQ(kInvalidId, root_node.GetFirstChildId());
323 ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag"));
326 ReadTransaction trans(FROM_HERE, user_share());
327 ReadNode node(&trans);
328 EXPECT_EQ(BaseNode::INIT_OK,
329 node.InitByClientTagLookup(BOOKMARKS, "testtag"));
330 EXPECT_NE(0, node.GetId());
332 ReadNode root_node(&trans);
333 root_node.InitByRootLookup();
334 EXPECT_EQ(node.GetId(), root_node.GetFirstChildId());
338 TEST_F(SyncApiTest, BasicTagWriteWithImplicitParent) {
339 int64 type_root = MakeTypeRoot(user_share(), PREFERENCES);
342 ReadTransaction trans(FROM_HERE, user_share());
343 ReadNode type_root_node(&trans);
344 EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
345 EXPECT_EQ(kInvalidId, type_root_node.GetFirstChildId());
348 ignore_result(MakeNode(user_share(), PREFERENCES, "testtag"));
351 ReadTransaction trans(FROM_HERE, user_share());
352 ReadNode node(&trans);
353 EXPECT_EQ(BaseNode::INIT_OK,
354 node.InitByClientTagLookup(PREFERENCES, "testtag"));
355 EXPECT_EQ(kInvalidId, node.GetParentId());
357 ReadNode type_root_node(&trans);
358 EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
359 EXPECT_EQ(node.GetId(), type_root_node.GetFirstChildId());
363 TEST_F(SyncApiTest, ModelTypesSiloed) {
365 WriteTransaction trans(FROM_HERE, user_share());
366 ReadNode root_node(&trans);
367 root_node.InitByRootLookup();
368 EXPECT_EQ(root_node.GetFirstChildId(), 0);
371 ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "collideme"));
372 ignore_result(MakeNodeWithRoot(user_share(), PREFERENCES, "collideme"));
373 ignore_result(MakeNodeWithRoot(user_share(), AUTOFILL, "collideme"));
376 ReadTransaction trans(FROM_HERE, user_share());
378 ReadNode bookmarknode(&trans);
379 EXPECT_EQ(BaseNode::INIT_OK,
380 bookmarknode.InitByClientTagLookup(BOOKMARKS,
381 "collideme"));
383 ReadNode prefnode(&trans);
384 EXPECT_EQ(BaseNode::INIT_OK,
385 prefnode.InitByClientTagLookup(PREFERENCES,
386 "collideme"));
388 ReadNode autofillnode(&trans);
389 EXPECT_EQ(BaseNode::INIT_OK,
390 autofillnode.InitByClientTagLookup(AUTOFILL,
391 "collideme"));
393 EXPECT_NE(bookmarknode.GetId(), prefnode.GetId());
394 EXPECT_NE(autofillnode.GetId(), prefnode.GetId());
395 EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId());
399 TEST_F(SyncApiTest, ReadMissingTagsFails) {
401 ReadTransaction trans(FROM_HERE, user_share());
402 ReadNode node(&trans);
403 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
404 node.InitByClientTagLookup(BOOKMARKS,
405 "testtag"));
408 WriteTransaction trans(FROM_HERE, user_share());
409 WriteNode node(&trans);
410 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
411 node.InitByClientTagLookup(BOOKMARKS,
412 "testtag"));
416 // TODO(chron): Hook this all up to the server and write full integration tests
417 // for update->undelete behavior.
418 TEST_F(SyncApiTest, TestDeleteBehavior) {
419 int64 node_id;
420 int64 folder_id;
421 std::string test_title("test1");
424 WriteTransaction trans(FROM_HERE, user_share());
425 ReadNode root_node(&trans);
426 root_node.InitByRootLookup();
428 // we'll use this spare folder later
429 WriteNode folder_node(&trans);
430 EXPECT_TRUE(folder_node.InitBookmarkByCreation(root_node, NULL));
431 folder_id = folder_node.GetId();
433 WriteNode wnode(&trans);
434 WriteNode::InitUniqueByCreationResult result =
435 wnode.InitUniqueByCreation(BOOKMARKS, root_node, "testtag");
436 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
437 wnode.SetIsFolder(false);
438 wnode.SetTitle(test_title);
440 node_id = wnode.GetId();
443 // Ensure we can delete something with a tag.
445 WriteTransaction trans(FROM_HERE, user_share());
446 WriteNode wnode(&trans);
447 EXPECT_EQ(BaseNode::INIT_OK,
448 wnode.InitByClientTagLookup(BOOKMARKS,
449 "testtag"));
450 EXPECT_FALSE(wnode.GetIsFolder());
451 EXPECT_EQ(wnode.GetTitle(), test_title);
453 wnode.Tombstone();
456 // Lookup of a node which was deleted should return failure,
457 // but have found some data about the node.
459 ReadTransaction trans(FROM_HERE, user_share());
460 ReadNode node(&trans);
461 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL,
462 node.InitByClientTagLookup(BOOKMARKS,
463 "testtag"));
464 // Note that for proper function of this API this doesn't need to be
465 // filled, we're checking just to make sure the DB worked in this test.
466 EXPECT_EQ(node.GetTitle(), test_title);
470 WriteTransaction trans(FROM_HERE, user_share());
471 ReadNode folder_node(&trans);
472 EXPECT_EQ(BaseNode::INIT_OK, folder_node.InitByIdLookup(folder_id));
474 WriteNode wnode(&trans);
475 // This will undelete the tag.
476 WriteNode::InitUniqueByCreationResult result =
477 wnode.InitUniqueByCreation(BOOKMARKS, folder_node, "testtag");
478 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
479 EXPECT_EQ(wnode.GetIsFolder(), false);
480 EXPECT_EQ(wnode.GetParentId(), folder_node.GetId());
481 EXPECT_EQ(wnode.GetId(), node_id);
482 EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared
483 wnode.SetTitle(test_title);
486 // Now look up should work.
488 ReadTransaction trans(FROM_HERE, user_share());
489 ReadNode node(&trans);
490 EXPECT_EQ(BaseNode::INIT_OK,
491 node.InitByClientTagLookup(BOOKMARKS,
492 "testtag"));
493 EXPECT_EQ(node.GetTitle(), test_title);
494 EXPECT_EQ(node.GetModelType(), BOOKMARKS);
498 TEST_F(SyncApiTest, WriteAndReadPassword) {
499 KeyParams params = {"localhost", "username", "passphrase"};
501 ReadTransaction trans(FROM_HERE, user_share());
502 trans.GetCryptographer()->AddKey(params);
505 WriteTransaction trans(FROM_HERE, user_share());
506 ReadNode root_node(&trans);
507 root_node.InitByRootLookup();
509 WriteNode password_node(&trans);
510 WriteNode::InitUniqueByCreationResult result =
511 password_node.InitUniqueByCreation(PASSWORDS,
512 root_node, "foo");
513 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
514 sync_pb::PasswordSpecificsData data;
515 data.set_password_value("secret");
516 password_node.SetPasswordSpecifics(data);
519 ReadTransaction trans(FROM_HERE, user_share());
520 ReadNode root_node(&trans);
521 root_node.InitByRootLookup();
523 ReadNode password_node(&trans);
524 EXPECT_EQ(BaseNode::INIT_OK,
525 password_node.InitByClientTagLookup(PASSWORDS, "foo"));
526 const sync_pb::PasswordSpecificsData& data =
527 password_node.GetPasswordSpecifics();
528 EXPECT_EQ("secret", data.password_value());
532 TEST_F(SyncApiTest, WriteEncryptedTitle) {
533 KeyParams params = {"localhost", "username", "passphrase"};
535 ReadTransaction trans(FROM_HERE, user_share());
536 trans.GetCryptographer()->AddKey(params);
538 encryption_handler()->EnableEncryptEverything();
539 int bookmark_id;
541 WriteTransaction trans(FROM_HERE, user_share());
542 ReadNode root_node(&trans);
543 root_node.InitByRootLookup();
545 WriteNode bookmark_node(&trans);
546 ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
547 bookmark_id = bookmark_node.GetId();
548 bookmark_node.SetTitle("foo");
550 WriteNode pref_node(&trans);
551 WriteNode::InitUniqueByCreationResult result =
552 pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar");
553 ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
554 pref_node.SetTitle("bar");
557 ReadTransaction trans(FROM_HERE, user_share());
558 ReadNode root_node(&trans);
559 root_node.InitByRootLookup();
561 ReadNode bookmark_node(&trans);
562 ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
563 EXPECT_EQ("foo", bookmark_node.GetTitle());
564 EXPECT_EQ(kEncryptedString,
565 bookmark_node.GetEntry()->GetNonUniqueName());
567 ReadNode pref_node(&trans);
568 ASSERT_EQ(BaseNode::INIT_OK,
569 pref_node.InitByClientTagLookup(PREFERENCES,
570 "bar"));
571 EXPECT_EQ(kEncryptedString, pref_node.GetTitle());
575 TEST_F(SyncApiTest, BaseNodeSetSpecifics) {
576 int64 child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
577 WriteTransaction trans(FROM_HERE, user_share());
578 WriteNode node(&trans);
579 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
581 sync_pb::EntitySpecifics entity_specifics;
582 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
584 EXPECT_NE(entity_specifics.SerializeAsString(),
585 node.GetEntitySpecifics().SerializeAsString());
586 node.SetEntitySpecifics(entity_specifics);
587 EXPECT_EQ(entity_specifics.SerializeAsString(),
588 node.GetEntitySpecifics().SerializeAsString());
591 TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) {
592 int64 child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
593 WriteTransaction trans(FROM_HERE, user_share());
594 WriteNode node(&trans);
595 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
596 EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty());
598 sync_pb::EntitySpecifics entity_specifics;
599 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
600 entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100);
601 node.SetEntitySpecifics(entity_specifics);
602 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
604 entity_specifics.mutable_unknown_fields()->Clear();
605 node.SetEntitySpecifics(entity_specifics);
606 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
609 TEST_F(SyncApiTest, EmptyTags) {
610 WriteTransaction trans(FROM_HERE, user_share());
611 ReadNode root_node(&trans);
612 root_node.InitByRootLookup();
613 WriteNode node(&trans);
614 std::string empty_tag;
615 WriteNode::InitUniqueByCreationResult result =
616 node.InitUniqueByCreation(TYPED_URLS, root_node, empty_tag);
617 EXPECT_NE(WriteNode::INIT_SUCCESS, result);
618 EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION,
619 node.InitByClientTagLookup(TYPED_URLS, empty_tag));
622 // Test counting nodes when the type's root node has no children.
623 TEST_F(SyncApiTest, GetTotalNodeCountEmpty) {
624 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
626 ReadTransaction trans(FROM_HERE, user_share());
627 ReadNode type_root_node(&trans);
628 EXPECT_EQ(BaseNode::INIT_OK,
629 type_root_node.InitByIdLookup(type_root));
630 EXPECT_EQ(1, type_root_node.GetTotalNodeCount());
634 // Test counting nodes when there is one child beneath the type's root.
635 TEST_F(SyncApiTest, GetTotalNodeCountOneChild) {
636 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
637 int64 parent = MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL);
639 ReadTransaction trans(FROM_HERE, user_share());
640 ReadNode type_root_node(&trans);
641 EXPECT_EQ(BaseNode::INIT_OK,
642 type_root_node.InitByIdLookup(type_root));
643 EXPECT_EQ(2, type_root_node.GetTotalNodeCount());
644 ReadNode parent_node(&trans);
645 EXPECT_EQ(BaseNode::INIT_OK,
646 parent_node.InitByIdLookup(parent));
647 EXPECT_EQ(1, parent_node.GetTotalNodeCount());
651 // Test counting nodes when there are multiple children beneath the type root,
652 // and one of those children has children of its own.
653 TEST_F(SyncApiTest, GetTotalNodeCountMultipleChildren) {
654 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
655 int64 parent = MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL);
656 ignore_result(MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL));
657 int64 child1 = MakeFolderWithParent(user_share(), BOOKMARKS, parent, NULL);
658 ignore_result(MakeBookmarkWithParent(user_share(), parent, NULL));
659 ignore_result(MakeBookmarkWithParent(user_share(), child1, NULL));
662 ReadTransaction trans(FROM_HERE, user_share());
663 ReadNode type_root_node(&trans);
664 EXPECT_EQ(BaseNode::INIT_OK,
665 type_root_node.InitByIdLookup(type_root));
666 EXPECT_EQ(6, type_root_node.GetTotalNodeCount());
667 ReadNode node(&trans);
668 EXPECT_EQ(BaseNode::INIT_OK,
669 node.InitByIdLookup(parent));
670 EXPECT_EQ(4, node.GetTotalNodeCount());
674 // Verify that Directory keeps track of which attachments are referenced by
675 // which entries.
676 TEST_F(SyncApiTest, AttachmentLinking) {
677 // Add an entry with an attachment.
678 std::string tag1("some tag");
679 syncer::AttachmentId attachment_id(syncer::AttachmentId::Create(0, 0));
680 sync_pb::AttachmentMetadata attachment_metadata;
681 sync_pb::AttachmentMetadataRecord* record = attachment_metadata.add_record();
682 *record->mutable_id() = attachment_id.GetProto();
683 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
684 CreateEntryWithAttachmentMetadata(PREFERENCES, tag1, attachment_metadata);
686 // See that the directory knows it's linked.
687 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
689 // Add a second entry referencing the same attachment.
690 std::string tag2("some other tag");
691 CreateEntryWithAttachmentMetadata(PREFERENCES, tag2, attachment_metadata);
693 // See that the directory knows it's still linked.
694 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
696 // Tombstone the first entry.
697 ReplaceWithTombstone(syncer::PREFERENCES, tag1);
699 // See that the attachment is still considered linked because the entry hasn't
700 // been purged from the Directory.
701 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
703 // Save changes and see that the entry is truly gone.
704 ASSERT_TRUE(dir()->SaveChanges());
705 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag1),
706 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
708 // However, the attachment is still linked.
709 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
711 // Save, destroy, and recreate the directory. See that it's still linked.
712 ASSERT_TRUE(ReloadDir());
713 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
715 // Tombstone the second entry, save changes, see that it's truly gone.
716 ReplaceWithTombstone(syncer::PREFERENCES, tag2);
717 ASSERT_TRUE(dir()->SaveChanges());
718 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag2),
719 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
721 // Finally, the attachment is no longer linked.
722 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
725 namespace {
727 class TestHttpPostProviderInterface : public HttpPostProviderInterface {
728 public:
729 ~TestHttpPostProviderInterface() override {}
731 void SetExtraRequestHeaders(const char* headers) override {}
732 void SetURL(const char* url, int port) override {}
733 void SetPostPayload(const char* content_type,
734 int content_length,
735 const char* content) override {}
736 bool MakeSynchronousPost(int* error_code, int* response_code) override {
737 return false;
739 int GetResponseContentLength() const override { return 0; }
740 const char* GetResponseContent() const override { return ""; }
741 const std::string GetResponseHeaderValue(
742 const std::string& name) const override {
743 return std::string();
745 void Abort() override {}
748 class TestHttpPostProviderFactory : public HttpPostProviderFactory {
749 public:
750 ~TestHttpPostProviderFactory() override {}
751 void Init(const std::string& user_agent) override {}
752 HttpPostProviderInterface* Create() override {
753 return new TestHttpPostProviderInterface();
755 void Destroy(HttpPostProviderInterface* http) override {
756 delete static_cast<TestHttpPostProviderInterface*>(http);
760 class SyncManagerObserverMock : public SyncManager::Observer {
761 public:
762 MOCK_METHOD1(OnSyncCycleCompleted,
763 void(const SyncSessionSnapshot&)); // NOLINT
764 MOCK_METHOD4(OnInitializationComplete,
765 void(const WeakHandle<JsBackend>&,
766 const WeakHandle<DataTypeDebugInfoListener>&,
767 bool,
768 syncer::ModelTypeSet)); // NOLINT
769 MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT
770 MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT
771 MOCK_METHOD1(OnActionableError, void(const SyncProtocolError&)); // NOLINT
772 MOCK_METHOD1(OnMigrationRequested, void(syncer::ModelTypeSet)); // NOLINT
773 MOCK_METHOD1(OnProtocolEvent, void(const ProtocolEvent&)); // NOLINT
776 class SyncEncryptionHandlerObserverMock
777 : public SyncEncryptionHandler::Observer {
778 public:
779 MOCK_METHOD2(OnPassphraseRequired,
780 void(PassphraseRequiredReason,
781 const sync_pb::EncryptedData&)); // NOLINT
782 MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT
783 MOCK_METHOD2(OnBootstrapTokenUpdated,
784 void(const std::string&, BootstrapTokenType type)); // NOLINT
785 MOCK_METHOD2(OnEncryptedTypesChanged,
786 void(ModelTypeSet, bool)); // NOLINT
787 MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT
788 MOCK_METHOD1(OnCryptographerStateChanged, void(Cryptographer*)); // NOLINT
789 MOCK_METHOD2(OnPassphraseTypeChanged, void(PassphraseType,
790 base::Time)); // NOLINT
793 } // namespace
795 class SyncManagerTest : public testing::Test,
796 public SyncManager::ChangeDelegate {
797 protected:
798 enum NigoriStatus {
799 DONT_WRITE_NIGORI,
800 WRITE_TO_NIGORI
803 enum EncryptionStatus {
804 UNINITIALIZED,
805 DEFAULT_ENCRYPTION,
806 FULL_ENCRYPTION
809 SyncManagerTest()
810 : sync_manager_("Test sync manager") {
811 switches_.encryption_method =
812 InternalComponentsFactory::ENCRYPTION_KEYSTORE;
815 virtual ~SyncManagerTest() {
818 // Test implementation.
819 void SetUp() {
820 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
822 extensions_activity_ = new ExtensionsActivity();
824 SyncCredentials credentials;
825 credentials.email = "foo@bar.com";
826 credentials.sync_token = "sometoken";
827 OAuth2TokenService::ScopeSet scope_set;
828 scope_set.insert(GaiaConstants::kChromeSyncOAuth2Scope);
829 credentials.scope_set = scope_set;
831 sync_manager_.AddObserver(&manager_observer_);
832 EXPECT_CALL(manager_observer_, OnInitializationComplete(_, _, _, _)).
833 WillOnce(DoAll(SaveArg<0>(&js_backend_),
834 SaveArg<2>(&initialization_succeeded_)));
836 EXPECT_FALSE(js_backend_.IsInitialized());
838 std::vector<scoped_refptr<ModelSafeWorker> > workers;
839 ModelSafeRoutingInfo routing_info;
840 GetModelSafeRoutingInfo(&routing_info);
842 // This works only because all routing info types are GROUP_PASSIVE.
843 // If we had types in other groups, we would need additional workers
844 // to support them.
845 scoped_refptr<ModelSafeWorker> worker = new FakeModelWorker(GROUP_PASSIVE);
846 workers.push_back(worker);
848 SyncManager::InitArgs args;
849 args.database_location = temp_dir_.path();
850 args.service_url = GURL("https://example.com/");
851 args.post_factory =
852 scoped_ptr<HttpPostProviderFactory>(new TestHttpPostProviderFactory());
853 args.workers = workers;
854 args.extensions_activity = extensions_activity_.get(),
855 args.change_delegate = this;
856 args.credentials = credentials;
857 args.invalidator_client_id = "fake_invalidator_client_id";
858 args.internal_components_factory.reset(GetFactory());
859 args.encryptor = &encryptor_;
860 args.unrecoverable_error_handler.reset(new TestUnrecoverableErrorHandler);
861 args.cancelation_signal = &cancelation_signal_;
862 sync_manager_.Init(&args);
864 sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_);
866 EXPECT_TRUE(js_backend_.IsInitialized());
867 EXPECT_EQ(InternalComponentsFactory::STORAGE_ON_DISK,
868 storage_used_);
870 if (initialization_succeeded_) {
871 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
872 i != routing_info.end(); ++i) {
873 type_roots_[i->first] =
874 MakeTypeRoot(sync_manager_.GetUserShare(), i->first);
878 PumpLoop();
881 void TearDown() {
882 sync_manager_.RemoveObserver(&manager_observer_);
883 sync_manager_.ShutdownOnSyncThread(STOP_SYNC);
884 PumpLoop();
887 void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) {
888 (*out)[NIGORI] = GROUP_PASSIVE;
889 (*out)[DEVICE_INFO] = GROUP_PASSIVE;
890 (*out)[EXPERIMENTS] = GROUP_PASSIVE;
891 (*out)[BOOKMARKS] = GROUP_PASSIVE;
892 (*out)[THEMES] = GROUP_PASSIVE;
893 (*out)[SESSIONS] = GROUP_PASSIVE;
894 (*out)[PASSWORDS] = GROUP_PASSIVE;
895 (*out)[PREFERENCES] = GROUP_PASSIVE;
896 (*out)[PRIORITY_PREFERENCES] = GROUP_PASSIVE;
897 (*out)[ARTICLES] = GROUP_PASSIVE;
900 ModelTypeSet GetEnabledTypes() {
901 ModelSafeRoutingInfo routing_info;
902 GetModelSafeRoutingInfo(&routing_info);
903 return GetRoutingInfoTypes(routing_info);
906 virtual void OnChangesApplied(
907 ModelType model_type,
908 int64 model_version,
909 const BaseTransaction* trans,
910 const ImmutableChangeRecordList& changes) override {}
912 virtual void OnChangesComplete(ModelType model_type) override {}
914 // Helper methods.
915 bool SetUpEncryption(NigoriStatus nigori_status,
916 EncryptionStatus encryption_status) {
917 UserShare* share = sync_manager_.GetUserShare();
919 // We need to create the nigori node as if it were an applied server update.
920 int64 nigori_id = GetIdForDataType(NIGORI);
921 if (nigori_id == kInvalidId)
922 return false;
924 // Set the nigori cryptographer information.
925 if (encryption_status == FULL_ENCRYPTION)
926 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
928 WriteTransaction trans(FROM_HERE, share);
929 Cryptographer* cryptographer = trans.GetCryptographer();
930 if (!cryptographer)
931 return false;
932 if (encryption_status != UNINITIALIZED) {
933 KeyParams params = {"localhost", "dummy", "foobar"};
934 cryptographer->AddKey(params);
935 } else {
936 DCHECK_NE(nigori_status, WRITE_TO_NIGORI);
938 if (nigori_status == WRITE_TO_NIGORI) {
939 sync_pb::NigoriSpecifics nigori;
940 cryptographer->GetKeys(nigori.mutable_encryption_keybag());
941 share->directory->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
942 &nigori,
943 trans.GetWrappedTrans());
944 WriteNode node(&trans);
945 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(nigori_id));
946 node.SetNigoriSpecifics(nigori);
948 return cryptographer->is_ready();
951 int64 GetIdForDataType(ModelType type) {
952 if (type_roots_.count(type) == 0)
953 return 0;
954 return type_roots_[type];
957 void PumpLoop() {
958 base::RunLoop().RunUntilIdle();
961 void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) {
962 js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler,
963 event_handler);
964 PumpLoop();
967 // Looks up an entry by client tag and resets IS_UNSYNCED value to false.
968 // Returns true if entry was previously unsynced, false if IS_UNSYNCED was
969 // already false.
970 bool ResetUnsyncedEntry(ModelType type,
971 const std::string& client_tag) {
972 UserShare* share = sync_manager_.GetUserShare();
973 syncable::WriteTransaction trans(
974 FROM_HERE, syncable::UNITTEST, share->directory.get());
975 const std::string hash = syncable::GenerateSyncableHash(type, client_tag);
976 syncable::MutableEntry entry(&trans, syncable::GET_BY_CLIENT_TAG,
977 hash);
978 EXPECT_TRUE(entry.good());
979 if (!entry.GetIsUnsynced())
980 return false;
981 entry.PutIsUnsynced(false);
982 return true;
985 virtual InternalComponentsFactory* GetFactory() {
986 return new TestInternalComponentsFactory(
987 GetSwitches(), InternalComponentsFactory::STORAGE_IN_MEMORY,
988 &storage_used_);
991 // Returns true if we are currently encrypting all sync data. May
992 // be called on any thread.
993 bool EncryptEverythingEnabledForTest() {
994 return sync_manager_.GetEncryptionHandler()->EncryptEverythingEnabled();
997 // Gets the set of encrypted types from the cryptographer
998 // Note: opens a transaction. May be called from any thread.
999 ModelTypeSet GetEncryptedTypes() {
1000 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1001 return GetEncryptedTypesWithTrans(&trans);
1004 ModelTypeSet GetEncryptedTypesWithTrans(BaseTransaction* trans) {
1005 return trans->GetDirectory()->GetNigoriHandler()->
1006 GetEncryptedTypes(trans->GetWrappedTrans());
1009 void SimulateInvalidatorEnabledForTest(bool is_enabled) {
1010 DCHECK(sync_manager_.thread_checker_.CalledOnValidThread());
1011 sync_manager_.SetInvalidatorEnabled(is_enabled);
1014 void SetProgressMarkerForType(ModelType type, bool set) {
1015 if (set) {
1016 sync_pb::DataTypeProgressMarker marker;
1017 marker.set_token("token");
1018 marker.set_data_type_id(GetSpecificsFieldNumberFromModelType(type));
1019 sync_manager_.directory()->SetDownloadProgress(type, marker);
1020 } else {
1021 sync_pb::DataTypeProgressMarker marker;
1022 sync_manager_.directory()->SetDownloadProgress(type, marker);
1026 InternalComponentsFactory::Switches GetSwitches() const {
1027 return switches_;
1030 void ExpectPassphraseAcceptance() {
1031 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1032 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1033 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1036 void SetImplicitPassphraseAndCheck(const std::string& passphrase) {
1037 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1038 passphrase,
1039 false);
1040 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1041 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1044 void SetCustomPassphraseAndCheck(const std::string& passphrase) {
1045 EXPECT_CALL(encryption_observer_,
1046 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1047 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1048 passphrase,
1049 true);
1050 EXPECT_EQ(CUSTOM_PASSPHRASE,
1051 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1054 private:
1055 // Needed by |sync_manager_|.
1056 base::MessageLoop message_loop_;
1057 // Needed by |sync_manager_|.
1058 base::ScopedTempDir temp_dir_;
1059 // Sync Id's for the roots of the enabled datatypes.
1060 std::map<ModelType, int64> type_roots_;
1061 scoped_refptr<ExtensionsActivity> extensions_activity_;
1063 protected:
1064 FakeEncryptor encryptor_;
1065 SyncManagerImpl sync_manager_;
1066 CancelationSignal cancelation_signal_;
1067 WeakHandle<JsBackend> js_backend_;
1068 bool initialization_succeeded_;
1069 StrictMock<SyncManagerObserverMock> manager_observer_;
1070 StrictMock<SyncEncryptionHandlerObserverMock> encryption_observer_;
1071 InternalComponentsFactory::Switches switches_;
1072 InternalComponentsFactory::StorageOption storage_used_;
1075 TEST_F(SyncManagerTest, GetAllNodesForTypeTest) {
1076 ModelSafeRoutingInfo routing_info;
1077 GetModelSafeRoutingInfo(&routing_info);
1078 sync_manager_.StartSyncingNormally(routing_info);
1080 scoped_ptr<base::ListValue> node_list(
1081 sync_manager_.GetAllNodesForType(syncer::PREFERENCES));
1083 // Should have one node: the type root node.
1084 ASSERT_EQ(1U, node_list->GetSize());
1086 const base::DictionaryValue* first_result;
1087 ASSERT_TRUE(node_list->GetDictionary(0, &first_result));
1088 EXPECT_TRUE(first_result->HasKey("ID"));
1089 EXPECT_TRUE(first_result->HasKey("NON_UNIQUE_NAME"));
1092 TEST_F(SyncManagerTest, RefreshEncryptionReady) {
1093 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1094 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1095 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1096 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1098 sync_manager_.GetEncryptionHandler()->Init();
1099 PumpLoop();
1101 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1102 EXPECT_TRUE(encrypted_types.Has(PASSWORDS));
1103 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1106 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1107 ReadNode node(&trans);
1108 EXPECT_EQ(BaseNode::INIT_OK,
1109 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1110 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1111 EXPECT_TRUE(nigori.has_encryption_keybag());
1112 Cryptographer* cryptographer = trans.GetCryptographer();
1113 EXPECT_TRUE(cryptographer->is_ready());
1114 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1118 // Attempt to refresh encryption when nigori not downloaded.
1119 TEST_F(SyncManagerTest, RefreshEncryptionNotReady) {
1120 // Don't set up encryption (no nigori node created).
1122 // Should fail. Triggers an OnPassphraseRequired because the cryptographer
1123 // is not ready.
1124 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)).Times(1);
1125 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1126 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1127 sync_manager_.GetEncryptionHandler()->Init();
1128 PumpLoop();
1130 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1131 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1132 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1135 // Attempt to refresh encryption when nigori is empty.
1136 TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) {
1137 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION));
1138 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(1);
1139 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1140 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1142 // Should write to nigori.
1143 sync_manager_.GetEncryptionHandler()->Init();
1144 PumpLoop();
1146 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1147 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1148 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1151 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1152 ReadNode node(&trans);
1153 EXPECT_EQ(BaseNode::INIT_OK,
1154 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1155 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1156 EXPECT_TRUE(nigori.has_encryption_keybag());
1157 Cryptographer* cryptographer = trans.GetCryptographer();
1158 EXPECT_TRUE(cryptographer->is_ready());
1159 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1163 TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) {
1164 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1165 EXPECT_CALL(encryption_observer_,
1166 OnEncryptedTypesChanged(
1167 HasModelTypes(EncryptableUserTypes()), true));
1168 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1169 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1170 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1173 TEST_F(SyncManagerTest, EncryptDataTypesWithData) {
1174 size_t batch_size = 5;
1175 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1177 // Create some unencrypted unsynced data.
1178 int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(),
1179 BOOKMARKS,
1180 GetIdForDataType(BOOKMARKS),
1181 NULL);
1182 // First batch_size nodes are children of folder.
1183 size_t i;
1184 for (i = 0; i < batch_size; ++i) {
1185 MakeBookmarkWithParent(sync_manager_.GetUserShare(), folder, NULL);
1187 // Next batch_size nodes are a different type and on their own.
1188 for (; i < 2*batch_size; ++i) {
1189 MakeNodeWithRoot(sync_manager_.GetUserShare(), SESSIONS,
1190 base::StringPrintf("%" PRIuS "", i));
1192 // Last batch_size nodes are a third type that will not need encryption.
1193 for (; i < 3*batch_size; ++i) {
1194 MakeNodeWithRoot(sync_manager_.GetUserShare(), THEMES,
1195 base::StringPrintf("%" PRIuS "", i));
1199 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1200 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1201 SyncEncryptionHandler::SensitiveTypes()));
1202 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1203 trans.GetWrappedTrans(),
1204 BOOKMARKS,
1205 false /* not encrypted */));
1206 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1207 trans.GetWrappedTrans(),
1208 SESSIONS,
1209 false /* not encrypted */));
1210 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1211 trans.GetWrappedTrans(),
1212 THEMES,
1213 false /* not encrypted */));
1216 EXPECT_CALL(encryption_observer_,
1217 OnEncryptedTypesChanged(
1218 HasModelTypes(EncryptableUserTypes()), true));
1219 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1220 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1221 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1223 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1224 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1225 EncryptableUserTypes()));
1226 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1227 trans.GetWrappedTrans(),
1228 BOOKMARKS,
1229 true /* is encrypted */));
1230 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1231 trans.GetWrappedTrans(),
1232 SESSIONS,
1233 true /* is encrypted */));
1234 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1235 trans.GetWrappedTrans(),
1236 THEMES,
1237 true /* is encrypted */));
1240 // Trigger's a ReEncryptEverything with new passphrase.
1241 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1242 EXPECT_CALL(encryption_observer_,
1243 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1244 ExpectPassphraseAcceptance();
1245 SetCustomPassphraseAndCheck("new_passphrase");
1246 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1248 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1249 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1250 EncryptableUserTypes()));
1251 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1252 trans.GetWrappedTrans(),
1253 BOOKMARKS,
1254 true /* is encrypted */));
1255 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1256 trans.GetWrappedTrans(),
1257 SESSIONS,
1258 true /* is encrypted */));
1259 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1260 trans.GetWrappedTrans(),
1261 THEMES,
1262 true /* is encrypted */));
1264 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1265 // a reencryption and should just notify immediately.
1266 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1267 EXPECT_CALL(encryption_observer_,
1268 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)).Times(0);
1269 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()).Times(0);
1270 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(0);
1271 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1274 // Test that when there are no pending keys and the cryptographer is not
1275 // initialized, we add a key based on the current GAIA password.
1276 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1277 TEST_F(SyncManagerTest, SetInitialGaiaPass) {
1278 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1279 EXPECT_CALL(encryption_observer_,
1280 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1281 ExpectPassphraseAcceptance();
1282 SetImplicitPassphraseAndCheck("new_passphrase");
1283 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1285 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1286 ReadNode node(&trans);
1287 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1288 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1289 Cryptographer* cryptographer = trans.GetCryptographer();
1290 EXPECT_TRUE(cryptographer->is_ready());
1291 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1295 // Test that when there are no pending keys and we have on the old GAIA
1296 // password, we update and re-encrypt everything with the new GAIA password.
1297 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1298 TEST_F(SyncManagerTest, UpdateGaiaPass) {
1299 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1300 Cryptographer verifier(&encryptor_);
1302 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1303 Cryptographer* cryptographer = trans.GetCryptographer();
1304 std::string bootstrap_token;
1305 cryptographer->GetBootstrapToken(&bootstrap_token);
1306 verifier.Bootstrap(bootstrap_token);
1308 EXPECT_CALL(encryption_observer_,
1309 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1310 ExpectPassphraseAcceptance();
1311 SetImplicitPassphraseAndCheck("new_passphrase");
1312 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1314 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1315 Cryptographer* cryptographer = trans.GetCryptographer();
1316 EXPECT_TRUE(cryptographer->is_ready());
1317 // Verify the default key has changed.
1318 sync_pb::EncryptedData encrypted;
1319 cryptographer->GetKeys(&encrypted);
1320 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1324 // Sets a new explicit passphrase. This should update the bootstrap token
1325 // and re-encrypt everything.
1326 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1327 TEST_F(SyncManagerTest, SetPassphraseWithPassword) {
1328 Cryptographer verifier(&encryptor_);
1329 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1331 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1332 // Store the default (soon to be old) key.
1333 Cryptographer* cryptographer = trans.GetCryptographer();
1334 std::string bootstrap_token;
1335 cryptographer->GetBootstrapToken(&bootstrap_token);
1336 verifier.Bootstrap(bootstrap_token);
1338 ReadNode root_node(&trans);
1339 root_node.InitByRootLookup();
1341 WriteNode password_node(&trans);
1342 WriteNode::InitUniqueByCreationResult result =
1343 password_node.InitUniqueByCreation(PASSWORDS,
1344 root_node, "foo");
1345 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1346 sync_pb::PasswordSpecificsData data;
1347 data.set_password_value("secret");
1348 password_node.SetPasswordSpecifics(data);
1350 EXPECT_CALL(encryption_observer_,
1351 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1352 ExpectPassphraseAcceptance();
1353 SetCustomPassphraseAndCheck("new_passphrase");
1354 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1356 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1357 Cryptographer* cryptographer = trans.GetCryptographer();
1358 EXPECT_TRUE(cryptographer->is_ready());
1359 // Verify the default key has changed.
1360 sync_pb::EncryptedData encrypted;
1361 cryptographer->GetKeys(&encrypted);
1362 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1364 ReadNode password_node(&trans);
1365 EXPECT_EQ(BaseNode::INIT_OK,
1366 password_node.InitByClientTagLookup(PASSWORDS,
1367 "foo"));
1368 const sync_pb::PasswordSpecificsData& data =
1369 password_node.GetPasswordSpecifics();
1370 EXPECT_EQ("secret", data.password_value());
1374 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1375 // being encrypted with a new (unprovided) GAIA password, then supply the
1376 // password.
1377 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1378 TEST_F(SyncManagerTest, SupplyPendingGAIAPass) {
1379 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1380 Cryptographer other_cryptographer(&encryptor_);
1382 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1383 Cryptographer* cryptographer = trans.GetCryptographer();
1384 std::string bootstrap_token;
1385 cryptographer->GetBootstrapToken(&bootstrap_token);
1386 other_cryptographer.Bootstrap(bootstrap_token);
1388 // Now update the nigori to reflect the new keys, and update the
1389 // cryptographer to have pending keys.
1390 KeyParams params = {"localhost", "dummy", "passphrase2"};
1391 other_cryptographer.AddKey(params);
1392 WriteNode node(&trans);
1393 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1394 sync_pb::NigoriSpecifics nigori;
1395 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1396 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1397 EXPECT_TRUE(cryptographer->has_pending_keys());
1398 node.SetNigoriSpecifics(nigori);
1400 EXPECT_CALL(encryption_observer_,
1401 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1402 ExpectPassphraseAcceptance();
1403 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
1404 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1405 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1406 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1408 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1409 Cryptographer* cryptographer = trans.GetCryptographer();
1410 EXPECT_TRUE(cryptographer->is_ready());
1411 // Verify we're encrypting with the new key.
1412 sync_pb::EncryptedData encrypted;
1413 cryptographer->GetKeys(&encrypted);
1414 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1418 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1419 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1420 // the current GAIA password and verify the bootstrap token is updated. Then
1421 // supply the old GAIA password, and verify we re-encrypt all data with the
1422 // new GAIA password.
1423 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1424 TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) {
1425 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1426 Cryptographer other_cryptographer(&encryptor_);
1428 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1429 Cryptographer* cryptographer = trans.GetCryptographer();
1430 std::string bootstrap_token;
1431 cryptographer->GetBootstrapToken(&bootstrap_token);
1432 other_cryptographer.Bootstrap(bootstrap_token);
1434 // Now update the nigori to reflect the new keys, and update the
1435 // cryptographer to have pending keys.
1436 KeyParams params = {"localhost", "dummy", "old_gaia"};
1437 other_cryptographer.AddKey(params);
1438 WriteNode node(&trans);
1439 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1440 sync_pb::NigoriSpecifics nigori;
1441 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1442 node.SetNigoriSpecifics(nigori);
1443 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1445 // other_cryptographer now contains all encryption keys, and is encrypting
1446 // with the newest gaia.
1447 KeyParams new_params = {"localhost", "dummy", "new_gaia"};
1448 other_cryptographer.AddKey(new_params);
1450 // The bootstrap token should have been updated. Save it to ensure it's based
1451 // on the new GAIA password.
1452 std::string bootstrap_token;
1453 EXPECT_CALL(encryption_observer_,
1454 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN))
1455 .WillOnce(SaveArg<0>(&bootstrap_token));
1456 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_,_));
1457 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1458 SetImplicitPassphraseAndCheck("new_gaia");
1459 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1460 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1462 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1463 Cryptographer* cryptographer = trans.GetCryptographer();
1464 EXPECT_TRUE(cryptographer->is_initialized());
1465 EXPECT_FALSE(cryptographer->is_ready());
1466 // Verify we're encrypting with the new key, even though we have pending
1467 // keys.
1468 sync_pb::EncryptedData encrypted;
1469 other_cryptographer.GetKeys(&encrypted);
1470 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1472 EXPECT_CALL(encryption_observer_,
1473 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1474 ExpectPassphraseAcceptance();
1475 SetImplicitPassphraseAndCheck("old_gaia");
1477 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1478 Cryptographer* cryptographer = trans.GetCryptographer();
1479 EXPECT_TRUE(cryptographer->is_ready());
1481 // Verify we're encrypting with the new key.
1482 sync_pb::EncryptedData encrypted;
1483 other_cryptographer.GetKeys(&encrypted);
1484 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1486 // Verify the saved bootstrap token is based on the new gaia password.
1487 Cryptographer temp_cryptographer(&encryptor_);
1488 temp_cryptographer.Bootstrap(bootstrap_token);
1489 EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted));
1493 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1494 // being encrypted with an explicit (unprovided) passphrase, then supply the
1495 // passphrase.
1496 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1497 TEST_F(SyncManagerTest, SupplyPendingExplicitPass) {
1498 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1499 Cryptographer other_cryptographer(&encryptor_);
1501 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1502 Cryptographer* cryptographer = trans.GetCryptographer();
1503 std::string bootstrap_token;
1504 cryptographer->GetBootstrapToken(&bootstrap_token);
1505 other_cryptographer.Bootstrap(bootstrap_token);
1507 // Now update the nigori to reflect the new keys, and update the
1508 // cryptographer to have pending keys.
1509 KeyParams params = {"localhost", "dummy", "explicit"};
1510 other_cryptographer.AddKey(params);
1511 WriteNode node(&trans);
1512 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1513 sync_pb::NigoriSpecifics nigori;
1514 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1515 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1516 EXPECT_TRUE(cryptographer->has_pending_keys());
1517 nigori.set_keybag_is_frozen(true);
1518 node.SetNigoriSpecifics(nigori);
1520 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1521 EXPECT_CALL(encryption_observer_,
1522 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1523 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _));
1524 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1525 sync_manager_.GetEncryptionHandler()->Init();
1526 EXPECT_CALL(encryption_observer_,
1527 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1528 ExpectPassphraseAcceptance();
1529 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
1530 EXPECT_EQ(CUSTOM_PASSPHRASE,
1531 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1532 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1534 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1535 Cryptographer* cryptographer = trans.GetCryptographer();
1536 EXPECT_TRUE(cryptographer->is_ready());
1537 // Verify we're encrypting with the new key.
1538 sync_pb::EncryptedData encrypted;
1539 cryptographer->GetKeys(&encrypted);
1540 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1544 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1545 // being encrypted with a new (unprovided) GAIA password, then supply the
1546 // password as a user-provided password.
1547 // This is the android case 7/8.
1548 TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) {
1549 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1550 Cryptographer other_cryptographer(&encryptor_);
1552 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1553 Cryptographer* cryptographer = trans.GetCryptographer();
1554 // Now update the nigori to reflect the new keys, and update the
1555 // cryptographer to have pending keys.
1556 KeyParams params = {"localhost", "dummy", "passphrase"};
1557 other_cryptographer.AddKey(params);
1558 WriteNode node(&trans);
1559 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1560 sync_pb::NigoriSpecifics nigori;
1561 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1562 node.SetNigoriSpecifics(nigori);
1563 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1564 EXPECT_FALSE(cryptographer->is_ready());
1566 EXPECT_CALL(encryption_observer_,
1567 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1568 ExpectPassphraseAcceptance();
1569 SetImplicitPassphraseAndCheck("passphrase");
1570 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1572 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1573 Cryptographer* cryptographer = trans.GetCryptographer();
1574 EXPECT_TRUE(cryptographer->is_ready());
1578 TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) {
1579 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1580 int64 node_id = 0;
1581 std::string tag = "foo";
1583 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1584 ReadNode root_node(&trans);
1585 root_node.InitByRootLookup();
1587 WriteNode password_node(&trans);
1588 WriteNode::InitUniqueByCreationResult result =
1589 password_node.InitUniqueByCreation(PASSWORDS, root_node, tag);
1590 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1591 node_id = password_node.GetId();
1593 EXPECT_CALL(encryption_observer_,
1594 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1595 ExpectPassphraseAcceptance();
1596 SetCustomPassphraseAndCheck("new_passphrase");
1597 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1599 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1600 ReadNode password_node(&trans);
1601 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1602 password_node.InitByClientTagLookup(PASSWORDS,
1603 tag));
1606 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1607 ReadNode password_node(&trans);
1608 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1609 password_node.InitByIdLookup(node_id));
1613 // Friended by WriteNode, so can't be in an anonymouse namespace.
1614 TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) {
1615 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1616 std::string title;
1617 SyncAPINameToServerName("Google", &title);
1618 std::string url = "http://www.google.com";
1619 std::string raw_title2 = ".."; // An invalid cosmo title.
1620 std::string title2;
1621 SyncAPINameToServerName(raw_title2, &title2);
1622 std::string url2 = "http://www.bla.com";
1624 // Create a bookmark using the legacy format.
1625 int64 node_id1 =
1626 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag");
1627 int64 node_id2 =
1628 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag2");
1630 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1631 WriteNode node(&trans);
1632 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1634 sync_pb::EntitySpecifics entity_specifics;
1635 entity_specifics.mutable_bookmark()->set_url(url);
1636 node.SetEntitySpecifics(entity_specifics);
1638 // Set the old style title.
1639 syncable::MutableEntry* node_entry = node.entry_;
1640 node_entry->PutNonUniqueName(title);
1642 WriteNode node2(&trans);
1643 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1645 sync_pb::EntitySpecifics entity_specifics2;
1646 entity_specifics2.mutable_bookmark()->set_url(url2);
1647 node2.SetEntitySpecifics(entity_specifics2);
1649 // Set the old style title.
1650 syncable::MutableEntry* node_entry2 = node2.entry_;
1651 node_entry2->PutNonUniqueName(title2);
1655 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1656 ReadNode node(&trans);
1657 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1658 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1659 EXPECT_EQ(title, node.GetTitle());
1660 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1661 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1663 ReadNode node2(&trans);
1664 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1665 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1666 // We should de-canonicalize the title in GetTitle(), but the title in the
1667 // specifics should be stored in the server legal form.
1668 EXPECT_EQ(raw_title2, node2.GetTitle());
1669 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1670 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1674 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1675 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1676 trans.GetWrappedTrans(),
1677 BOOKMARKS,
1678 false /* not encrypted */));
1681 EXPECT_CALL(encryption_observer_,
1682 OnEncryptedTypesChanged(
1683 HasModelTypes(EncryptableUserTypes()), true));
1684 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1685 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1686 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1689 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1690 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1691 EncryptableUserTypes()));
1692 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1693 trans.GetWrappedTrans(),
1694 BOOKMARKS,
1695 true /* is encrypted */));
1697 ReadNode node(&trans);
1698 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1699 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1700 EXPECT_EQ(title, node.GetTitle());
1701 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1702 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1704 ReadNode node2(&trans);
1705 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1706 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1707 // We should de-canonicalize the title in GetTitle(), but the title in the
1708 // specifics should be stored in the server legal form.
1709 EXPECT_EQ(raw_title2, node2.GetTitle());
1710 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1711 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1715 // Create a bookmark and set the title/url, then verify the data was properly
1716 // set. This replicates the unique way bookmarks have of creating sync nodes.
1717 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1718 TEST_F(SyncManagerTest, CreateLocalBookmark) {
1719 std::string title = "title";
1720 std::string url = "url";
1722 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1723 ReadNode bookmark_root(&trans);
1724 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1725 WriteNode node(&trans);
1726 ASSERT_TRUE(node.InitBookmarkByCreation(bookmark_root, NULL));
1727 node.SetIsFolder(false);
1728 node.SetTitle(title);
1730 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
1731 bookmark_specifics.set_url(url);
1732 node.SetBookmarkSpecifics(bookmark_specifics);
1735 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1736 ReadNode bookmark_root(&trans);
1737 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1738 int64 child_id = bookmark_root.GetFirstChildId();
1740 ReadNode node(&trans);
1741 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
1742 EXPECT_FALSE(node.GetIsFolder());
1743 EXPECT_EQ(title, node.GetTitle());
1744 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1748 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1749 // changes.
1750 TEST_F(SyncManagerTest, UpdateEntryWithEncryption) {
1751 std::string client_tag = "title";
1752 sync_pb::EntitySpecifics entity_specifics;
1753 entity_specifics.mutable_bookmark()->set_url("url");
1754 entity_specifics.mutable_bookmark()->set_title("title");
1755 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
1756 syncable::GenerateSyncableHash(BOOKMARKS,
1757 client_tag),
1758 entity_specifics);
1759 // New node shouldn't start off unsynced.
1760 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1761 // Manually change to the same data. Should not set is_unsynced.
1763 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1764 WriteNode node(&trans);
1765 EXPECT_EQ(BaseNode::INIT_OK,
1766 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1767 node.SetEntitySpecifics(entity_specifics);
1769 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1771 // Encrypt the datatatype, should set is_unsynced.
1772 EXPECT_CALL(encryption_observer_,
1773 OnEncryptedTypesChanged(
1774 HasModelTypes(EncryptableUserTypes()), true));
1775 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1776 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
1778 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1779 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1780 sync_manager_.GetEncryptionHandler()->Init();
1781 PumpLoop();
1783 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1784 ReadNode node(&trans);
1785 EXPECT_EQ(BaseNode::INIT_OK,
1786 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1787 const syncable::Entry* node_entry = node.GetEntry();
1788 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1789 EXPECT_TRUE(specifics.has_encrypted());
1790 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1791 Cryptographer* cryptographer = trans.GetCryptographer();
1792 EXPECT_TRUE(cryptographer->is_ready());
1793 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1794 specifics.encrypted()));
1796 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1798 // Set a new passphrase. Should set is_unsynced.
1799 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1800 EXPECT_CALL(encryption_observer_,
1801 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1802 ExpectPassphraseAcceptance();
1803 SetCustomPassphraseAndCheck("new_passphrase");
1805 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1806 ReadNode node(&trans);
1807 EXPECT_EQ(BaseNode::INIT_OK,
1808 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1809 const syncable::Entry* node_entry = node.GetEntry();
1810 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1811 EXPECT_TRUE(specifics.has_encrypted());
1812 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1813 Cryptographer* cryptographer = trans.GetCryptographer();
1814 EXPECT_TRUE(cryptographer->is_ready());
1815 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1816 specifics.encrypted()));
1818 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1820 // Force a re-encrypt everything. Should not set is_unsynced.
1821 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1822 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1823 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1824 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1826 sync_manager_.GetEncryptionHandler()->Init();
1827 PumpLoop();
1830 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1831 ReadNode node(&trans);
1832 EXPECT_EQ(BaseNode::INIT_OK,
1833 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1834 const syncable::Entry* node_entry = node.GetEntry();
1835 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1836 EXPECT_TRUE(specifics.has_encrypted());
1837 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1838 Cryptographer* cryptographer = trans.GetCryptographer();
1839 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1840 specifics.encrypted()));
1842 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1844 // Manually change to the same data. Should not set is_unsynced.
1846 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1847 WriteNode node(&trans);
1848 EXPECT_EQ(BaseNode::INIT_OK,
1849 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1850 node.SetEntitySpecifics(entity_specifics);
1851 const syncable::Entry* node_entry = node.GetEntry();
1852 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1853 EXPECT_TRUE(specifics.has_encrypted());
1854 EXPECT_FALSE(node_entry->GetIsUnsynced());
1855 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1856 Cryptographer* cryptographer = trans.GetCryptographer();
1857 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1858 specifics.encrypted()));
1860 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1862 // Manually change to different data. Should set is_unsynced.
1864 entity_specifics.mutable_bookmark()->set_url("url2");
1865 entity_specifics.mutable_bookmark()->set_title("title2");
1866 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1867 WriteNode node(&trans);
1868 EXPECT_EQ(BaseNode::INIT_OK,
1869 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1870 node.SetEntitySpecifics(entity_specifics);
1871 const syncable::Entry* node_entry = node.GetEntry();
1872 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1873 EXPECT_TRUE(specifics.has_encrypted());
1874 EXPECT_TRUE(node_entry->GetIsUnsynced());
1875 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1876 Cryptographer* cryptographer = trans.GetCryptographer();
1877 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1878 specifics.encrypted()));
1882 // Passwords have their own handling for encryption. Verify it does not result
1883 // in unnecessary writes via SetEntitySpecifics.
1884 TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) {
1885 std::string client_tag = "title";
1886 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1887 sync_pb::EntitySpecifics entity_specifics;
1889 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1890 Cryptographer* cryptographer = trans.GetCryptographer();
1891 sync_pb::PasswordSpecificsData data;
1892 data.set_password_value("secret");
1893 cryptographer->Encrypt(
1894 data,
1895 entity_specifics.mutable_password()->
1896 mutable_encrypted());
1898 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1899 syncable::GenerateSyncableHash(PASSWORDS,
1900 client_tag),
1901 entity_specifics);
1902 // New node shouldn't start off unsynced.
1903 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1905 // Manually change to the same data via SetEntitySpecifics. Should not set
1906 // is_unsynced.
1908 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1909 WriteNode node(&trans);
1910 EXPECT_EQ(BaseNode::INIT_OK,
1911 node.InitByClientTagLookup(PASSWORDS, client_tag));
1912 node.SetEntitySpecifics(entity_specifics);
1914 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1917 // Passwords have their own handling for encryption. Verify it does not result
1918 // in unnecessary writes via SetPasswordSpecifics.
1919 TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) {
1920 std::string client_tag = "title";
1921 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1922 sync_pb::EntitySpecifics entity_specifics;
1924 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1925 Cryptographer* cryptographer = trans.GetCryptographer();
1926 sync_pb::PasswordSpecificsData data;
1927 data.set_password_value("secret");
1928 cryptographer->Encrypt(
1929 data,
1930 entity_specifics.mutable_password()->
1931 mutable_encrypted());
1933 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1934 syncable::GenerateSyncableHash(PASSWORDS,
1935 client_tag),
1936 entity_specifics);
1937 // New node shouldn't start off unsynced.
1938 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1940 // Manually change to the same data via SetPasswordSpecifics. Should not set
1941 // is_unsynced.
1943 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1944 WriteNode node(&trans);
1945 EXPECT_EQ(BaseNode::INIT_OK,
1946 node.InitByClientTagLookup(PASSWORDS, client_tag));
1947 node.SetPasswordSpecifics(node.GetPasswordSpecifics());
1949 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1951 // Manually change to different data. Should set is_unsynced.
1953 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1954 WriteNode node(&trans);
1955 EXPECT_EQ(BaseNode::INIT_OK,
1956 node.InitByClientTagLookup(PASSWORDS, client_tag));
1957 Cryptographer* cryptographer = trans.GetCryptographer();
1958 sync_pb::PasswordSpecificsData data;
1959 data.set_password_value("secret2");
1960 cryptographer->Encrypt(
1961 data,
1962 entity_specifics.mutable_password()->mutable_encrypted());
1963 node.SetPasswordSpecifics(data);
1964 const syncable::Entry* node_entry = node.GetEntry();
1965 EXPECT_TRUE(node_entry->GetIsUnsynced());
1969 // Passwords have their own handling for encryption. Verify setting a new
1970 // passphrase updates the data.
1971 TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) {
1972 std::string client_tag = "title";
1973 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1974 sync_pb::EntitySpecifics entity_specifics;
1976 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1977 Cryptographer* cryptographer = trans.GetCryptographer();
1978 sync_pb::PasswordSpecificsData data;
1979 data.set_password_value("secret");
1980 cryptographer->Encrypt(
1981 data,
1982 entity_specifics.mutable_password()->mutable_encrypted());
1984 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1985 syncable::GenerateSyncableHash(PASSWORDS,
1986 client_tag),
1987 entity_specifics);
1988 // New node shouldn't start off unsynced.
1989 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1991 // Set a new passphrase. Should set is_unsynced.
1992 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1993 EXPECT_CALL(encryption_observer_,
1994 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1995 ExpectPassphraseAcceptance();
1996 SetCustomPassphraseAndCheck("new_passphrase");
1997 EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2000 // Passwords have their own handling for encryption. Verify it does not result
2001 // in unnecessary writes via ReencryptEverything.
2002 TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) {
2003 std::string client_tag = "title";
2004 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2005 sync_pb::EntitySpecifics entity_specifics;
2007 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2008 Cryptographer* cryptographer = trans.GetCryptographer();
2009 sync_pb::PasswordSpecificsData data;
2010 data.set_password_value("secret");
2011 cryptographer->Encrypt(
2012 data,
2013 entity_specifics.mutable_password()->mutable_encrypted());
2015 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2016 syncable::GenerateSyncableHash(PASSWORDS,
2017 client_tag),
2018 entity_specifics);
2019 // New node shouldn't start off unsynced.
2020 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2022 // Force a re-encrypt everything. Should not set is_unsynced.
2023 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2024 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2025 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2026 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
2027 sync_manager_.GetEncryptionHandler()->Init();
2028 PumpLoop();
2029 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2032 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2033 // when we write the same data, but does set it when we write new data.
2034 TEST_F(SyncManagerTest, SetBookmarkTitle) {
2035 std::string client_tag = "title";
2036 sync_pb::EntitySpecifics entity_specifics;
2037 entity_specifics.mutable_bookmark()->set_url("url");
2038 entity_specifics.mutable_bookmark()->set_title("title");
2039 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2040 syncable::GenerateSyncableHash(BOOKMARKS,
2041 client_tag),
2042 entity_specifics);
2043 // New node shouldn't start off unsynced.
2044 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2046 // Manually change to the same title. Should not set is_unsynced.
2048 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2049 WriteNode node(&trans);
2050 EXPECT_EQ(BaseNode::INIT_OK,
2051 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2052 node.SetTitle(client_tag);
2054 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2056 // Manually change to new title. Should set is_unsynced.
2058 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2059 WriteNode node(&trans);
2060 EXPECT_EQ(BaseNode::INIT_OK,
2061 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2062 node.SetTitle("title2");
2064 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2067 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2068 // bookmarks when we write the same data, but does set it when we write new
2069 // data.
2070 TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) {
2071 std::string client_tag = "title";
2072 sync_pb::EntitySpecifics entity_specifics;
2073 entity_specifics.mutable_bookmark()->set_url("url");
2074 entity_specifics.mutable_bookmark()->set_title("title");
2075 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2076 syncable::GenerateSyncableHash(BOOKMARKS,
2077 client_tag),
2078 entity_specifics);
2079 // New node shouldn't start off unsynced.
2080 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2082 // Encrypt the datatatype, should set is_unsynced.
2083 EXPECT_CALL(encryption_observer_,
2084 OnEncryptedTypesChanged(
2085 HasModelTypes(EncryptableUserTypes()), true));
2086 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2087 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2088 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2089 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2090 sync_manager_.GetEncryptionHandler()->Init();
2091 PumpLoop();
2092 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2094 // Manually change to the same title. Should not set is_unsynced.
2095 // NON_UNIQUE_NAME should be kEncryptedString.
2097 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2098 WriteNode node(&trans);
2099 EXPECT_EQ(BaseNode::INIT_OK,
2100 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2101 node.SetTitle(client_tag);
2102 const syncable::Entry* node_entry = node.GetEntry();
2103 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2104 EXPECT_TRUE(specifics.has_encrypted());
2105 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2107 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2109 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2110 // should still be kEncryptedString.
2112 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2113 WriteNode node(&trans);
2114 EXPECT_EQ(BaseNode::INIT_OK,
2115 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2116 node.SetTitle("title2");
2117 const syncable::Entry* node_entry = node.GetEntry();
2118 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2119 EXPECT_TRUE(specifics.has_encrypted());
2120 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2122 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2125 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2126 // when we write the same data, but does set it when we write new data.
2127 TEST_F(SyncManagerTest, SetNonBookmarkTitle) {
2128 std::string client_tag = "title";
2129 sync_pb::EntitySpecifics entity_specifics;
2130 entity_specifics.mutable_preference()->set_name("name");
2131 entity_specifics.mutable_preference()->set_value("value");
2132 MakeServerNode(sync_manager_.GetUserShare(),
2133 PREFERENCES,
2134 client_tag,
2135 syncable::GenerateSyncableHash(PREFERENCES,
2136 client_tag),
2137 entity_specifics);
2138 // New node shouldn't start off unsynced.
2139 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2141 // Manually change to the same title. Should not set is_unsynced.
2143 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2144 WriteNode node(&trans);
2145 EXPECT_EQ(BaseNode::INIT_OK,
2146 node.InitByClientTagLookup(PREFERENCES, client_tag));
2147 node.SetTitle(client_tag);
2149 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2151 // Manually change to new title. Should set is_unsynced.
2153 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2154 WriteNode node(&trans);
2155 EXPECT_EQ(BaseNode::INIT_OK,
2156 node.InitByClientTagLookup(PREFERENCES, client_tag));
2157 node.SetTitle("title2");
2159 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2162 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2163 // non-bookmarks when we write the same data or when we write new data
2164 // data (should remained kEncryptedString).
2165 TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) {
2166 std::string client_tag = "title";
2167 sync_pb::EntitySpecifics entity_specifics;
2168 entity_specifics.mutable_preference()->set_name("name");
2169 entity_specifics.mutable_preference()->set_value("value");
2170 MakeServerNode(sync_manager_.GetUserShare(),
2171 PREFERENCES,
2172 client_tag,
2173 syncable::GenerateSyncableHash(PREFERENCES,
2174 client_tag),
2175 entity_specifics);
2176 // New node shouldn't start off unsynced.
2177 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2179 // Encrypt the datatatype, should set is_unsynced.
2180 EXPECT_CALL(encryption_observer_,
2181 OnEncryptedTypesChanged(
2182 HasModelTypes(EncryptableUserTypes()), true));
2183 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2184 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2185 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2186 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2187 sync_manager_.GetEncryptionHandler()->Init();
2188 PumpLoop();
2189 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2191 // Manually change to the same title. Should not set is_unsynced.
2192 // NON_UNIQUE_NAME should be kEncryptedString.
2194 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2195 WriteNode node(&trans);
2196 EXPECT_EQ(BaseNode::INIT_OK,
2197 node.InitByClientTagLookup(PREFERENCES, client_tag));
2198 node.SetTitle(client_tag);
2199 const syncable::Entry* node_entry = node.GetEntry();
2200 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2201 EXPECT_TRUE(specifics.has_encrypted());
2202 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2204 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2206 // Manually change to new title. Should not set is_unsynced because the
2207 // NON_UNIQUE_NAME should still be kEncryptedString.
2209 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2210 WriteNode node(&trans);
2211 EXPECT_EQ(BaseNode::INIT_OK,
2212 node.InitByClientTagLookup(PREFERENCES, client_tag));
2213 node.SetTitle("title2");
2214 const syncable::Entry* node_entry = node.GetEntry();
2215 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2216 EXPECT_TRUE(specifics.has_encrypted());
2217 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2218 EXPECT_FALSE(node_entry->GetIsUnsynced());
2222 // Ensure that titles are truncated to 255 bytes, and attempting to reset
2223 // them to their longer version does not set IS_UNSYNCED.
2224 TEST_F(SyncManagerTest, SetLongTitle) {
2225 const int kNumChars = 512;
2226 const std::string kClientTag = "tag";
2227 std::string title(kNumChars, '0');
2228 sync_pb::EntitySpecifics entity_specifics;
2229 entity_specifics.mutable_preference()->set_name("name");
2230 entity_specifics.mutable_preference()->set_value("value");
2231 MakeServerNode(sync_manager_.GetUserShare(),
2232 PREFERENCES,
2233 "short_title",
2234 syncable::GenerateSyncableHash(PREFERENCES,
2235 kClientTag),
2236 entity_specifics);
2237 // New node shouldn't start off unsynced.
2238 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2240 // Manually change to the long title. Should set is_unsynced.
2242 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2243 WriteNode node(&trans);
2244 EXPECT_EQ(BaseNode::INIT_OK,
2245 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2246 node.SetTitle(title);
2247 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2249 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2251 // Manually change to the same title. Should not set is_unsynced.
2253 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2254 WriteNode node(&trans);
2255 EXPECT_EQ(BaseNode::INIT_OK,
2256 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2257 node.SetTitle(title);
2258 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2260 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2262 // Manually change to new title. Should set is_unsynced.
2264 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2265 WriteNode node(&trans);
2266 EXPECT_EQ(BaseNode::INIT_OK,
2267 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2268 node.SetTitle("title2");
2270 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2273 // Create an encrypted entry when the cryptographer doesn't think the type is
2274 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2275 // the data.
2276 TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) {
2277 std::string client_tag = "tag";
2278 std::string url = "url";
2279 std::string url2 = "new_url";
2280 std::string title = "title";
2281 sync_pb::EntitySpecifics entity_specifics;
2282 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2284 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2285 Cryptographer* crypto = trans.GetCryptographer();
2286 sync_pb::EntitySpecifics bm_specifics;
2287 bm_specifics.mutable_bookmark()->set_title("title");
2288 bm_specifics.mutable_bookmark()->set_url("url");
2289 sync_pb::EncryptedData encrypted;
2290 crypto->Encrypt(bm_specifics, &encrypted);
2291 entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
2292 AddDefaultFieldValue(BOOKMARKS, &entity_specifics);
2294 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2295 syncable::GenerateSyncableHash(BOOKMARKS,
2296 client_tag),
2297 entity_specifics);
2300 // Verify the data.
2301 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2302 ReadNode node(&trans);
2303 EXPECT_EQ(BaseNode::INIT_OK,
2304 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2305 EXPECT_EQ(title, node.GetTitle());
2306 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
2310 // Overwrite the url (which overwrites the specifics).
2311 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2312 WriteNode node(&trans);
2313 EXPECT_EQ(BaseNode::INIT_OK,
2314 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2316 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
2317 bookmark_specifics.set_url(url2);
2318 node.SetBookmarkSpecifics(bookmark_specifics);
2322 // Verify it's still encrypted and it has the most recent url.
2323 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2324 ReadNode node(&trans);
2325 EXPECT_EQ(BaseNode::INIT_OK,
2326 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2327 EXPECT_EQ(title, node.GetTitle());
2328 EXPECT_EQ(url2, node.GetBookmarkSpecifics().url());
2329 const syncable::Entry* node_entry = node.GetEntry();
2330 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2331 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2332 EXPECT_TRUE(specifics.has_encrypted());
2336 // Verify transaction version of a model type is incremented when node of
2337 // that type is updated.
2338 TEST_F(SyncManagerTest, IncrementTransactionVersion) {
2339 ModelSafeRoutingInfo routing_info;
2340 GetModelSafeRoutingInfo(&routing_info);
2343 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2344 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2345 i != routing_info.end(); ++i) {
2346 // Transaction version is incremented when SyncManagerTest::SetUp()
2347 // creates a node of each type.
2348 EXPECT_EQ(1,
2349 sync_manager_.GetUserShare()->directory->
2350 GetTransactionVersion(i->first));
2354 // Create bookmark node to increment transaction version of bookmark model.
2355 std::string client_tag = "title";
2356 sync_pb::EntitySpecifics entity_specifics;
2357 entity_specifics.mutable_bookmark()->set_url("url");
2358 entity_specifics.mutable_bookmark()->set_title("title");
2359 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2360 syncable::GenerateSyncableHash(BOOKMARKS,
2361 client_tag),
2362 entity_specifics);
2365 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2366 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2367 i != routing_info.end(); ++i) {
2368 EXPECT_EQ(i->first == BOOKMARKS ? 2 : 1,
2369 sync_manager_.GetUserShare()->directory->
2370 GetTransactionVersion(i->first));
2375 class MockSyncScheduler : public FakeSyncScheduler {
2376 public:
2377 MockSyncScheduler() : FakeSyncScheduler() {}
2378 virtual ~MockSyncScheduler() {}
2380 MOCK_METHOD1(Start, void(SyncScheduler::Mode));
2381 MOCK_METHOD1(ScheduleConfiguration, void(const ConfigurationParams&));
2384 class ComponentsFactory : public TestInternalComponentsFactory {
2385 public:
2386 ComponentsFactory(const Switches& switches,
2387 SyncScheduler* scheduler_to_use,
2388 sessions::SyncSessionContext** session_context,
2389 InternalComponentsFactory::StorageOption* storage_used)
2390 : TestInternalComponentsFactory(
2391 switches, InternalComponentsFactory::STORAGE_IN_MEMORY, storage_used),
2392 scheduler_to_use_(scheduler_to_use),
2393 session_context_(session_context) {}
2394 ~ComponentsFactory() override {}
2396 scoped_ptr<SyncScheduler> BuildScheduler(
2397 const std::string& name,
2398 sessions::SyncSessionContext* context,
2399 CancelationSignal* stop_handle) override {
2400 *session_context_ = context;
2401 return scheduler_to_use_.Pass();
2404 private:
2405 scoped_ptr<SyncScheduler> scheduler_to_use_;
2406 sessions::SyncSessionContext** session_context_;
2409 class SyncManagerTestWithMockScheduler : public SyncManagerTest {
2410 public:
2411 SyncManagerTestWithMockScheduler() : scheduler_(NULL) {}
2412 InternalComponentsFactory* GetFactory() override {
2413 scheduler_ = new MockSyncScheduler();
2414 return new ComponentsFactory(GetSwitches(), scheduler_, &session_context_,
2415 &storage_used_);
2418 MockSyncScheduler* scheduler() { return scheduler_; }
2419 sessions::SyncSessionContext* session_context() {
2420 return session_context_;
2423 private:
2424 MockSyncScheduler* scheduler_;
2425 sessions::SyncSessionContext* session_context_;
2428 // Test that the configuration params are properly created and sent to
2429 // ScheduleConfigure. No callback should be invoked. Any disabled datatypes
2430 // should be purged.
2431 TEST_F(SyncManagerTestWithMockScheduler, BasicConfiguration) {
2432 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2433 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2434 ModelSafeRoutingInfo new_routing_info;
2435 GetModelSafeRoutingInfo(&new_routing_info);
2436 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2437 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2439 ConfigurationParams params;
2440 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE));
2441 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2442 WillOnce(SaveArg<0>(&params));
2444 // Set data for all types.
2445 ModelTypeSet protocol_types = ProtocolTypes();
2446 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2447 iter.Inc()) {
2448 SetProgressMarkerForType(iter.Get(), true);
2451 CallbackCounter ready_task_counter, retry_task_counter;
2452 sync_manager_.ConfigureSyncer(
2453 reason,
2454 types_to_download,
2455 disabled_types,
2456 ModelTypeSet(),
2457 ModelTypeSet(),
2458 new_routing_info,
2459 base::Bind(&CallbackCounter::Callback,
2460 base::Unretained(&ready_task_counter)),
2461 base::Bind(&CallbackCounter::Callback,
2462 base::Unretained(&retry_task_counter)));
2463 EXPECT_EQ(0, ready_task_counter.times_called());
2464 EXPECT_EQ(0, retry_task_counter.times_called());
2465 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2466 params.source);
2467 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2468 EXPECT_EQ(new_routing_info, params.routing_info);
2470 // Verify all the disabled types were purged.
2471 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().Equals(
2472 enabled_types));
2473 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2474 ModelTypeSet::All()).Equals(disabled_types));
2477 // Test that on a reconfiguration (configuration where the session context
2478 // already has routing info), only those recently disabled types are purged.
2479 TEST_F(SyncManagerTestWithMockScheduler, ReConfiguration) {
2480 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2481 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2482 ModelTypeSet disabled_types = ModelTypeSet(THEMES, SESSIONS);
2483 ModelSafeRoutingInfo old_routing_info;
2484 ModelSafeRoutingInfo new_routing_info;
2485 GetModelSafeRoutingInfo(&old_routing_info);
2486 new_routing_info = old_routing_info;
2487 new_routing_info.erase(THEMES);
2488 new_routing_info.erase(SESSIONS);
2489 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2491 ConfigurationParams params;
2492 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE));
2493 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2494 WillOnce(SaveArg<0>(&params));
2496 // Set data for all types except those recently disabled (so we can verify
2497 // only those recently disabled are purged) .
2498 ModelTypeSet protocol_types = ProtocolTypes();
2499 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2500 iter.Inc()) {
2501 if (!disabled_types.Has(iter.Get())) {
2502 SetProgressMarkerForType(iter.Get(), true);
2503 } else {
2504 SetProgressMarkerForType(iter.Get(), false);
2508 // Set the context to have the old routing info.
2509 session_context()->SetRoutingInfo(old_routing_info);
2511 CallbackCounter ready_task_counter, retry_task_counter;
2512 sync_manager_.ConfigureSyncer(
2513 reason,
2514 types_to_download,
2515 ModelTypeSet(),
2516 ModelTypeSet(),
2517 ModelTypeSet(),
2518 new_routing_info,
2519 base::Bind(&CallbackCounter::Callback,
2520 base::Unretained(&ready_task_counter)),
2521 base::Bind(&CallbackCounter::Callback,
2522 base::Unretained(&retry_task_counter)));
2523 EXPECT_EQ(0, ready_task_counter.times_called());
2524 EXPECT_EQ(0, retry_task_counter.times_called());
2525 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2526 params.source);
2527 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2528 EXPECT_EQ(new_routing_info, params.routing_info);
2530 // Verify only the recently disabled types were purged.
2531 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2532 ProtocolTypes()).Equals(disabled_types));
2535 // Test that PurgePartiallySyncedTypes purges only those types that have not
2536 // fully completed their initial download and apply.
2537 TEST_F(SyncManagerTest, PurgePartiallySyncedTypes) {
2538 ModelSafeRoutingInfo routing_info;
2539 GetModelSafeRoutingInfo(&routing_info);
2540 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2542 UserShare* share = sync_manager_.GetUserShare();
2544 // The test harness automatically initializes all types in the routing info.
2545 // Check that autofill is not among them.
2546 ASSERT_FALSE(enabled_types.Has(AUTOFILL));
2548 // Further ensure that the test harness did not create its root node.
2550 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2551 syncable::Entry autofill_root_node(&trans,
2552 syncable::GET_TYPE_ROOT,
2553 AUTOFILL);
2554 ASSERT_FALSE(autofill_root_node.good());
2557 // One more redundant check.
2558 ASSERT_FALSE(sync_manager_.InitialSyncEndedTypes().Has(AUTOFILL));
2560 // Give autofill a progress marker.
2561 sync_pb::DataTypeProgressMarker autofill_marker;
2562 autofill_marker.set_data_type_id(
2563 GetSpecificsFieldNumberFromModelType(AUTOFILL));
2564 autofill_marker.set_token("token");
2565 share->directory->SetDownloadProgress(AUTOFILL, autofill_marker);
2567 // Also add a pending autofill root node update from the server.
2568 TestEntryFactory factory_(share->directory.get());
2569 int autofill_meta = factory_.CreateUnappliedRootNode(AUTOFILL);
2571 // Preferences is an enabled type. Check that the harness initialized it.
2572 ASSERT_TRUE(enabled_types.Has(PREFERENCES));
2573 ASSERT_TRUE(sync_manager_.InitialSyncEndedTypes().Has(PREFERENCES));
2575 // Give preferencse a progress marker.
2576 sync_pb::DataTypeProgressMarker prefs_marker;
2577 prefs_marker.set_data_type_id(
2578 GetSpecificsFieldNumberFromModelType(PREFERENCES));
2579 prefs_marker.set_token("token");
2580 share->directory->SetDownloadProgress(PREFERENCES, prefs_marker);
2582 // Add a fully synced preferences node under the root.
2583 std::string pref_client_tag = "prefABC";
2584 std::string pref_hashed_tag = "hashXYZ";
2585 sync_pb::EntitySpecifics pref_specifics;
2586 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2587 int pref_meta = MakeServerNode(
2588 share, PREFERENCES, pref_client_tag, pref_hashed_tag, pref_specifics);
2590 // And now, the purge.
2591 EXPECT_TRUE(sync_manager_.PurgePartiallySyncedTypes());
2593 // Ensure that autofill lost its progress marker, but preferences did not.
2594 ModelTypeSet empty_tokens =
2595 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
2596 EXPECT_TRUE(empty_tokens.Has(AUTOFILL));
2597 EXPECT_FALSE(empty_tokens.Has(PREFERENCES));
2599 // Ensure that autofill lots its node, but preferences did not.
2601 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2602 syncable::Entry autofill_node(&trans, GET_BY_HANDLE, autofill_meta);
2603 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref_meta);
2604 EXPECT_FALSE(autofill_node.good());
2605 EXPECT_TRUE(pref_node.good());
2609 // Test CleanupDisabledTypes properly purges all disabled types as specified
2610 // by the previous and current enabled params.
2611 TEST_F(SyncManagerTest, PurgeDisabledTypes) {
2612 ModelSafeRoutingInfo routing_info;
2613 GetModelSafeRoutingInfo(&routing_info);
2614 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2615 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2617 // The harness should have initialized the enabled_types for us.
2618 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2620 // Set progress markers for all types.
2621 ModelTypeSet protocol_types = ProtocolTypes();
2622 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2623 iter.Inc()) {
2624 SetProgressMarkerForType(iter.Get(), true);
2627 // Verify all the enabled types remain after cleanup, and all the disabled
2628 // types were purged.
2629 sync_manager_.PurgeDisabledTypes(disabled_types,
2630 ModelTypeSet(),
2631 ModelTypeSet());
2632 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2633 EXPECT_TRUE(disabled_types.Equals(
2634 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2636 // Disable some more types.
2637 disabled_types.Put(BOOKMARKS);
2638 disabled_types.Put(PREFERENCES);
2639 ModelTypeSet new_enabled_types =
2640 Difference(ModelTypeSet::All(), disabled_types);
2642 // Verify only the non-disabled types remain after cleanup.
2643 sync_manager_.PurgeDisabledTypes(disabled_types,
2644 ModelTypeSet(),
2645 ModelTypeSet());
2646 EXPECT_TRUE(new_enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2647 EXPECT_TRUE(disabled_types.Equals(
2648 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2651 // Test PurgeDisabledTypes properly unapplies types by deleting their local data
2652 // and preserving their server data and progress marker.
2653 TEST_F(SyncManagerTest, PurgeUnappliedTypes) {
2654 ModelSafeRoutingInfo routing_info;
2655 GetModelSafeRoutingInfo(&routing_info);
2656 ModelTypeSet unapplied_types = ModelTypeSet(BOOKMARKS, PREFERENCES);
2657 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2658 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2660 // The harness should have initialized the enabled_types for us.
2661 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2663 // Set progress markers for all types.
2664 ModelTypeSet protocol_types = ProtocolTypes();
2665 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2666 iter.Inc()) {
2667 SetProgressMarkerForType(iter.Get(), true);
2670 // Add the following kinds of items:
2671 // 1. Fully synced preference.
2672 // 2. Locally created preference, server unknown, unsynced
2673 // 3. Locally deleted preference, server known, unsynced
2674 // 4. Server deleted preference, locally known.
2675 // 5. Server created preference, locally unknown, unapplied.
2676 // 6. A fully synced bookmark (no unique_client_tag).
2677 UserShare* share = sync_manager_.GetUserShare();
2678 sync_pb::EntitySpecifics pref_specifics;
2679 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2680 sync_pb::EntitySpecifics bm_specifics;
2681 AddDefaultFieldValue(BOOKMARKS, &bm_specifics);
2682 int pref1_meta = MakeServerNode(
2683 share, PREFERENCES, "pref1", "hash1", pref_specifics);
2684 int64 pref2_meta = MakeNodeWithRoot(share, PREFERENCES, "pref2");
2685 int pref3_meta = MakeServerNode(
2686 share, PREFERENCES, "pref3", "hash3", pref_specifics);
2687 int pref4_meta = MakeServerNode(
2688 share, PREFERENCES, "pref4", "hash4", pref_specifics);
2689 int pref5_meta = MakeServerNode(
2690 share, PREFERENCES, "pref5", "hash5", pref_specifics);
2691 int bookmark_meta = MakeServerNode(
2692 share, BOOKMARKS, "bookmark", "", bm_specifics);
2695 syncable::WriteTransaction trans(FROM_HERE,
2696 syncable::SYNCER,
2697 share->directory.get());
2698 // Pref's 1 and 2 are already set up properly.
2699 // Locally delete pref 3.
2700 syncable::MutableEntry pref3(&trans, GET_BY_HANDLE, pref3_meta);
2701 pref3.PutIsDel(true);
2702 pref3.PutIsUnsynced(true);
2703 // Delete pref 4 at the server.
2704 syncable::MutableEntry pref4(&trans, GET_BY_HANDLE, pref4_meta);
2705 pref4.PutServerIsDel(true);
2706 pref4.PutIsUnappliedUpdate(true);
2707 pref4.PutServerVersion(2);
2708 // Pref 5 is an new unapplied update.
2709 syncable::MutableEntry pref5(&trans, GET_BY_HANDLE, pref5_meta);
2710 pref5.PutIsUnappliedUpdate(true);
2711 pref5.PutIsDel(true);
2712 pref5.PutBaseVersion(-1);
2713 // Bookmark is already set up properly
2716 // Take a snapshot to clear all the dirty bits.
2717 share->directory.get()->SaveChanges();
2719 // Now request a purge for the unapplied types.
2720 disabled_types.PutAll(unapplied_types);
2721 sync_manager_.PurgeDisabledTypes(disabled_types,
2722 ModelTypeSet(),
2723 unapplied_types);
2725 // Verify the unapplied types still have progress markers and initial sync
2726 // ended after cleanup.
2727 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().HasAll(unapplied_types));
2728 EXPECT_TRUE(
2729 sync_manager_.GetTypesWithEmptyProgressMarkerToken(unapplied_types).
2730 Empty());
2732 // Ensure the items were unapplied as necessary.
2734 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2735 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref1_meta);
2736 ASSERT_TRUE(pref_node.good());
2737 EXPECT_TRUE(pref_node.GetKernelCopy().is_dirty());
2738 EXPECT_FALSE(pref_node.GetIsUnsynced());
2739 EXPECT_TRUE(pref_node.GetIsUnappliedUpdate());
2740 EXPECT_TRUE(pref_node.GetIsDel());
2741 EXPECT_GT(pref_node.GetServerVersion(), 0);
2742 EXPECT_EQ(pref_node.GetBaseVersion(), -1);
2744 // Pref 2 should just be locally deleted.
2745 syncable::Entry pref2_node(&trans, GET_BY_HANDLE, pref2_meta);
2746 ASSERT_TRUE(pref2_node.good());
2747 EXPECT_TRUE(pref2_node.GetKernelCopy().is_dirty());
2748 EXPECT_FALSE(pref2_node.GetIsUnsynced());
2749 EXPECT_TRUE(pref2_node.GetIsDel());
2750 EXPECT_FALSE(pref2_node.GetIsUnappliedUpdate());
2751 EXPECT_TRUE(pref2_node.GetIsDel());
2752 EXPECT_EQ(pref2_node.GetServerVersion(), 0);
2753 EXPECT_EQ(pref2_node.GetBaseVersion(), -1);
2755 syncable::Entry pref3_node(&trans, GET_BY_HANDLE, pref3_meta);
2756 ASSERT_TRUE(pref3_node.good());
2757 EXPECT_TRUE(pref3_node.GetKernelCopy().is_dirty());
2758 EXPECT_FALSE(pref3_node.GetIsUnsynced());
2759 EXPECT_TRUE(pref3_node.GetIsUnappliedUpdate());
2760 EXPECT_TRUE(pref3_node.GetIsDel());
2761 EXPECT_GT(pref3_node.GetServerVersion(), 0);
2762 EXPECT_EQ(pref3_node.GetBaseVersion(), -1);
2764 syncable::Entry pref4_node(&trans, GET_BY_HANDLE, pref4_meta);
2765 ASSERT_TRUE(pref4_node.good());
2766 EXPECT_TRUE(pref4_node.GetKernelCopy().is_dirty());
2767 EXPECT_FALSE(pref4_node.GetIsUnsynced());
2768 EXPECT_TRUE(pref4_node.GetIsUnappliedUpdate());
2769 EXPECT_TRUE(pref4_node.GetIsDel());
2770 EXPECT_GT(pref4_node.GetServerVersion(), 0);
2771 EXPECT_EQ(pref4_node.GetBaseVersion(), -1);
2773 // Pref 5 should remain untouched.
2774 syncable::Entry pref5_node(&trans, GET_BY_HANDLE, pref5_meta);
2775 ASSERT_TRUE(pref5_node.good());
2776 EXPECT_FALSE(pref5_node.GetKernelCopy().is_dirty());
2777 EXPECT_FALSE(pref5_node.GetIsUnsynced());
2778 EXPECT_TRUE(pref5_node.GetIsUnappliedUpdate());
2779 EXPECT_TRUE(pref5_node.GetIsDel());
2780 EXPECT_GT(pref5_node.GetServerVersion(), 0);
2781 EXPECT_EQ(pref5_node.GetBaseVersion(), -1);
2783 syncable::Entry bookmark_node(&trans, GET_BY_HANDLE, bookmark_meta);
2784 ASSERT_TRUE(bookmark_node.good());
2785 EXPECT_TRUE(bookmark_node.GetKernelCopy().is_dirty());
2786 EXPECT_FALSE(bookmark_node.GetIsUnsynced());
2787 EXPECT_TRUE(bookmark_node.GetIsUnappliedUpdate());
2788 EXPECT_TRUE(bookmark_node.GetIsDel());
2789 EXPECT_GT(bookmark_node.GetServerVersion(), 0);
2790 EXPECT_EQ(bookmark_node.GetBaseVersion(), -1);
2794 // A test harness to exercise the code that processes and passes changes from
2795 // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
2796 // ChangeProcessor.
2797 class SyncManagerChangeProcessingTest : public SyncManagerTest {
2798 public:
2799 void OnChangesApplied(ModelType model_type,
2800 int64 model_version,
2801 const BaseTransaction* trans,
2802 const ImmutableChangeRecordList& changes) override {
2803 last_changes_ = changes;
2806 void OnChangesComplete(ModelType model_type) override {}
2808 const ImmutableChangeRecordList& GetRecentChangeList() {
2809 return last_changes_;
2812 UserShare* share() {
2813 return sync_manager_.GetUserShare();
2816 // Set some flags so our nodes reasonably approximate the real world scenario
2817 // and can get past CheckTreeInvariants.
2819 // It's never going to be truly accurate, since we're squashing update
2820 // receipt, processing and application into a single transaction.
2821 void SetNodeProperties(syncable::MutableEntry *entry) {
2822 entry->PutId(id_factory_.NewServerId());
2823 entry->PutBaseVersion(10);
2824 entry->PutServerVersion(10);
2827 // Looks for the given change in the list. Returns the index at which it was
2828 // found. Returns -1 on lookup failure.
2829 size_t FindChangeInList(int64 id, ChangeRecord::Action action) {
2830 SCOPED_TRACE(id);
2831 for (size_t i = 0; i < last_changes_.Get().size(); ++i) {
2832 if (last_changes_.Get()[i].id == id
2833 && last_changes_.Get()[i].action == action) {
2834 return i;
2837 ADD_FAILURE() << "Failed to find specified change";
2838 return static_cast<size_t>(-1);
2841 // Returns the current size of the change list.
2843 // Note that spurious changes do not necessarily indicate a problem.
2844 // Assertions on change list size can help detect problems, but it may be
2845 // necessary to reduce their strictness if the implementation changes.
2846 size_t GetChangeListSize() {
2847 return last_changes_.Get().size();
2850 void ClearChangeList() { last_changes_ = ImmutableChangeRecordList(); }
2852 protected:
2853 ImmutableChangeRecordList last_changes_;
2854 TestIdFactory id_factory_;
2857 // Test creation of a folder and a bookmark.
2858 TEST_F(SyncManagerChangeProcessingTest, AddBookmarks) {
2859 int64 type_root = GetIdForDataType(BOOKMARKS);
2860 int64 folder_id = kInvalidId;
2861 int64 child_id = kInvalidId;
2863 // Create a folder and a bookmark under it.
2865 syncable::WriteTransaction trans(
2866 FROM_HERE, syncable::SYNCER, share()->directory.get());
2867 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
2868 ASSERT_TRUE(root.good());
2870 syncable::MutableEntry folder(&trans, syncable::CREATE,
2871 BOOKMARKS, root.GetId(), "folder");
2872 ASSERT_TRUE(folder.good());
2873 SetNodeProperties(&folder);
2874 folder.PutIsDir(true);
2875 folder_id = folder.GetMetahandle();
2877 syncable::MutableEntry child(&trans, syncable::CREATE,
2878 BOOKMARKS, folder.GetId(), "child");
2879 ASSERT_TRUE(child.good());
2880 SetNodeProperties(&child);
2881 child_id = child.GetMetahandle();
2884 // The closing of the above scope will delete the transaction. Its processed
2885 // changes should be waiting for us in a member of the test harness.
2886 EXPECT_EQ(2UL, GetChangeListSize());
2888 // We don't need to check these return values here. The function will add a
2889 // non-fatal failure if these changes are not found.
2890 size_t folder_change_pos =
2891 FindChangeInList(folder_id, ChangeRecord::ACTION_ADD);
2892 size_t child_change_pos =
2893 FindChangeInList(child_id, ChangeRecord::ACTION_ADD);
2895 // Parents are delivered before children.
2896 EXPECT_LT(folder_change_pos, child_change_pos);
2899 // Test creation of a preferences (with implicit parent Id)
2900 TEST_F(SyncManagerChangeProcessingTest, AddPreferences) {
2901 int64 item1_id = kInvalidId;
2902 int64 item2_id = kInvalidId;
2904 // Create two preferences.
2906 syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
2907 share()->directory.get());
2909 syncable::MutableEntry item1(&trans, syncable::CREATE, PREFERENCES,
2910 "test_item_1");
2911 ASSERT_TRUE(item1.good());
2912 SetNodeProperties(&item1);
2913 item1_id = item1.GetMetahandle();
2915 // Need at least two items to ensure hitting all possible codepaths in
2916 // ChangeReorderBuffer::Traversal::ExpandToInclude.
2917 syncable::MutableEntry item2(&trans, syncable::CREATE, PREFERENCES,
2918 "test_item_2");
2919 ASSERT_TRUE(item2.good());
2920 SetNodeProperties(&item2);
2921 item2_id = item2.GetMetahandle();
2924 // The closing of the above scope will delete the transaction. Its processed
2925 // changes should be waiting for us in a member of the test harness.
2926 EXPECT_EQ(2UL, GetChangeListSize());
2928 FindChangeInList(item1_id, ChangeRecord::ACTION_ADD);
2929 FindChangeInList(item2_id, ChangeRecord::ACTION_ADD);
2932 // Test moving a bookmark into an empty folder.
2933 TEST_F(SyncManagerChangeProcessingTest, MoveBookmarkIntoEmptyFolder) {
2934 int64 type_root = GetIdForDataType(BOOKMARKS);
2935 int64 folder_b_id = kInvalidId;
2936 int64 child_id = kInvalidId;
2938 // Create two folders. Place a child under folder A.
2940 syncable::WriteTransaction trans(
2941 FROM_HERE, syncable::SYNCER, share()->directory.get());
2942 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
2943 ASSERT_TRUE(root.good());
2945 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
2946 BOOKMARKS, root.GetId(), "folderA");
2947 ASSERT_TRUE(folder_a.good());
2948 SetNodeProperties(&folder_a);
2949 folder_a.PutIsDir(true);
2951 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
2952 BOOKMARKS, root.GetId(), "folderB");
2953 ASSERT_TRUE(folder_b.good());
2954 SetNodeProperties(&folder_b);
2955 folder_b.PutIsDir(true);
2956 folder_b_id = folder_b.GetMetahandle();
2958 syncable::MutableEntry child(&trans, syncable::CREATE,
2959 BOOKMARKS, folder_a.GetId(),
2960 "child");
2961 ASSERT_TRUE(child.good());
2962 SetNodeProperties(&child);
2963 child_id = child.GetMetahandle();
2966 // Close that transaction. The above was to setup the initial scenario. The
2967 // real test starts now.
2969 // Move the child from folder A to folder B.
2971 syncable::WriteTransaction trans(
2972 FROM_HERE, syncable::SYNCER, share()->directory.get());
2974 syncable::Entry folder_b(&trans, syncable::GET_BY_HANDLE, folder_b_id);
2975 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
2977 child.PutParentId(folder_b.GetId());
2980 EXPECT_EQ(1UL, GetChangeListSize());
2982 // Verify that this was detected as a real change. An early version of the
2983 // UniquePosition code had a bug where moves from one folder to another were
2984 // ignored unless the moved node's UniquePosition value was also changed in
2985 // some way.
2986 FindChangeInList(child_id, ChangeRecord::ACTION_UPDATE);
2989 // Test moving a bookmark into a non-empty folder.
2990 TEST_F(SyncManagerChangeProcessingTest, MoveIntoPopulatedFolder) {
2991 int64 type_root = GetIdForDataType(BOOKMARKS);
2992 int64 child_a_id = kInvalidId;
2993 int64 child_b_id = kInvalidId;
2995 // Create two folders. Place one child each under folder A and folder B.
2997 syncable::WriteTransaction trans(
2998 FROM_HERE, syncable::SYNCER, share()->directory.get());
2999 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3000 ASSERT_TRUE(root.good());
3002 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3003 BOOKMARKS, root.GetId(), "folderA");
3004 ASSERT_TRUE(folder_a.good());
3005 SetNodeProperties(&folder_a);
3006 folder_a.PutIsDir(true);
3008 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3009 BOOKMARKS, root.GetId(), "folderB");
3010 ASSERT_TRUE(folder_b.good());
3011 SetNodeProperties(&folder_b);
3012 folder_b.PutIsDir(true);
3014 syncable::MutableEntry child_a(&trans, syncable::CREATE,
3015 BOOKMARKS, folder_a.GetId(),
3016 "childA");
3017 ASSERT_TRUE(child_a.good());
3018 SetNodeProperties(&child_a);
3019 child_a_id = child_a.GetMetahandle();
3021 syncable::MutableEntry child_b(&trans, syncable::CREATE,
3022 BOOKMARKS, folder_b.GetId(),
3023 "childB");
3024 SetNodeProperties(&child_b);
3025 child_b_id = child_b.GetMetahandle();
3028 // Close that transaction. The above was to setup the initial scenario. The
3029 // real test starts now.
3032 syncable::WriteTransaction trans(
3033 FROM_HERE, syncable::SYNCER, share()->directory.get());
3035 syncable::MutableEntry child_a(&trans, syncable::GET_BY_HANDLE, child_a_id);
3036 syncable::MutableEntry child_b(&trans, syncable::GET_BY_HANDLE, child_b_id);
3038 // Move child A from folder A to folder B and update its position.
3039 child_a.PutParentId(child_b.GetParentId());
3040 child_a.PutPredecessor(child_b.GetId());
3043 EXPECT_EQ(1UL, GetChangeListSize());
3045 // Verify that only child a is in the change list.
3046 // (This function will add a failure if the lookup fails.)
3047 FindChangeInList(child_a_id, ChangeRecord::ACTION_UPDATE);
3050 // Tests the ordering of deletion changes.
3051 TEST_F(SyncManagerChangeProcessingTest, DeletionsAndChanges) {
3052 int64 type_root = GetIdForDataType(BOOKMARKS);
3053 int64 folder_a_id = kInvalidId;
3054 int64 folder_b_id = kInvalidId;
3055 int64 child_id = kInvalidId;
3057 // Create two folders. Place a child under folder A.
3059 syncable::WriteTransaction trans(
3060 FROM_HERE, syncable::SYNCER, share()->directory.get());
3061 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3062 ASSERT_TRUE(root.good());
3064 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3065 BOOKMARKS, root.GetId(), "folderA");
3066 ASSERT_TRUE(folder_a.good());
3067 SetNodeProperties(&folder_a);
3068 folder_a.PutIsDir(true);
3069 folder_a_id = folder_a.GetMetahandle();
3071 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3072 BOOKMARKS, root.GetId(), "folderB");
3073 ASSERT_TRUE(folder_b.good());
3074 SetNodeProperties(&folder_b);
3075 folder_b.PutIsDir(true);
3076 folder_b_id = folder_b.GetMetahandle();
3078 syncable::MutableEntry child(&trans, syncable::CREATE,
3079 BOOKMARKS, folder_a.GetId(),
3080 "child");
3081 ASSERT_TRUE(child.good());
3082 SetNodeProperties(&child);
3083 child_id = child.GetMetahandle();
3086 // Close that transaction. The above was to setup the initial scenario. The
3087 // real test starts now.
3090 syncable::WriteTransaction trans(
3091 FROM_HERE, syncable::SYNCER, share()->directory.get());
3093 syncable::MutableEntry folder_a(
3094 &trans, syncable::GET_BY_HANDLE, folder_a_id);
3095 syncable::MutableEntry folder_b(
3096 &trans, syncable::GET_BY_HANDLE, folder_b_id);
3097 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3099 // Delete folder B and its child.
3100 child.PutIsDel(true);
3101 folder_b.PutIsDel(true);
3103 // Make an unrelated change to folder A.
3104 folder_a.PutNonUniqueName("NewNameA");
3107 EXPECT_EQ(3UL, GetChangeListSize());
3109 size_t folder_a_pos =
3110 FindChangeInList(folder_a_id, ChangeRecord::ACTION_UPDATE);
3111 size_t folder_b_pos =
3112 FindChangeInList(folder_b_id, ChangeRecord::ACTION_DELETE);
3113 size_t child_pos = FindChangeInList(child_id, ChangeRecord::ACTION_DELETE);
3115 // Deletes should appear before updates.
3116 EXPECT_LT(child_pos, folder_a_pos);
3117 EXPECT_LT(folder_b_pos, folder_a_pos);
3120 // See that attachment metadata changes are not filtered out by
3121 // SyncManagerImpl::VisiblePropertiesDiffer.
3122 TEST_F(SyncManagerChangeProcessingTest, AttachmentMetadataOnlyChanges) {
3123 // Create an article with no attachments. See that a change is generated.
3124 int64 article_id = kInvalidId;
3126 syncable::WriteTransaction trans(
3127 FROM_HERE, syncable::SYNCER, share()->directory.get());
3128 int64 type_root = GetIdForDataType(ARTICLES);
3129 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3130 ASSERT_TRUE(root.good());
3131 syncable::MutableEntry article(
3132 &trans, syncable::CREATE, ARTICLES, root.GetId(), "article");
3133 ASSERT_TRUE(article.good());
3134 SetNodeProperties(&article);
3135 article_id = article.GetMetahandle();
3137 ASSERT_EQ(1UL, GetChangeListSize());
3138 FindChangeInList(article_id, ChangeRecord::ACTION_ADD);
3139 ClearChangeList();
3141 // Modify the article by adding one attachment. Don't touch anything else.
3142 // See that a change is generated.
3144 syncable::WriteTransaction trans(
3145 FROM_HERE, syncable::SYNCER, share()->directory.get());
3146 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3147 sync_pb::AttachmentMetadata metadata;
3148 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3149 article.PutAttachmentMetadata(metadata);
3151 ASSERT_EQ(1UL, GetChangeListSize());
3152 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3153 ClearChangeList();
3155 // Modify the article by replacing its attachment with a different one. See
3156 // that a change is generated.
3158 syncable::WriteTransaction trans(
3159 FROM_HERE, syncable::SYNCER, share()->directory.get());
3160 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3161 sync_pb::AttachmentMetadata metadata = article.GetAttachmentMetadata();
3162 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3163 article.PutAttachmentMetadata(metadata);
3165 ASSERT_EQ(1UL, GetChangeListSize());
3166 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3167 ClearChangeList();
3169 // Modify the article by replacing its attachment metadata with the same
3170 // attachment metadata. No change should be generated.
3172 syncable::WriteTransaction trans(
3173 FROM_HERE, syncable::SYNCER, share()->directory.get());
3174 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3175 article.PutAttachmentMetadata(article.GetAttachmentMetadata());
3177 ASSERT_EQ(0UL, GetChangeListSize());
3180 // During initialization SyncManagerImpl loads sqlite database. If it fails to
3181 // do so it should fail initialization. This test verifies this behavior.
3182 // Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
3183 // InternalComponentsFactory to return DirectoryBackingStore that always fails
3184 // to load.
3185 class SyncManagerInitInvalidStorageTest : public SyncManagerTest {
3186 public:
3187 SyncManagerInitInvalidStorageTest() {
3190 InternalComponentsFactory* GetFactory() override {
3191 return new TestInternalComponentsFactory(
3192 GetSwitches(), InternalComponentsFactory::STORAGE_INVALID,
3193 &storage_used_);
3197 // SyncManagerInitInvalidStorageTest::GetFactory will return
3198 // DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
3199 // SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
3200 // task is to ensure that SyncManagerImpl reported initialization failure in
3201 // OnInitializationComplete callback.
3202 TEST_F(SyncManagerInitInvalidStorageTest, FailToOpenDatabase) {
3203 EXPECT_FALSE(initialization_succeeded_);
3206 } // namespace syncer