Add ICU message format support
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl_unittest.cc
blobfcd55d344a7a5d7857a789a2476720d46c9858d6
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Unit tests for the SyncApi. Note that a lot of the underlying
6 // functionality is provided by the Syncable layer, which has its own
7 // unit tests. We'll test SyncApi specific things in this harness.
9 #include <cstddef>
10 #include <map>
12 #include "base/basictypes.h"
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/files/scoped_temp_dir.h"
16 #include "base/format_macros.h"
17 #include "base/location.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/run_loop.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/test/values_test_util.h"
24 #include "base/values.h"
25 #include "google_apis/gaia/gaia_constants.h"
26 #include "sync/engine/sync_scheduler.h"
27 #include "sync/internal_api/public/base/attachment_id_proto.h"
28 #include "sync/internal_api/public/base/cancelation_signal.h"
29 #include "sync/internal_api/public/base/model_type_test_util.h"
30 #include "sync/internal_api/public/change_record.h"
31 #include "sync/internal_api/public/engine/model_safe_worker.h"
32 #include "sync/internal_api/public/engine/polling_constants.h"
33 #include "sync/internal_api/public/events/protocol_event.h"
34 #include "sync/internal_api/public/http_post_provider_factory.h"
35 #include "sync/internal_api/public/http_post_provider_interface.h"
36 #include "sync/internal_api/public/read_node.h"
37 #include "sync/internal_api/public/read_transaction.h"
38 #include "sync/internal_api/public/test/test_entry_factory.h"
39 #include "sync/internal_api/public/test/test_internal_components_factory.h"
40 #include "sync/internal_api/public/test/test_user_share.h"
41 #include "sync/internal_api/public/write_node.h"
42 #include "sync/internal_api/public/write_transaction.h"
43 #include "sync/internal_api/sync_encryption_handler_impl.h"
44 #include "sync/internal_api/sync_manager_impl.h"
45 #include "sync/internal_api/syncapi_internal.h"
46 #include "sync/js/js_backend.h"
47 #include "sync/js/js_event_handler.h"
48 #include "sync/js/js_test_util.h"
49 #include "sync/protocol/bookmark_specifics.pb.h"
50 #include "sync/protocol/encryption.pb.h"
51 #include "sync/protocol/extension_specifics.pb.h"
52 #include "sync/protocol/password_specifics.pb.h"
53 #include "sync/protocol/preference_specifics.pb.h"
54 #include "sync/protocol/proto_value_conversions.h"
55 #include "sync/protocol/sync.pb.h"
56 #include "sync/sessions/sync_session.h"
57 #include "sync/syncable/directory.h"
58 #include "sync/syncable/entry.h"
59 #include "sync/syncable/mutable_entry.h"
60 #include "sync/syncable/nigori_util.h"
61 #include "sync/syncable/syncable_id.h"
62 #include "sync/syncable/syncable_read_transaction.h"
63 #include "sync/syncable/syncable_util.h"
64 #include "sync/syncable/syncable_write_transaction.h"
65 #include "sync/test/callback_counter.h"
66 #include "sync/test/engine/fake_model_worker.h"
67 #include "sync/test/engine/fake_sync_scheduler.h"
68 #include "sync/test/engine/test_id_factory.h"
69 #include "sync/test/fake_encryptor.h"
70 #include "sync/util/cryptographer.h"
71 #include "sync/util/extensions_activity.h"
72 #include "sync/util/mock_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.PutSpecifics(specifics);
177 entry.PutUniqueServerTag(type_tag);
178 entry.PutNonUniqueName(type_tag);
179 entry.PutIsDel(false);
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.PutSpecifics(specifics);
206 entry.PutNonUniqueName(client_tag);
207 entry.PutUniqueClientTag(hashed_tag);
208 entry.PutIsDel(false);
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());
521 ReadNode password_node(&trans);
522 EXPECT_EQ(BaseNode::INIT_OK,
523 password_node.InitByClientTagLookup(PASSWORDS, "foo"));
524 const sync_pb::PasswordSpecificsData& data =
525 password_node.GetPasswordSpecifics();
526 EXPECT_EQ("secret", data.password_value());
530 TEST_F(SyncApiTest, WriteEncryptedTitle) {
531 KeyParams params = {"localhost", "username", "passphrase"};
533 ReadTransaction trans(FROM_HERE, user_share());
534 trans.GetCryptographer()->AddKey(params);
536 encryption_handler()->EnableEncryptEverything();
537 int bookmark_id;
539 WriteTransaction trans(FROM_HERE, user_share());
540 ReadNode root_node(&trans);
541 root_node.InitByRootLookup();
543 WriteNode bookmark_node(&trans);
544 ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
545 bookmark_id = bookmark_node.GetId();
546 bookmark_node.SetTitle("foo");
548 WriteNode pref_node(&trans);
549 WriteNode::InitUniqueByCreationResult result =
550 pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar");
551 ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
552 pref_node.SetTitle("bar");
555 ReadTransaction trans(FROM_HERE, user_share());
557 ReadNode bookmark_node(&trans);
558 ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
559 EXPECT_EQ("foo", bookmark_node.GetTitle());
560 EXPECT_EQ(kEncryptedString,
561 bookmark_node.GetEntry()->GetNonUniqueName());
563 ReadNode pref_node(&trans);
564 ASSERT_EQ(BaseNode::INIT_OK,
565 pref_node.InitByClientTagLookup(PREFERENCES,
566 "bar"));
567 EXPECT_EQ(kEncryptedString, pref_node.GetTitle());
571 // Non-unique name should not be empty. For bookmarks non-unique name is copied
572 // from bookmark title. This test verifies that setting bookmark title to ""
573 // results in single space title and non-unique name in internal representation.
574 // GetTitle should still return empty string.
575 TEST_F(SyncApiTest, WriteEmptyBookmarkTitle) {
576 int bookmark_id;
578 WriteTransaction trans(FROM_HERE, user_share());
579 ReadNode root_node(&trans);
580 root_node.InitByRootLookup();
582 WriteNode bookmark_node(&trans);
583 ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
584 bookmark_id = bookmark_node.GetId();
585 bookmark_node.SetTitle("");
588 ReadTransaction trans(FROM_HERE, user_share());
590 ReadNode bookmark_node(&trans);
591 ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
592 EXPECT_EQ("", bookmark_node.GetTitle());
593 EXPECT_EQ(" ", bookmark_node.GetEntry()->GetSpecifics().bookmark().title());
594 EXPECT_EQ(" ", bookmark_node.GetEntry()->GetNonUniqueName());
598 TEST_F(SyncApiTest, BaseNodeSetSpecifics) {
599 int64 child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
600 WriteTransaction trans(FROM_HERE, user_share());
601 WriteNode node(&trans);
602 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
604 sync_pb::EntitySpecifics entity_specifics;
605 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
607 EXPECT_NE(entity_specifics.SerializeAsString(),
608 node.GetEntitySpecifics().SerializeAsString());
609 node.SetEntitySpecifics(entity_specifics);
610 EXPECT_EQ(entity_specifics.SerializeAsString(),
611 node.GetEntitySpecifics().SerializeAsString());
614 TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) {
615 int64 child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
616 WriteTransaction trans(FROM_HERE, user_share());
617 WriteNode node(&trans);
618 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
619 EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty());
621 sync_pb::EntitySpecifics entity_specifics;
622 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
623 entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100);
624 node.SetEntitySpecifics(entity_specifics);
625 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
627 entity_specifics.mutable_unknown_fields()->Clear();
628 node.SetEntitySpecifics(entity_specifics);
629 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
632 TEST_F(SyncApiTest, EmptyTags) {
633 WriteTransaction trans(FROM_HERE, user_share());
634 ReadNode root_node(&trans);
635 root_node.InitByRootLookup();
636 WriteNode node(&trans);
637 std::string empty_tag;
638 WriteNode::InitUniqueByCreationResult result =
639 node.InitUniqueByCreation(TYPED_URLS, root_node, empty_tag);
640 EXPECT_NE(WriteNode::INIT_SUCCESS, result);
641 EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION,
642 node.InitByClientTagLookup(TYPED_URLS, empty_tag));
645 // Test counting nodes when the type's root node has no children.
646 TEST_F(SyncApiTest, GetTotalNodeCountEmpty) {
647 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
649 ReadTransaction trans(FROM_HERE, user_share());
650 ReadNode type_root_node(&trans);
651 EXPECT_EQ(BaseNode::INIT_OK,
652 type_root_node.InitByIdLookup(type_root));
653 EXPECT_EQ(1, type_root_node.GetTotalNodeCount());
657 // Test counting nodes when there is one child beneath the type's root.
658 TEST_F(SyncApiTest, GetTotalNodeCountOneChild) {
659 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
660 int64 parent = MakeFolderWithParent(user_share(), BOOKMARKS, type_root, 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(2, type_root_node.GetTotalNodeCount());
667 ReadNode parent_node(&trans);
668 EXPECT_EQ(BaseNode::INIT_OK,
669 parent_node.InitByIdLookup(parent));
670 EXPECT_EQ(1, parent_node.GetTotalNodeCount());
674 // Test counting nodes when there are multiple children beneath the type root,
675 // and one of those children has children of its own.
676 TEST_F(SyncApiTest, GetTotalNodeCountMultipleChildren) {
677 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
678 int64 parent = MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL);
679 ignore_result(MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL));
680 int64 child1 = MakeFolderWithParent(user_share(), BOOKMARKS, parent, NULL);
681 ignore_result(MakeBookmarkWithParent(user_share(), parent, NULL));
682 ignore_result(MakeBookmarkWithParent(user_share(), child1, NULL));
685 ReadTransaction trans(FROM_HERE, user_share());
686 ReadNode type_root_node(&trans);
687 EXPECT_EQ(BaseNode::INIT_OK,
688 type_root_node.InitByIdLookup(type_root));
689 EXPECT_EQ(6, type_root_node.GetTotalNodeCount());
690 ReadNode node(&trans);
691 EXPECT_EQ(BaseNode::INIT_OK,
692 node.InitByIdLookup(parent));
693 EXPECT_EQ(4, node.GetTotalNodeCount());
697 // Verify that Directory keeps track of which attachments are referenced by
698 // which entries.
699 TEST_F(SyncApiTest, AttachmentLinking) {
700 // Add an entry with an attachment.
701 std::string tag1("some tag");
702 syncer::AttachmentId attachment_id(syncer::AttachmentId::Create(0, 0));
703 sync_pb::AttachmentMetadata attachment_metadata;
704 sync_pb::AttachmentMetadataRecord* record = attachment_metadata.add_record();
705 *record->mutable_id() = attachment_id.GetProto();
706 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
707 CreateEntryWithAttachmentMetadata(PREFERENCES, tag1, attachment_metadata);
709 // See that the directory knows it's linked.
710 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
712 // Add a second entry referencing the same attachment.
713 std::string tag2("some other tag");
714 CreateEntryWithAttachmentMetadata(PREFERENCES, tag2, attachment_metadata);
716 // See that the directory knows it's still linked.
717 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
719 // Tombstone the first entry.
720 ReplaceWithTombstone(syncer::PREFERENCES, tag1);
722 // See that the attachment is still considered linked because the entry hasn't
723 // been purged from the Directory.
724 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
726 // Save changes and see that the entry is truly gone.
727 ASSERT_TRUE(dir()->SaveChanges());
728 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag1),
729 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
731 // However, the attachment is still linked.
732 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
734 // Save, destroy, and recreate the directory. See that it's still linked.
735 ASSERT_TRUE(ReloadDir());
736 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
738 // Tombstone the second entry, save changes, see that it's truly gone.
739 ReplaceWithTombstone(syncer::PREFERENCES, tag2);
740 ASSERT_TRUE(dir()->SaveChanges());
741 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag2),
742 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
744 // Finally, the attachment is no longer linked.
745 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
748 namespace {
750 class TestHttpPostProviderInterface : public HttpPostProviderInterface {
751 public:
752 ~TestHttpPostProviderInterface() override {}
754 void SetExtraRequestHeaders(const char* headers) override {}
755 void SetURL(const char* url, int port) override {}
756 void SetPostPayload(const char* content_type,
757 int content_length,
758 const char* content) override {}
759 bool MakeSynchronousPost(int* error_code, int* response_code) override {
760 return false;
762 int GetResponseContentLength() const override { return 0; }
763 const char* GetResponseContent() const override { return ""; }
764 const std::string GetResponseHeaderValue(
765 const std::string& name) const override {
766 return std::string();
768 void Abort() override {}
771 class TestHttpPostProviderFactory : public HttpPostProviderFactory {
772 public:
773 ~TestHttpPostProviderFactory() override {}
774 void Init(const std::string& user_agent) override {}
775 HttpPostProviderInterface* Create() override {
776 return new TestHttpPostProviderInterface();
778 void Destroy(HttpPostProviderInterface* http) override {
779 delete static_cast<TestHttpPostProviderInterface*>(http);
783 class SyncManagerObserverMock : public SyncManager::Observer {
784 public:
785 MOCK_METHOD1(OnSyncCycleCompleted,
786 void(const SyncSessionSnapshot&)); // NOLINT
787 MOCK_METHOD4(OnInitializationComplete,
788 void(const WeakHandle<JsBackend>&,
789 const WeakHandle<DataTypeDebugInfoListener>&,
790 bool,
791 syncer::ModelTypeSet)); // NOLINT
792 MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT
793 MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT
794 MOCK_METHOD1(OnActionableError, void(const SyncProtocolError&)); // NOLINT
795 MOCK_METHOD1(OnMigrationRequested, void(syncer::ModelTypeSet)); // NOLINT
796 MOCK_METHOD1(OnProtocolEvent, void(const ProtocolEvent&)); // NOLINT
799 class SyncEncryptionHandlerObserverMock
800 : public SyncEncryptionHandler::Observer {
801 public:
802 MOCK_METHOD2(OnPassphraseRequired,
803 void(PassphraseRequiredReason,
804 const sync_pb::EncryptedData&)); // NOLINT
805 MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT
806 MOCK_METHOD2(OnBootstrapTokenUpdated,
807 void(const std::string&, BootstrapTokenType type)); // NOLINT
808 MOCK_METHOD2(OnEncryptedTypesChanged,
809 void(ModelTypeSet, bool)); // NOLINT
810 MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT
811 MOCK_METHOD1(OnCryptographerStateChanged, void(Cryptographer*)); // NOLINT
812 MOCK_METHOD2(OnPassphraseTypeChanged, void(PassphraseType,
813 base::Time)); // NOLINT
814 MOCK_METHOD1(OnLocalSetPassphraseEncryption,
815 void(const SyncEncryptionHandler::NigoriState&)); // NOLINT
818 } // namespace
820 class SyncManagerTest : public testing::Test,
821 public SyncManager::ChangeDelegate {
822 protected:
823 enum NigoriStatus {
824 DONT_WRITE_NIGORI,
825 WRITE_TO_NIGORI
828 enum EncryptionStatus {
829 UNINITIALIZED,
830 DEFAULT_ENCRYPTION,
831 FULL_ENCRYPTION
834 SyncManagerTest()
835 : sync_manager_("Test sync manager"),
836 mock_unrecoverable_error_handler_(NULL) {
837 switches_.encryption_method =
838 InternalComponentsFactory::ENCRYPTION_KEYSTORE;
841 virtual ~SyncManagerTest() {
844 // Test implementation.
845 void SetUp() {
846 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
848 extensions_activity_ = new ExtensionsActivity();
850 SyncCredentials credentials;
851 credentials.email = "foo@bar.com";
852 credentials.sync_token = "sometoken";
853 OAuth2TokenService::ScopeSet scope_set;
854 scope_set.insert(GaiaConstants::kChromeSyncOAuth2Scope);
855 credentials.scope_set = scope_set;
857 sync_manager_.AddObserver(&manager_observer_);
858 EXPECT_CALL(manager_observer_, OnInitializationComplete(_, _, _, _)).
859 WillOnce(DoAll(SaveArg<0>(&js_backend_),
860 SaveArg<2>(&initialization_succeeded_)));
862 EXPECT_FALSE(js_backend_.IsInitialized());
864 std::vector<scoped_refptr<ModelSafeWorker> > workers;
865 ModelSafeRoutingInfo routing_info;
866 GetModelSafeRoutingInfo(&routing_info);
868 // This works only because all routing info types are GROUP_PASSIVE.
869 // If we had types in other groups, we would need additional workers
870 // to support them.
871 scoped_refptr<ModelSafeWorker> worker = new FakeModelWorker(GROUP_PASSIVE);
872 workers.push_back(worker);
874 SyncManager::InitArgs args;
875 args.database_location = temp_dir_.path();
876 args.service_url = GURL("https://example.com/");
877 args.post_factory =
878 scoped_ptr<HttpPostProviderFactory>(new TestHttpPostProviderFactory());
879 args.workers = workers;
880 args.extensions_activity = extensions_activity_.get(),
881 args.change_delegate = this;
882 args.credentials = credentials;
883 args.invalidator_client_id = "fake_invalidator_client_id";
884 args.internal_components_factory.reset(GetFactory());
885 args.encryptor = &encryptor_;
886 mock_unrecoverable_error_handler_ = new MockUnrecoverableErrorHandler();
887 args.unrecoverable_error_handler.reset(mock_unrecoverable_error_handler_);
888 args.cancelation_signal = &cancelation_signal_;
889 sync_manager_.Init(&args);
891 sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_);
893 EXPECT_TRUE(js_backend_.IsInitialized());
894 EXPECT_EQ(InternalComponentsFactory::STORAGE_ON_DISK,
895 storage_used_);
897 if (initialization_succeeded_) {
898 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
899 i != routing_info.end(); ++i) {
900 type_roots_[i->first] =
901 MakeTypeRoot(sync_manager_.GetUserShare(), i->first);
905 PumpLoop();
908 void TearDown() {
909 sync_manager_.RemoveObserver(&manager_observer_);
910 sync_manager_.ShutdownOnSyncThread(STOP_SYNC);
911 PumpLoop();
914 void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) {
915 (*out)[NIGORI] = GROUP_PASSIVE;
916 (*out)[DEVICE_INFO] = GROUP_PASSIVE;
917 (*out)[EXPERIMENTS] = GROUP_PASSIVE;
918 (*out)[BOOKMARKS] = GROUP_PASSIVE;
919 (*out)[THEMES] = GROUP_PASSIVE;
920 (*out)[SESSIONS] = GROUP_PASSIVE;
921 (*out)[PASSWORDS] = GROUP_PASSIVE;
922 (*out)[PREFERENCES] = GROUP_PASSIVE;
923 (*out)[PRIORITY_PREFERENCES] = GROUP_PASSIVE;
924 (*out)[ARTICLES] = GROUP_PASSIVE;
927 ModelTypeSet GetEnabledTypes() {
928 ModelSafeRoutingInfo routing_info;
929 GetModelSafeRoutingInfo(&routing_info);
930 return GetRoutingInfoTypes(routing_info);
933 void OnChangesApplied(
934 ModelType model_type,
935 int64 model_version,
936 const BaseTransaction* trans,
937 const ImmutableChangeRecordList& changes) override {}
939 void OnChangesComplete(ModelType model_type) override {}
941 // Helper methods.
942 bool SetUpEncryption(NigoriStatus nigori_status,
943 EncryptionStatus encryption_status) {
944 UserShare* share = sync_manager_.GetUserShare();
946 // We need to create the nigori node as if it were an applied server update.
947 int64 nigori_id = GetIdForDataType(NIGORI);
948 if (nigori_id == kInvalidId)
949 return false;
951 // Set the nigori cryptographer information.
952 if (encryption_status == FULL_ENCRYPTION)
953 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
955 WriteTransaction trans(FROM_HERE, share);
956 Cryptographer* cryptographer = trans.GetCryptographer();
957 if (!cryptographer)
958 return false;
959 if (encryption_status != UNINITIALIZED) {
960 KeyParams params = {"localhost", "dummy", "foobar"};
961 cryptographer->AddKey(params);
962 } else {
963 DCHECK_NE(nigori_status, WRITE_TO_NIGORI);
965 if (nigori_status == WRITE_TO_NIGORI) {
966 sync_pb::NigoriSpecifics nigori;
967 cryptographer->GetKeys(nigori.mutable_encryption_keybag());
968 share->directory->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
969 &nigori,
970 trans.GetWrappedTrans());
971 WriteNode node(&trans);
972 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(nigori_id));
973 node.SetNigoriSpecifics(nigori);
975 return cryptographer->is_ready();
978 int64 GetIdForDataType(ModelType type) {
979 if (type_roots_.count(type) == 0)
980 return 0;
981 return type_roots_[type];
984 void PumpLoop() {
985 base::RunLoop().RunUntilIdle();
988 void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) {
989 js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler,
990 event_handler);
991 PumpLoop();
994 // Looks up an entry by client tag and resets IS_UNSYNCED value to false.
995 // Returns true if entry was previously unsynced, false if IS_UNSYNCED was
996 // already false.
997 bool ResetUnsyncedEntry(ModelType type,
998 const std::string& client_tag) {
999 UserShare* share = sync_manager_.GetUserShare();
1000 syncable::WriteTransaction trans(
1001 FROM_HERE, syncable::UNITTEST, share->directory.get());
1002 const std::string hash = syncable::GenerateSyncableHash(type, client_tag);
1003 syncable::MutableEntry entry(&trans, syncable::GET_BY_CLIENT_TAG,
1004 hash);
1005 EXPECT_TRUE(entry.good());
1006 if (!entry.GetIsUnsynced())
1007 return false;
1008 entry.PutIsUnsynced(false);
1009 return true;
1012 virtual InternalComponentsFactory* GetFactory() {
1013 return new TestInternalComponentsFactory(
1014 GetSwitches(), InternalComponentsFactory::STORAGE_IN_MEMORY,
1015 &storage_used_);
1018 // Returns true if we are currently encrypting all sync data. May
1019 // be called on any thread.
1020 bool EncryptEverythingEnabledForTest() {
1021 return sync_manager_.GetEncryptionHandler()->EncryptEverythingEnabled();
1024 // Gets the set of encrypted types from the cryptographer
1025 // Note: opens a transaction. May be called from any thread.
1026 ModelTypeSet GetEncryptedTypes() {
1027 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1028 return GetEncryptedTypesWithTrans(&trans);
1031 ModelTypeSet GetEncryptedTypesWithTrans(BaseTransaction* trans) {
1032 return trans->GetDirectory()->GetNigoriHandler()->
1033 GetEncryptedTypes(trans->GetWrappedTrans());
1036 void SimulateInvalidatorEnabledForTest(bool is_enabled) {
1037 DCHECK(sync_manager_.thread_checker_.CalledOnValidThread());
1038 sync_manager_.SetInvalidatorEnabled(is_enabled);
1041 void SetProgressMarkerForType(ModelType type, bool set) {
1042 if (set) {
1043 sync_pb::DataTypeProgressMarker marker;
1044 marker.set_token("token");
1045 marker.set_data_type_id(GetSpecificsFieldNumberFromModelType(type));
1046 sync_manager_.directory()->SetDownloadProgress(type, marker);
1047 } else {
1048 sync_pb::DataTypeProgressMarker marker;
1049 sync_manager_.directory()->SetDownloadProgress(type, marker);
1053 InternalComponentsFactory::Switches GetSwitches() const {
1054 return switches_;
1057 void ExpectPassphraseAcceptance() {
1058 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1059 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1060 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1063 void SetImplicitPassphraseAndCheck(const std::string& passphrase) {
1064 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1065 passphrase,
1066 false);
1067 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1068 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1071 void SetCustomPassphraseAndCheck(const std::string& passphrase) {
1072 EXPECT_CALL(encryption_observer_,
1073 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1074 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1075 passphrase,
1076 true);
1077 EXPECT_EQ(CUSTOM_PASSPHRASE,
1078 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1081 bool HasUnrecoverableError() {
1082 if (mock_unrecoverable_error_handler_)
1083 return mock_unrecoverable_error_handler_->invocation_count() > 0;
1084 return false;
1087 private:
1088 // Needed by |sync_manager_|.
1089 base::MessageLoop message_loop_;
1090 // Needed by |sync_manager_|.
1091 base::ScopedTempDir temp_dir_;
1092 // Sync Id's for the roots of the enabled datatypes.
1093 std::map<ModelType, int64> type_roots_;
1094 scoped_refptr<ExtensionsActivity> extensions_activity_;
1096 protected:
1097 FakeEncryptor encryptor_;
1098 SyncManagerImpl sync_manager_;
1099 CancelationSignal cancelation_signal_;
1100 WeakHandle<JsBackend> js_backend_;
1101 bool initialization_succeeded_;
1102 StrictMock<SyncManagerObserverMock> manager_observer_;
1103 StrictMock<SyncEncryptionHandlerObserverMock> encryption_observer_;
1104 InternalComponentsFactory::Switches switches_;
1105 InternalComponentsFactory::StorageOption storage_used_;
1107 // Not owned (ownership is passed to the SyncManager).
1108 MockUnrecoverableErrorHandler* mock_unrecoverable_error_handler_;
1111 TEST_F(SyncManagerTest, GetAllNodesForTypeTest) {
1112 ModelSafeRoutingInfo routing_info;
1113 GetModelSafeRoutingInfo(&routing_info);
1114 sync_manager_.StartSyncingNormally(routing_info, base::Time());
1116 scoped_ptr<base::ListValue> node_list(
1117 sync_manager_.GetAllNodesForType(syncer::PREFERENCES));
1119 // Should have one node: the type root node.
1120 ASSERT_EQ(1U, node_list->GetSize());
1122 const base::DictionaryValue* first_result;
1123 ASSERT_TRUE(node_list->GetDictionary(0, &first_result));
1124 EXPECT_TRUE(first_result->HasKey("ID"));
1125 EXPECT_TRUE(first_result->HasKey("NON_UNIQUE_NAME"));
1128 TEST_F(SyncManagerTest, RefreshEncryptionReady) {
1129 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1130 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1131 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1132 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1134 sync_manager_.GetEncryptionHandler()->Init();
1135 PumpLoop();
1137 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1138 EXPECT_TRUE(encrypted_types.Has(PASSWORDS));
1139 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1142 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1143 ReadNode node(&trans);
1144 EXPECT_EQ(BaseNode::INIT_OK,
1145 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1146 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1147 EXPECT_TRUE(nigori.has_encryption_keybag());
1148 Cryptographer* cryptographer = trans.GetCryptographer();
1149 EXPECT_TRUE(cryptographer->is_ready());
1150 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1154 // Attempt to refresh encryption when nigori not downloaded.
1155 TEST_F(SyncManagerTest, RefreshEncryptionNotReady) {
1156 // Don't set up encryption (no nigori node created).
1158 // Should fail. Triggers an OnPassphraseRequired because the cryptographer
1159 // is not ready.
1160 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)).Times(1);
1161 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1162 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1163 sync_manager_.GetEncryptionHandler()->Init();
1164 PumpLoop();
1166 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1167 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1168 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1171 // Attempt to refresh encryption when nigori is empty.
1172 TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) {
1173 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION));
1174 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(1);
1175 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1176 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1178 // Should write to nigori.
1179 sync_manager_.GetEncryptionHandler()->Init();
1180 PumpLoop();
1182 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1183 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1184 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1187 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1188 ReadNode node(&trans);
1189 EXPECT_EQ(BaseNode::INIT_OK,
1190 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1191 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1192 EXPECT_TRUE(nigori.has_encryption_keybag());
1193 Cryptographer* cryptographer = trans.GetCryptographer();
1194 EXPECT_TRUE(cryptographer->is_ready());
1195 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1199 TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) {
1200 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1201 EXPECT_CALL(encryption_observer_,
1202 OnEncryptedTypesChanged(
1203 HasModelTypes(EncryptableUserTypes()), true));
1204 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1205 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1206 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1209 TEST_F(SyncManagerTest, EncryptDataTypesWithData) {
1210 size_t batch_size = 5;
1211 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1213 // Create some unencrypted unsynced data.
1214 int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(),
1215 BOOKMARKS,
1216 GetIdForDataType(BOOKMARKS),
1217 NULL);
1218 // First batch_size nodes are children of folder.
1219 size_t i;
1220 for (i = 0; i < batch_size; ++i) {
1221 MakeBookmarkWithParent(sync_manager_.GetUserShare(), folder, NULL);
1223 // Next batch_size nodes are a different type and on their own.
1224 for (; i < 2*batch_size; ++i) {
1225 MakeNodeWithRoot(sync_manager_.GetUserShare(), SESSIONS,
1226 base::StringPrintf("%" PRIuS "", i));
1228 // Last batch_size nodes are a third type that will not need encryption.
1229 for (; i < 3*batch_size; ++i) {
1230 MakeNodeWithRoot(sync_manager_.GetUserShare(), THEMES,
1231 base::StringPrintf("%" PRIuS "", i));
1235 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1236 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1237 SyncEncryptionHandler::SensitiveTypes()));
1238 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1239 trans.GetWrappedTrans(),
1240 BOOKMARKS,
1241 false /* not encrypted */));
1242 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1243 trans.GetWrappedTrans(),
1244 SESSIONS,
1245 false /* not encrypted */));
1246 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1247 trans.GetWrappedTrans(),
1248 THEMES,
1249 false /* not encrypted */));
1252 EXPECT_CALL(encryption_observer_,
1253 OnEncryptedTypesChanged(
1254 HasModelTypes(EncryptableUserTypes()), true));
1255 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1256 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1257 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1259 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1260 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1261 EncryptableUserTypes()));
1262 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1263 trans.GetWrappedTrans(),
1264 BOOKMARKS,
1265 true /* is encrypted */));
1266 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1267 trans.GetWrappedTrans(),
1268 SESSIONS,
1269 true /* is encrypted */));
1270 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1271 trans.GetWrappedTrans(),
1272 THEMES,
1273 true /* is encrypted */));
1276 // Trigger's a ReEncryptEverything with new passphrase.
1277 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1278 EXPECT_CALL(encryption_observer_,
1279 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1280 ExpectPassphraseAcceptance();
1281 SetCustomPassphraseAndCheck("new_passphrase");
1282 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1284 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1285 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1286 EncryptableUserTypes()));
1287 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1288 trans.GetWrappedTrans(),
1289 BOOKMARKS,
1290 true /* is encrypted */));
1291 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1292 trans.GetWrappedTrans(),
1293 SESSIONS,
1294 true /* is encrypted */));
1295 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1296 trans.GetWrappedTrans(),
1297 THEMES,
1298 true /* is encrypted */));
1300 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1301 // a reencryption and should just notify immediately.
1302 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1303 EXPECT_CALL(encryption_observer_,
1304 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)).Times(0);
1305 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()).Times(0);
1306 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(0);
1307 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1310 // Test that when there are no pending keys and the cryptographer is not
1311 // initialized, we add a key based on the current GAIA password.
1312 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1313 TEST_F(SyncManagerTest, SetInitialGaiaPass) {
1314 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1315 EXPECT_CALL(encryption_observer_,
1316 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1317 ExpectPassphraseAcceptance();
1318 SetImplicitPassphraseAndCheck("new_passphrase");
1319 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1321 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1322 ReadNode node(&trans);
1323 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1324 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1325 Cryptographer* cryptographer = trans.GetCryptographer();
1326 EXPECT_TRUE(cryptographer->is_ready());
1327 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1331 // Test that when there are no pending keys and we have on the old GAIA
1332 // password, we update and re-encrypt everything with the new GAIA password.
1333 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1334 TEST_F(SyncManagerTest, UpdateGaiaPass) {
1335 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1336 Cryptographer verifier(&encryptor_);
1338 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1339 Cryptographer* cryptographer = trans.GetCryptographer();
1340 std::string bootstrap_token;
1341 cryptographer->GetBootstrapToken(&bootstrap_token);
1342 verifier.Bootstrap(bootstrap_token);
1344 EXPECT_CALL(encryption_observer_,
1345 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1346 ExpectPassphraseAcceptance();
1347 SetImplicitPassphraseAndCheck("new_passphrase");
1348 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1350 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1351 Cryptographer* cryptographer = trans.GetCryptographer();
1352 EXPECT_TRUE(cryptographer->is_ready());
1353 // Verify the default key has changed.
1354 sync_pb::EncryptedData encrypted;
1355 cryptographer->GetKeys(&encrypted);
1356 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1360 // Sets a new explicit passphrase. This should update the bootstrap token
1361 // and re-encrypt everything.
1362 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1363 TEST_F(SyncManagerTest, SetPassphraseWithPassword) {
1364 Cryptographer verifier(&encryptor_);
1365 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1367 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1368 // Store the default (soon to be old) key.
1369 Cryptographer* cryptographer = trans.GetCryptographer();
1370 std::string bootstrap_token;
1371 cryptographer->GetBootstrapToken(&bootstrap_token);
1372 verifier.Bootstrap(bootstrap_token);
1374 ReadNode root_node(&trans);
1375 root_node.InitByRootLookup();
1377 WriteNode password_node(&trans);
1378 WriteNode::InitUniqueByCreationResult result =
1379 password_node.InitUniqueByCreation(PASSWORDS,
1380 root_node, "foo");
1381 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1382 sync_pb::PasswordSpecificsData data;
1383 data.set_password_value("secret");
1384 password_node.SetPasswordSpecifics(data);
1386 EXPECT_CALL(encryption_observer_,
1387 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1388 ExpectPassphraseAcceptance();
1389 SetCustomPassphraseAndCheck("new_passphrase");
1390 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1392 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1393 Cryptographer* cryptographer = trans.GetCryptographer();
1394 EXPECT_TRUE(cryptographer->is_ready());
1395 // Verify the default key has changed.
1396 sync_pb::EncryptedData encrypted;
1397 cryptographer->GetKeys(&encrypted);
1398 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1400 ReadNode password_node(&trans);
1401 EXPECT_EQ(BaseNode::INIT_OK,
1402 password_node.InitByClientTagLookup(PASSWORDS,
1403 "foo"));
1404 const sync_pb::PasswordSpecificsData& data =
1405 password_node.GetPasswordSpecifics();
1406 EXPECT_EQ("secret", data.password_value());
1410 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1411 // being encrypted with a new (unprovided) GAIA password, then supply the
1412 // password.
1413 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1414 TEST_F(SyncManagerTest, SupplyPendingGAIAPass) {
1415 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1416 Cryptographer other_cryptographer(&encryptor_);
1418 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1419 Cryptographer* cryptographer = trans.GetCryptographer();
1420 std::string bootstrap_token;
1421 cryptographer->GetBootstrapToken(&bootstrap_token);
1422 other_cryptographer.Bootstrap(bootstrap_token);
1424 // Now update the nigori to reflect the new keys, and update the
1425 // cryptographer to have pending keys.
1426 KeyParams params = {"localhost", "dummy", "passphrase2"};
1427 other_cryptographer.AddKey(params);
1428 WriteNode node(&trans);
1429 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1430 sync_pb::NigoriSpecifics nigori;
1431 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1432 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1433 EXPECT_TRUE(cryptographer->has_pending_keys());
1434 node.SetNigoriSpecifics(nigori);
1436 EXPECT_CALL(encryption_observer_,
1437 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1438 ExpectPassphraseAcceptance();
1439 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
1440 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1441 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1442 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1444 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1445 Cryptographer* cryptographer = trans.GetCryptographer();
1446 EXPECT_TRUE(cryptographer->is_ready());
1447 // Verify we're encrypting with the new key.
1448 sync_pb::EncryptedData encrypted;
1449 cryptographer->GetKeys(&encrypted);
1450 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1454 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1455 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1456 // the current GAIA password and verify the bootstrap token is updated. Then
1457 // supply the old GAIA password, and verify we re-encrypt all data with the
1458 // new GAIA password.
1459 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1460 TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) {
1461 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1462 Cryptographer other_cryptographer(&encryptor_);
1464 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1465 Cryptographer* cryptographer = trans.GetCryptographer();
1466 std::string bootstrap_token;
1467 cryptographer->GetBootstrapToken(&bootstrap_token);
1468 other_cryptographer.Bootstrap(bootstrap_token);
1470 // Now update the nigori to reflect the new keys, and update the
1471 // cryptographer to have pending keys.
1472 KeyParams params = {"localhost", "dummy", "old_gaia"};
1473 other_cryptographer.AddKey(params);
1474 WriteNode node(&trans);
1475 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1476 sync_pb::NigoriSpecifics nigori;
1477 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1478 node.SetNigoriSpecifics(nigori);
1479 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1481 // other_cryptographer now contains all encryption keys, and is encrypting
1482 // with the newest gaia.
1483 KeyParams new_params = {"localhost", "dummy", "new_gaia"};
1484 other_cryptographer.AddKey(new_params);
1486 // The bootstrap token should have been updated. Save it to ensure it's based
1487 // on the new GAIA password.
1488 std::string bootstrap_token;
1489 EXPECT_CALL(encryption_observer_,
1490 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN))
1491 .WillOnce(SaveArg<0>(&bootstrap_token));
1492 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_,_));
1493 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1494 SetImplicitPassphraseAndCheck("new_gaia");
1495 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1496 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1498 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1499 Cryptographer* cryptographer = trans.GetCryptographer();
1500 EXPECT_TRUE(cryptographer->is_initialized());
1501 EXPECT_FALSE(cryptographer->is_ready());
1502 // Verify we're encrypting with the new key, even though we have pending
1503 // keys.
1504 sync_pb::EncryptedData encrypted;
1505 other_cryptographer.GetKeys(&encrypted);
1506 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1508 EXPECT_CALL(encryption_observer_,
1509 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1510 ExpectPassphraseAcceptance();
1511 SetImplicitPassphraseAndCheck("old_gaia");
1513 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1514 Cryptographer* cryptographer = trans.GetCryptographer();
1515 EXPECT_TRUE(cryptographer->is_ready());
1517 // Verify we're encrypting with the new key.
1518 sync_pb::EncryptedData encrypted;
1519 other_cryptographer.GetKeys(&encrypted);
1520 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1522 // Verify the saved bootstrap token is based on the new gaia password.
1523 Cryptographer temp_cryptographer(&encryptor_);
1524 temp_cryptographer.Bootstrap(bootstrap_token);
1525 EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted));
1529 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1530 // being encrypted with an explicit (unprovided) passphrase, then supply the
1531 // passphrase.
1532 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1533 TEST_F(SyncManagerTest, SupplyPendingExplicitPass) {
1534 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1535 Cryptographer other_cryptographer(&encryptor_);
1537 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1538 Cryptographer* cryptographer = trans.GetCryptographer();
1539 std::string bootstrap_token;
1540 cryptographer->GetBootstrapToken(&bootstrap_token);
1541 other_cryptographer.Bootstrap(bootstrap_token);
1543 // Now update the nigori to reflect the new keys, and update the
1544 // cryptographer to have pending keys.
1545 KeyParams params = {"localhost", "dummy", "explicit"};
1546 other_cryptographer.AddKey(params);
1547 WriteNode node(&trans);
1548 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1549 sync_pb::NigoriSpecifics nigori;
1550 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1551 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1552 EXPECT_TRUE(cryptographer->has_pending_keys());
1553 nigori.set_keybag_is_frozen(true);
1554 node.SetNigoriSpecifics(nigori);
1556 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1557 EXPECT_CALL(encryption_observer_,
1558 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1559 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _));
1560 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1561 sync_manager_.GetEncryptionHandler()->Init();
1562 EXPECT_CALL(encryption_observer_,
1563 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1564 ExpectPassphraseAcceptance();
1565 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
1566 EXPECT_EQ(CUSTOM_PASSPHRASE,
1567 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1568 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1570 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1571 Cryptographer* cryptographer = trans.GetCryptographer();
1572 EXPECT_TRUE(cryptographer->is_ready());
1573 // Verify we're encrypting with the new key.
1574 sync_pb::EncryptedData encrypted;
1575 cryptographer->GetKeys(&encrypted);
1576 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1580 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1581 // being encrypted with a new (unprovided) GAIA password, then supply the
1582 // password as a user-provided password.
1583 // This is the android case 7/8.
1584 TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) {
1585 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1586 Cryptographer other_cryptographer(&encryptor_);
1588 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1589 Cryptographer* cryptographer = trans.GetCryptographer();
1590 // Now update the nigori to reflect the new keys, and update the
1591 // cryptographer to have pending keys.
1592 KeyParams params = {"localhost", "dummy", "passphrase"};
1593 other_cryptographer.AddKey(params);
1594 WriteNode node(&trans);
1595 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1596 sync_pb::NigoriSpecifics nigori;
1597 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1598 node.SetNigoriSpecifics(nigori);
1599 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1600 EXPECT_FALSE(cryptographer->is_ready());
1602 EXPECT_CALL(encryption_observer_,
1603 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1604 ExpectPassphraseAcceptance();
1605 SetImplicitPassphraseAndCheck("passphrase");
1606 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1608 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1609 Cryptographer* cryptographer = trans.GetCryptographer();
1610 EXPECT_TRUE(cryptographer->is_ready());
1614 TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) {
1615 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1616 int64 node_id = 0;
1617 std::string tag = "foo";
1619 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1620 ReadNode root_node(&trans);
1621 root_node.InitByRootLookup();
1623 WriteNode password_node(&trans);
1624 WriteNode::InitUniqueByCreationResult result =
1625 password_node.InitUniqueByCreation(PASSWORDS, root_node, tag);
1626 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1627 node_id = password_node.GetId();
1629 EXPECT_CALL(encryption_observer_,
1630 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1631 ExpectPassphraseAcceptance();
1632 SetCustomPassphraseAndCheck("new_passphrase");
1633 EXPECT_FALSE(EncryptEverythingEnabledForTest());
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.InitByClientTagLookup(PASSWORDS,
1639 tag));
1642 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1643 ReadNode password_node(&trans);
1644 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1645 password_node.InitByIdLookup(node_id));
1649 // Friended by WriteNode, so can't be in an anonymouse namespace.
1650 TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) {
1651 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1652 std::string title;
1653 SyncAPINameToServerName("Google", &title);
1654 std::string url = "http://www.google.com";
1655 std::string raw_title2 = ".."; // An invalid cosmo title.
1656 std::string title2;
1657 SyncAPINameToServerName(raw_title2, &title2);
1658 std::string url2 = "http://www.bla.com";
1660 // Create a bookmark using the legacy format.
1661 int64 node_id1 =
1662 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag");
1663 int64 node_id2 =
1664 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag2");
1666 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1667 WriteNode node(&trans);
1668 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1670 sync_pb::EntitySpecifics entity_specifics;
1671 entity_specifics.mutable_bookmark()->set_url(url);
1672 node.SetEntitySpecifics(entity_specifics);
1674 // Set the old style title.
1675 syncable::MutableEntry* node_entry = node.entry_;
1676 node_entry->PutNonUniqueName(title);
1678 WriteNode node2(&trans);
1679 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1681 sync_pb::EntitySpecifics entity_specifics2;
1682 entity_specifics2.mutable_bookmark()->set_url(url2);
1683 node2.SetEntitySpecifics(entity_specifics2);
1685 // Set the old style title.
1686 syncable::MutableEntry* node_entry2 = node2.entry_;
1687 node_entry2->PutNonUniqueName(title2);
1691 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1692 ReadNode node(&trans);
1693 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1694 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1695 EXPECT_EQ(title, node.GetTitle());
1696 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1697 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1699 ReadNode node2(&trans);
1700 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1701 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1702 // We should de-canonicalize the title in GetTitle(), but the title in the
1703 // specifics should be stored in the server legal form.
1704 EXPECT_EQ(raw_title2, node2.GetTitle());
1705 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1706 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1710 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1711 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1712 trans.GetWrappedTrans(),
1713 BOOKMARKS,
1714 false /* not encrypted */));
1717 EXPECT_CALL(encryption_observer_,
1718 OnEncryptedTypesChanged(
1719 HasModelTypes(EncryptableUserTypes()), true));
1720 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1721 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1722 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1725 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1726 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1727 EncryptableUserTypes()));
1728 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1729 trans.GetWrappedTrans(),
1730 BOOKMARKS,
1731 true /* is encrypted */));
1733 ReadNode node(&trans);
1734 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1735 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1736 EXPECT_EQ(title, node.GetTitle());
1737 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1738 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1740 ReadNode node2(&trans);
1741 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1742 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1743 // We should de-canonicalize the title in GetTitle(), but the title in the
1744 // specifics should be stored in the server legal form.
1745 EXPECT_EQ(raw_title2, node2.GetTitle());
1746 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1747 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1751 // Create a bookmark and set the title/url, then verify the data was properly
1752 // set. This replicates the unique way bookmarks have of creating sync nodes.
1753 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1754 TEST_F(SyncManagerTest, CreateLocalBookmark) {
1755 std::string title = "title";
1756 std::string url = "url";
1758 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1759 ReadNode bookmark_root(&trans);
1760 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1761 WriteNode node(&trans);
1762 ASSERT_TRUE(node.InitBookmarkByCreation(bookmark_root, NULL));
1763 node.SetIsFolder(false);
1764 node.SetTitle(title);
1766 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
1767 bookmark_specifics.set_url(url);
1768 node.SetBookmarkSpecifics(bookmark_specifics);
1771 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1772 ReadNode bookmark_root(&trans);
1773 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1774 int64 child_id = bookmark_root.GetFirstChildId();
1776 ReadNode node(&trans);
1777 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
1778 EXPECT_FALSE(node.GetIsFolder());
1779 EXPECT_EQ(title, node.GetTitle());
1780 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1784 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1785 // changes.
1786 TEST_F(SyncManagerTest, UpdateEntryWithEncryption) {
1787 std::string client_tag = "title";
1788 sync_pb::EntitySpecifics entity_specifics;
1789 entity_specifics.mutable_bookmark()->set_url("url");
1790 entity_specifics.mutable_bookmark()->set_title("title");
1791 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
1792 syncable::GenerateSyncableHash(BOOKMARKS,
1793 client_tag),
1794 entity_specifics);
1795 // New node shouldn't start off unsynced.
1796 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1797 // Manually change to the same data. Should not set is_unsynced.
1799 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1800 WriteNode node(&trans);
1801 EXPECT_EQ(BaseNode::INIT_OK,
1802 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1803 node.SetEntitySpecifics(entity_specifics);
1805 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1807 // Encrypt the datatatype, should set is_unsynced.
1808 EXPECT_CALL(encryption_observer_,
1809 OnEncryptedTypesChanged(
1810 HasModelTypes(EncryptableUserTypes()), true));
1811 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1812 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
1814 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1815 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1816 sync_manager_.GetEncryptionHandler()->Init();
1817 PumpLoop();
1819 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1820 ReadNode node(&trans);
1821 EXPECT_EQ(BaseNode::INIT_OK,
1822 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1823 const syncable::Entry* node_entry = node.GetEntry();
1824 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1825 EXPECT_TRUE(specifics.has_encrypted());
1826 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1827 Cryptographer* cryptographer = trans.GetCryptographer();
1828 EXPECT_TRUE(cryptographer->is_ready());
1829 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1830 specifics.encrypted()));
1832 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1834 // Set a new passphrase. Should set is_unsynced.
1835 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1836 EXPECT_CALL(encryption_observer_,
1837 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1838 ExpectPassphraseAcceptance();
1839 SetCustomPassphraseAndCheck("new_passphrase");
1841 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1842 ReadNode node(&trans);
1843 EXPECT_EQ(BaseNode::INIT_OK,
1844 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1845 const syncable::Entry* node_entry = node.GetEntry();
1846 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1847 EXPECT_TRUE(specifics.has_encrypted());
1848 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1849 Cryptographer* cryptographer = trans.GetCryptographer();
1850 EXPECT_TRUE(cryptographer->is_ready());
1851 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1852 specifics.encrypted()));
1854 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1856 // Force a re-encrypt everything. Should not set is_unsynced.
1857 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1858 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1859 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1860 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1862 sync_manager_.GetEncryptionHandler()->Init();
1863 PumpLoop();
1866 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1867 ReadNode node(&trans);
1868 EXPECT_EQ(BaseNode::INIT_OK,
1869 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1870 const syncable::Entry* node_entry = node.GetEntry();
1871 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1872 EXPECT_TRUE(specifics.has_encrypted());
1873 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1874 Cryptographer* cryptographer = trans.GetCryptographer();
1875 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1876 specifics.encrypted()));
1878 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1880 // Manually change to the same data. Should not set is_unsynced.
1882 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1883 WriteNode node(&trans);
1884 EXPECT_EQ(BaseNode::INIT_OK,
1885 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1886 node.SetEntitySpecifics(entity_specifics);
1887 const syncable::Entry* node_entry = node.GetEntry();
1888 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1889 EXPECT_TRUE(specifics.has_encrypted());
1890 EXPECT_FALSE(node_entry->GetIsUnsynced());
1891 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1892 Cryptographer* cryptographer = trans.GetCryptographer();
1893 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1894 specifics.encrypted()));
1896 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1898 // Manually change to different data. Should set is_unsynced.
1900 entity_specifics.mutable_bookmark()->set_url("url2");
1901 entity_specifics.mutable_bookmark()->set_title("title2");
1902 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1903 WriteNode node(&trans);
1904 EXPECT_EQ(BaseNode::INIT_OK,
1905 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1906 node.SetEntitySpecifics(entity_specifics);
1907 const syncable::Entry* node_entry = node.GetEntry();
1908 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1909 EXPECT_TRUE(specifics.has_encrypted());
1910 EXPECT_TRUE(node_entry->GetIsUnsynced());
1911 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1912 Cryptographer* cryptographer = trans.GetCryptographer();
1913 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1914 specifics.encrypted()));
1918 // Passwords have their own handling for encryption. Verify it does not result
1919 // in unnecessary writes via SetEntitySpecifics.
1920 TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) {
1921 std::string client_tag = "title";
1922 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1923 sync_pb::EntitySpecifics entity_specifics;
1925 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1926 Cryptographer* cryptographer = trans.GetCryptographer();
1927 sync_pb::PasswordSpecificsData data;
1928 data.set_password_value("secret");
1929 cryptographer->Encrypt(
1930 data,
1931 entity_specifics.mutable_password()->
1932 mutable_encrypted());
1934 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1935 syncable::GenerateSyncableHash(PASSWORDS,
1936 client_tag),
1937 entity_specifics);
1938 // New node shouldn't start off unsynced.
1939 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1941 // Manually change to the same data via SetEntitySpecifics. Should not set
1942 // is_unsynced.
1944 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1945 WriteNode node(&trans);
1946 EXPECT_EQ(BaseNode::INIT_OK,
1947 node.InitByClientTagLookup(PASSWORDS, client_tag));
1948 node.SetEntitySpecifics(entity_specifics);
1950 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1953 // Passwords have their own handling for encryption. Verify it does not result
1954 // in unnecessary writes via SetPasswordSpecifics.
1955 TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) {
1956 std::string client_tag = "title";
1957 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1958 sync_pb::EntitySpecifics entity_specifics;
1960 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1961 Cryptographer* cryptographer = trans.GetCryptographer();
1962 sync_pb::PasswordSpecificsData data;
1963 data.set_password_value("secret");
1964 cryptographer->Encrypt(
1965 data,
1966 entity_specifics.mutable_password()->
1967 mutable_encrypted());
1969 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1970 syncable::GenerateSyncableHash(PASSWORDS,
1971 client_tag),
1972 entity_specifics);
1973 // New node shouldn't start off unsynced.
1974 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1976 // Manually change to the same data via SetPasswordSpecifics. Should not set
1977 // is_unsynced.
1979 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1980 WriteNode node(&trans);
1981 EXPECT_EQ(BaseNode::INIT_OK,
1982 node.InitByClientTagLookup(PASSWORDS, client_tag));
1983 node.SetPasswordSpecifics(node.GetPasswordSpecifics());
1985 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1987 // Manually change to different data. Should set is_unsynced.
1989 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1990 WriteNode node(&trans);
1991 EXPECT_EQ(BaseNode::INIT_OK,
1992 node.InitByClientTagLookup(PASSWORDS, client_tag));
1993 Cryptographer* cryptographer = trans.GetCryptographer();
1994 sync_pb::PasswordSpecificsData data;
1995 data.set_password_value("secret2");
1996 cryptographer->Encrypt(
1997 data,
1998 entity_specifics.mutable_password()->mutable_encrypted());
1999 node.SetPasswordSpecifics(data);
2000 const syncable::Entry* node_entry = node.GetEntry();
2001 EXPECT_TRUE(node_entry->GetIsUnsynced());
2005 // Passwords have their own handling for encryption. Verify setting a new
2006 // passphrase updates the data.
2007 TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) {
2008 std::string client_tag = "title";
2009 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2010 sync_pb::EntitySpecifics entity_specifics;
2012 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2013 Cryptographer* cryptographer = trans.GetCryptographer();
2014 sync_pb::PasswordSpecificsData data;
2015 data.set_password_value("secret");
2016 cryptographer->Encrypt(
2017 data,
2018 entity_specifics.mutable_password()->mutable_encrypted());
2020 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2021 syncable::GenerateSyncableHash(PASSWORDS,
2022 client_tag),
2023 entity_specifics);
2024 // New node shouldn't start off unsynced.
2025 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2027 // Set a new passphrase. Should set is_unsynced.
2028 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2029 EXPECT_CALL(encryption_observer_,
2030 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
2031 ExpectPassphraseAcceptance();
2032 SetCustomPassphraseAndCheck("new_passphrase");
2033 EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2036 // Passwords have their own handling for encryption. Verify it does not result
2037 // in unnecessary writes via ReencryptEverything.
2038 TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) {
2039 std::string client_tag = "title";
2040 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2041 sync_pb::EntitySpecifics entity_specifics;
2043 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2044 Cryptographer* cryptographer = trans.GetCryptographer();
2045 sync_pb::PasswordSpecificsData data;
2046 data.set_password_value("secret");
2047 cryptographer->Encrypt(
2048 data,
2049 entity_specifics.mutable_password()->mutable_encrypted());
2051 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2052 syncable::GenerateSyncableHash(PASSWORDS,
2053 client_tag),
2054 entity_specifics);
2055 // New node shouldn't start off unsynced.
2056 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2058 // Force a re-encrypt everything. Should not set is_unsynced.
2059 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2060 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2061 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2062 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
2063 sync_manager_.GetEncryptionHandler()->Init();
2064 PumpLoop();
2065 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2068 // Test that attempting to start up with corrupted password data triggers
2069 // an unrecoverable error (rather than crashing).
2070 TEST_F(SyncManagerTest, ReencryptEverythingWithUnrecoverableErrorPasswords) {
2071 const char kClientTag[] = "client_tag";
2073 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2074 sync_pb::EntitySpecifics entity_specifics;
2076 // Create a synced bookmark with undecryptable data.
2077 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2079 Cryptographer other_cryptographer(&encryptor_);
2080 KeyParams fake_params = {"localhost", "dummy", "fake_key"};
2081 other_cryptographer.AddKey(fake_params);
2082 sync_pb::PasswordSpecificsData data;
2083 data.set_password_value("secret");
2084 other_cryptographer.Encrypt(
2085 data,
2086 entity_specifics.mutable_password()->mutable_encrypted());
2088 // Set up the real cryptographer with a different key.
2089 KeyParams real_params = {"localhost", "username", "real_key"};
2090 trans.GetCryptographer()->AddKey(real_params);
2092 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, kClientTag,
2093 syncable::GenerateSyncableHash(PASSWORDS,
2094 kClientTag),
2095 entity_specifics);
2096 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
2098 // Force a re-encrypt everything. Should trigger an unrecoverable error due
2099 // to being unable to decrypt the data that was previously applied.
2100 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2101 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2102 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2103 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
2104 EXPECT_FALSE(HasUnrecoverableError());
2105 sync_manager_.GetEncryptionHandler()->Init();
2106 PumpLoop();
2107 EXPECT_TRUE(HasUnrecoverableError());
2110 // Test that attempting to start up with corrupted bookmark data triggers
2111 // an unrecoverable error (rather than crashing).
2112 TEST_F(SyncManagerTest, ReencryptEverythingWithUnrecoverableErrorBookmarks) {
2113 const char kClientTag[] = "client_tag";
2114 EXPECT_CALL(encryption_observer_,
2115 OnEncryptedTypesChanged(
2116 HasModelTypes(EncryptableUserTypes()), true));
2117 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2118 sync_pb::EntitySpecifics entity_specifics;
2120 // Create a synced bookmark with undecryptable data.
2121 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2123 Cryptographer other_cryptographer(&encryptor_);
2124 KeyParams fake_params = {"localhost", "dummy", "fake_key"};
2125 other_cryptographer.AddKey(fake_params);
2126 sync_pb::EntitySpecifics bm_specifics;
2127 bm_specifics.mutable_bookmark()->set_title("title");
2128 bm_specifics.mutable_bookmark()->set_url("url");
2129 sync_pb::EncryptedData encrypted;
2130 other_cryptographer.Encrypt(bm_specifics, &encrypted);
2131 entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
2133 // Set up the real cryptographer with a different key.
2134 KeyParams real_params = {"localhost", "username", "real_key"};
2135 trans.GetCryptographer()->AddKey(real_params);
2137 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, kClientTag,
2138 syncable::GenerateSyncableHash(BOOKMARKS,
2139 kClientTag),
2140 entity_specifics);
2141 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, kClientTag));
2143 // Force a re-encrypt everything. Should trigger an unrecoverable error due
2144 // to being unable to decrypt the data that was previously applied.
2145 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2146 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2147 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2148 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2149 EXPECT_FALSE(HasUnrecoverableError());
2150 sync_manager_.GetEncryptionHandler()->Init();
2151 PumpLoop();
2152 EXPECT_TRUE(HasUnrecoverableError());
2155 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2156 // when we write the same data, but does set it when we write new data.
2157 TEST_F(SyncManagerTest, SetBookmarkTitle) {
2158 std::string client_tag = "title";
2159 sync_pb::EntitySpecifics entity_specifics;
2160 entity_specifics.mutable_bookmark()->set_url("url");
2161 entity_specifics.mutable_bookmark()->set_title("title");
2162 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2163 syncable::GenerateSyncableHash(BOOKMARKS,
2164 client_tag),
2165 entity_specifics);
2166 // New node shouldn't start off unsynced.
2167 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2169 // Manually change to the same title. Should not set is_unsynced.
2171 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2172 WriteNode node(&trans);
2173 EXPECT_EQ(BaseNode::INIT_OK,
2174 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2175 node.SetTitle(client_tag);
2177 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2179 // Manually change to new title. Should set is_unsynced.
2181 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2182 WriteNode node(&trans);
2183 EXPECT_EQ(BaseNode::INIT_OK,
2184 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2185 node.SetTitle("title2");
2187 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2190 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2191 // bookmarks when we write the same data, but does set it when we write new
2192 // data.
2193 TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) {
2194 std::string client_tag = "title";
2195 sync_pb::EntitySpecifics entity_specifics;
2196 entity_specifics.mutable_bookmark()->set_url("url");
2197 entity_specifics.mutable_bookmark()->set_title("title");
2198 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2199 syncable::GenerateSyncableHash(BOOKMARKS,
2200 client_tag),
2201 entity_specifics);
2202 // New node shouldn't start off unsynced.
2203 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2205 // Encrypt the datatatype, should set is_unsynced.
2206 EXPECT_CALL(encryption_observer_,
2207 OnEncryptedTypesChanged(
2208 HasModelTypes(EncryptableUserTypes()), true));
2209 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2210 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2211 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2212 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2213 sync_manager_.GetEncryptionHandler()->Init();
2214 PumpLoop();
2215 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2217 // Manually change to the same title. Should not set is_unsynced.
2218 // NON_UNIQUE_NAME should be kEncryptedString.
2220 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2221 WriteNode node(&trans);
2222 EXPECT_EQ(BaseNode::INIT_OK,
2223 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2224 node.SetTitle(client_tag);
2225 const syncable::Entry* node_entry = node.GetEntry();
2226 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2227 EXPECT_TRUE(specifics.has_encrypted());
2228 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2230 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2232 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2233 // should still be kEncryptedString.
2235 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2236 WriteNode node(&trans);
2237 EXPECT_EQ(BaseNode::INIT_OK,
2238 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2239 node.SetTitle("title2");
2240 const syncable::Entry* node_entry = node.GetEntry();
2241 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2242 EXPECT_TRUE(specifics.has_encrypted());
2243 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2245 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2248 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2249 // when we write the same data, but does set it when we write new data.
2250 TEST_F(SyncManagerTest, SetNonBookmarkTitle) {
2251 std::string client_tag = "title";
2252 sync_pb::EntitySpecifics entity_specifics;
2253 entity_specifics.mutable_preference()->set_name("name");
2254 entity_specifics.mutable_preference()->set_value("value");
2255 MakeServerNode(sync_manager_.GetUserShare(),
2256 PREFERENCES,
2257 client_tag,
2258 syncable::GenerateSyncableHash(PREFERENCES,
2259 client_tag),
2260 entity_specifics);
2261 // New node shouldn't start off unsynced.
2262 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2264 // Manually change to the same title. Should not set is_unsynced.
2266 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2267 WriteNode node(&trans);
2268 EXPECT_EQ(BaseNode::INIT_OK,
2269 node.InitByClientTagLookup(PREFERENCES, client_tag));
2270 node.SetTitle(client_tag);
2272 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2274 // Manually change to new title. Should set is_unsynced.
2276 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2277 WriteNode node(&trans);
2278 EXPECT_EQ(BaseNode::INIT_OK,
2279 node.InitByClientTagLookup(PREFERENCES, client_tag));
2280 node.SetTitle("title2");
2282 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2285 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2286 // non-bookmarks when we write the same data or when we write new data
2287 // data (should remained kEncryptedString).
2288 TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) {
2289 std::string client_tag = "title";
2290 sync_pb::EntitySpecifics entity_specifics;
2291 entity_specifics.mutable_preference()->set_name("name");
2292 entity_specifics.mutable_preference()->set_value("value");
2293 MakeServerNode(sync_manager_.GetUserShare(),
2294 PREFERENCES,
2295 client_tag,
2296 syncable::GenerateSyncableHash(PREFERENCES,
2297 client_tag),
2298 entity_specifics);
2299 // New node shouldn't start off unsynced.
2300 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2302 // Encrypt the datatatype, should set is_unsynced.
2303 EXPECT_CALL(encryption_observer_,
2304 OnEncryptedTypesChanged(
2305 HasModelTypes(EncryptableUserTypes()), true));
2306 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2307 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2308 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2309 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2310 sync_manager_.GetEncryptionHandler()->Init();
2311 PumpLoop();
2312 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2314 // Manually change to the same title. Should not set is_unsynced.
2315 // NON_UNIQUE_NAME should be kEncryptedString.
2317 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2318 WriteNode node(&trans);
2319 EXPECT_EQ(BaseNode::INIT_OK,
2320 node.InitByClientTagLookup(PREFERENCES, client_tag));
2321 node.SetTitle(client_tag);
2322 const syncable::Entry* node_entry = node.GetEntry();
2323 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2324 EXPECT_TRUE(specifics.has_encrypted());
2325 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2327 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2329 // Manually change to new title. Should not set is_unsynced because the
2330 // NON_UNIQUE_NAME should still be kEncryptedString.
2332 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2333 WriteNode node(&trans);
2334 EXPECT_EQ(BaseNode::INIT_OK,
2335 node.InitByClientTagLookup(PREFERENCES, client_tag));
2336 node.SetTitle("title2");
2337 const syncable::Entry* node_entry = node.GetEntry();
2338 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2339 EXPECT_TRUE(specifics.has_encrypted());
2340 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2341 EXPECT_FALSE(node_entry->GetIsUnsynced());
2345 // Ensure that titles are truncated to 255 bytes, and attempting to reset
2346 // them to their longer version does not set IS_UNSYNCED.
2347 TEST_F(SyncManagerTest, SetLongTitle) {
2348 const int kNumChars = 512;
2349 const std::string kClientTag = "tag";
2350 std::string title(kNumChars, '0');
2351 sync_pb::EntitySpecifics entity_specifics;
2352 entity_specifics.mutable_preference()->set_name("name");
2353 entity_specifics.mutable_preference()->set_value("value");
2354 MakeServerNode(sync_manager_.GetUserShare(),
2355 PREFERENCES,
2356 "short_title",
2357 syncable::GenerateSyncableHash(PREFERENCES,
2358 kClientTag),
2359 entity_specifics);
2360 // New node shouldn't start off unsynced.
2361 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2363 // Manually change to the long title. Should set is_unsynced.
2365 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2366 WriteNode node(&trans);
2367 EXPECT_EQ(BaseNode::INIT_OK,
2368 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2369 node.SetTitle(title);
2370 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2372 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2374 // Manually change to the same title. Should not set is_unsynced.
2376 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2377 WriteNode node(&trans);
2378 EXPECT_EQ(BaseNode::INIT_OK,
2379 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2380 node.SetTitle(title);
2381 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2383 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2385 // Manually change to new title. Should set is_unsynced.
2387 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2388 WriteNode node(&trans);
2389 EXPECT_EQ(BaseNode::INIT_OK,
2390 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2391 node.SetTitle("title2");
2393 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2396 // Create an encrypted entry when the cryptographer doesn't think the type is
2397 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2398 // the data.
2399 TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) {
2400 std::string client_tag = "tag";
2401 std::string url = "url";
2402 std::string url2 = "new_url";
2403 std::string title = "title";
2404 sync_pb::EntitySpecifics entity_specifics;
2405 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2407 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2408 Cryptographer* crypto = trans.GetCryptographer();
2409 sync_pb::EntitySpecifics bm_specifics;
2410 bm_specifics.mutable_bookmark()->set_title("title");
2411 bm_specifics.mutable_bookmark()->set_url("url");
2412 sync_pb::EncryptedData encrypted;
2413 crypto->Encrypt(bm_specifics, &encrypted);
2414 entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
2415 AddDefaultFieldValue(BOOKMARKS, &entity_specifics);
2417 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2418 syncable::GenerateSyncableHash(BOOKMARKS,
2419 client_tag),
2420 entity_specifics);
2423 // Verify the data.
2424 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2425 ReadNode node(&trans);
2426 EXPECT_EQ(BaseNode::INIT_OK,
2427 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2428 EXPECT_EQ(title, node.GetTitle());
2429 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
2433 // Overwrite the url (which overwrites the specifics).
2434 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2435 WriteNode node(&trans);
2436 EXPECT_EQ(BaseNode::INIT_OK,
2437 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2439 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
2440 bookmark_specifics.set_url(url2);
2441 node.SetBookmarkSpecifics(bookmark_specifics);
2445 // Verify it's still encrypted and it has the most recent url.
2446 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2447 ReadNode node(&trans);
2448 EXPECT_EQ(BaseNode::INIT_OK,
2449 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2450 EXPECT_EQ(title, node.GetTitle());
2451 EXPECT_EQ(url2, node.GetBookmarkSpecifics().url());
2452 const syncable::Entry* node_entry = node.GetEntry();
2453 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2454 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2455 EXPECT_TRUE(specifics.has_encrypted());
2459 // Verify transaction version of a model type is incremented when node of
2460 // that type is updated.
2461 TEST_F(SyncManagerTest, IncrementTransactionVersion) {
2462 ModelSafeRoutingInfo routing_info;
2463 GetModelSafeRoutingInfo(&routing_info);
2466 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2467 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2468 i != routing_info.end(); ++i) {
2469 // Transaction version is incremented when SyncManagerTest::SetUp()
2470 // creates a node of each type.
2471 EXPECT_EQ(1,
2472 sync_manager_.GetUserShare()->directory->
2473 GetTransactionVersion(i->first));
2477 // Create bookmark node to increment transaction version of bookmark model.
2478 std::string client_tag = "title";
2479 sync_pb::EntitySpecifics entity_specifics;
2480 entity_specifics.mutable_bookmark()->set_url("url");
2481 entity_specifics.mutable_bookmark()->set_title("title");
2482 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2483 syncable::GenerateSyncableHash(BOOKMARKS,
2484 client_tag),
2485 entity_specifics);
2488 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2489 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2490 i != routing_info.end(); ++i) {
2491 EXPECT_EQ(i->first == BOOKMARKS ? 2 : 1,
2492 sync_manager_.GetUserShare()->directory->
2493 GetTransactionVersion(i->first));
2498 class MockSyncScheduler : public FakeSyncScheduler {
2499 public:
2500 MockSyncScheduler() : FakeSyncScheduler() {}
2501 virtual ~MockSyncScheduler() {}
2503 MOCK_METHOD2(Start, void(SyncScheduler::Mode, base::Time));
2504 MOCK_METHOD1(ScheduleConfiguration, void(const ConfigurationParams&));
2507 class ComponentsFactory : public TestInternalComponentsFactory {
2508 public:
2509 ComponentsFactory(const Switches& switches,
2510 SyncScheduler* scheduler_to_use,
2511 sessions::SyncSessionContext** session_context,
2512 InternalComponentsFactory::StorageOption* storage_used)
2513 : TestInternalComponentsFactory(
2514 switches, InternalComponentsFactory::STORAGE_IN_MEMORY, storage_used),
2515 scheduler_to_use_(scheduler_to_use),
2516 session_context_(session_context) {}
2517 ~ComponentsFactory() override {}
2519 scoped_ptr<SyncScheduler> BuildScheduler(
2520 const std::string& name,
2521 sessions::SyncSessionContext* context,
2522 CancelationSignal* stop_handle) override {
2523 *session_context_ = context;
2524 return scheduler_to_use_.Pass();
2527 private:
2528 scoped_ptr<SyncScheduler> scheduler_to_use_;
2529 sessions::SyncSessionContext** session_context_;
2532 class SyncManagerTestWithMockScheduler : public SyncManagerTest {
2533 public:
2534 SyncManagerTestWithMockScheduler() : scheduler_(NULL) {}
2535 InternalComponentsFactory* GetFactory() override {
2536 scheduler_ = new MockSyncScheduler();
2537 return new ComponentsFactory(GetSwitches(), scheduler_, &session_context_,
2538 &storage_used_);
2541 MockSyncScheduler* scheduler() { return scheduler_; }
2542 sessions::SyncSessionContext* session_context() {
2543 return session_context_;
2546 private:
2547 MockSyncScheduler* scheduler_;
2548 sessions::SyncSessionContext* session_context_;
2551 // Test that the configuration params are properly created and sent to
2552 // ScheduleConfigure. No callback should be invoked. Any disabled datatypes
2553 // should be purged.
2554 TEST_F(SyncManagerTestWithMockScheduler, BasicConfiguration) {
2555 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2556 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2557 ModelSafeRoutingInfo new_routing_info;
2558 GetModelSafeRoutingInfo(&new_routing_info);
2559 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2560 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2562 ConfigurationParams params;
2563 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE, _));
2564 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2565 WillOnce(SaveArg<0>(&params));
2567 // Set data for all types.
2568 ModelTypeSet protocol_types = ProtocolTypes();
2569 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2570 iter.Inc()) {
2571 SetProgressMarkerForType(iter.Get(), true);
2574 CallbackCounter ready_task_counter, retry_task_counter;
2575 sync_manager_.ConfigureSyncer(
2576 reason,
2577 types_to_download,
2578 disabled_types,
2579 ModelTypeSet(),
2580 ModelTypeSet(),
2581 new_routing_info,
2582 base::Bind(&CallbackCounter::Callback,
2583 base::Unretained(&ready_task_counter)),
2584 base::Bind(&CallbackCounter::Callback,
2585 base::Unretained(&retry_task_counter)));
2586 EXPECT_EQ(0, ready_task_counter.times_called());
2587 EXPECT_EQ(0, retry_task_counter.times_called());
2588 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2589 params.source);
2590 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2591 EXPECT_EQ(new_routing_info, params.routing_info);
2593 // Verify all the disabled types were purged.
2594 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().Equals(
2595 enabled_types));
2596 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2597 ModelTypeSet::All()).Equals(disabled_types));
2600 // Test that on a reconfiguration (configuration where the session context
2601 // already has routing info), only those recently disabled types are purged.
2602 TEST_F(SyncManagerTestWithMockScheduler, ReConfiguration) {
2603 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2604 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2605 ModelTypeSet disabled_types = ModelTypeSet(THEMES, SESSIONS);
2606 ModelSafeRoutingInfo old_routing_info;
2607 ModelSafeRoutingInfo new_routing_info;
2608 GetModelSafeRoutingInfo(&old_routing_info);
2609 new_routing_info = old_routing_info;
2610 new_routing_info.erase(THEMES);
2611 new_routing_info.erase(SESSIONS);
2612 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2614 ConfigurationParams params;
2615 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE, _));
2616 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2617 WillOnce(SaveArg<0>(&params));
2619 // Set data for all types except those recently disabled (so we can verify
2620 // only those recently disabled are purged) .
2621 ModelTypeSet protocol_types = ProtocolTypes();
2622 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2623 iter.Inc()) {
2624 if (!disabled_types.Has(iter.Get())) {
2625 SetProgressMarkerForType(iter.Get(), true);
2626 } else {
2627 SetProgressMarkerForType(iter.Get(), false);
2631 // Set the context to have the old routing info.
2632 session_context()->SetRoutingInfo(old_routing_info);
2634 CallbackCounter ready_task_counter, retry_task_counter;
2635 sync_manager_.ConfigureSyncer(
2636 reason,
2637 types_to_download,
2638 ModelTypeSet(),
2639 ModelTypeSet(),
2640 ModelTypeSet(),
2641 new_routing_info,
2642 base::Bind(&CallbackCounter::Callback,
2643 base::Unretained(&ready_task_counter)),
2644 base::Bind(&CallbackCounter::Callback,
2645 base::Unretained(&retry_task_counter)));
2646 EXPECT_EQ(0, ready_task_counter.times_called());
2647 EXPECT_EQ(0, retry_task_counter.times_called());
2648 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2649 params.source);
2650 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2651 EXPECT_EQ(new_routing_info, params.routing_info);
2653 // Verify only the recently disabled types were purged.
2654 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2655 ProtocolTypes()).Equals(disabled_types));
2658 // Test that SyncManager::ClearServerData invokes the scheduler.
2659 TEST_F(SyncManagerTestWithMockScheduler, ClearServerData) {
2660 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CLEAR_SERVER_DATA_MODE, _));
2661 CallbackCounter callback_counter;
2662 sync_manager_.ClearServerData(base::Bind(
2663 &CallbackCounter::Callback, base::Unretained(&callback_counter)));
2664 PumpLoop();
2665 EXPECT_EQ(1, callback_counter.times_called());
2668 // Test that PurgePartiallySyncedTypes purges only those types that have not
2669 // fully completed their initial download and apply.
2670 TEST_F(SyncManagerTest, PurgePartiallySyncedTypes) {
2671 ModelSafeRoutingInfo routing_info;
2672 GetModelSafeRoutingInfo(&routing_info);
2673 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2675 UserShare* share = sync_manager_.GetUserShare();
2677 // The test harness automatically initializes all types in the routing info.
2678 // Check that autofill is not among them.
2679 ASSERT_FALSE(enabled_types.Has(AUTOFILL));
2681 // Further ensure that the test harness did not create its root node.
2683 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2684 syncable::Entry autofill_root_node(&trans,
2685 syncable::GET_TYPE_ROOT,
2686 AUTOFILL);
2687 ASSERT_FALSE(autofill_root_node.good());
2690 // One more redundant check.
2691 ASSERT_FALSE(sync_manager_.InitialSyncEndedTypes().Has(AUTOFILL));
2693 // Give autofill a progress marker.
2694 sync_pb::DataTypeProgressMarker autofill_marker;
2695 autofill_marker.set_data_type_id(
2696 GetSpecificsFieldNumberFromModelType(AUTOFILL));
2697 autofill_marker.set_token("token");
2698 share->directory->SetDownloadProgress(AUTOFILL, autofill_marker);
2700 // Also add a pending autofill root node update from the server.
2701 TestEntryFactory factory_(share->directory.get());
2702 int autofill_meta = factory_.CreateUnappliedRootNode(AUTOFILL);
2704 // Preferences is an enabled type. Check that the harness initialized it.
2705 ASSERT_TRUE(enabled_types.Has(PREFERENCES));
2706 ASSERT_TRUE(sync_manager_.InitialSyncEndedTypes().Has(PREFERENCES));
2708 // Give preferencse a progress marker.
2709 sync_pb::DataTypeProgressMarker prefs_marker;
2710 prefs_marker.set_data_type_id(
2711 GetSpecificsFieldNumberFromModelType(PREFERENCES));
2712 prefs_marker.set_token("token");
2713 share->directory->SetDownloadProgress(PREFERENCES, prefs_marker);
2715 // Add a fully synced preferences node under the root.
2716 std::string pref_client_tag = "prefABC";
2717 std::string pref_hashed_tag = "hashXYZ";
2718 sync_pb::EntitySpecifics pref_specifics;
2719 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2720 int pref_meta = MakeServerNode(
2721 share, PREFERENCES, pref_client_tag, pref_hashed_tag, pref_specifics);
2723 // And now, the purge.
2724 EXPECT_TRUE(sync_manager_.PurgePartiallySyncedTypes());
2726 // Ensure that autofill lost its progress marker, but preferences did not.
2727 ModelTypeSet empty_tokens =
2728 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
2729 EXPECT_TRUE(empty_tokens.Has(AUTOFILL));
2730 EXPECT_FALSE(empty_tokens.Has(PREFERENCES));
2732 // Ensure that autofill lots its node, but preferences did not.
2734 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2735 syncable::Entry autofill_node(&trans, GET_BY_HANDLE, autofill_meta);
2736 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref_meta);
2737 EXPECT_FALSE(autofill_node.good());
2738 EXPECT_TRUE(pref_node.good());
2742 // Test CleanupDisabledTypes properly purges all disabled types as specified
2743 // by the previous and current enabled params.
2744 TEST_F(SyncManagerTest, PurgeDisabledTypes) {
2745 ModelSafeRoutingInfo routing_info;
2746 GetModelSafeRoutingInfo(&routing_info);
2747 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2748 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2750 // The harness should have initialized the enabled_types for us.
2751 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2753 // Set progress markers for all types.
2754 ModelTypeSet protocol_types = ProtocolTypes();
2755 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2756 iter.Inc()) {
2757 SetProgressMarkerForType(iter.Get(), true);
2760 // Verify all the enabled types remain after cleanup, and all the disabled
2761 // types were purged.
2762 sync_manager_.PurgeDisabledTypes(disabled_types,
2763 ModelTypeSet(),
2764 ModelTypeSet());
2765 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2766 EXPECT_TRUE(disabled_types.Equals(
2767 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2769 // Disable some more types.
2770 disabled_types.Put(BOOKMARKS);
2771 disabled_types.Put(PREFERENCES);
2772 ModelTypeSet new_enabled_types =
2773 Difference(ModelTypeSet::All(), disabled_types);
2775 // Verify only the non-disabled types remain after cleanup.
2776 sync_manager_.PurgeDisabledTypes(disabled_types,
2777 ModelTypeSet(),
2778 ModelTypeSet());
2779 EXPECT_TRUE(new_enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2780 EXPECT_TRUE(disabled_types.Equals(
2781 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2784 // Test PurgeDisabledTypes properly unapplies types by deleting their local data
2785 // and preserving their server data and progress marker.
2786 TEST_F(SyncManagerTest, PurgeUnappliedTypes) {
2787 ModelSafeRoutingInfo routing_info;
2788 GetModelSafeRoutingInfo(&routing_info);
2789 ModelTypeSet unapplied_types = ModelTypeSet(BOOKMARKS, PREFERENCES);
2790 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2791 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2793 // The harness should have initialized the enabled_types for us.
2794 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2796 // Set progress markers for all types.
2797 ModelTypeSet protocol_types = ProtocolTypes();
2798 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2799 iter.Inc()) {
2800 SetProgressMarkerForType(iter.Get(), true);
2803 // Add the following kinds of items:
2804 // 1. Fully synced preference.
2805 // 2. Locally created preference, server unknown, unsynced
2806 // 3. Locally deleted preference, server known, unsynced
2807 // 4. Server deleted preference, locally known.
2808 // 5. Server created preference, locally unknown, unapplied.
2809 // 6. A fully synced bookmark (no unique_client_tag).
2810 UserShare* share = sync_manager_.GetUserShare();
2811 sync_pb::EntitySpecifics pref_specifics;
2812 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2813 sync_pb::EntitySpecifics bm_specifics;
2814 AddDefaultFieldValue(BOOKMARKS, &bm_specifics);
2815 int pref1_meta = MakeServerNode(
2816 share, PREFERENCES, "pref1", "hash1", pref_specifics);
2817 int64 pref2_meta = MakeNodeWithRoot(share, PREFERENCES, "pref2");
2818 int pref3_meta = MakeServerNode(
2819 share, PREFERENCES, "pref3", "hash3", pref_specifics);
2820 int pref4_meta = MakeServerNode(
2821 share, PREFERENCES, "pref4", "hash4", pref_specifics);
2822 int pref5_meta = MakeServerNode(
2823 share, PREFERENCES, "pref5", "hash5", pref_specifics);
2824 int bookmark_meta = MakeServerNode(
2825 share, BOOKMARKS, "bookmark", "", bm_specifics);
2828 syncable::WriteTransaction trans(FROM_HERE,
2829 syncable::SYNCER,
2830 share->directory.get());
2831 // Pref's 1 and 2 are already set up properly.
2832 // Locally delete pref 3.
2833 syncable::MutableEntry pref3(&trans, GET_BY_HANDLE, pref3_meta);
2834 pref3.PutIsDel(true);
2835 pref3.PutIsUnsynced(true);
2836 // Delete pref 4 at the server.
2837 syncable::MutableEntry pref4(&trans, GET_BY_HANDLE, pref4_meta);
2838 pref4.PutServerIsDel(true);
2839 pref4.PutIsUnappliedUpdate(true);
2840 pref4.PutServerVersion(2);
2841 // Pref 5 is an new unapplied update.
2842 syncable::MutableEntry pref5(&trans, GET_BY_HANDLE, pref5_meta);
2843 pref5.PutIsUnappliedUpdate(true);
2844 pref5.PutIsDel(true);
2845 pref5.PutBaseVersion(-1);
2846 // Bookmark is already set up properly
2849 // Take a snapshot to clear all the dirty bits.
2850 share->directory.get()->SaveChanges();
2852 // Now request a purge for the unapplied types.
2853 disabled_types.PutAll(unapplied_types);
2854 sync_manager_.PurgeDisabledTypes(disabled_types,
2855 ModelTypeSet(),
2856 unapplied_types);
2858 // Verify the unapplied types still have progress markers and initial sync
2859 // ended after cleanup.
2860 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().HasAll(unapplied_types));
2861 EXPECT_TRUE(
2862 sync_manager_.GetTypesWithEmptyProgressMarkerToken(unapplied_types).
2863 Empty());
2865 // Ensure the items were unapplied as necessary.
2867 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2868 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref1_meta);
2869 ASSERT_TRUE(pref_node.good());
2870 EXPECT_TRUE(pref_node.GetKernelCopy().is_dirty());
2871 EXPECT_FALSE(pref_node.GetIsUnsynced());
2872 EXPECT_TRUE(pref_node.GetIsUnappliedUpdate());
2873 EXPECT_TRUE(pref_node.GetIsDel());
2874 EXPECT_GT(pref_node.GetServerVersion(), 0);
2875 EXPECT_EQ(pref_node.GetBaseVersion(), -1);
2877 // Pref 2 should just be locally deleted.
2878 syncable::Entry pref2_node(&trans, GET_BY_HANDLE, pref2_meta);
2879 ASSERT_TRUE(pref2_node.good());
2880 EXPECT_TRUE(pref2_node.GetKernelCopy().is_dirty());
2881 EXPECT_FALSE(pref2_node.GetIsUnsynced());
2882 EXPECT_TRUE(pref2_node.GetIsDel());
2883 EXPECT_FALSE(pref2_node.GetIsUnappliedUpdate());
2884 EXPECT_TRUE(pref2_node.GetIsDel());
2885 EXPECT_EQ(pref2_node.GetServerVersion(), 0);
2886 EXPECT_EQ(pref2_node.GetBaseVersion(), -1);
2888 syncable::Entry pref3_node(&trans, GET_BY_HANDLE, pref3_meta);
2889 ASSERT_TRUE(pref3_node.good());
2890 EXPECT_TRUE(pref3_node.GetKernelCopy().is_dirty());
2891 EXPECT_FALSE(pref3_node.GetIsUnsynced());
2892 EXPECT_TRUE(pref3_node.GetIsUnappliedUpdate());
2893 EXPECT_TRUE(pref3_node.GetIsDel());
2894 EXPECT_GT(pref3_node.GetServerVersion(), 0);
2895 EXPECT_EQ(pref3_node.GetBaseVersion(), -1);
2897 syncable::Entry pref4_node(&trans, GET_BY_HANDLE, pref4_meta);
2898 ASSERT_TRUE(pref4_node.good());
2899 EXPECT_TRUE(pref4_node.GetKernelCopy().is_dirty());
2900 EXPECT_FALSE(pref4_node.GetIsUnsynced());
2901 EXPECT_TRUE(pref4_node.GetIsUnappliedUpdate());
2902 EXPECT_TRUE(pref4_node.GetIsDel());
2903 EXPECT_GT(pref4_node.GetServerVersion(), 0);
2904 EXPECT_EQ(pref4_node.GetBaseVersion(), -1);
2906 // Pref 5 should remain untouched.
2907 syncable::Entry pref5_node(&trans, GET_BY_HANDLE, pref5_meta);
2908 ASSERT_TRUE(pref5_node.good());
2909 EXPECT_FALSE(pref5_node.GetKernelCopy().is_dirty());
2910 EXPECT_FALSE(pref5_node.GetIsUnsynced());
2911 EXPECT_TRUE(pref5_node.GetIsUnappliedUpdate());
2912 EXPECT_TRUE(pref5_node.GetIsDel());
2913 EXPECT_GT(pref5_node.GetServerVersion(), 0);
2914 EXPECT_EQ(pref5_node.GetBaseVersion(), -1);
2916 syncable::Entry bookmark_node(&trans, GET_BY_HANDLE, bookmark_meta);
2917 ASSERT_TRUE(bookmark_node.good());
2918 EXPECT_TRUE(bookmark_node.GetKernelCopy().is_dirty());
2919 EXPECT_FALSE(bookmark_node.GetIsUnsynced());
2920 EXPECT_TRUE(bookmark_node.GetIsUnappliedUpdate());
2921 EXPECT_TRUE(bookmark_node.GetIsDel());
2922 EXPECT_GT(bookmark_node.GetServerVersion(), 0);
2923 EXPECT_EQ(bookmark_node.GetBaseVersion(), -1);
2927 // A test harness to exercise the code that processes and passes changes from
2928 // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
2929 // ChangeProcessor.
2930 class SyncManagerChangeProcessingTest : public SyncManagerTest {
2931 public:
2932 void OnChangesApplied(ModelType model_type,
2933 int64 model_version,
2934 const BaseTransaction* trans,
2935 const ImmutableChangeRecordList& changes) override {
2936 last_changes_ = changes;
2939 void OnChangesComplete(ModelType model_type) override {}
2941 const ImmutableChangeRecordList& GetRecentChangeList() {
2942 return last_changes_;
2945 UserShare* share() {
2946 return sync_manager_.GetUserShare();
2949 // Set some flags so our nodes reasonably approximate the real world scenario
2950 // and can get past CheckTreeInvariants.
2952 // It's never going to be truly accurate, since we're squashing update
2953 // receipt, processing and application into a single transaction.
2954 void SetNodeProperties(syncable::MutableEntry *entry) {
2955 entry->PutId(id_factory_.NewServerId());
2956 entry->PutBaseVersion(10);
2957 entry->PutServerVersion(10);
2960 // Looks for the given change in the list. Returns the index at which it was
2961 // found. Returns -1 on lookup failure.
2962 size_t FindChangeInList(int64 id, ChangeRecord::Action action) {
2963 SCOPED_TRACE(id);
2964 for (size_t i = 0; i < last_changes_.Get().size(); ++i) {
2965 if (last_changes_.Get()[i].id == id
2966 && last_changes_.Get()[i].action == action) {
2967 return i;
2970 ADD_FAILURE() << "Failed to find specified change";
2971 return static_cast<size_t>(-1);
2974 // Returns the current size of the change list.
2976 // Note that spurious changes do not necessarily indicate a problem.
2977 // Assertions on change list size can help detect problems, but it may be
2978 // necessary to reduce their strictness if the implementation changes.
2979 size_t GetChangeListSize() {
2980 return last_changes_.Get().size();
2983 void ClearChangeList() { last_changes_ = ImmutableChangeRecordList(); }
2985 protected:
2986 ImmutableChangeRecordList last_changes_;
2987 TestIdFactory id_factory_;
2990 // Test creation of a folder and a bookmark.
2991 TEST_F(SyncManagerChangeProcessingTest, AddBookmarks) {
2992 int64 type_root = GetIdForDataType(BOOKMARKS);
2993 int64 folder_id = kInvalidId;
2994 int64 child_id = kInvalidId;
2996 // Create a folder and a bookmark under it.
2998 syncable::WriteTransaction trans(
2999 FROM_HERE, syncable::SYNCER, share()->directory.get());
3000 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3001 ASSERT_TRUE(root.good());
3003 syncable::MutableEntry folder(&trans, syncable::CREATE,
3004 BOOKMARKS, root.GetId(), "folder");
3005 ASSERT_TRUE(folder.good());
3006 SetNodeProperties(&folder);
3007 folder.PutIsDir(true);
3008 folder_id = folder.GetMetahandle();
3010 syncable::MutableEntry child(&trans, syncable::CREATE,
3011 BOOKMARKS, folder.GetId(), "child");
3012 ASSERT_TRUE(child.good());
3013 SetNodeProperties(&child);
3014 child_id = child.GetMetahandle();
3017 // The closing of the above scope will delete the transaction. Its processed
3018 // changes should be waiting for us in a member of the test harness.
3019 EXPECT_EQ(2UL, GetChangeListSize());
3021 // We don't need to check these return values here. The function will add a
3022 // non-fatal failure if these changes are not found.
3023 size_t folder_change_pos =
3024 FindChangeInList(folder_id, ChangeRecord::ACTION_ADD);
3025 size_t child_change_pos =
3026 FindChangeInList(child_id, ChangeRecord::ACTION_ADD);
3028 // Parents are delivered before children.
3029 EXPECT_LT(folder_change_pos, child_change_pos);
3032 // Test creation of a preferences (with implicit parent Id)
3033 TEST_F(SyncManagerChangeProcessingTest, AddPreferences) {
3034 int64 item1_id = kInvalidId;
3035 int64 item2_id = kInvalidId;
3037 // Create two preferences.
3039 syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
3040 share()->directory.get());
3042 syncable::MutableEntry item1(&trans, syncable::CREATE, PREFERENCES,
3043 "test_item_1");
3044 ASSERT_TRUE(item1.good());
3045 SetNodeProperties(&item1);
3046 item1_id = item1.GetMetahandle();
3048 // Need at least two items to ensure hitting all possible codepaths in
3049 // ChangeReorderBuffer::Traversal::ExpandToInclude.
3050 syncable::MutableEntry item2(&trans, syncable::CREATE, PREFERENCES,
3051 "test_item_2");
3052 ASSERT_TRUE(item2.good());
3053 SetNodeProperties(&item2);
3054 item2_id = item2.GetMetahandle();
3057 // The closing of the above scope will delete the transaction. Its processed
3058 // changes should be waiting for us in a member of the test harness.
3059 EXPECT_EQ(2UL, GetChangeListSize());
3061 FindChangeInList(item1_id, ChangeRecord::ACTION_ADD);
3062 FindChangeInList(item2_id, ChangeRecord::ACTION_ADD);
3065 // Test moving a bookmark into an empty folder.
3066 TEST_F(SyncManagerChangeProcessingTest, MoveBookmarkIntoEmptyFolder) {
3067 int64 type_root = GetIdForDataType(BOOKMARKS);
3068 int64 folder_b_id = kInvalidId;
3069 int64 child_id = kInvalidId;
3071 // Create two folders. Place a child under folder A.
3073 syncable::WriteTransaction trans(
3074 FROM_HERE, syncable::SYNCER, share()->directory.get());
3075 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3076 ASSERT_TRUE(root.good());
3078 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3079 BOOKMARKS, root.GetId(), "folderA");
3080 ASSERT_TRUE(folder_a.good());
3081 SetNodeProperties(&folder_a);
3082 folder_a.PutIsDir(true);
3084 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3085 BOOKMARKS, root.GetId(), "folderB");
3086 ASSERT_TRUE(folder_b.good());
3087 SetNodeProperties(&folder_b);
3088 folder_b.PutIsDir(true);
3089 folder_b_id = folder_b.GetMetahandle();
3091 syncable::MutableEntry child(&trans, syncable::CREATE,
3092 BOOKMARKS, folder_a.GetId(),
3093 "child");
3094 ASSERT_TRUE(child.good());
3095 SetNodeProperties(&child);
3096 child_id = child.GetMetahandle();
3099 // Close that transaction. The above was to setup the initial scenario. The
3100 // real test starts now.
3102 // Move the child from folder A to folder B.
3104 syncable::WriteTransaction trans(
3105 FROM_HERE, syncable::SYNCER, share()->directory.get());
3107 syncable::Entry folder_b(&trans, syncable::GET_BY_HANDLE, folder_b_id);
3108 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3110 child.PutParentId(folder_b.GetId());
3113 EXPECT_EQ(1UL, GetChangeListSize());
3115 // Verify that this was detected as a real change. An early version of the
3116 // UniquePosition code had a bug where moves from one folder to another were
3117 // ignored unless the moved node's UniquePosition value was also changed in
3118 // some way.
3119 FindChangeInList(child_id, ChangeRecord::ACTION_UPDATE);
3122 // Test moving a bookmark into a non-empty folder.
3123 TEST_F(SyncManagerChangeProcessingTest, MoveIntoPopulatedFolder) {
3124 int64 type_root = GetIdForDataType(BOOKMARKS);
3125 int64 child_a_id = kInvalidId;
3126 int64 child_b_id = kInvalidId;
3128 // Create two folders. Place one child each under folder A and folder B.
3130 syncable::WriteTransaction trans(
3131 FROM_HERE, syncable::SYNCER, share()->directory.get());
3132 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3133 ASSERT_TRUE(root.good());
3135 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3136 BOOKMARKS, root.GetId(), "folderA");
3137 ASSERT_TRUE(folder_a.good());
3138 SetNodeProperties(&folder_a);
3139 folder_a.PutIsDir(true);
3141 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3142 BOOKMARKS, root.GetId(), "folderB");
3143 ASSERT_TRUE(folder_b.good());
3144 SetNodeProperties(&folder_b);
3145 folder_b.PutIsDir(true);
3147 syncable::MutableEntry child_a(&trans, syncable::CREATE,
3148 BOOKMARKS, folder_a.GetId(),
3149 "childA");
3150 ASSERT_TRUE(child_a.good());
3151 SetNodeProperties(&child_a);
3152 child_a_id = child_a.GetMetahandle();
3154 syncable::MutableEntry child_b(&trans, syncable::CREATE,
3155 BOOKMARKS, folder_b.GetId(),
3156 "childB");
3157 SetNodeProperties(&child_b);
3158 child_b_id = child_b.GetMetahandle();
3161 // Close that transaction. The above was to setup the initial scenario. The
3162 // real test starts now.
3165 syncable::WriteTransaction trans(
3166 FROM_HERE, syncable::SYNCER, share()->directory.get());
3168 syncable::MutableEntry child_a(&trans, syncable::GET_BY_HANDLE, child_a_id);
3169 syncable::MutableEntry child_b(&trans, syncable::GET_BY_HANDLE, child_b_id);
3171 // Move child A from folder A to folder B and update its position.
3172 child_a.PutParentId(child_b.GetParentId());
3173 child_a.PutPredecessor(child_b.GetId());
3176 EXPECT_EQ(1UL, GetChangeListSize());
3178 // Verify that only child a is in the change list.
3179 // (This function will add a failure if the lookup fails.)
3180 FindChangeInList(child_a_id, ChangeRecord::ACTION_UPDATE);
3183 // Tests the ordering of deletion changes.
3184 TEST_F(SyncManagerChangeProcessingTest, DeletionsAndChanges) {
3185 int64 type_root = GetIdForDataType(BOOKMARKS);
3186 int64 folder_a_id = kInvalidId;
3187 int64 folder_b_id = kInvalidId;
3188 int64 child_id = kInvalidId;
3190 // Create two folders. Place a child under folder A.
3192 syncable::WriteTransaction trans(
3193 FROM_HERE, syncable::SYNCER, share()->directory.get());
3194 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3195 ASSERT_TRUE(root.good());
3197 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3198 BOOKMARKS, root.GetId(), "folderA");
3199 ASSERT_TRUE(folder_a.good());
3200 SetNodeProperties(&folder_a);
3201 folder_a.PutIsDir(true);
3202 folder_a_id = folder_a.GetMetahandle();
3204 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3205 BOOKMARKS, root.GetId(), "folderB");
3206 ASSERT_TRUE(folder_b.good());
3207 SetNodeProperties(&folder_b);
3208 folder_b.PutIsDir(true);
3209 folder_b_id = folder_b.GetMetahandle();
3211 syncable::MutableEntry child(&trans, syncable::CREATE,
3212 BOOKMARKS, folder_a.GetId(),
3213 "child");
3214 ASSERT_TRUE(child.good());
3215 SetNodeProperties(&child);
3216 child_id = child.GetMetahandle();
3219 // Close that transaction. The above was to setup the initial scenario. The
3220 // real test starts now.
3223 syncable::WriteTransaction trans(
3224 FROM_HERE, syncable::SYNCER, share()->directory.get());
3226 syncable::MutableEntry folder_a(
3227 &trans, syncable::GET_BY_HANDLE, folder_a_id);
3228 syncable::MutableEntry folder_b(
3229 &trans, syncable::GET_BY_HANDLE, folder_b_id);
3230 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3232 // Delete folder B and its child.
3233 child.PutIsDel(true);
3234 folder_b.PutIsDel(true);
3236 // Make an unrelated change to folder A.
3237 folder_a.PutNonUniqueName("NewNameA");
3240 EXPECT_EQ(3UL, GetChangeListSize());
3242 size_t folder_a_pos =
3243 FindChangeInList(folder_a_id, ChangeRecord::ACTION_UPDATE);
3244 size_t folder_b_pos =
3245 FindChangeInList(folder_b_id, ChangeRecord::ACTION_DELETE);
3246 size_t child_pos = FindChangeInList(child_id, ChangeRecord::ACTION_DELETE);
3248 // Deletes should appear before updates.
3249 EXPECT_LT(child_pos, folder_a_pos);
3250 EXPECT_LT(folder_b_pos, folder_a_pos);
3253 // See that attachment metadata changes are not filtered out by
3254 // SyncManagerImpl::VisiblePropertiesDiffer.
3255 TEST_F(SyncManagerChangeProcessingTest, AttachmentMetadataOnlyChanges) {
3256 // Create an article with no attachments. See that a change is generated.
3257 int64 article_id = kInvalidId;
3259 syncable::WriteTransaction trans(
3260 FROM_HERE, syncable::SYNCER, share()->directory.get());
3261 int64 type_root = GetIdForDataType(ARTICLES);
3262 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3263 ASSERT_TRUE(root.good());
3264 syncable::MutableEntry article(
3265 &trans, syncable::CREATE, ARTICLES, root.GetId(), "article");
3266 ASSERT_TRUE(article.good());
3267 SetNodeProperties(&article);
3268 article_id = article.GetMetahandle();
3270 ASSERT_EQ(1UL, GetChangeListSize());
3271 FindChangeInList(article_id, ChangeRecord::ACTION_ADD);
3272 ClearChangeList();
3274 // Modify the article by adding one attachment. Don't touch anything else.
3275 // See that a change is generated.
3277 syncable::WriteTransaction trans(
3278 FROM_HERE, syncable::SYNCER, share()->directory.get());
3279 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3280 sync_pb::AttachmentMetadata metadata;
3281 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3282 article.PutAttachmentMetadata(metadata);
3284 ASSERT_EQ(1UL, GetChangeListSize());
3285 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3286 ClearChangeList();
3288 // Modify the article by replacing its attachment with a different one. See
3289 // that a change is generated.
3291 syncable::WriteTransaction trans(
3292 FROM_HERE, syncable::SYNCER, share()->directory.get());
3293 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3294 sync_pb::AttachmentMetadata metadata = article.GetAttachmentMetadata();
3295 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3296 article.PutAttachmentMetadata(metadata);
3298 ASSERT_EQ(1UL, GetChangeListSize());
3299 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3300 ClearChangeList();
3302 // Modify the article by replacing its attachment metadata with the same
3303 // attachment metadata. No change should be generated.
3305 syncable::WriteTransaction trans(
3306 FROM_HERE, syncable::SYNCER, share()->directory.get());
3307 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3308 article.PutAttachmentMetadata(article.GetAttachmentMetadata());
3310 ASSERT_EQ(0UL, GetChangeListSize());
3313 // During initialization SyncManagerImpl loads sqlite database. If it fails to
3314 // do so it should fail initialization. This test verifies this behavior.
3315 // Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
3316 // InternalComponentsFactory to return DirectoryBackingStore that always fails
3317 // to load.
3318 class SyncManagerInitInvalidStorageTest : public SyncManagerTest {
3319 public:
3320 SyncManagerInitInvalidStorageTest() {
3323 InternalComponentsFactory* GetFactory() override {
3324 return new TestInternalComponentsFactory(
3325 GetSwitches(), InternalComponentsFactory::STORAGE_INVALID,
3326 &storage_used_);
3330 // SyncManagerInitInvalidStorageTest::GetFactory will return
3331 // DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
3332 // SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
3333 // task is to ensure that SyncManagerImpl reported initialization failure in
3334 // OnInitializationComplete callback.
3335 TEST_F(SyncManagerInitInvalidStorageTest, FailToOpenDatabase) {
3336 EXPECT_FALSE(initialization_succeeded_);
3339 } // namespace syncer