[DevTools] Fix service worker hanging on restart.
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl_unittest.cc
blob8e77e706b676805e8ac0a3c8535cb34ce797c8f8
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/message_loop/message_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());
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 message_loop_.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 private:
1031 // Needed by |sync_manager_|.
1032 base::MessageLoop message_loop_;
1033 // Needed by |sync_manager_|.
1034 base::ScopedTempDir temp_dir_;
1035 // Sync Id's for the roots of the enabled datatypes.
1036 std::map<ModelType, int64> type_roots_;
1037 scoped_refptr<ExtensionsActivity> extensions_activity_;
1039 protected:
1040 FakeEncryptor encryptor_;
1041 SyncManagerImpl sync_manager_;
1042 CancelationSignal cancelation_signal_;
1043 WeakHandle<JsBackend> js_backend_;
1044 bool initialization_succeeded_;
1045 StrictMock<SyncManagerObserverMock> manager_observer_;
1046 StrictMock<SyncEncryptionHandlerObserverMock> encryption_observer_;
1047 InternalComponentsFactory::Switches switches_;
1048 InternalComponentsFactory::StorageOption storage_used_;
1051 TEST_F(SyncManagerTest, GetAllNodesForTypeTest) {
1052 ModelSafeRoutingInfo routing_info;
1053 GetModelSafeRoutingInfo(&routing_info);
1054 sync_manager_.StartSyncingNormally(routing_info);
1056 scoped_ptr<base::ListValue> node_list(
1057 sync_manager_.GetAllNodesForType(syncer::PREFERENCES));
1059 // Should have one node: the type root node.
1060 ASSERT_EQ(1U, node_list->GetSize());
1062 const base::DictionaryValue* first_result;
1063 ASSERT_TRUE(node_list->GetDictionary(0, &first_result));
1064 EXPECT_TRUE(first_result->HasKey("ID"));
1065 EXPECT_TRUE(first_result->HasKey("NON_UNIQUE_NAME"));
1068 TEST_F(SyncManagerTest, RefreshEncryptionReady) {
1069 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1070 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1071 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1072 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1074 sync_manager_.GetEncryptionHandler()->Init();
1075 PumpLoop();
1077 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1078 EXPECT_TRUE(encrypted_types.Has(PASSWORDS));
1079 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1082 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1083 ReadNode node(&trans);
1084 EXPECT_EQ(BaseNode::INIT_OK,
1085 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1086 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1087 EXPECT_TRUE(nigori.has_encryption_keybag());
1088 Cryptographer* cryptographer = trans.GetCryptographer();
1089 EXPECT_TRUE(cryptographer->is_ready());
1090 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1094 // Attempt to refresh encryption when nigori not downloaded.
1095 TEST_F(SyncManagerTest, RefreshEncryptionNotReady) {
1096 // Don't set up encryption (no nigori node created).
1098 // Should fail. Triggers an OnPassphraseRequired because the cryptographer
1099 // is not ready.
1100 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)).Times(1);
1101 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1102 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1103 sync_manager_.GetEncryptionHandler()->Init();
1104 PumpLoop();
1106 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1107 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1108 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1111 // Attempt to refresh encryption when nigori is empty.
1112 TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) {
1113 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION));
1114 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(1);
1115 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1116 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1118 // Should write to nigori.
1119 sync_manager_.GetEncryptionHandler()->Init();
1120 PumpLoop();
1122 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1123 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1124 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1127 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1128 ReadNode node(&trans);
1129 EXPECT_EQ(BaseNode::INIT_OK,
1130 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1131 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1132 EXPECT_TRUE(nigori.has_encryption_keybag());
1133 Cryptographer* cryptographer = trans.GetCryptographer();
1134 EXPECT_TRUE(cryptographer->is_ready());
1135 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1139 TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) {
1140 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1141 EXPECT_CALL(encryption_observer_,
1142 OnEncryptedTypesChanged(
1143 HasModelTypes(EncryptableUserTypes()), true));
1144 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1145 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1146 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1149 TEST_F(SyncManagerTest, EncryptDataTypesWithData) {
1150 size_t batch_size = 5;
1151 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1153 // Create some unencrypted unsynced data.
1154 int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(),
1155 BOOKMARKS,
1156 GetIdForDataType(BOOKMARKS),
1157 NULL);
1158 // First batch_size nodes are children of folder.
1159 size_t i;
1160 for (i = 0; i < batch_size; ++i) {
1161 MakeBookmarkWithParent(sync_manager_.GetUserShare(), folder, NULL);
1163 // Next batch_size nodes are a different type and on their own.
1164 for (; i < 2*batch_size; ++i) {
1165 MakeNodeWithRoot(sync_manager_.GetUserShare(), SESSIONS,
1166 base::StringPrintf("%" PRIuS "", i));
1168 // Last batch_size nodes are a third type that will not need encryption.
1169 for (; i < 3*batch_size; ++i) {
1170 MakeNodeWithRoot(sync_manager_.GetUserShare(), THEMES,
1171 base::StringPrintf("%" PRIuS "", i));
1175 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1176 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1177 SyncEncryptionHandler::SensitiveTypes()));
1178 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1179 trans.GetWrappedTrans(),
1180 BOOKMARKS,
1181 false /* not encrypted */));
1182 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1183 trans.GetWrappedTrans(),
1184 SESSIONS,
1185 false /* not encrypted */));
1186 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1187 trans.GetWrappedTrans(),
1188 THEMES,
1189 false /* not encrypted */));
1192 EXPECT_CALL(encryption_observer_,
1193 OnEncryptedTypesChanged(
1194 HasModelTypes(EncryptableUserTypes()), true));
1195 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1196 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1197 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1199 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1200 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1201 EncryptableUserTypes()));
1202 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1203 trans.GetWrappedTrans(),
1204 BOOKMARKS,
1205 true /* is encrypted */));
1206 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1207 trans.GetWrappedTrans(),
1208 SESSIONS,
1209 true /* is encrypted */));
1210 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1211 trans.GetWrappedTrans(),
1212 THEMES,
1213 true /* is encrypted */));
1216 // Trigger's a ReEncryptEverything with new passphrase.
1217 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1218 EXPECT_CALL(encryption_observer_,
1219 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1220 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1221 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1222 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1223 EXPECT_CALL(encryption_observer_,
1224 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1225 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1226 "new_passphrase", true);
1227 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1229 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1230 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1231 EncryptableUserTypes()));
1232 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1233 trans.GetWrappedTrans(),
1234 BOOKMARKS,
1235 true /* is encrypted */));
1236 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1237 trans.GetWrappedTrans(),
1238 SESSIONS,
1239 true /* is encrypted */));
1240 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1241 trans.GetWrappedTrans(),
1242 THEMES,
1243 true /* is encrypted */));
1245 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1246 // a reencryption and should just notify immediately.
1247 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1248 EXPECT_CALL(encryption_observer_,
1249 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)).Times(0);
1250 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()).Times(0);
1251 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(0);
1252 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1255 // Test that when there are no pending keys and the cryptographer is not
1256 // initialized, we add a key based on the current GAIA password.
1257 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1258 TEST_F(SyncManagerTest, SetInitialGaiaPass) {
1259 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1260 EXPECT_CALL(encryption_observer_,
1261 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1262 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1263 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1264 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1265 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1266 "new_passphrase",
1267 false);
1268 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1269 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1270 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1272 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1273 ReadNode node(&trans);
1274 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1275 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1276 Cryptographer* cryptographer = trans.GetCryptographer();
1277 EXPECT_TRUE(cryptographer->is_ready());
1278 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1282 // Test that when there are no pending keys and we have on the old GAIA
1283 // password, we update and re-encrypt everything with the new GAIA password.
1284 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1285 TEST_F(SyncManagerTest, UpdateGaiaPass) {
1286 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1287 Cryptographer verifier(&encryptor_);
1289 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1290 Cryptographer* cryptographer = trans.GetCryptographer();
1291 std::string bootstrap_token;
1292 cryptographer->GetBootstrapToken(&bootstrap_token);
1293 verifier.Bootstrap(bootstrap_token);
1295 EXPECT_CALL(encryption_observer_,
1296 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1297 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1298 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1299 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1300 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1301 "new_passphrase",
1302 false);
1303 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1304 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1305 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1307 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1308 Cryptographer* cryptographer = trans.GetCryptographer();
1309 EXPECT_TRUE(cryptographer->is_ready());
1310 // Verify the default key has changed.
1311 sync_pb::EncryptedData encrypted;
1312 cryptographer->GetKeys(&encrypted);
1313 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1317 // Sets a new explicit passphrase. This should update the bootstrap token
1318 // and re-encrypt everything.
1319 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1320 TEST_F(SyncManagerTest, SetPassphraseWithPassword) {
1321 Cryptographer verifier(&encryptor_);
1322 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1324 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1325 // Store the default (soon to be old) key.
1326 Cryptographer* cryptographer = trans.GetCryptographer();
1327 std::string bootstrap_token;
1328 cryptographer->GetBootstrapToken(&bootstrap_token);
1329 verifier.Bootstrap(bootstrap_token);
1331 ReadNode root_node(&trans);
1332 root_node.InitByRootLookup();
1334 WriteNode password_node(&trans);
1335 WriteNode::InitUniqueByCreationResult result =
1336 password_node.InitUniqueByCreation(PASSWORDS,
1337 root_node, "foo");
1338 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1339 sync_pb::PasswordSpecificsData data;
1340 data.set_password_value("secret");
1341 password_node.SetPasswordSpecifics(data);
1343 EXPECT_CALL(encryption_observer_,
1344 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1345 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1346 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1347 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1348 EXPECT_CALL(encryption_observer_,
1349 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1350 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1351 "new_passphrase",
1352 true);
1353 EXPECT_EQ(CUSTOM_PASSPHRASE,
1354 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1355 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1357 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1358 Cryptographer* cryptographer = trans.GetCryptographer();
1359 EXPECT_TRUE(cryptographer->is_ready());
1360 // Verify the default key has changed.
1361 sync_pb::EncryptedData encrypted;
1362 cryptographer->GetKeys(&encrypted);
1363 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1365 ReadNode password_node(&trans);
1366 EXPECT_EQ(BaseNode::INIT_OK,
1367 password_node.InitByClientTagLookup(PASSWORDS,
1368 "foo"));
1369 const sync_pb::PasswordSpecificsData& data =
1370 password_node.GetPasswordSpecifics();
1371 EXPECT_EQ("secret", data.password_value());
1375 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1376 // being encrypted with a new (unprovided) GAIA password, then supply the
1377 // password.
1378 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1379 TEST_F(SyncManagerTest, SupplyPendingGAIAPass) {
1380 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1381 Cryptographer other_cryptographer(&encryptor_);
1383 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1384 Cryptographer* cryptographer = trans.GetCryptographer();
1385 std::string bootstrap_token;
1386 cryptographer->GetBootstrapToken(&bootstrap_token);
1387 other_cryptographer.Bootstrap(bootstrap_token);
1389 // Now update the nigori to reflect the new keys, and update the
1390 // cryptographer to have pending keys.
1391 KeyParams params = {"localhost", "dummy", "passphrase2"};
1392 other_cryptographer.AddKey(params);
1393 WriteNode node(&trans);
1394 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1395 sync_pb::NigoriSpecifics nigori;
1396 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1397 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1398 EXPECT_TRUE(cryptographer->has_pending_keys());
1399 node.SetNigoriSpecifics(nigori);
1401 EXPECT_CALL(encryption_observer_,
1402 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1403 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1404 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1405 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1406 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
1407 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1408 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1409 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1411 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1412 Cryptographer* cryptographer = trans.GetCryptographer();
1413 EXPECT_TRUE(cryptographer->is_ready());
1414 // Verify we're encrypting with the new key.
1415 sync_pb::EncryptedData encrypted;
1416 cryptographer->GetKeys(&encrypted);
1417 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1421 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1422 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1423 // the current GAIA password and verify the bootstrap token is updated. Then
1424 // supply the old GAIA password, and verify we re-encrypt all data with the
1425 // new GAIA password.
1426 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1427 TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) {
1428 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1429 Cryptographer other_cryptographer(&encryptor_);
1431 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1432 Cryptographer* cryptographer = trans.GetCryptographer();
1433 std::string bootstrap_token;
1434 cryptographer->GetBootstrapToken(&bootstrap_token);
1435 other_cryptographer.Bootstrap(bootstrap_token);
1437 // Now update the nigori to reflect the new keys, and update the
1438 // cryptographer to have pending keys.
1439 KeyParams params = {"localhost", "dummy", "old_gaia"};
1440 other_cryptographer.AddKey(params);
1441 WriteNode node(&trans);
1442 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1443 sync_pb::NigoriSpecifics nigori;
1444 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1445 node.SetNigoriSpecifics(nigori);
1446 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1448 // other_cryptographer now contains all encryption keys, and is encrypting
1449 // with the newest gaia.
1450 KeyParams new_params = {"localhost", "dummy", "new_gaia"};
1451 other_cryptographer.AddKey(new_params);
1453 // The bootstrap token should have been updated. Save it to ensure it's based
1454 // on the new GAIA password.
1455 std::string bootstrap_token;
1456 EXPECT_CALL(encryption_observer_,
1457 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN))
1458 .WillOnce(SaveArg<0>(&bootstrap_token));
1459 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_,_));
1460 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1461 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1462 "new_gaia",
1463 false);
1464 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1465 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1466 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1467 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1469 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1470 Cryptographer* cryptographer = trans.GetCryptographer();
1471 EXPECT_TRUE(cryptographer->is_initialized());
1472 EXPECT_FALSE(cryptographer->is_ready());
1473 // Verify we're encrypting with the new key, even though we have pending
1474 // keys.
1475 sync_pb::EncryptedData encrypted;
1476 other_cryptographer.GetKeys(&encrypted);
1477 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1479 EXPECT_CALL(encryption_observer_,
1480 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1481 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1482 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1483 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1484 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1485 "old_gaia",
1486 false);
1487 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1488 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1490 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1491 Cryptographer* cryptographer = trans.GetCryptographer();
1492 EXPECT_TRUE(cryptographer->is_ready());
1494 // Verify we're encrypting with the new key.
1495 sync_pb::EncryptedData encrypted;
1496 other_cryptographer.GetKeys(&encrypted);
1497 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1499 // Verify the saved bootstrap token is based on the new gaia password.
1500 Cryptographer temp_cryptographer(&encryptor_);
1501 temp_cryptographer.Bootstrap(bootstrap_token);
1502 EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted));
1506 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1507 // being encrypted with an explicit (unprovided) passphrase, then supply the
1508 // passphrase.
1509 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1510 TEST_F(SyncManagerTest, SupplyPendingExplicitPass) {
1511 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1512 Cryptographer other_cryptographer(&encryptor_);
1514 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1515 Cryptographer* cryptographer = trans.GetCryptographer();
1516 std::string bootstrap_token;
1517 cryptographer->GetBootstrapToken(&bootstrap_token);
1518 other_cryptographer.Bootstrap(bootstrap_token);
1520 // Now update the nigori to reflect the new keys, and update the
1521 // cryptographer to have pending keys.
1522 KeyParams params = {"localhost", "dummy", "explicit"};
1523 other_cryptographer.AddKey(params);
1524 WriteNode node(&trans);
1525 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1526 sync_pb::NigoriSpecifics nigori;
1527 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1528 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1529 EXPECT_TRUE(cryptographer->has_pending_keys());
1530 nigori.set_keybag_is_frozen(true);
1531 node.SetNigoriSpecifics(nigori);
1533 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1534 EXPECT_CALL(encryption_observer_,
1535 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1536 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _));
1537 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1538 sync_manager_.GetEncryptionHandler()->Init();
1539 EXPECT_CALL(encryption_observer_,
1540 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1541 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1542 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1543 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1544 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
1545 EXPECT_EQ(CUSTOM_PASSPHRASE,
1546 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1547 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1549 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1550 Cryptographer* cryptographer = trans.GetCryptographer();
1551 EXPECT_TRUE(cryptographer->is_ready());
1552 // Verify we're encrypting with the new key.
1553 sync_pb::EncryptedData encrypted;
1554 cryptographer->GetKeys(&encrypted);
1555 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1559 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1560 // being encrypted with a new (unprovided) GAIA password, then supply the
1561 // password as a user-provided password.
1562 // This is the android case 7/8.
1563 TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) {
1564 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1565 Cryptographer other_cryptographer(&encryptor_);
1567 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1568 Cryptographer* cryptographer = trans.GetCryptographer();
1569 // Now update the nigori to reflect the new keys, and update the
1570 // cryptographer to have pending keys.
1571 KeyParams params = {"localhost", "dummy", "passphrase"};
1572 other_cryptographer.AddKey(params);
1573 WriteNode node(&trans);
1574 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1575 sync_pb::NigoriSpecifics nigori;
1576 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1577 node.SetNigoriSpecifics(nigori);
1578 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1579 EXPECT_FALSE(cryptographer->is_ready());
1581 EXPECT_CALL(encryption_observer_,
1582 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1583 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1584 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1585 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1586 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1587 "passphrase",
1588 false);
1589 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1590 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1591 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1593 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1594 Cryptographer* cryptographer = trans.GetCryptographer();
1595 EXPECT_TRUE(cryptographer->is_ready());
1599 TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) {
1600 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1601 int64 node_id = 0;
1602 std::string tag = "foo";
1604 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1605 ReadNode root_node(&trans);
1606 root_node.InitByRootLookup();
1608 WriteNode password_node(&trans);
1609 WriteNode::InitUniqueByCreationResult result =
1610 password_node.InitUniqueByCreation(PASSWORDS, root_node, tag);
1611 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1612 node_id = password_node.GetId();
1614 EXPECT_CALL(encryption_observer_,
1615 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1616 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1617 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1618 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1619 EXPECT_CALL(encryption_observer_,
1620 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1621 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1622 "new_passphrase",
1623 true);
1624 EXPECT_EQ(CUSTOM_PASSPHRASE,
1625 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1626 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1628 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1629 ReadNode password_node(&trans);
1630 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1631 password_node.InitByClientTagLookup(PASSWORDS,
1632 tag));
1635 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1636 ReadNode password_node(&trans);
1637 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1638 password_node.InitByIdLookup(node_id));
1642 // Friended by WriteNode, so can't be in an anonymouse namespace.
1643 TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) {
1644 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1645 std::string title;
1646 SyncAPINameToServerName("Google", &title);
1647 std::string url = "http://www.google.com";
1648 std::string raw_title2 = ".."; // An invalid cosmo title.
1649 std::string title2;
1650 SyncAPINameToServerName(raw_title2, &title2);
1651 std::string url2 = "http://www.bla.com";
1653 // Create a bookmark using the legacy format.
1654 int64 node_id1 =
1655 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag");
1656 int64 node_id2 =
1657 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag2");
1659 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1660 WriteNode node(&trans);
1661 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1663 sync_pb::EntitySpecifics entity_specifics;
1664 entity_specifics.mutable_bookmark()->set_url(url);
1665 node.SetEntitySpecifics(entity_specifics);
1667 // Set the old style title.
1668 syncable::MutableEntry* node_entry = node.entry_;
1669 node_entry->PutNonUniqueName(title);
1671 WriteNode node2(&trans);
1672 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1674 sync_pb::EntitySpecifics entity_specifics2;
1675 entity_specifics2.mutable_bookmark()->set_url(url2);
1676 node2.SetEntitySpecifics(entity_specifics2);
1678 // Set the old style title.
1679 syncable::MutableEntry* node_entry2 = node2.entry_;
1680 node_entry2->PutNonUniqueName(title2);
1684 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1685 ReadNode node(&trans);
1686 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1687 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1688 EXPECT_EQ(title, node.GetTitle());
1689 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1690 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1692 ReadNode node2(&trans);
1693 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1694 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1695 // We should de-canonicalize the title in GetTitle(), but the title in the
1696 // specifics should be stored in the server legal form.
1697 EXPECT_EQ(raw_title2, node2.GetTitle());
1698 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1699 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1703 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1704 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1705 trans.GetWrappedTrans(),
1706 BOOKMARKS,
1707 false /* not encrypted */));
1710 EXPECT_CALL(encryption_observer_,
1711 OnEncryptedTypesChanged(
1712 HasModelTypes(EncryptableUserTypes()), true));
1713 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1714 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1715 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1718 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1719 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1720 EncryptableUserTypes()));
1721 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1722 trans.GetWrappedTrans(),
1723 BOOKMARKS,
1724 true /* is encrypted */));
1726 ReadNode node(&trans);
1727 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1728 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1729 EXPECT_EQ(title, node.GetTitle());
1730 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1731 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1733 ReadNode node2(&trans);
1734 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1735 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1736 // We should de-canonicalize the title in GetTitle(), but the title in the
1737 // specifics should be stored in the server legal form.
1738 EXPECT_EQ(raw_title2, node2.GetTitle());
1739 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1740 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1744 // Create a bookmark and set the title/url, then verify the data was properly
1745 // set. This replicates the unique way bookmarks have of creating sync nodes.
1746 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1747 TEST_F(SyncManagerTest, CreateLocalBookmark) {
1748 std::string title = "title";
1749 std::string url = "url";
1751 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1752 ReadNode bookmark_root(&trans);
1753 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1754 WriteNode node(&trans);
1755 ASSERT_TRUE(node.InitBookmarkByCreation(bookmark_root, NULL));
1756 node.SetIsFolder(false);
1757 node.SetTitle(title);
1759 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
1760 bookmark_specifics.set_url(url);
1761 node.SetBookmarkSpecifics(bookmark_specifics);
1764 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1765 ReadNode bookmark_root(&trans);
1766 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1767 int64 child_id = bookmark_root.GetFirstChildId();
1769 ReadNode node(&trans);
1770 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
1771 EXPECT_FALSE(node.GetIsFolder());
1772 EXPECT_EQ(title, node.GetTitle());
1773 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1777 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1778 // changes.
1779 TEST_F(SyncManagerTest, UpdateEntryWithEncryption) {
1780 std::string client_tag = "title";
1781 sync_pb::EntitySpecifics entity_specifics;
1782 entity_specifics.mutable_bookmark()->set_url("url");
1783 entity_specifics.mutable_bookmark()->set_title("title");
1784 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
1785 syncable::GenerateSyncableHash(BOOKMARKS,
1786 client_tag),
1787 entity_specifics);
1788 // New node shouldn't start off unsynced.
1789 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1790 // Manually change to the same data. Should not set is_unsynced.
1792 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1793 WriteNode node(&trans);
1794 EXPECT_EQ(BaseNode::INIT_OK,
1795 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1796 node.SetEntitySpecifics(entity_specifics);
1798 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1800 // Encrypt the datatatype, should set is_unsynced.
1801 EXPECT_CALL(encryption_observer_,
1802 OnEncryptedTypesChanged(
1803 HasModelTypes(EncryptableUserTypes()), true));
1804 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1805 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
1807 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1808 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1809 sync_manager_.GetEncryptionHandler()->Init();
1810 PumpLoop();
1812 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1813 ReadNode node(&trans);
1814 EXPECT_EQ(BaseNode::INIT_OK,
1815 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1816 const syncable::Entry* node_entry = node.GetEntry();
1817 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1818 EXPECT_TRUE(specifics.has_encrypted());
1819 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1820 Cryptographer* cryptographer = trans.GetCryptographer();
1821 EXPECT_TRUE(cryptographer->is_ready());
1822 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1823 specifics.encrypted()));
1825 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1827 // Set a new passphrase. Should set is_unsynced.
1828 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1829 EXPECT_CALL(encryption_observer_,
1830 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1831 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1832 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1833 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1834 EXPECT_CALL(encryption_observer_,
1835 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1836 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1837 "new_passphrase",
1838 true);
1840 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1841 ReadNode node(&trans);
1842 EXPECT_EQ(BaseNode::INIT_OK,
1843 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1844 const syncable::Entry* node_entry = node.GetEntry();
1845 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1846 EXPECT_TRUE(specifics.has_encrypted());
1847 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1848 Cryptographer* cryptographer = trans.GetCryptographer();
1849 EXPECT_TRUE(cryptographer->is_ready());
1850 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1851 specifics.encrypted()));
1853 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1855 // Force a re-encrypt everything. Should not set is_unsynced.
1856 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1857 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1858 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1859 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1861 sync_manager_.GetEncryptionHandler()->Init();
1862 PumpLoop();
1865 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1866 ReadNode node(&trans);
1867 EXPECT_EQ(BaseNode::INIT_OK,
1868 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1869 const syncable::Entry* node_entry = node.GetEntry();
1870 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1871 EXPECT_TRUE(specifics.has_encrypted());
1872 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1873 Cryptographer* cryptographer = trans.GetCryptographer();
1874 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1875 specifics.encrypted()));
1877 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1879 // Manually change to the same data. Should not set is_unsynced.
1881 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1882 WriteNode node(&trans);
1883 EXPECT_EQ(BaseNode::INIT_OK,
1884 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1885 node.SetEntitySpecifics(entity_specifics);
1886 const syncable::Entry* node_entry = node.GetEntry();
1887 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1888 EXPECT_TRUE(specifics.has_encrypted());
1889 EXPECT_FALSE(node_entry->GetIsUnsynced());
1890 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1891 Cryptographer* cryptographer = trans.GetCryptographer();
1892 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1893 specifics.encrypted()));
1895 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1897 // Manually change to different data. Should set is_unsynced.
1899 entity_specifics.mutable_bookmark()->set_url("url2");
1900 entity_specifics.mutable_bookmark()->set_title("title2");
1901 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1902 WriteNode node(&trans);
1903 EXPECT_EQ(BaseNode::INIT_OK,
1904 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1905 node.SetEntitySpecifics(entity_specifics);
1906 const syncable::Entry* node_entry = node.GetEntry();
1907 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1908 EXPECT_TRUE(specifics.has_encrypted());
1909 EXPECT_TRUE(node_entry->GetIsUnsynced());
1910 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1911 Cryptographer* cryptographer = trans.GetCryptographer();
1912 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1913 specifics.encrypted()));
1917 // Passwords have their own handling for encryption. Verify it does not result
1918 // in unnecessary writes via SetEntitySpecifics.
1919 TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) {
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 SetEntitySpecifics. 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.SetEntitySpecifics(entity_specifics);
1949 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1952 // Passwords have their own handling for encryption. Verify it does not result
1953 // in unnecessary writes via SetPasswordSpecifics.
1954 TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) {
1955 std::string client_tag = "title";
1956 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1957 sync_pb::EntitySpecifics entity_specifics;
1959 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1960 Cryptographer* cryptographer = trans.GetCryptographer();
1961 sync_pb::PasswordSpecificsData data;
1962 data.set_password_value("secret");
1963 cryptographer->Encrypt(
1964 data,
1965 entity_specifics.mutable_password()->
1966 mutable_encrypted());
1968 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1969 syncable::GenerateSyncableHash(PASSWORDS,
1970 client_tag),
1971 entity_specifics);
1972 // New node shouldn't start off unsynced.
1973 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1975 // Manually change to the same data via SetPasswordSpecifics. Should not set
1976 // is_unsynced.
1978 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1979 WriteNode node(&trans);
1980 EXPECT_EQ(BaseNode::INIT_OK,
1981 node.InitByClientTagLookup(PASSWORDS, client_tag));
1982 node.SetPasswordSpecifics(node.GetPasswordSpecifics());
1984 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1986 // Manually change to different data. Should set is_unsynced.
1988 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1989 WriteNode node(&trans);
1990 EXPECT_EQ(BaseNode::INIT_OK,
1991 node.InitByClientTagLookup(PASSWORDS, client_tag));
1992 Cryptographer* cryptographer = trans.GetCryptographer();
1993 sync_pb::PasswordSpecificsData data;
1994 data.set_password_value("secret2");
1995 cryptographer->Encrypt(
1996 data,
1997 entity_specifics.mutable_password()->mutable_encrypted());
1998 node.SetPasswordSpecifics(data);
1999 const syncable::Entry* node_entry = node.GetEntry();
2000 EXPECT_TRUE(node_entry->GetIsUnsynced());
2004 // Passwords have their own handling for encryption. Verify setting a new
2005 // passphrase updates the data.
2006 TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) {
2007 std::string client_tag = "title";
2008 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2009 sync_pb::EntitySpecifics entity_specifics;
2011 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2012 Cryptographer* cryptographer = trans.GetCryptographer();
2013 sync_pb::PasswordSpecificsData data;
2014 data.set_password_value("secret");
2015 cryptographer->Encrypt(
2016 data,
2017 entity_specifics.mutable_password()->mutable_encrypted());
2019 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2020 syncable::GenerateSyncableHash(PASSWORDS,
2021 client_tag),
2022 entity_specifics);
2023 // New node shouldn't start off unsynced.
2024 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2026 // Set a new passphrase. Should set is_unsynced.
2027 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2028 EXPECT_CALL(encryption_observer_,
2029 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
2030 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
2031 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2032 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2033 EXPECT_CALL(encryption_observer_,
2034 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
2035 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
2036 "new_passphrase",
2037 true);
2038 EXPECT_EQ(CUSTOM_PASSPHRASE,
2039 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
2040 EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2043 // Passwords have their own handling for encryption. Verify it does not result
2044 // in unnecessary writes via ReencryptEverything.
2045 TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) {
2046 std::string client_tag = "title";
2047 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2048 sync_pb::EntitySpecifics entity_specifics;
2050 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2051 Cryptographer* cryptographer = trans.GetCryptographer();
2052 sync_pb::PasswordSpecificsData data;
2053 data.set_password_value("secret");
2054 cryptographer->Encrypt(
2055 data,
2056 entity_specifics.mutable_password()->mutable_encrypted());
2058 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2059 syncable::GenerateSyncableHash(PASSWORDS,
2060 client_tag),
2061 entity_specifics);
2062 // New node shouldn't start off unsynced.
2063 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2065 // Force a re-encrypt everything. Should not set is_unsynced.
2066 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2067 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2068 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2069 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
2070 sync_manager_.GetEncryptionHandler()->Init();
2071 PumpLoop();
2072 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2075 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2076 // when we write the same data, but does set it when we write new data.
2077 TEST_F(SyncManagerTest, SetBookmarkTitle) {
2078 std::string client_tag = "title";
2079 sync_pb::EntitySpecifics entity_specifics;
2080 entity_specifics.mutable_bookmark()->set_url("url");
2081 entity_specifics.mutable_bookmark()->set_title("title");
2082 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2083 syncable::GenerateSyncableHash(BOOKMARKS,
2084 client_tag),
2085 entity_specifics);
2086 // New node shouldn't start off unsynced.
2087 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2089 // Manually change to the same title. Should not set is_unsynced.
2091 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2092 WriteNode node(&trans);
2093 EXPECT_EQ(BaseNode::INIT_OK,
2094 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2095 node.SetTitle(client_tag);
2097 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2099 // Manually change to new title. Should set is_unsynced.
2101 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2102 WriteNode node(&trans);
2103 EXPECT_EQ(BaseNode::INIT_OK,
2104 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2105 node.SetTitle("title2");
2107 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2110 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2111 // bookmarks when we write the same data, but does set it when we write new
2112 // data.
2113 TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) {
2114 std::string client_tag = "title";
2115 sync_pb::EntitySpecifics entity_specifics;
2116 entity_specifics.mutable_bookmark()->set_url("url");
2117 entity_specifics.mutable_bookmark()->set_title("title");
2118 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2119 syncable::GenerateSyncableHash(BOOKMARKS,
2120 client_tag),
2121 entity_specifics);
2122 // New node shouldn't start off unsynced.
2123 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2125 // Encrypt the datatatype, should set is_unsynced.
2126 EXPECT_CALL(encryption_observer_,
2127 OnEncryptedTypesChanged(
2128 HasModelTypes(EncryptableUserTypes()), true));
2129 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2130 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2131 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2132 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2133 sync_manager_.GetEncryptionHandler()->Init();
2134 PumpLoop();
2135 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2137 // Manually change to the same title. Should not set is_unsynced.
2138 // NON_UNIQUE_NAME should be kEncryptedString.
2140 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2141 WriteNode node(&trans);
2142 EXPECT_EQ(BaseNode::INIT_OK,
2143 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2144 node.SetTitle(client_tag);
2145 const syncable::Entry* node_entry = node.GetEntry();
2146 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2147 EXPECT_TRUE(specifics.has_encrypted());
2148 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2150 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2152 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2153 // should still be kEncryptedString.
2155 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2156 WriteNode node(&trans);
2157 EXPECT_EQ(BaseNode::INIT_OK,
2158 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2159 node.SetTitle("title2");
2160 const syncable::Entry* node_entry = node.GetEntry();
2161 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2162 EXPECT_TRUE(specifics.has_encrypted());
2163 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2165 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2168 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2169 // when we write the same data, but does set it when we write new data.
2170 TEST_F(SyncManagerTest, SetNonBookmarkTitle) {
2171 std::string client_tag = "title";
2172 sync_pb::EntitySpecifics entity_specifics;
2173 entity_specifics.mutable_preference()->set_name("name");
2174 entity_specifics.mutable_preference()->set_value("value");
2175 MakeServerNode(sync_manager_.GetUserShare(),
2176 PREFERENCES,
2177 client_tag,
2178 syncable::GenerateSyncableHash(PREFERENCES,
2179 client_tag),
2180 entity_specifics);
2181 // New node shouldn't start off unsynced.
2182 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2184 // Manually change to the same title. Should not set is_unsynced.
2186 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2187 WriteNode node(&trans);
2188 EXPECT_EQ(BaseNode::INIT_OK,
2189 node.InitByClientTagLookup(PREFERENCES, client_tag));
2190 node.SetTitle(client_tag);
2192 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2194 // Manually change to new title. Should set is_unsynced.
2196 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2197 WriteNode node(&trans);
2198 EXPECT_EQ(BaseNode::INIT_OK,
2199 node.InitByClientTagLookup(PREFERENCES, client_tag));
2200 node.SetTitle("title2");
2202 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2205 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2206 // non-bookmarks when we write the same data or when we write new data
2207 // data (should remained kEncryptedString).
2208 TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) {
2209 std::string client_tag = "title";
2210 sync_pb::EntitySpecifics entity_specifics;
2211 entity_specifics.mutable_preference()->set_name("name");
2212 entity_specifics.mutable_preference()->set_value("value");
2213 MakeServerNode(sync_manager_.GetUserShare(),
2214 PREFERENCES,
2215 client_tag,
2216 syncable::GenerateSyncableHash(PREFERENCES,
2217 client_tag),
2218 entity_specifics);
2219 // New node shouldn't start off unsynced.
2220 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2222 // Encrypt the datatatype, should set is_unsynced.
2223 EXPECT_CALL(encryption_observer_,
2224 OnEncryptedTypesChanged(
2225 HasModelTypes(EncryptableUserTypes()), true));
2226 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2227 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2228 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2229 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2230 sync_manager_.GetEncryptionHandler()->Init();
2231 PumpLoop();
2232 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2234 // Manually change to the same title. Should not set is_unsynced.
2235 // NON_UNIQUE_NAME should be kEncryptedString.
2237 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2238 WriteNode node(&trans);
2239 EXPECT_EQ(BaseNode::INIT_OK,
2240 node.InitByClientTagLookup(PREFERENCES, client_tag));
2241 node.SetTitle(client_tag);
2242 const syncable::Entry* node_entry = node.GetEntry();
2243 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2244 EXPECT_TRUE(specifics.has_encrypted());
2245 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2247 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2249 // Manually change to new title. Should not set is_unsynced because the
2250 // NON_UNIQUE_NAME should still be kEncryptedString.
2252 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2253 WriteNode node(&trans);
2254 EXPECT_EQ(BaseNode::INIT_OK,
2255 node.InitByClientTagLookup(PREFERENCES, client_tag));
2256 node.SetTitle("title2");
2257 const syncable::Entry* node_entry = node.GetEntry();
2258 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2259 EXPECT_TRUE(specifics.has_encrypted());
2260 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2261 EXPECT_FALSE(node_entry->GetIsUnsynced());
2265 // Ensure that titles are truncated to 255 bytes, and attempting to reset
2266 // them to their longer version does not set IS_UNSYNCED.
2267 TEST_F(SyncManagerTest, SetLongTitle) {
2268 const int kNumChars = 512;
2269 const std::string kClientTag = "tag";
2270 std::string title(kNumChars, '0');
2271 sync_pb::EntitySpecifics entity_specifics;
2272 entity_specifics.mutable_preference()->set_name("name");
2273 entity_specifics.mutable_preference()->set_value("value");
2274 MakeServerNode(sync_manager_.GetUserShare(),
2275 PREFERENCES,
2276 "short_title",
2277 syncable::GenerateSyncableHash(PREFERENCES,
2278 kClientTag),
2279 entity_specifics);
2280 // New node shouldn't start off unsynced.
2281 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2283 // Manually change to the long title. Should set is_unsynced.
2285 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2286 WriteNode node(&trans);
2287 EXPECT_EQ(BaseNode::INIT_OK,
2288 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2289 node.SetTitle(title);
2290 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2292 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2294 // Manually change to the same title. Should not set is_unsynced.
2296 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2297 WriteNode node(&trans);
2298 EXPECT_EQ(BaseNode::INIT_OK,
2299 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2300 node.SetTitle(title);
2301 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2303 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2305 // Manually change to new title. Should set is_unsynced.
2307 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2308 WriteNode node(&trans);
2309 EXPECT_EQ(BaseNode::INIT_OK,
2310 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2311 node.SetTitle("title2");
2313 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2316 // Create an encrypted entry when the cryptographer doesn't think the type is
2317 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2318 // the data.
2319 TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) {
2320 std::string client_tag = "tag";
2321 std::string url = "url";
2322 std::string url2 = "new_url";
2323 std::string title = "title";
2324 sync_pb::EntitySpecifics entity_specifics;
2325 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2327 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2328 Cryptographer* crypto = trans.GetCryptographer();
2329 sync_pb::EntitySpecifics bm_specifics;
2330 bm_specifics.mutable_bookmark()->set_title("title");
2331 bm_specifics.mutable_bookmark()->set_url("url");
2332 sync_pb::EncryptedData encrypted;
2333 crypto->Encrypt(bm_specifics, &encrypted);
2334 entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
2335 AddDefaultFieldValue(BOOKMARKS, &entity_specifics);
2337 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2338 syncable::GenerateSyncableHash(BOOKMARKS,
2339 client_tag),
2340 entity_specifics);
2343 // Verify the data.
2344 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2345 ReadNode node(&trans);
2346 EXPECT_EQ(BaseNode::INIT_OK,
2347 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2348 EXPECT_EQ(title, node.GetTitle());
2349 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
2353 // Overwrite the url (which overwrites the specifics).
2354 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2355 WriteNode node(&trans);
2356 EXPECT_EQ(BaseNode::INIT_OK,
2357 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2359 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
2360 bookmark_specifics.set_url(url2);
2361 node.SetBookmarkSpecifics(bookmark_specifics);
2365 // Verify it's still encrypted and it has the most recent url.
2366 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2367 ReadNode node(&trans);
2368 EXPECT_EQ(BaseNode::INIT_OK,
2369 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2370 EXPECT_EQ(title, node.GetTitle());
2371 EXPECT_EQ(url2, node.GetBookmarkSpecifics().url());
2372 const syncable::Entry* node_entry = node.GetEntry();
2373 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2374 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2375 EXPECT_TRUE(specifics.has_encrypted());
2379 // Verify transaction version of a model type is incremented when node of
2380 // that type is updated.
2381 TEST_F(SyncManagerTest, IncrementTransactionVersion) {
2382 ModelSafeRoutingInfo routing_info;
2383 GetModelSafeRoutingInfo(&routing_info);
2386 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2387 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2388 i != routing_info.end(); ++i) {
2389 // Transaction version is incremented when SyncManagerTest::SetUp()
2390 // creates a node of each type.
2391 EXPECT_EQ(1,
2392 sync_manager_.GetUserShare()->directory->
2393 GetTransactionVersion(i->first));
2397 // Create bookmark node to increment transaction version of bookmark model.
2398 std::string client_tag = "title";
2399 sync_pb::EntitySpecifics entity_specifics;
2400 entity_specifics.mutable_bookmark()->set_url("url");
2401 entity_specifics.mutable_bookmark()->set_title("title");
2402 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2403 syncable::GenerateSyncableHash(BOOKMARKS,
2404 client_tag),
2405 entity_specifics);
2408 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2409 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2410 i != routing_info.end(); ++i) {
2411 EXPECT_EQ(i->first == BOOKMARKS ? 2 : 1,
2412 sync_manager_.GetUserShare()->directory->
2413 GetTransactionVersion(i->first));
2418 class MockSyncScheduler : public FakeSyncScheduler {
2419 public:
2420 MockSyncScheduler() : FakeSyncScheduler() {}
2421 virtual ~MockSyncScheduler() {}
2423 MOCK_METHOD1(Start, void(SyncScheduler::Mode));
2424 MOCK_METHOD1(ScheduleConfiguration, void(const ConfigurationParams&));
2427 class ComponentsFactory : public TestInternalComponentsFactory {
2428 public:
2429 ComponentsFactory(const Switches& switches,
2430 SyncScheduler* scheduler_to_use,
2431 sessions::SyncSessionContext** session_context,
2432 InternalComponentsFactory::StorageOption* storage_used)
2433 : TestInternalComponentsFactory(
2434 switches, InternalComponentsFactory::STORAGE_IN_MEMORY, storage_used),
2435 scheduler_to_use_(scheduler_to_use),
2436 session_context_(session_context) {}
2437 ~ComponentsFactory() override {}
2439 scoped_ptr<SyncScheduler> BuildScheduler(
2440 const std::string& name,
2441 sessions::SyncSessionContext* context,
2442 CancelationSignal* stop_handle) override {
2443 *session_context_ = context;
2444 return scheduler_to_use_.Pass();
2447 private:
2448 scoped_ptr<SyncScheduler> scheduler_to_use_;
2449 sessions::SyncSessionContext** session_context_;
2452 class SyncManagerTestWithMockScheduler : public SyncManagerTest {
2453 public:
2454 SyncManagerTestWithMockScheduler() : scheduler_(NULL) {}
2455 InternalComponentsFactory* GetFactory() override {
2456 scheduler_ = new MockSyncScheduler();
2457 return new ComponentsFactory(GetSwitches(), scheduler_, &session_context_,
2458 &storage_used_);
2461 MockSyncScheduler* scheduler() { return scheduler_; }
2462 sessions::SyncSessionContext* session_context() {
2463 return session_context_;
2466 private:
2467 MockSyncScheduler* scheduler_;
2468 sessions::SyncSessionContext* session_context_;
2471 // Test that the configuration params are properly created and sent to
2472 // ScheduleConfigure. No callback should be invoked. Any disabled datatypes
2473 // should be purged.
2474 TEST_F(SyncManagerTestWithMockScheduler, BasicConfiguration) {
2475 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2476 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2477 ModelSafeRoutingInfo new_routing_info;
2478 GetModelSafeRoutingInfo(&new_routing_info);
2479 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2480 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2482 ConfigurationParams params;
2483 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE));
2484 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2485 WillOnce(SaveArg<0>(&params));
2487 // Set data for all types.
2488 ModelTypeSet protocol_types = ProtocolTypes();
2489 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2490 iter.Inc()) {
2491 SetProgressMarkerForType(iter.Get(), true);
2494 CallbackCounter ready_task_counter, retry_task_counter;
2495 sync_manager_.ConfigureSyncer(
2496 reason,
2497 types_to_download,
2498 disabled_types,
2499 ModelTypeSet(),
2500 ModelTypeSet(),
2501 new_routing_info,
2502 base::Bind(&CallbackCounter::Callback,
2503 base::Unretained(&ready_task_counter)),
2504 base::Bind(&CallbackCounter::Callback,
2505 base::Unretained(&retry_task_counter)));
2506 EXPECT_EQ(0, ready_task_counter.times_called());
2507 EXPECT_EQ(0, retry_task_counter.times_called());
2508 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2509 params.source);
2510 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2511 EXPECT_EQ(new_routing_info, params.routing_info);
2513 // Verify all the disabled types were purged.
2514 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().Equals(
2515 enabled_types));
2516 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2517 ModelTypeSet::All()).Equals(disabled_types));
2520 // Test that on a reconfiguration (configuration where the session context
2521 // already has routing info), only those recently disabled types are purged.
2522 TEST_F(SyncManagerTestWithMockScheduler, ReConfiguration) {
2523 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2524 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2525 ModelTypeSet disabled_types = ModelTypeSet(THEMES, SESSIONS);
2526 ModelSafeRoutingInfo old_routing_info;
2527 ModelSafeRoutingInfo new_routing_info;
2528 GetModelSafeRoutingInfo(&old_routing_info);
2529 new_routing_info = old_routing_info;
2530 new_routing_info.erase(THEMES);
2531 new_routing_info.erase(SESSIONS);
2532 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2534 ConfigurationParams params;
2535 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE));
2536 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2537 WillOnce(SaveArg<0>(&params));
2539 // Set data for all types except those recently disabled (so we can verify
2540 // only those recently disabled are purged) .
2541 ModelTypeSet protocol_types = ProtocolTypes();
2542 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2543 iter.Inc()) {
2544 if (!disabled_types.Has(iter.Get())) {
2545 SetProgressMarkerForType(iter.Get(), true);
2546 } else {
2547 SetProgressMarkerForType(iter.Get(), false);
2551 // Set the context to have the old routing info.
2552 session_context()->SetRoutingInfo(old_routing_info);
2554 CallbackCounter ready_task_counter, retry_task_counter;
2555 sync_manager_.ConfigureSyncer(
2556 reason,
2557 types_to_download,
2558 ModelTypeSet(),
2559 ModelTypeSet(),
2560 ModelTypeSet(),
2561 new_routing_info,
2562 base::Bind(&CallbackCounter::Callback,
2563 base::Unretained(&ready_task_counter)),
2564 base::Bind(&CallbackCounter::Callback,
2565 base::Unretained(&retry_task_counter)));
2566 EXPECT_EQ(0, ready_task_counter.times_called());
2567 EXPECT_EQ(0, retry_task_counter.times_called());
2568 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2569 params.source);
2570 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2571 EXPECT_EQ(new_routing_info, params.routing_info);
2573 // Verify only the recently disabled types were purged.
2574 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2575 ProtocolTypes()).Equals(disabled_types));
2578 // Test that PurgePartiallySyncedTypes purges only those types that have not
2579 // fully completed their initial download and apply.
2580 TEST_F(SyncManagerTest, PurgePartiallySyncedTypes) {
2581 ModelSafeRoutingInfo routing_info;
2582 GetModelSafeRoutingInfo(&routing_info);
2583 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2585 UserShare* share = sync_manager_.GetUserShare();
2587 // The test harness automatically initializes all types in the routing info.
2588 // Check that autofill is not among them.
2589 ASSERT_FALSE(enabled_types.Has(AUTOFILL));
2591 // Further ensure that the test harness did not create its root node.
2593 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2594 syncable::Entry autofill_root_node(&trans,
2595 syncable::GET_TYPE_ROOT,
2596 AUTOFILL);
2597 ASSERT_FALSE(autofill_root_node.good());
2600 // One more redundant check.
2601 ASSERT_FALSE(sync_manager_.InitialSyncEndedTypes().Has(AUTOFILL));
2603 // Give autofill a progress marker.
2604 sync_pb::DataTypeProgressMarker autofill_marker;
2605 autofill_marker.set_data_type_id(
2606 GetSpecificsFieldNumberFromModelType(AUTOFILL));
2607 autofill_marker.set_token("token");
2608 share->directory->SetDownloadProgress(AUTOFILL, autofill_marker);
2610 // Also add a pending autofill root node update from the server.
2611 TestEntryFactory factory_(share->directory.get());
2612 int autofill_meta = factory_.CreateUnappliedRootNode(AUTOFILL);
2614 // Preferences is an enabled type. Check that the harness initialized it.
2615 ASSERT_TRUE(enabled_types.Has(PREFERENCES));
2616 ASSERT_TRUE(sync_manager_.InitialSyncEndedTypes().Has(PREFERENCES));
2618 // Give preferencse a progress marker.
2619 sync_pb::DataTypeProgressMarker prefs_marker;
2620 prefs_marker.set_data_type_id(
2621 GetSpecificsFieldNumberFromModelType(PREFERENCES));
2622 prefs_marker.set_token("token");
2623 share->directory->SetDownloadProgress(PREFERENCES, prefs_marker);
2625 // Add a fully synced preferences node under the root.
2626 std::string pref_client_tag = "prefABC";
2627 std::string pref_hashed_tag = "hashXYZ";
2628 sync_pb::EntitySpecifics pref_specifics;
2629 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2630 int pref_meta = MakeServerNode(
2631 share, PREFERENCES, pref_client_tag, pref_hashed_tag, pref_specifics);
2633 // And now, the purge.
2634 EXPECT_TRUE(sync_manager_.PurgePartiallySyncedTypes());
2636 // Ensure that autofill lost its progress marker, but preferences did not.
2637 ModelTypeSet empty_tokens =
2638 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
2639 EXPECT_TRUE(empty_tokens.Has(AUTOFILL));
2640 EXPECT_FALSE(empty_tokens.Has(PREFERENCES));
2642 // Ensure that autofill lots its node, but preferences did not.
2644 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2645 syncable::Entry autofill_node(&trans, GET_BY_HANDLE, autofill_meta);
2646 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref_meta);
2647 EXPECT_FALSE(autofill_node.good());
2648 EXPECT_TRUE(pref_node.good());
2652 // Test CleanupDisabledTypes properly purges all disabled types as specified
2653 // by the previous and current enabled params.
2654 TEST_F(SyncManagerTest, PurgeDisabledTypes) {
2655 ModelSafeRoutingInfo routing_info;
2656 GetModelSafeRoutingInfo(&routing_info);
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 // Verify all the enabled types remain after cleanup, and all the disabled
2671 // types were purged.
2672 sync_manager_.PurgeDisabledTypes(disabled_types,
2673 ModelTypeSet(),
2674 ModelTypeSet());
2675 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2676 EXPECT_TRUE(disabled_types.Equals(
2677 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2679 // Disable some more types.
2680 disabled_types.Put(BOOKMARKS);
2681 disabled_types.Put(PREFERENCES);
2682 ModelTypeSet new_enabled_types =
2683 Difference(ModelTypeSet::All(), disabled_types);
2685 // Verify only the non-disabled types remain after cleanup.
2686 sync_manager_.PurgeDisabledTypes(disabled_types,
2687 ModelTypeSet(),
2688 ModelTypeSet());
2689 EXPECT_TRUE(new_enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2690 EXPECT_TRUE(disabled_types.Equals(
2691 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2694 // Test PurgeDisabledTypes properly unapplies types by deleting their local data
2695 // and preserving their server data and progress marker.
2696 TEST_F(SyncManagerTest, PurgeUnappliedTypes) {
2697 ModelSafeRoutingInfo routing_info;
2698 GetModelSafeRoutingInfo(&routing_info);
2699 ModelTypeSet unapplied_types = ModelTypeSet(BOOKMARKS, PREFERENCES);
2700 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2701 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2703 // The harness should have initialized the enabled_types for us.
2704 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2706 // Set progress markers for all types.
2707 ModelTypeSet protocol_types = ProtocolTypes();
2708 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2709 iter.Inc()) {
2710 SetProgressMarkerForType(iter.Get(), true);
2713 // Add the following kinds of items:
2714 // 1. Fully synced preference.
2715 // 2. Locally created preference, server unknown, unsynced
2716 // 3. Locally deleted preference, server known, unsynced
2717 // 4. Server deleted preference, locally known.
2718 // 5. Server created preference, locally unknown, unapplied.
2719 // 6. A fully synced bookmark (no unique_client_tag).
2720 UserShare* share = sync_manager_.GetUserShare();
2721 sync_pb::EntitySpecifics pref_specifics;
2722 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2723 sync_pb::EntitySpecifics bm_specifics;
2724 AddDefaultFieldValue(BOOKMARKS, &bm_specifics);
2725 int pref1_meta = MakeServerNode(
2726 share, PREFERENCES, "pref1", "hash1", pref_specifics);
2727 int64 pref2_meta = MakeNodeWithRoot(share, PREFERENCES, "pref2");
2728 int pref3_meta = MakeServerNode(
2729 share, PREFERENCES, "pref3", "hash3", pref_specifics);
2730 int pref4_meta = MakeServerNode(
2731 share, PREFERENCES, "pref4", "hash4", pref_specifics);
2732 int pref5_meta = MakeServerNode(
2733 share, PREFERENCES, "pref5", "hash5", pref_specifics);
2734 int bookmark_meta = MakeServerNode(
2735 share, BOOKMARKS, "bookmark", "", bm_specifics);
2738 syncable::WriteTransaction trans(FROM_HERE,
2739 syncable::SYNCER,
2740 share->directory.get());
2741 // Pref's 1 and 2 are already set up properly.
2742 // Locally delete pref 3.
2743 syncable::MutableEntry pref3(&trans, GET_BY_HANDLE, pref3_meta);
2744 pref3.PutIsDel(true);
2745 pref3.PutIsUnsynced(true);
2746 // Delete pref 4 at the server.
2747 syncable::MutableEntry pref4(&trans, GET_BY_HANDLE, pref4_meta);
2748 pref4.PutServerIsDel(true);
2749 pref4.PutIsUnappliedUpdate(true);
2750 pref4.PutServerVersion(2);
2751 // Pref 5 is an new unapplied update.
2752 syncable::MutableEntry pref5(&trans, GET_BY_HANDLE, pref5_meta);
2753 pref5.PutIsUnappliedUpdate(true);
2754 pref5.PutIsDel(true);
2755 pref5.PutBaseVersion(-1);
2756 // Bookmark is already set up properly
2759 // Take a snapshot to clear all the dirty bits.
2760 share->directory.get()->SaveChanges();
2762 // Now request a purge for the unapplied types.
2763 disabled_types.PutAll(unapplied_types);
2764 sync_manager_.PurgeDisabledTypes(disabled_types,
2765 ModelTypeSet(),
2766 unapplied_types);
2768 // Verify the unapplied types still have progress markers and initial sync
2769 // ended after cleanup.
2770 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().HasAll(unapplied_types));
2771 EXPECT_TRUE(
2772 sync_manager_.GetTypesWithEmptyProgressMarkerToken(unapplied_types).
2773 Empty());
2775 // Ensure the items were unapplied as necessary.
2777 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2778 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref1_meta);
2779 ASSERT_TRUE(pref_node.good());
2780 EXPECT_TRUE(pref_node.GetKernelCopy().is_dirty());
2781 EXPECT_FALSE(pref_node.GetIsUnsynced());
2782 EXPECT_TRUE(pref_node.GetIsUnappliedUpdate());
2783 EXPECT_TRUE(pref_node.GetIsDel());
2784 EXPECT_GT(pref_node.GetServerVersion(), 0);
2785 EXPECT_EQ(pref_node.GetBaseVersion(), -1);
2787 // Pref 2 should just be locally deleted.
2788 syncable::Entry pref2_node(&trans, GET_BY_HANDLE, pref2_meta);
2789 ASSERT_TRUE(pref2_node.good());
2790 EXPECT_TRUE(pref2_node.GetKernelCopy().is_dirty());
2791 EXPECT_FALSE(pref2_node.GetIsUnsynced());
2792 EXPECT_TRUE(pref2_node.GetIsDel());
2793 EXPECT_FALSE(pref2_node.GetIsUnappliedUpdate());
2794 EXPECT_TRUE(pref2_node.GetIsDel());
2795 EXPECT_EQ(pref2_node.GetServerVersion(), 0);
2796 EXPECT_EQ(pref2_node.GetBaseVersion(), -1);
2798 syncable::Entry pref3_node(&trans, GET_BY_HANDLE, pref3_meta);
2799 ASSERT_TRUE(pref3_node.good());
2800 EXPECT_TRUE(pref3_node.GetKernelCopy().is_dirty());
2801 EXPECT_FALSE(pref3_node.GetIsUnsynced());
2802 EXPECT_TRUE(pref3_node.GetIsUnappliedUpdate());
2803 EXPECT_TRUE(pref3_node.GetIsDel());
2804 EXPECT_GT(pref3_node.GetServerVersion(), 0);
2805 EXPECT_EQ(pref3_node.GetBaseVersion(), -1);
2807 syncable::Entry pref4_node(&trans, GET_BY_HANDLE, pref4_meta);
2808 ASSERT_TRUE(pref4_node.good());
2809 EXPECT_TRUE(pref4_node.GetKernelCopy().is_dirty());
2810 EXPECT_FALSE(pref4_node.GetIsUnsynced());
2811 EXPECT_TRUE(pref4_node.GetIsUnappliedUpdate());
2812 EXPECT_TRUE(pref4_node.GetIsDel());
2813 EXPECT_GT(pref4_node.GetServerVersion(), 0);
2814 EXPECT_EQ(pref4_node.GetBaseVersion(), -1);
2816 // Pref 5 should remain untouched.
2817 syncable::Entry pref5_node(&trans, GET_BY_HANDLE, pref5_meta);
2818 ASSERT_TRUE(pref5_node.good());
2819 EXPECT_FALSE(pref5_node.GetKernelCopy().is_dirty());
2820 EXPECT_FALSE(pref5_node.GetIsUnsynced());
2821 EXPECT_TRUE(pref5_node.GetIsUnappliedUpdate());
2822 EXPECT_TRUE(pref5_node.GetIsDel());
2823 EXPECT_GT(pref5_node.GetServerVersion(), 0);
2824 EXPECT_EQ(pref5_node.GetBaseVersion(), -1);
2826 syncable::Entry bookmark_node(&trans, GET_BY_HANDLE, bookmark_meta);
2827 ASSERT_TRUE(bookmark_node.good());
2828 EXPECT_TRUE(bookmark_node.GetKernelCopy().is_dirty());
2829 EXPECT_FALSE(bookmark_node.GetIsUnsynced());
2830 EXPECT_TRUE(bookmark_node.GetIsUnappliedUpdate());
2831 EXPECT_TRUE(bookmark_node.GetIsDel());
2832 EXPECT_GT(bookmark_node.GetServerVersion(), 0);
2833 EXPECT_EQ(bookmark_node.GetBaseVersion(), -1);
2837 // A test harness to exercise the code that processes and passes changes from
2838 // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
2839 // ChangeProcessor.
2840 class SyncManagerChangeProcessingTest : public SyncManagerTest {
2841 public:
2842 void OnChangesApplied(ModelType model_type,
2843 int64 model_version,
2844 const BaseTransaction* trans,
2845 const ImmutableChangeRecordList& changes) override {
2846 last_changes_ = changes;
2849 void OnChangesComplete(ModelType model_type) override {}
2851 const ImmutableChangeRecordList& GetRecentChangeList() {
2852 return last_changes_;
2855 UserShare* share() {
2856 return sync_manager_.GetUserShare();
2859 // Set some flags so our nodes reasonably approximate the real world scenario
2860 // and can get past CheckTreeInvariants.
2862 // It's never going to be truly accurate, since we're squashing update
2863 // receipt, processing and application into a single transaction.
2864 void SetNodeProperties(syncable::MutableEntry *entry) {
2865 entry->PutId(id_factory_.NewServerId());
2866 entry->PutBaseVersion(10);
2867 entry->PutServerVersion(10);
2870 // Looks for the given change in the list. Returns the index at which it was
2871 // found. Returns -1 on lookup failure.
2872 size_t FindChangeInList(int64 id, ChangeRecord::Action action) {
2873 SCOPED_TRACE(id);
2874 for (size_t i = 0; i < last_changes_.Get().size(); ++i) {
2875 if (last_changes_.Get()[i].id == id
2876 && last_changes_.Get()[i].action == action) {
2877 return i;
2880 ADD_FAILURE() << "Failed to find specified change";
2881 return static_cast<size_t>(-1);
2884 // Returns the current size of the change list.
2886 // Note that spurious changes do not necessarily indicate a problem.
2887 // Assertions on change list size can help detect problems, but it may be
2888 // necessary to reduce their strictness if the implementation changes.
2889 size_t GetChangeListSize() {
2890 return last_changes_.Get().size();
2893 void ClearChangeList() { last_changes_ = ImmutableChangeRecordList(); }
2895 protected:
2896 ImmutableChangeRecordList last_changes_;
2897 TestIdFactory id_factory_;
2900 // Test creation of a folder and a bookmark.
2901 TEST_F(SyncManagerChangeProcessingTest, AddBookmarks) {
2902 int64 type_root = GetIdForDataType(BOOKMARKS);
2903 int64 folder_id = kInvalidId;
2904 int64 child_id = kInvalidId;
2906 // Create a folder and a bookmark under it.
2908 syncable::WriteTransaction trans(
2909 FROM_HERE, syncable::SYNCER, share()->directory.get());
2910 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
2911 ASSERT_TRUE(root.good());
2913 syncable::MutableEntry folder(&trans, syncable::CREATE,
2914 BOOKMARKS, root.GetId(), "folder");
2915 ASSERT_TRUE(folder.good());
2916 SetNodeProperties(&folder);
2917 folder.PutIsDir(true);
2918 folder_id = folder.GetMetahandle();
2920 syncable::MutableEntry child(&trans, syncable::CREATE,
2921 BOOKMARKS, folder.GetId(), "child");
2922 ASSERT_TRUE(child.good());
2923 SetNodeProperties(&child);
2924 child_id = child.GetMetahandle();
2927 // The closing of the above scope will delete the transaction. Its processed
2928 // changes should be waiting for us in a member of the test harness.
2929 EXPECT_EQ(2UL, GetChangeListSize());
2931 // We don't need to check these return values here. The function will add a
2932 // non-fatal failure if these changes are not found.
2933 size_t folder_change_pos =
2934 FindChangeInList(folder_id, ChangeRecord::ACTION_ADD);
2935 size_t child_change_pos =
2936 FindChangeInList(child_id, ChangeRecord::ACTION_ADD);
2938 // Parents are delivered before children.
2939 EXPECT_LT(folder_change_pos, child_change_pos);
2942 // Test moving a bookmark into an empty folder.
2943 TEST_F(SyncManagerChangeProcessingTest, MoveBookmarkIntoEmptyFolder) {
2944 int64 type_root = GetIdForDataType(BOOKMARKS);
2945 int64 folder_b_id = kInvalidId;
2946 int64 child_id = kInvalidId;
2948 // Create two folders. Place a child under folder A.
2950 syncable::WriteTransaction trans(
2951 FROM_HERE, syncable::SYNCER, share()->directory.get());
2952 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
2953 ASSERT_TRUE(root.good());
2955 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
2956 BOOKMARKS, root.GetId(), "folderA");
2957 ASSERT_TRUE(folder_a.good());
2958 SetNodeProperties(&folder_a);
2959 folder_a.PutIsDir(true);
2961 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
2962 BOOKMARKS, root.GetId(), "folderB");
2963 ASSERT_TRUE(folder_b.good());
2964 SetNodeProperties(&folder_b);
2965 folder_b.PutIsDir(true);
2966 folder_b_id = folder_b.GetMetahandle();
2968 syncable::MutableEntry child(&trans, syncable::CREATE,
2969 BOOKMARKS, folder_a.GetId(),
2970 "child");
2971 ASSERT_TRUE(child.good());
2972 SetNodeProperties(&child);
2973 child_id = child.GetMetahandle();
2976 // Close that transaction. The above was to setup the initial scenario. The
2977 // real test starts now.
2979 // Move the child from folder A to folder B.
2981 syncable::WriteTransaction trans(
2982 FROM_HERE, syncable::SYNCER, share()->directory.get());
2984 syncable::Entry folder_b(&trans, syncable::GET_BY_HANDLE, folder_b_id);
2985 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
2987 child.PutParentId(folder_b.GetId());
2990 EXPECT_EQ(1UL, GetChangeListSize());
2992 // Verify that this was detected as a real change. An early version of the
2993 // UniquePosition code had a bug where moves from one folder to another were
2994 // ignored unless the moved node's UniquePosition value was also changed in
2995 // some way.
2996 FindChangeInList(child_id, ChangeRecord::ACTION_UPDATE);
2999 // Test moving a bookmark into a non-empty folder.
3000 TEST_F(SyncManagerChangeProcessingTest, MoveIntoPopulatedFolder) {
3001 int64 type_root = GetIdForDataType(BOOKMARKS);
3002 int64 child_a_id = kInvalidId;
3003 int64 child_b_id = kInvalidId;
3005 // Create two folders. Place one child each under folder A and folder B.
3007 syncable::WriteTransaction trans(
3008 FROM_HERE, syncable::SYNCER, share()->directory.get());
3009 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3010 ASSERT_TRUE(root.good());
3012 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3013 BOOKMARKS, root.GetId(), "folderA");
3014 ASSERT_TRUE(folder_a.good());
3015 SetNodeProperties(&folder_a);
3016 folder_a.PutIsDir(true);
3018 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3019 BOOKMARKS, root.GetId(), "folderB");
3020 ASSERT_TRUE(folder_b.good());
3021 SetNodeProperties(&folder_b);
3022 folder_b.PutIsDir(true);
3024 syncable::MutableEntry child_a(&trans, syncable::CREATE,
3025 BOOKMARKS, folder_a.GetId(),
3026 "childA");
3027 ASSERT_TRUE(child_a.good());
3028 SetNodeProperties(&child_a);
3029 child_a_id = child_a.GetMetahandle();
3031 syncable::MutableEntry child_b(&trans, syncable::CREATE,
3032 BOOKMARKS, folder_b.GetId(),
3033 "childB");
3034 SetNodeProperties(&child_b);
3035 child_b_id = child_b.GetMetahandle();
3038 // Close that transaction. The above was to setup the initial scenario. The
3039 // real test starts now.
3042 syncable::WriteTransaction trans(
3043 FROM_HERE, syncable::SYNCER, share()->directory.get());
3045 syncable::MutableEntry child_a(&trans, syncable::GET_BY_HANDLE, child_a_id);
3046 syncable::MutableEntry child_b(&trans, syncable::GET_BY_HANDLE, child_b_id);
3048 // Move child A from folder A to folder B and update its position.
3049 child_a.PutParentId(child_b.GetParentId());
3050 child_a.PutPredecessor(child_b.GetId());
3053 EXPECT_EQ(1UL, GetChangeListSize());
3055 // Verify that only child a is in the change list.
3056 // (This function will add a failure if the lookup fails.)
3057 FindChangeInList(child_a_id, ChangeRecord::ACTION_UPDATE);
3060 // Tests the ordering of deletion changes.
3061 TEST_F(SyncManagerChangeProcessingTest, DeletionsAndChanges) {
3062 int64 type_root = GetIdForDataType(BOOKMARKS);
3063 int64 folder_a_id = kInvalidId;
3064 int64 folder_b_id = kInvalidId;
3065 int64 child_id = kInvalidId;
3067 // Create two folders. Place a child under folder A.
3069 syncable::WriteTransaction trans(
3070 FROM_HERE, syncable::SYNCER, share()->directory.get());
3071 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3072 ASSERT_TRUE(root.good());
3074 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3075 BOOKMARKS, root.GetId(), "folderA");
3076 ASSERT_TRUE(folder_a.good());
3077 SetNodeProperties(&folder_a);
3078 folder_a.PutIsDir(true);
3079 folder_a_id = folder_a.GetMetahandle();
3081 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3082 BOOKMARKS, root.GetId(), "folderB");
3083 ASSERT_TRUE(folder_b.good());
3084 SetNodeProperties(&folder_b);
3085 folder_b.PutIsDir(true);
3086 folder_b_id = folder_b.GetMetahandle();
3088 syncable::MutableEntry child(&trans, syncable::CREATE,
3089 BOOKMARKS, folder_a.GetId(),
3090 "child");
3091 ASSERT_TRUE(child.good());
3092 SetNodeProperties(&child);
3093 child_id = child.GetMetahandle();
3096 // Close that transaction. The above was to setup the initial scenario. The
3097 // real test starts now.
3100 syncable::WriteTransaction trans(
3101 FROM_HERE, syncable::SYNCER, share()->directory.get());
3103 syncable::MutableEntry folder_a(
3104 &trans, syncable::GET_BY_HANDLE, folder_a_id);
3105 syncable::MutableEntry folder_b(
3106 &trans, syncable::GET_BY_HANDLE, folder_b_id);
3107 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3109 // Delete folder B and its child.
3110 child.PutIsDel(true);
3111 folder_b.PutIsDel(true);
3113 // Make an unrelated change to folder A.
3114 folder_a.PutNonUniqueName("NewNameA");
3117 EXPECT_EQ(3UL, GetChangeListSize());
3119 size_t folder_a_pos =
3120 FindChangeInList(folder_a_id, ChangeRecord::ACTION_UPDATE);
3121 size_t folder_b_pos =
3122 FindChangeInList(folder_b_id, ChangeRecord::ACTION_DELETE);
3123 size_t child_pos = FindChangeInList(child_id, ChangeRecord::ACTION_DELETE);
3125 // Deletes should appear before updates.
3126 EXPECT_LT(child_pos, folder_a_pos);
3127 EXPECT_LT(folder_b_pos, folder_a_pos);
3130 // See that attachment metadata changes are not filtered out by
3131 // SyncManagerImpl::VisiblePropertiesDiffer.
3132 TEST_F(SyncManagerChangeProcessingTest, AttachmentMetadataOnlyChanges) {
3133 // Create an article with no attachments. See that a change is generated.
3134 int64 article_id = kInvalidId;
3136 syncable::WriteTransaction trans(
3137 FROM_HERE, syncable::SYNCER, share()->directory.get());
3138 int64 type_root = GetIdForDataType(ARTICLES);
3139 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3140 ASSERT_TRUE(root.good());
3141 syncable::MutableEntry article(
3142 &trans, syncable::CREATE, ARTICLES, root.GetId(), "article");
3143 ASSERT_TRUE(article.good());
3144 SetNodeProperties(&article);
3145 article_id = article.GetMetahandle();
3147 ASSERT_EQ(1UL, GetChangeListSize());
3148 FindChangeInList(article_id, ChangeRecord::ACTION_ADD);
3149 ClearChangeList();
3151 // Modify the article by adding one attachment. Don't touch anything else.
3152 // See that a change is generated.
3154 syncable::WriteTransaction trans(
3155 FROM_HERE, syncable::SYNCER, share()->directory.get());
3156 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3157 sync_pb::AttachmentMetadata metadata;
3158 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto();
3159 article.PutAttachmentMetadata(metadata);
3161 ASSERT_EQ(1UL, GetChangeListSize());
3162 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3163 ClearChangeList();
3165 // Modify the article by replacing its attachment with a different one. See
3166 // that a change is generated.
3168 syncable::WriteTransaction trans(
3169 FROM_HERE, syncable::SYNCER, share()->directory.get());
3170 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3171 sync_pb::AttachmentMetadata metadata = article.GetAttachmentMetadata();
3172 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto();
3173 article.PutAttachmentMetadata(metadata);
3175 ASSERT_EQ(1UL, GetChangeListSize());
3176 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3177 ClearChangeList();
3179 // Modify the article by replacing its attachment metadata with the same
3180 // attachment metadata. No change should be generated.
3182 syncable::WriteTransaction trans(
3183 FROM_HERE, syncable::SYNCER, share()->directory.get());
3184 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3185 article.PutAttachmentMetadata(article.GetAttachmentMetadata());
3187 ASSERT_EQ(0UL, GetChangeListSize());
3190 // During initialization SyncManagerImpl loads sqlite database. If it fails to
3191 // do so it should fail initialization. This test verifies this behavior.
3192 // Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
3193 // InternalComponentsFactory to return DirectoryBackingStore that always fails
3194 // to load.
3195 class SyncManagerInitInvalidStorageTest : public SyncManagerTest {
3196 public:
3197 SyncManagerInitInvalidStorageTest() {
3200 InternalComponentsFactory* GetFactory() override {
3201 return new TestInternalComponentsFactory(
3202 GetSwitches(), InternalComponentsFactory::STORAGE_INVALID,
3203 &storage_used_);
3207 // SyncManagerInitInvalidStorageTest::GetFactory will return
3208 // DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
3209 // SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
3210 // task is to ensure that SyncManagerImpl reported initialization failure in
3211 // OnInitializationComplete callback.
3212 TEST_F(SyncManagerInitInvalidStorageTest, FailToOpenDatabase) {
3213 EXPECT_FALSE(initialization_succeeded_);
3216 } // namespace syncer