crazy linker: Fix incorrect link map l_addr value.
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl_unittest.cc
blob41b2e2df4b812fe06aa8eac08a32809131e66088
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Unit tests for the SyncApi. Note that a lot of the underlying
6 // functionality is provided by the Syncable layer, which has its own
7 // unit tests. We'll test SyncApi specific things in this harness.
9 #include <cstddef>
10 #include <map>
12 #include "base/basictypes.h"
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/files/scoped_temp_dir.h"
16 #include "base/format_macros.h"
17 #include "base/location.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/run_loop.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/test/values_test_util.h"
24 #include "base/values.h"
25 #include "google_apis/gaia/gaia_constants.h"
26 #include "sync/engine/sync_scheduler.h"
27 #include "sync/internal_api/public/base/attachment_id_proto.h"
28 #include "sync/internal_api/public/base/cancelation_signal.h"
29 #include "sync/internal_api/public/base/model_type_test_util.h"
30 #include "sync/internal_api/public/change_record.h"
31 #include "sync/internal_api/public/engine/model_safe_worker.h"
32 #include "sync/internal_api/public/engine/polling_constants.h"
33 #include "sync/internal_api/public/events/protocol_event.h"
34 #include "sync/internal_api/public/http_post_provider_factory.h"
35 #include "sync/internal_api/public/http_post_provider_interface.h"
36 #include "sync/internal_api/public/read_node.h"
37 #include "sync/internal_api/public/read_transaction.h"
38 #include "sync/internal_api/public/test/test_entry_factory.h"
39 #include "sync/internal_api/public/test/test_internal_components_factory.h"
40 #include "sync/internal_api/public/test/test_user_share.h"
41 #include "sync/internal_api/public/write_node.h"
42 #include "sync/internal_api/public/write_transaction.h"
43 #include "sync/internal_api/sync_encryption_handler_impl.h"
44 #include "sync/internal_api/sync_manager_impl.h"
45 #include "sync/internal_api/syncapi_internal.h"
46 #include "sync/js/js_backend.h"
47 #include "sync/js/js_event_handler.h"
48 #include "sync/js/js_test_util.h"
49 #include "sync/protocol/bookmark_specifics.pb.h"
50 #include "sync/protocol/encryption.pb.h"
51 #include "sync/protocol/extension_specifics.pb.h"
52 #include "sync/protocol/password_specifics.pb.h"
53 #include "sync/protocol/preference_specifics.pb.h"
54 #include "sync/protocol/proto_value_conversions.h"
55 #include "sync/protocol/sync.pb.h"
56 #include "sync/sessions/sync_session.h"
57 #include "sync/syncable/directory.h"
58 #include "sync/syncable/entry.h"
59 #include "sync/syncable/mutable_entry.h"
60 #include "sync/syncable/nigori_util.h"
61 #include "sync/syncable/syncable_id.h"
62 #include "sync/syncable/syncable_read_transaction.h"
63 #include "sync/syncable/syncable_util.h"
64 #include "sync/syncable/syncable_write_transaction.h"
65 #include "sync/test/callback_counter.h"
66 #include "sync/test/engine/fake_model_worker.h"
67 #include "sync/test/engine/fake_sync_scheduler.h"
68 #include "sync/test/engine/test_id_factory.h"
69 #include "sync/test/fake_encryptor.h"
70 #include "sync/util/cryptographer.h"
71 #include "sync/util/extensions_activity.h"
72 #include "sync/util/test_unrecoverable_error_handler.h"
73 #include "sync/util/time.h"
74 #include "testing/gmock/include/gmock/gmock.h"
75 #include "testing/gtest/include/gtest/gtest.h"
76 #include "url/gurl.h"
78 using base::ExpectDictStringValue;
79 using testing::_;
80 using testing::DoAll;
81 using testing::InSequence;
82 using testing::Return;
83 using testing::SaveArg;
84 using testing::StrictMock;
86 namespace syncer {
88 using sessions::SyncSessionSnapshot;
89 using syncable::GET_BY_HANDLE;
90 using syncable::IS_DEL;
91 using syncable::IS_UNSYNCED;
92 using syncable::NON_UNIQUE_NAME;
93 using syncable::SPECIFICS;
94 using syncable::kEncryptedString;
96 namespace {
98 // Makes a child node under the type root folder. Returns the id of the
99 // newly-created node.
100 int64 MakeNode(UserShare* share,
101 ModelType model_type,
102 const std::string& client_tag) {
103 WriteTransaction trans(FROM_HERE, share);
104 WriteNode node(&trans);
105 WriteNode::InitUniqueByCreationResult result =
106 node.InitUniqueByCreation(model_type, client_tag);
107 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
108 node.SetIsFolder(false);
109 return node.GetId();
112 // Makes a non-folder child of the root node. Returns the id of the
113 // newly-created node.
114 int64 MakeNodeWithRoot(UserShare* share,
115 ModelType model_type,
116 const std::string& client_tag) {
117 WriteTransaction trans(FROM_HERE, share);
118 ReadNode root_node(&trans);
119 root_node.InitByRootLookup();
120 WriteNode node(&trans);
121 WriteNode::InitUniqueByCreationResult result =
122 node.InitUniqueByCreation(model_type, root_node, client_tag);
123 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
124 node.SetIsFolder(false);
125 return node.GetId();
128 // Makes a folder child of a non-root node. Returns the id of the
129 // newly-created node.
130 int64 MakeFolderWithParent(UserShare* share,
131 ModelType model_type,
132 int64 parent_id,
133 BaseNode* predecessor) {
134 WriteTransaction trans(FROM_HERE, share);
135 ReadNode parent_node(&trans);
136 EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
137 WriteNode node(&trans);
138 EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
139 node.SetIsFolder(true);
140 return node.GetId();
143 int64 MakeBookmarkWithParent(UserShare* share,
144 int64 parent_id,
145 BaseNode* predecessor) {
146 WriteTransaction trans(FROM_HERE, share);
147 ReadNode parent_node(&trans);
148 EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
149 WriteNode node(&trans);
150 EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
151 return node.GetId();
154 // Creates the "synced" root node for a particular datatype. We use the syncable
155 // methods here so that the syncer treats these nodes as if they were already
156 // received from the server.
157 int64 MakeTypeRoot(UserShare* share, ModelType model_type) {
158 sync_pb::EntitySpecifics specifics;
159 AddDefaultFieldValue(model_type, &specifics);
160 syncable::WriteTransaction trans(
161 FROM_HERE, syncable::UNITTEST, share->directory.get());
162 // Attempt to lookup by nigori tag.
163 std::string type_tag = ModelTypeToRootTag(model_type);
164 syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag);
165 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
166 node_id);
167 EXPECT_TRUE(entry.good());
168 entry.PutBaseVersion(1);
169 entry.PutServerVersion(1);
170 entry.PutIsUnappliedUpdate(false);
171 entry.PutParentId(syncable::Id::GetRoot());
172 entry.PutServerParentId(syncable::Id::GetRoot());
173 entry.PutServerIsDir(true);
174 entry.PutIsDir(true);
175 entry.PutServerSpecifics(specifics);
176 entry.PutUniqueServerTag(type_tag);
177 entry.PutNonUniqueName(type_tag);
178 entry.PutIsDel(false);
179 entry.PutSpecifics(specifics);
180 return entry.GetMetahandle();
183 // Simulates creating a "synced" node as a child of the root datatype node.
184 int64 MakeServerNode(UserShare* share, ModelType model_type,
185 const std::string& client_tag,
186 const std::string& hashed_tag,
187 const sync_pb::EntitySpecifics& specifics) {
188 syncable::WriteTransaction trans(
189 FROM_HERE, syncable::UNITTEST, share->directory.get());
190 syncable::Entry root_entry(&trans, syncable::GET_TYPE_ROOT, model_type);
191 EXPECT_TRUE(root_entry.good());
192 syncable::Id root_id = root_entry.GetId();
193 syncable::Id node_id = syncable::Id::CreateFromServerId(client_tag);
194 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
195 node_id);
196 EXPECT_TRUE(entry.good());
197 entry.PutBaseVersion(1);
198 entry.PutServerVersion(1);
199 entry.PutIsUnappliedUpdate(false);
200 entry.PutServerParentId(root_id);
201 entry.PutParentId(root_id);
202 entry.PutServerIsDir(false);
203 entry.PutIsDir(false);
204 entry.PutServerSpecifics(specifics);
205 entry.PutNonUniqueName(client_tag);
206 entry.PutUniqueClientTag(hashed_tag);
207 entry.PutIsDel(false);
208 entry.PutSpecifics(specifics);
209 return entry.GetMetahandle();
212 } // namespace
214 class SyncApiTest : public testing::Test {
215 public:
216 void SetUp() override { test_user_share_.SetUp(); }
218 void TearDown() override { test_user_share_.TearDown(); }
220 protected:
221 // Create an entry with the given |model_type|, |client_tag| and
222 // |attachment_metadata|.
223 void CreateEntryWithAttachmentMetadata(
224 const ModelType& model_type,
225 const std::string& client_tag,
226 const sync_pb::AttachmentMetadata& attachment_metadata);
228 // Attempts to load the entry specified by |model_type| and |client_tag| and
229 // returns the lookup result code.
230 BaseNode::InitByLookupResult LookupEntryByClientTag(
231 const ModelType& model_type,
232 const std::string& client_tag);
234 // Replace the entry specified by |model_type| and |client_tag| with a
235 // tombstone.
236 void ReplaceWithTombstone(const ModelType& model_type,
237 const std::string& client_tag);
239 // Save changes to the Directory, destroy it then reload it.
240 bool ReloadDir();
242 UserShare* user_share();
243 syncable::Directory* dir();
244 SyncEncryptionHandler* encryption_handler();
246 private:
247 base::MessageLoop message_loop_;
248 TestUserShare test_user_share_;
251 UserShare* SyncApiTest::user_share() {
252 return test_user_share_.user_share();
255 syncable::Directory* SyncApiTest::dir() {
256 return test_user_share_.user_share()->directory.get();
259 SyncEncryptionHandler* SyncApiTest::encryption_handler() {
260 return test_user_share_.encryption_handler();
263 bool SyncApiTest::ReloadDir() {
264 return test_user_share_.Reload();
267 void SyncApiTest::CreateEntryWithAttachmentMetadata(
268 const ModelType& model_type,
269 const std::string& client_tag,
270 const sync_pb::AttachmentMetadata& attachment_metadata) {
271 syncer::WriteTransaction trans(FROM_HERE, user_share());
272 syncer::ReadNode root_node(&trans);
273 root_node.InitByRootLookup();
274 syncer::WriteNode node(&trans);
275 ASSERT_EQ(node.InitUniqueByCreation(model_type, root_node, client_tag),
276 syncer::WriteNode::INIT_SUCCESS);
277 node.SetAttachmentMetadata(attachment_metadata);
280 BaseNode::InitByLookupResult SyncApiTest::LookupEntryByClientTag(
281 const ModelType& model_type,
282 const std::string& client_tag) {
283 syncer::ReadTransaction trans(FROM_HERE, user_share());
284 syncer::ReadNode node(&trans);
285 return node.InitByClientTagLookup(model_type, client_tag);
288 void SyncApiTest::ReplaceWithTombstone(const ModelType& model_type,
289 const std::string& client_tag) {
290 syncer::WriteTransaction trans(FROM_HERE, user_share());
291 syncer::WriteNode node(&trans);
292 ASSERT_EQ(node.InitByClientTagLookup(model_type, client_tag),
293 syncer::WriteNode::INIT_OK);
294 node.Tombstone();
297 TEST_F(SyncApiTest, SanityCheckTest) {
299 ReadTransaction trans(FROM_HERE, user_share());
300 EXPECT_TRUE(trans.GetWrappedTrans());
303 WriteTransaction trans(FROM_HERE, user_share());
304 EXPECT_TRUE(trans.GetWrappedTrans());
307 // No entries but root should exist
308 ReadTransaction trans(FROM_HERE, user_share());
309 ReadNode node(&trans);
310 // Metahandle 1 can be root, sanity check 2
311 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByIdLookup(2));
315 TEST_F(SyncApiTest, BasicTagWrite) {
317 ReadTransaction trans(FROM_HERE, user_share());
318 ReadNode root_node(&trans);
319 root_node.InitByRootLookup();
320 EXPECT_EQ(kInvalidId, root_node.GetFirstChildId());
323 ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag"));
326 ReadTransaction trans(FROM_HERE, user_share());
327 ReadNode node(&trans);
328 EXPECT_EQ(BaseNode::INIT_OK,
329 node.InitByClientTagLookup(BOOKMARKS, "testtag"));
330 EXPECT_NE(0, node.GetId());
332 ReadNode root_node(&trans);
333 root_node.InitByRootLookup();
334 EXPECT_EQ(node.GetId(), root_node.GetFirstChildId());
338 TEST_F(SyncApiTest, BasicTagWriteWithImplicitParent) {
339 int64 type_root = MakeTypeRoot(user_share(), PREFERENCES);
342 ReadTransaction trans(FROM_HERE, user_share());
343 ReadNode type_root_node(&trans);
344 EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
345 EXPECT_EQ(kInvalidId, type_root_node.GetFirstChildId());
348 ignore_result(MakeNode(user_share(), PREFERENCES, "testtag"));
351 ReadTransaction trans(FROM_HERE, user_share());
352 ReadNode node(&trans);
353 EXPECT_EQ(BaseNode::INIT_OK,
354 node.InitByClientTagLookup(PREFERENCES, "testtag"));
355 EXPECT_EQ(kInvalidId, node.GetParentId());
357 ReadNode type_root_node(&trans);
358 EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
359 EXPECT_EQ(node.GetId(), type_root_node.GetFirstChildId());
363 TEST_F(SyncApiTest, ModelTypesSiloed) {
365 WriteTransaction trans(FROM_HERE, user_share());
366 ReadNode root_node(&trans);
367 root_node.InitByRootLookup();
368 EXPECT_EQ(root_node.GetFirstChildId(), 0);
371 ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "collideme"));
372 ignore_result(MakeNodeWithRoot(user_share(), PREFERENCES, "collideme"));
373 ignore_result(MakeNodeWithRoot(user_share(), AUTOFILL, "collideme"));
376 ReadTransaction trans(FROM_HERE, user_share());
378 ReadNode bookmarknode(&trans);
379 EXPECT_EQ(BaseNode::INIT_OK,
380 bookmarknode.InitByClientTagLookup(BOOKMARKS,
381 "collideme"));
383 ReadNode prefnode(&trans);
384 EXPECT_EQ(BaseNode::INIT_OK,
385 prefnode.InitByClientTagLookup(PREFERENCES,
386 "collideme"));
388 ReadNode autofillnode(&trans);
389 EXPECT_EQ(BaseNode::INIT_OK,
390 autofillnode.InitByClientTagLookup(AUTOFILL,
391 "collideme"));
393 EXPECT_NE(bookmarknode.GetId(), prefnode.GetId());
394 EXPECT_NE(autofillnode.GetId(), prefnode.GetId());
395 EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId());
399 TEST_F(SyncApiTest, ReadMissingTagsFails) {
401 ReadTransaction trans(FROM_HERE, user_share());
402 ReadNode node(&trans);
403 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
404 node.InitByClientTagLookup(BOOKMARKS,
405 "testtag"));
408 WriteTransaction trans(FROM_HERE, user_share());
409 WriteNode node(&trans);
410 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
411 node.InitByClientTagLookup(BOOKMARKS,
412 "testtag"));
416 // TODO(chron): Hook this all up to the server and write full integration tests
417 // for update->undelete behavior.
418 TEST_F(SyncApiTest, TestDeleteBehavior) {
419 int64 node_id;
420 int64 folder_id;
421 std::string test_title("test1");
424 WriteTransaction trans(FROM_HERE, user_share());
425 ReadNode root_node(&trans);
426 root_node.InitByRootLookup();
428 // we'll use this spare folder later
429 WriteNode folder_node(&trans);
430 EXPECT_TRUE(folder_node.InitBookmarkByCreation(root_node, NULL));
431 folder_id = folder_node.GetId();
433 WriteNode wnode(&trans);
434 WriteNode::InitUniqueByCreationResult result =
435 wnode.InitUniqueByCreation(BOOKMARKS, root_node, "testtag");
436 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
437 wnode.SetIsFolder(false);
438 wnode.SetTitle(test_title);
440 node_id = wnode.GetId();
443 // Ensure we can delete something with a tag.
445 WriteTransaction trans(FROM_HERE, user_share());
446 WriteNode wnode(&trans);
447 EXPECT_EQ(BaseNode::INIT_OK,
448 wnode.InitByClientTagLookup(BOOKMARKS,
449 "testtag"));
450 EXPECT_FALSE(wnode.GetIsFolder());
451 EXPECT_EQ(wnode.GetTitle(), test_title);
453 wnode.Tombstone();
456 // Lookup of a node which was deleted should return failure,
457 // but have found some data about the node.
459 ReadTransaction trans(FROM_HERE, user_share());
460 ReadNode node(&trans);
461 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL,
462 node.InitByClientTagLookup(BOOKMARKS,
463 "testtag"));
464 // Note that for proper function of this API this doesn't need to be
465 // filled, we're checking just to make sure the DB worked in this test.
466 EXPECT_EQ(node.GetTitle(), test_title);
470 WriteTransaction trans(FROM_HERE, user_share());
471 ReadNode folder_node(&trans);
472 EXPECT_EQ(BaseNode::INIT_OK, folder_node.InitByIdLookup(folder_id));
474 WriteNode wnode(&trans);
475 // This will undelete the tag.
476 WriteNode::InitUniqueByCreationResult result =
477 wnode.InitUniqueByCreation(BOOKMARKS, folder_node, "testtag");
478 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
479 EXPECT_EQ(wnode.GetIsFolder(), false);
480 EXPECT_EQ(wnode.GetParentId(), folder_node.GetId());
481 EXPECT_EQ(wnode.GetId(), node_id);
482 EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared
483 wnode.SetTitle(test_title);
486 // Now look up should work.
488 ReadTransaction trans(FROM_HERE, user_share());
489 ReadNode node(&trans);
490 EXPECT_EQ(BaseNode::INIT_OK,
491 node.InitByClientTagLookup(BOOKMARKS,
492 "testtag"));
493 EXPECT_EQ(node.GetTitle(), test_title);
494 EXPECT_EQ(node.GetModelType(), BOOKMARKS);
498 TEST_F(SyncApiTest, WriteAndReadPassword) {
499 KeyParams params = {"localhost", "username", "passphrase"};
501 ReadTransaction trans(FROM_HERE, user_share());
502 trans.GetCryptographer()->AddKey(params);
505 WriteTransaction trans(FROM_HERE, user_share());
506 ReadNode root_node(&trans);
507 root_node.InitByRootLookup();
509 WriteNode password_node(&trans);
510 WriteNode::InitUniqueByCreationResult result =
511 password_node.InitUniqueByCreation(PASSWORDS,
512 root_node, "foo");
513 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
514 sync_pb::PasswordSpecificsData data;
515 data.set_password_value("secret");
516 password_node.SetPasswordSpecifics(data);
519 ReadTransaction trans(FROM_HERE, user_share());
520 ReadNode root_node(&trans);
521 root_node.InitByRootLookup();
523 ReadNode password_node(&trans);
524 EXPECT_EQ(BaseNode::INIT_OK,
525 password_node.InitByClientTagLookup(PASSWORDS, "foo"));
526 const sync_pb::PasswordSpecificsData& data =
527 password_node.GetPasswordSpecifics();
528 EXPECT_EQ("secret", data.password_value());
532 TEST_F(SyncApiTest, WriteEncryptedTitle) {
533 KeyParams params = {"localhost", "username", "passphrase"};
535 ReadTransaction trans(FROM_HERE, user_share());
536 trans.GetCryptographer()->AddKey(params);
538 encryption_handler()->EnableEncryptEverything();
539 int bookmark_id;
541 WriteTransaction trans(FROM_HERE, user_share());
542 ReadNode root_node(&trans);
543 root_node.InitByRootLookup();
545 WriteNode bookmark_node(&trans);
546 ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
547 bookmark_id = bookmark_node.GetId();
548 bookmark_node.SetTitle("foo");
550 WriteNode pref_node(&trans);
551 WriteNode::InitUniqueByCreationResult result =
552 pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar");
553 ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
554 pref_node.SetTitle("bar");
557 ReadTransaction trans(FROM_HERE, user_share());
558 ReadNode root_node(&trans);
559 root_node.InitByRootLookup();
561 ReadNode bookmark_node(&trans);
562 ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
563 EXPECT_EQ("foo", bookmark_node.GetTitle());
564 EXPECT_EQ(kEncryptedString,
565 bookmark_node.GetEntry()->GetNonUniqueName());
567 ReadNode pref_node(&trans);
568 ASSERT_EQ(BaseNode::INIT_OK,
569 pref_node.InitByClientTagLookup(PREFERENCES,
570 "bar"));
571 EXPECT_EQ(kEncryptedString, pref_node.GetTitle());
575 // Non-unique name should not be empty. For bookmarks non-unique name is copied
576 // from bookmark title. This test verifies that setting bookmark title to ""
577 // results in single space title and non-unique name in internal representation.
578 // GetTitle should still return empty string.
579 TEST_F(SyncApiTest, WriteEmptyBookmarkTitle) {
580 int bookmark_id;
582 WriteTransaction trans(FROM_HERE, user_share());
583 ReadNode root_node(&trans);
584 root_node.InitByRootLookup();
586 WriteNode bookmark_node(&trans);
587 ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
588 bookmark_id = bookmark_node.GetId();
589 bookmark_node.SetTitle("");
592 ReadTransaction trans(FROM_HERE, user_share());
593 ReadNode root_node(&trans);
594 root_node.InitByRootLookup();
596 ReadNode bookmark_node(&trans);
597 ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
598 EXPECT_EQ("", bookmark_node.GetTitle());
599 EXPECT_EQ(" ", bookmark_node.GetEntry()->GetSpecifics().bookmark().title());
600 EXPECT_EQ(" ", bookmark_node.GetEntry()->GetNonUniqueName());
604 TEST_F(SyncApiTest, BaseNodeSetSpecifics) {
605 int64 child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
606 WriteTransaction trans(FROM_HERE, user_share());
607 WriteNode node(&trans);
608 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
610 sync_pb::EntitySpecifics entity_specifics;
611 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
613 EXPECT_NE(entity_specifics.SerializeAsString(),
614 node.GetEntitySpecifics().SerializeAsString());
615 node.SetEntitySpecifics(entity_specifics);
616 EXPECT_EQ(entity_specifics.SerializeAsString(),
617 node.GetEntitySpecifics().SerializeAsString());
620 TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) {
621 int64 child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
622 WriteTransaction trans(FROM_HERE, user_share());
623 WriteNode node(&trans);
624 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
625 EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty());
627 sync_pb::EntitySpecifics entity_specifics;
628 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
629 entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100);
630 node.SetEntitySpecifics(entity_specifics);
631 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
633 entity_specifics.mutable_unknown_fields()->Clear();
634 node.SetEntitySpecifics(entity_specifics);
635 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
638 TEST_F(SyncApiTest, EmptyTags) {
639 WriteTransaction trans(FROM_HERE, user_share());
640 ReadNode root_node(&trans);
641 root_node.InitByRootLookup();
642 WriteNode node(&trans);
643 std::string empty_tag;
644 WriteNode::InitUniqueByCreationResult result =
645 node.InitUniqueByCreation(TYPED_URLS, root_node, empty_tag);
646 EXPECT_NE(WriteNode::INIT_SUCCESS, result);
647 EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION,
648 node.InitByClientTagLookup(TYPED_URLS, empty_tag));
651 // Test counting nodes when the type's root node has no children.
652 TEST_F(SyncApiTest, GetTotalNodeCountEmpty) {
653 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
655 ReadTransaction trans(FROM_HERE, user_share());
656 ReadNode type_root_node(&trans);
657 EXPECT_EQ(BaseNode::INIT_OK,
658 type_root_node.InitByIdLookup(type_root));
659 EXPECT_EQ(1, type_root_node.GetTotalNodeCount());
663 // Test counting nodes when there is one child beneath the type's root.
664 TEST_F(SyncApiTest, GetTotalNodeCountOneChild) {
665 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
666 int64 parent = MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL);
668 ReadTransaction trans(FROM_HERE, user_share());
669 ReadNode type_root_node(&trans);
670 EXPECT_EQ(BaseNode::INIT_OK,
671 type_root_node.InitByIdLookup(type_root));
672 EXPECT_EQ(2, type_root_node.GetTotalNodeCount());
673 ReadNode parent_node(&trans);
674 EXPECT_EQ(BaseNode::INIT_OK,
675 parent_node.InitByIdLookup(parent));
676 EXPECT_EQ(1, parent_node.GetTotalNodeCount());
680 // Test counting nodes when there are multiple children beneath the type root,
681 // and one of those children has children of its own.
682 TEST_F(SyncApiTest, GetTotalNodeCountMultipleChildren) {
683 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
684 int64 parent = MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL);
685 ignore_result(MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL));
686 int64 child1 = MakeFolderWithParent(user_share(), BOOKMARKS, parent, NULL);
687 ignore_result(MakeBookmarkWithParent(user_share(), parent, NULL));
688 ignore_result(MakeBookmarkWithParent(user_share(), child1, NULL));
691 ReadTransaction trans(FROM_HERE, user_share());
692 ReadNode type_root_node(&trans);
693 EXPECT_EQ(BaseNode::INIT_OK,
694 type_root_node.InitByIdLookup(type_root));
695 EXPECT_EQ(6, type_root_node.GetTotalNodeCount());
696 ReadNode node(&trans);
697 EXPECT_EQ(BaseNode::INIT_OK,
698 node.InitByIdLookup(parent));
699 EXPECT_EQ(4, node.GetTotalNodeCount());
703 // Verify that Directory keeps track of which attachments are referenced by
704 // which entries.
705 TEST_F(SyncApiTest, AttachmentLinking) {
706 // Add an entry with an attachment.
707 std::string tag1("some tag");
708 syncer::AttachmentId attachment_id(syncer::AttachmentId::Create(0, 0));
709 sync_pb::AttachmentMetadata attachment_metadata;
710 sync_pb::AttachmentMetadataRecord* record = attachment_metadata.add_record();
711 *record->mutable_id() = attachment_id.GetProto();
712 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
713 CreateEntryWithAttachmentMetadata(PREFERENCES, tag1, attachment_metadata);
715 // See that the directory knows it's linked.
716 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
718 // Add a second entry referencing the same attachment.
719 std::string tag2("some other tag");
720 CreateEntryWithAttachmentMetadata(PREFERENCES, tag2, attachment_metadata);
722 // See that the directory knows it's still linked.
723 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
725 // Tombstone the first entry.
726 ReplaceWithTombstone(syncer::PREFERENCES, tag1);
728 // See that the attachment is still considered linked because the entry hasn't
729 // been purged from the Directory.
730 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
732 // Save changes and see that the entry is truly gone.
733 ASSERT_TRUE(dir()->SaveChanges());
734 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag1),
735 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
737 // However, the attachment is still linked.
738 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
740 // Save, destroy, and recreate the directory. See that it's still linked.
741 ASSERT_TRUE(ReloadDir());
742 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
744 // Tombstone the second entry, save changes, see that it's truly gone.
745 ReplaceWithTombstone(syncer::PREFERENCES, tag2);
746 ASSERT_TRUE(dir()->SaveChanges());
747 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag2),
748 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
750 // Finally, the attachment is no longer linked.
751 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
754 namespace {
756 class TestHttpPostProviderInterface : public HttpPostProviderInterface {
757 public:
758 ~TestHttpPostProviderInterface() override {}
760 void SetExtraRequestHeaders(const char* headers) override {}
761 void SetURL(const char* url, int port) override {}
762 void SetPostPayload(const char* content_type,
763 int content_length,
764 const char* content) override {}
765 bool MakeSynchronousPost(int* error_code, int* response_code) override {
766 return false;
768 int GetResponseContentLength() const override { return 0; }
769 const char* GetResponseContent() const override { return ""; }
770 const std::string GetResponseHeaderValue(
771 const std::string& name) const override {
772 return std::string();
774 void Abort() override {}
777 class TestHttpPostProviderFactory : public HttpPostProviderFactory {
778 public:
779 ~TestHttpPostProviderFactory() override {}
780 void Init(const std::string& user_agent) override {}
781 HttpPostProviderInterface* Create() override {
782 return new TestHttpPostProviderInterface();
784 void Destroy(HttpPostProviderInterface* http) override {
785 delete static_cast<TestHttpPostProviderInterface*>(http);
789 class SyncManagerObserverMock : public SyncManager::Observer {
790 public:
791 MOCK_METHOD1(OnSyncCycleCompleted,
792 void(const SyncSessionSnapshot&)); // NOLINT
793 MOCK_METHOD4(OnInitializationComplete,
794 void(const WeakHandle<JsBackend>&,
795 const WeakHandle<DataTypeDebugInfoListener>&,
796 bool,
797 syncer::ModelTypeSet)); // NOLINT
798 MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT
799 MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT
800 MOCK_METHOD1(OnActionableError, void(const SyncProtocolError&)); // NOLINT
801 MOCK_METHOD1(OnMigrationRequested, void(syncer::ModelTypeSet)); // NOLINT
802 MOCK_METHOD1(OnProtocolEvent, void(const ProtocolEvent&)); // NOLINT
805 class SyncEncryptionHandlerObserverMock
806 : public SyncEncryptionHandler::Observer {
807 public:
808 MOCK_METHOD2(OnPassphraseRequired,
809 void(PassphraseRequiredReason,
810 const sync_pb::EncryptedData&)); // NOLINT
811 MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT
812 MOCK_METHOD2(OnBootstrapTokenUpdated,
813 void(const std::string&, BootstrapTokenType type)); // NOLINT
814 MOCK_METHOD2(OnEncryptedTypesChanged,
815 void(ModelTypeSet, bool)); // NOLINT
816 MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT
817 MOCK_METHOD1(OnCryptographerStateChanged, void(Cryptographer*)); // NOLINT
818 MOCK_METHOD2(OnPassphraseTypeChanged, void(PassphraseType,
819 base::Time)); // NOLINT
822 } // namespace
824 class SyncManagerTest : public testing::Test,
825 public SyncManager::ChangeDelegate {
826 protected:
827 enum NigoriStatus {
828 DONT_WRITE_NIGORI,
829 WRITE_TO_NIGORI
832 enum EncryptionStatus {
833 UNINITIALIZED,
834 DEFAULT_ENCRYPTION,
835 FULL_ENCRYPTION
838 SyncManagerTest()
839 : sync_manager_("Test sync manager") {
840 switches_.encryption_method =
841 InternalComponentsFactory::ENCRYPTION_KEYSTORE;
844 virtual ~SyncManagerTest() {
847 // Test implementation.
848 void SetUp() {
849 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
851 extensions_activity_ = new ExtensionsActivity();
853 SyncCredentials credentials;
854 credentials.email = "foo@bar.com";
855 credentials.sync_token = "sometoken";
856 OAuth2TokenService::ScopeSet scope_set;
857 scope_set.insert(GaiaConstants::kChromeSyncOAuth2Scope);
858 credentials.scope_set = scope_set;
860 sync_manager_.AddObserver(&manager_observer_);
861 EXPECT_CALL(manager_observer_, OnInitializationComplete(_, _, _, _)).
862 WillOnce(DoAll(SaveArg<0>(&js_backend_),
863 SaveArg<2>(&initialization_succeeded_)));
865 EXPECT_FALSE(js_backend_.IsInitialized());
867 std::vector<scoped_refptr<ModelSafeWorker> > workers;
868 ModelSafeRoutingInfo routing_info;
869 GetModelSafeRoutingInfo(&routing_info);
871 // This works only because all routing info types are GROUP_PASSIVE.
872 // If we had types in other groups, we would need additional workers
873 // to support them.
874 scoped_refptr<ModelSafeWorker> worker = new FakeModelWorker(GROUP_PASSIVE);
875 workers.push_back(worker);
877 SyncManager::InitArgs args;
878 args.database_location = temp_dir_.path();
879 args.service_url = GURL("https://example.com/");
880 args.post_factory =
881 scoped_ptr<HttpPostProviderFactory>(new TestHttpPostProviderFactory());
882 args.workers = workers;
883 args.extensions_activity = extensions_activity_.get(),
884 args.change_delegate = this;
885 args.credentials = credentials;
886 args.invalidator_client_id = "fake_invalidator_client_id";
887 args.internal_components_factory.reset(GetFactory());
888 args.encryptor = &encryptor_;
889 args.unrecoverable_error_handler.reset(new TestUnrecoverableErrorHandler);
890 args.cancelation_signal = &cancelation_signal_;
891 sync_manager_.Init(&args);
893 sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_);
895 EXPECT_TRUE(js_backend_.IsInitialized());
896 EXPECT_EQ(InternalComponentsFactory::STORAGE_ON_DISK,
897 storage_used_);
899 if (initialization_succeeded_) {
900 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
901 i != routing_info.end(); ++i) {
902 type_roots_[i->first] =
903 MakeTypeRoot(sync_manager_.GetUserShare(), i->first);
907 PumpLoop();
910 void TearDown() {
911 sync_manager_.RemoveObserver(&manager_observer_);
912 sync_manager_.ShutdownOnSyncThread(STOP_SYNC);
913 PumpLoop();
916 void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) {
917 (*out)[NIGORI] = GROUP_PASSIVE;
918 (*out)[DEVICE_INFO] = GROUP_PASSIVE;
919 (*out)[EXPERIMENTS] = GROUP_PASSIVE;
920 (*out)[BOOKMARKS] = GROUP_PASSIVE;
921 (*out)[THEMES] = GROUP_PASSIVE;
922 (*out)[SESSIONS] = GROUP_PASSIVE;
923 (*out)[PASSWORDS] = GROUP_PASSIVE;
924 (*out)[PREFERENCES] = GROUP_PASSIVE;
925 (*out)[PRIORITY_PREFERENCES] = GROUP_PASSIVE;
926 (*out)[ARTICLES] = GROUP_PASSIVE;
929 ModelTypeSet GetEnabledTypes() {
930 ModelSafeRoutingInfo routing_info;
931 GetModelSafeRoutingInfo(&routing_info);
932 return GetRoutingInfoTypes(routing_info);
935 void OnChangesApplied(
936 ModelType model_type,
937 int64 model_version,
938 const BaseTransaction* trans,
939 const ImmutableChangeRecordList& changes) override {}
941 void OnChangesComplete(ModelType model_type) override {}
943 // Helper methods.
944 bool SetUpEncryption(NigoriStatus nigori_status,
945 EncryptionStatus encryption_status) {
946 UserShare* share = sync_manager_.GetUserShare();
948 // We need to create the nigori node as if it were an applied server update.
949 int64 nigori_id = GetIdForDataType(NIGORI);
950 if (nigori_id == kInvalidId)
951 return false;
953 // Set the nigori cryptographer information.
954 if (encryption_status == FULL_ENCRYPTION)
955 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
957 WriteTransaction trans(FROM_HERE, share);
958 Cryptographer* cryptographer = trans.GetCryptographer();
959 if (!cryptographer)
960 return false;
961 if (encryption_status != UNINITIALIZED) {
962 KeyParams params = {"localhost", "dummy", "foobar"};
963 cryptographer->AddKey(params);
964 } else {
965 DCHECK_NE(nigori_status, WRITE_TO_NIGORI);
967 if (nigori_status == WRITE_TO_NIGORI) {
968 sync_pb::NigoriSpecifics nigori;
969 cryptographer->GetKeys(nigori.mutable_encryption_keybag());
970 share->directory->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
971 &nigori,
972 trans.GetWrappedTrans());
973 WriteNode node(&trans);
974 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(nigori_id));
975 node.SetNigoriSpecifics(nigori);
977 return cryptographer->is_ready();
980 int64 GetIdForDataType(ModelType type) {
981 if (type_roots_.count(type) == 0)
982 return 0;
983 return type_roots_[type];
986 void PumpLoop() {
987 base::RunLoop().RunUntilIdle();
990 void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) {
991 js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler,
992 event_handler);
993 PumpLoop();
996 // Looks up an entry by client tag and resets IS_UNSYNCED value to false.
997 // Returns true if entry was previously unsynced, false if IS_UNSYNCED was
998 // already false.
999 bool ResetUnsyncedEntry(ModelType type,
1000 const std::string& client_tag) {
1001 UserShare* share = sync_manager_.GetUserShare();
1002 syncable::WriteTransaction trans(
1003 FROM_HERE, syncable::UNITTEST, share->directory.get());
1004 const std::string hash = syncable::GenerateSyncableHash(type, client_tag);
1005 syncable::MutableEntry entry(&trans, syncable::GET_BY_CLIENT_TAG,
1006 hash);
1007 EXPECT_TRUE(entry.good());
1008 if (!entry.GetIsUnsynced())
1009 return false;
1010 entry.PutIsUnsynced(false);
1011 return true;
1014 virtual InternalComponentsFactory* GetFactory() {
1015 return new TestInternalComponentsFactory(
1016 GetSwitches(), InternalComponentsFactory::STORAGE_IN_MEMORY,
1017 &storage_used_);
1020 // Returns true if we are currently encrypting all sync data. May
1021 // be called on any thread.
1022 bool EncryptEverythingEnabledForTest() {
1023 return sync_manager_.GetEncryptionHandler()->EncryptEverythingEnabled();
1026 // Gets the set of encrypted types from the cryptographer
1027 // Note: opens a transaction. May be called from any thread.
1028 ModelTypeSet GetEncryptedTypes() {
1029 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1030 return GetEncryptedTypesWithTrans(&trans);
1033 ModelTypeSet GetEncryptedTypesWithTrans(BaseTransaction* trans) {
1034 return trans->GetDirectory()->GetNigoriHandler()->
1035 GetEncryptedTypes(trans->GetWrappedTrans());
1038 void SimulateInvalidatorEnabledForTest(bool is_enabled) {
1039 DCHECK(sync_manager_.thread_checker_.CalledOnValidThread());
1040 sync_manager_.SetInvalidatorEnabled(is_enabled);
1043 void SetProgressMarkerForType(ModelType type, bool set) {
1044 if (set) {
1045 sync_pb::DataTypeProgressMarker marker;
1046 marker.set_token("token");
1047 marker.set_data_type_id(GetSpecificsFieldNumberFromModelType(type));
1048 sync_manager_.directory()->SetDownloadProgress(type, marker);
1049 } else {
1050 sync_pb::DataTypeProgressMarker marker;
1051 sync_manager_.directory()->SetDownloadProgress(type, marker);
1055 InternalComponentsFactory::Switches GetSwitches() const {
1056 return switches_;
1059 void ExpectPassphraseAcceptance() {
1060 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1061 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1062 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1065 void SetImplicitPassphraseAndCheck(const std::string& passphrase) {
1066 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1067 passphrase,
1068 false);
1069 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1070 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1073 void SetCustomPassphraseAndCheck(const std::string& passphrase) {
1074 EXPECT_CALL(encryption_observer_,
1075 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1076 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1077 passphrase,
1078 true);
1079 EXPECT_EQ(CUSTOM_PASSPHRASE,
1080 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1083 private:
1084 // Needed by |sync_manager_|.
1085 base::MessageLoop message_loop_;
1086 // Needed by |sync_manager_|.
1087 base::ScopedTempDir temp_dir_;
1088 // Sync Id's for the roots of the enabled datatypes.
1089 std::map<ModelType, int64> type_roots_;
1090 scoped_refptr<ExtensionsActivity> extensions_activity_;
1092 protected:
1093 FakeEncryptor encryptor_;
1094 SyncManagerImpl sync_manager_;
1095 CancelationSignal cancelation_signal_;
1096 WeakHandle<JsBackend> js_backend_;
1097 bool initialization_succeeded_;
1098 StrictMock<SyncManagerObserverMock> manager_observer_;
1099 StrictMock<SyncEncryptionHandlerObserverMock> encryption_observer_;
1100 InternalComponentsFactory::Switches switches_;
1101 InternalComponentsFactory::StorageOption storage_used_;
1104 TEST_F(SyncManagerTest, GetAllNodesForTypeTest) {
1105 ModelSafeRoutingInfo routing_info;
1106 GetModelSafeRoutingInfo(&routing_info);
1107 sync_manager_.StartSyncingNormally(routing_info, base::Time());
1109 scoped_ptr<base::ListValue> node_list(
1110 sync_manager_.GetAllNodesForType(syncer::PREFERENCES));
1112 // Should have one node: the type root node.
1113 ASSERT_EQ(1U, node_list->GetSize());
1115 const base::DictionaryValue* first_result;
1116 ASSERT_TRUE(node_list->GetDictionary(0, &first_result));
1117 EXPECT_TRUE(first_result->HasKey("ID"));
1118 EXPECT_TRUE(first_result->HasKey("NON_UNIQUE_NAME"));
1121 TEST_F(SyncManagerTest, RefreshEncryptionReady) {
1122 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1123 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1124 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1125 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1127 sync_manager_.GetEncryptionHandler()->Init();
1128 PumpLoop();
1130 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1131 EXPECT_TRUE(encrypted_types.Has(PASSWORDS));
1132 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1135 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1136 ReadNode node(&trans);
1137 EXPECT_EQ(BaseNode::INIT_OK,
1138 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1139 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1140 EXPECT_TRUE(nigori.has_encryption_keybag());
1141 Cryptographer* cryptographer = trans.GetCryptographer();
1142 EXPECT_TRUE(cryptographer->is_ready());
1143 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1147 // Attempt to refresh encryption when nigori not downloaded.
1148 TEST_F(SyncManagerTest, RefreshEncryptionNotReady) {
1149 // Don't set up encryption (no nigori node created).
1151 // Should fail. Triggers an OnPassphraseRequired because the cryptographer
1152 // is not ready.
1153 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)).Times(1);
1154 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1155 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1156 sync_manager_.GetEncryptionHandler()->Init();
1157 PumpLoop();
1159 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1160 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1161 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1164 // Attempt to refresh encryption when nigori is empty.
1165 TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) {
1166 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION));
1167 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(1);
1168 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1169 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1171 // Should write to nigori.
1172 sync_manager_.GetEncryptionHandler()->Init();
1173 PumpLoop();
1175 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1176 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1177 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1180 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1181 ReadNode node(&trans);
1182 EXPECT_EQ(BaseNode::INIT_OK,
1183 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1184 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1185 EXPECT_TRUE(nigori.has_encryption_keybag());
1186 Cryptographer* cryptographer = trans.GetCryptographer();
1187 EXPECT_TRUE(cryptographer->is_ready());
1188 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1192 TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) {
1193 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1194 EXPECT_CALL(encryption_observer_,
1195 OnEncryptedTypesChanged(
1196 HasModelTypes(EncryptableUserTypes()), true));
1197 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1198 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1199 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1202 TEST_F(SyncManagerTest, EncryptDataTypesWithData) {
1203 size_t batch_size = 5;
1204 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1206 // Create some unencrypted unsynced data.
1207 int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(),
1208 BOOKMARKS,
1209 GetIdForDataType(BOOKMARKS),
1210 NULL);
1211 // First batch_size nodes are children of folder.
1212 size_t i;
1213 for (i = 0; i < batch_size; ++i) {
1214 MakeBookmarkWithParent(sync_manager_.GetUserShare(), folder, NULL);
1216 // Next batch_size nodes are a different type and on their own.
1217 for (; i < 2*batch_size; ++i) {
1218 MakeNodeWithRoot(sync_manager_.GetUserShare(), SESSIONS,
1219 base::StringPrintf("%" PRIuS "", i));
1221 // Last batch_size nodes are a third type that will not need encryption.
1222 for (; i < 3*batch_size; ++i) {
1223 MakeNodeWithRoot(sync_manager_.GetUserShare(), THEMES,
1224 base::StringPrintf("%" PRIuS "", i));
1228 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1229 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1230 SyncEncryptionHandler::SensitiveTypes()));
1231 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1232 trans.GetWrappedTrans(),
1233 BOOKMARKS,
1234 false /* not encrypted */));
1235 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1236 trans.GetWrappedTrans(),
1237 SESSIONS,
1238 false /* not encrypted */));
1239 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1240 trans.GetWrappedTrans(),
1241 THEMES,
1242 false /* not encrypted */));
1245 EXPECT_CALL(encryption_observer_,
1246 OnEncryptedTypesChanged(
1247 HasModelTypes(EncryptableUserTypes()), true));
1248 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1249 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1250 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1252 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1253 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1254 EncryptableUserTypes()));
1255 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1256 trans.GetWrappedTrans(),
1257 BOOKMARKS,
1258 true /* is encrypted */));
1259 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1260 trans.GetWrappedTrans(),
1261 SESSIONS,
1262 true /* is encrypted */));
1263 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1264 trans.GetWrappedTrans(),
1265 THEMES,
1266 true /* is encrypted */));
1269 // Trigger's a ReEncryptEverything with new passphrase.
1270 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1271 EXPECT_CALL(encryption_observer_,
1272 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1273 ExpectPassphraseAcceptance();
1274 SetCustomPassphraseAndCheck("new_passphrase");
1275 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1277 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1278 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1279 EncryptableUserTypes()));
1280 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1281 trans.GetWrappedTrans(),
1282 BOOKMARKS,
1283 true /* is encrypted */));
1284 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1285 trans.GetWrappedTrans(),
1286 SESSIONS,
1287 true /* is encrypted */));
1288 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1289 trans.GetWrappedTrans(),
1290 THEMES,
1291 true /* is encrypted */));
1293 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1294 // a reencryption and should just notify immediately.
1295 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1296 EXPECT_CALL(encryption_observer_,
1297 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)).Times(0);
1298 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()).Times(0);
1299 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(0);
1300 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1303 // Test that when there are no pending keys and the cryptographer is not
1304 // initialized, we add a key based on the current GAIA password.
1305 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1306 TEST_F(SyncManagerTest, SetInitialGaiaPass) {
1307 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1308 EXPECT_CALL(encryption_observer_,
1309 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1310 ExpectPassphraseAcceptance();
1311 SetImplicitPassphraseAndCheck("new_passphrase");
1312 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1314 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1315 ReadNode node(&trans);
1316 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1317 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1318 Cryptographer* cryptographer = trans.GetCryptographer();
1319 EXPECT_TRUE(cryptographer->is_ready());
1320 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1324 // Test that when there are no pending keys and we have on the old GAIA
1325 // password, we update and re-encrypt everything with the new GAIA password.
1326 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1327 TEST_F(SyncManagerTest, UpdateGaiaPass) {
1328 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1329 Cryptographer verifier(&encryptor_);
1331 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1332 Cryptographer* cryptographer = trans.GetCryptographer();
1333 std::string bootstrap_token;
1334 cryptographer->GetBootstrapToken(&bootstrap_token);
1335 verifier.Bootstrap(bootstrap_token);
1337 EXPECT_CALL(encryption_observer_,
1338 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1339 ExpectPassphraseAcceptance();
1340 SetImplicitPassphraseAndCheck("new_passphrase");
1341 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1343 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1344 Cryptographer* cryptographer = trans.GetCryptographer();
1345 EXPECT_TRUE(cryptographer->is_ready());
1346 // Verify the default key has changed.
1347 sync_pb::EncryptedData encrypted;
1348 cryptographer->GetKeys(&encrypted);
1349 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1353 // Sets a new explicit passphrase. This should update the bootstrap token
1354 // and re-encrypt everything.
1355 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1356 TEST_F(SyncManagerTest, SetPassphraseWithPassword) {
1357 Cryptographer verifier(&encryptor_);
1358 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1360 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1361 // Store the default (soon to be old) key.
1362 Cryptographer* cryptographer = trans.GetCryptographer();
1363 std::string bootstrap_token;
1364 cryptographer->GetBootstrapToken(&bootstrap_token);
1365 verifier.Bootstrap(bootstrap_token);
1367 ReadNode root_node(&trans);
1368 root_node.InitByRootLookup();
1370 WriteNode password_node(&trans);
1371 WriteNode::InitUniqueByCreationResult result =
1372 password_node.InitUniqueByCreation(PASSWORDS,
1373 root_node, "foo");
1374 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1375 sync_pb::PasswordSpecificsData data;
1376 data.set_password_value("secret");
1377 password_node.SetPasswordSpecifics(data);
1379 EXPECT_CALL(encryption_observer_,
1380 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1381 ExpectPassphraseAcceptance();
1382 SetCustomPassphraseAndCheck("new_passphrase");
1383 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1385 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1386 Cryptographer* cryptographer = trans.GetCryptographer();
1387 EXPECT_TRUE(cryptographer->is_ready());
1388 // Verify the default key has changed.
1389 sync_pb::EncryptedData encrypted;
1390 cryptographer->GetKeys(&encrypted);
1391 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1393 ReadNode password_node(&trans);
1394 EXPECT_EQ(BaseNode::INIT_OK,
1395 password_node.InitByClientTagLookup(PASSWORDS,
1396 "foo"));
1397 const sync_pb::PasswordSpecificsData& data =
1398 password_node.GetPasswordSpecifics();
1399 EXPECT_EQ("secret", data.password_value());
1403 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1404 // being encrypted with a new (unprovided) GAIA password, then supply the
1405 // password.
1406 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1407 TEST_F(SyncManagerTest, SupplyPendingGAIAPass) {
1408 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1409 Cryptographer other_cryptographer(&encryptor_);
1411 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1412 Cryptographer* cryptographer = trans.GetCryptographer();
1413 std::string bootstrap_token;
1414 cryptographer->GetBootstrapToken(&bootstrap_token);
1415 other_cryptographer.Bootstrap(bootstrap_token);
1417 // Now update the nigori to reflect the new keys, and update the
1418 // cryptographer to have pending keys.
1419 KeyParams params = {"localhost", "dummy", "passphrase2"};
1420 other_cryptographer.AddKey(params);
1421 WriteNode node(&trans);
1422 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1423 sync_pb::NigoriSpecifics nigori;
1424 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1425 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1426 EXPECT_TRUE(cryptographer->has_pending_keys());
1427 node.SetNigoriSpecifics(nigori);
1429 EXPECT_CALL(encryption_observer_,
1430 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1431 ExpectPassphraseAcceptance();
1432 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
1433 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1434 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1435 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1437 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1438 Cryptographer* cryptographer = trans.GetCryptographer();
1439 EXPECT_TRUE(cryptographer->is_ready());
1440 // Verify we're encrypting with the new key.
1441 sync_pb::EncryptedData encrypted;
1442 cryptographer->GetKeys(&encrypted);
1443 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1447 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1448 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1449 // the current GAIA password and verify the bootstrap token is updated. Then
1450 // supply the old GAIA password, and verify we re-encrypt all data with the
1451 // new GAIA password.
1452 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1453 TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) {
1454 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1455 Cryptographer other_cryptographer(&encryptor_);
1457 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1458 Cryptographer* cryptographer = trans.GetCryptographer();
1459 std::string bootstrap_token;
1460 cryptographer->GetBootstrapToken(&bootstrap_token);
1461 other_cryptographer.Bootstrap(bootstrap_token);
1463 // Now update the nigori to reflect the new keys, and update the
1464 // cryptographer to have pending keys.
1465 KeyParams params = {"localhost", "dummy", "old_gaia"};
1466 other_cryptographer.AddKey(params);
1467 WriteNode node(&trans);
1468 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1469 sync_pb::NigoriSpecifics nigori;
1470 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1471 node.SetNigoriSpecifics(nigori);
1472 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1474 // other_cryptographer now contains all encryption keys, and is encrypting
1475 // with the newest gaia.
1476 KeyParams new_params = {"localhost", "dummy", "new_gaia"};
1477 other_cryptographer.AddKey(new_params);
1479 // The bootstrap token should have been updated. Save it to ensure it's based
1480 // on the new GAIA password.
1481 std::string bootstrap_token;
1482 EXPECT_CALL(encryption_observer_,
1483 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN))
1484 .WillOnce(SaveArg<0>(&bootstrap_token));
1485 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_,_));
1486 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1487 SetImplicitPassphraseAndCheck("new_gaia");
1488 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1489 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1491 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1492 Cryptographer* cryptographer = trans.GetCryptographer();
1493 EXPECT_TRUE(cryptographer->is_initialized());
1494 EXPECT_FALSE(cryptographer->is_ready());
1495 // Verify we're encrypting with the new key, even though we have pending
1496 // keys.
1497 sync_pb::EncryptedData encrypted;
1498 other_cryptographer.GetKeys(&encrypted);
1499 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1501 EXPECT_CALL(encryption_observer_,
1502 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1503 ExpectPassphraseAcceptance();
1504 SetImplicitPassphraseAndCheck("old_gaia");
1506 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1507 Cryptographer* cryptographer = trans.GetCryptographer();
1508 EXPECT_TRUE(cryptographer->is_ready());
1510 // Verify we're encrypting with the new key.
1511 sync_pb::EncryptedData encrypted;
1512 other_cryptographer.GetKeys(&encrypted);
1513 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1515 // Verify the saved bootstrap token is based on the new gaia password.
1516 Cryptographer temp_cryptographer(&encryptor_);
1517 temp_cryptographer.Bootstrap(bootstrap_token);
1518 EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted));
1522 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1523 // being encrypted with an explicit (unprovided) passphrase, then supply the
1524 // passphrase.
1525 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1526 TEST_F(SyncManagerTest, SupplyPendingExplicitPass) {
1527 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1528 Cryptographer other_cryptographer(&encryptor_);
1530 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1531 Cryptographer* cryptographer = trans.GetCryptographer();
1532 std::string bootstrap_token;
1533 cryptographer->GetBootstrapToken(&bootstrap_token);
1534 other_cryptographer.Bootstrap(bootstrap_token);
1536 // Now update the nigori to reflect the new keys, and update the
1537 // cryptographer to have pending keys.
1538 KeyParams params = {"localhost", "dummy", "explicit"};
1539 other_cryptographer.AddKey(params);
1540 WriteNode node(&trans);
1541 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1542 sync_pb::NigoriSpecifics nigori;
1543 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1544 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1545 EXPECT_TRUE(cryptographer->has_pending_keys());
1546 nigori.set_keybag_is_frozen(true);
1547 node.SetNigoriSpecifics(nigori);
1549 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1550 EXPECT_CALL(encryption_observer_,
1551 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1552 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _));
1553 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1554 sync_manager_.GetEncryptionHandler()->Init();
1555 EXPECT_CALL(encryption_observer_,
1556 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1557 ExpectPassphraseAcceptance();
1558 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
1559 EXPECT_EQ(CUSTOM_PASSPHRASE,
1560 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1561 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1563 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1564 Cryptographer* cryptographer = trans.GetCryptographer();
1565 EXPECT_TRUE(cryptographer->is_ready());
1566 // Verify we're encrypting with the new key.
1567 sync_pb::EncryptedData encrypted;
1568 cryptographer->GetKeys(&encrypted);
1569 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1573 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1574 // being encrypted with a new (unprovided) GAIA password, then supply the
1575 // password as a user-provided password.
1576 // This is the android case 7/8.
1577 TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) {
1578 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1579 Cryptographer other_cryptographer(&encryptor_);
1581 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1582 Cryptographer* cryptographer = trans.GetCryptographer();
1583 // Now update the nigori to reflect the new keys, and update the
1584 // cryptographer to have pending keys.
1585 KeyParams params = {"localhost", "dummy", "passphrase"};
1586 other_cryptographer.AddKey(params);
1587 WriteNode node(&trans);
1588 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1589 sync_pb::NigoriSpecifics nigori;
1590 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1591 node.SetNigoriSpecifics(nigori);
1592 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1593 EXPECT_FALSE(cryptographer->is_ready());
1595 EXPECT_CALL(encryption_observer_,
1596 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1597 ExpectPassphraseAcceptance();
1598 SetImplicitPassphraseAndCheck("passphrase");
1599 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1601 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1602 Cryptographer* cryptographer = trans.GetCryptographer();
1603 EXPECT_TRUE(cryptographer->is_ready());
1607 TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) {
1608 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1609 int64 node_id = 0;
1610 std::string tag = "foo";
1612 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1613 ReadNode root_node(&trans);
1614 root_node.InitByRootLookup();
1616 WriteNode password_node(&trans);
1617 WriteNode::InitUniqueByCreationResult result =
1618 password_node.InitUniqueByCreation(PASSWORDS, root_node, tag);
1619 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1620 node_id = password_node.GetId();
1622 EXPECT_CALL(encryption_observer_,
1623 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1624 ExpectPassphraseAcceptance();
1625 SetCustomPassphraseAndCheck("new_passphrase");
1626 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1628 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1629 ReadNode password_node(&trans);
1630 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1631 password_node.InitByClientTagLookup(PASSWORDS,
1632 tag));
1635 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1636 ReadNode password_node(&trans);
1637 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1638 password_node.InitByIdLookup(node_id));
1642 // Friended by WriteNode, so can't be in an anonymouse namespace.
1643 TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) {
1644 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1645 std::string title;
1646 SyncAPINameToServerName("Google", &title);
1647 std::string url = "http://www.google.com";
1648 std::string raw_title2 = ".."; // An invalid cosmo title.
1649 std::string title2;
1650 SyncAPINameToServerName(raw_title2, &title2);
1651 std::string url2 = "http://www.bla.com";
1653 // Create a bookmark using the legacy format.
1654 int64 node_id1 =
1655 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag");
1656 int64 node_id2 =
1657 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag2");
1659 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1660 WriteNode node(&trans);
1661 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1663 sync_pb::EntitySpecifics entity_specifics;
1664 entity_specifics.mutable_bookmark()->set_url(url);
1665 node.SetEntitySpecifics(entity_specifics);
1667 // Set the old style title.
1668 syncable::MutableEntry* node_entry = node.entry_;
1669 node_entry->PutNonUniqueName(title);
1671 WriteNode node2(&trans);
1672 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1674 sync_pb::EntitySpecifics entity_specifics2;
1675 entity_specifics2.mutable_bookmark()->set_url(url2);
1676 node2.SetEntitySpecifics(entity_specifics2);
1678 // Set the old style title.
1679 syncable::MutableEntry* node_entry2 = node2.entry_;
1680 node_entry2->PutNonUniqueName(title2);
1684 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1685 ReadNode node(&trans);
1686 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1687 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1688 EXPECT_EQ(title, node.GetTitle());
1689 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1690 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1692 ReadNode node2(&trans);
1693 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1694 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1695 // We should de-canonicalize the title in GetTitle(), but the title in the
1696 // specifics should be stored in the server legal form.
1697 EXPECT_EQ(raw_title2, node2.GetTitle());
1698 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1699 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1703 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1704 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1705 trans.GetWrappedTrans(),
1706 BOOKMARKS,
1707 false /* not encrypted */));
1710 EXPECT_CALL(encryption_observer_,
1711 OnEncryptedTypesChanged(
1712 HasModelTypes(EncryptableUserTypes()), true));
1713 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1714 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1715 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1718 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1719 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1720 EncryptableUserTypes()));
1721 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1722 trans.GetWrappedTrans(),
1723 BOOKMARKS,
1724 true /* is encrypted */));
1726 ReadNode node(&trans);
1727 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1728 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1729 EXPECT_EQ(title, node.GetTitle());
1730 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1731 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1733 ReadNode node2(&trans);
1734 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1735 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1736 // We should de-canonicalize the title in GetTitle(), but the title in the
1737 // specifics should be stored in the server legal form.
1738 EXPECT_EQ(raw_title2, node2.GetTitle());
1739 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1740 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1744 // Create a bookmark and set the title/url, then verify the data was properly
1745 // set. This replicates the unique way bookmarks have of creating sync nodes.
1746 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1747 TEST_F(SyncManagerTest, CreateLocalBookmark) {
1748 std::string title = "title";
1749 std::string url = "url";
1751 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1752 ReadNode bookmark_root(&trans);
1753 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1754 WriteNode node(&trans);
1755 ASSERT_TRUE(node.InitBookmarkByCreation(bookmark_root, NULL));
1756 node.SetIsFolder(false);
1757 node.SetTitle(title);
1759 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
1760 bookmark_specifics.set_url(url);
1761 node.SetBookmarkSpecifics(bookmark_specifics);
1764 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1765 ReadNode bookmark_root(&trans);
1766 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1767 int64 child_id = bookmark_root.GetFirstChildId();
1769 ReadNode node(&trans);
1770 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
1771 EXPECT_FALSE(node.GetIsFolder());
1772 EXPECT_EQ(title, node.GetTitle());
1773 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1777 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1778 // changes.
1779 TEST_F(SyncManagerTest, UpdateEntryWithEncryption) {
1780 std::string client_tag = "title";
1781 sync_pb::EntitySpecifics entity_specifics;
1782 entity_specifics.mutable_bookmark()->set_url("url");
1783 entity_specifics.mutable_bookmark()->set_title("title");
1784 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
1785 syncable::GenerateSyncableHash(BOOKMARKS,
1786 client_tag),
1787 entity_specifics);
1788 // New node shouldn't start off unsynced.
1789 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1790 // Manually change to the same data. Should not set is_unsynced.
1792 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1793 WriteNode node(&trans);
1794 EXPECT_EQ(BaseNode::INIT_OK,
1795 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1796 node.SetEntitySpecifics(entity_specifics);
1798 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1800 // Encrypt the datatatype, should set is_unsynced.
1801 EXPECT_CALL(encryption_observer_,
1802 OnEncryptedTypesChanged(
1803 HasModelTypes(EncryptableUserTypes()), true));
1804 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1805 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
1807 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1808 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1809 sync_manager_.GetEncryptionHandler()->Init();
1810 PumpLoop();
1812 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1813 ReadNode node(&trans);
1814 EXPECT_EQ(BaseNode::INIT_OK,
1815 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1816 const syncable::Entry* node_entry = node.GetEntry();
1817 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1818 EXPECT_TRUE(specifics.has_encrypted());
1819 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1820 Cryptographer* cryptographer = trans.GetCryptographer();
1821 EXPECT_TRUE(cryptographer->is_ready());
1822 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1823 specifics.encrypted()));
1825 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1827 // Set a new passphrase. Should set is_unsynced.
1828 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1829 EXPECT_CALL(encryption_observer_,
1830 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1831 ExpectPassphraseAcceptance();
1832 SetCustomPassphraseAndCheck("new_passphrase");
1834 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1835 ReadNode node(&trans);
1836 EXPECT_EQ(BaseNode::INIT_OK,
1837 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1838 const syncable::Entry* node_entry = node.GetEntry();
1839 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1840 EXPECT_TRUE(specifics.has_encrypted());
1841 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1842 Cryptographer* cryptographer = trans.GetCryptographer();
1843 EXPECT_TRUE(cryptographer->is_ready());
1844 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1845 specifics.encrypted()));
1847 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1849 // Force a re-encrypt everything. Should not set is_unsynced.
1850 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1851 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1852 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1853 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1855 sync_manager_.GetEncryptionHandler()->Init();
1856 PumpLoop();
1859 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1860 ReadNode node(&trans);
1861 EXPECT_EQ(BaseNode::INIT_OK,
1862 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1863 const syncable::Entry* node_entry = node.GetEntry();
1864 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1865 EXPECT_TRUE(specifics.has_encrypted());
1866 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1867 Cryptographer* cryptographer = trans.GetCryptographer();
1868 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1869 specifics.encrypted()));
1871 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1873 // Manually change to the same data. Should not set is_unsynced.
1875 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1876 WriteNode node(&trans);
1877 EXPECT_EQ(BaseNode::INIT_OK,
1878 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1879 node.SetEntitySpecifics(entity_specifics);
1880 const syncable::Entry* node_entry = node.GetEntry();
1881 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1882 EXPECT_TRUE(specifics.has_encrypted());
1883 EXPECT_FALSE(node_entry->GetIsUnsynced());
1884 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1885 Cryptographer* cryptographer = trans.GetCryptographer();
1886 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1887 specifics.encrypted()));
1889 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1891 // Manually change to different data. Should set is_unsynced.
1893 entity_specifics.mutable_bookmark()->set_url("url2");
1894 entity_specifics.mutable_bookmark()->set_title("title2");
1895 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1896 WriteNode node(&trans);
1897 EXPECT_EQ(BaseNode::INIT_OK,
1898 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1899 node.SetEntitySpecifics(entity_specifics);
1900 const syncable::Entry* node_entry = node.GetEntry();
1901 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1902 EXPECT_TRUE(specifics.has_encrypted());
1903 EXPECT_TRUE(node_entry->GetIsUnsynced());
1904 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1905 Cryptographer* cryptographer = trans.GetCryptographer();
1906 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1907 specifics.encrypted()));
1911 // Passwords have their own handling for encryption. Verify it does not result
1912 // in unnecessary writes via SetEntitySpecifics.
1913 TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) {
1914 std::string client_tag = "title";
1915 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1916 sync_pb::EntitySpecifics entity_specifics;
1918 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1919 Cryptographer* cryptographer = trans.GetCryptographer();
1920 sync_pb::PasswordSpecificsData data;
1921 data.set_password_value("secret");
1922 cryptographer->Encrypt(
1923 data,
1924 entity_specifics.mutable_password()->
1925 mutable_encrypted());
1927 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1928 syncable::GenerateSyncableHash(PASSWORDS,
1929 client_tag),
1930 entity_specifics);
1931 // New node shouldn't start off unsynced.
1932 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1934 // Manually change to the same data via SetEntitySpecifics. Should not set
1935 // is_unsynced.
1937 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1938 WriteNode node(&trans);
1939 EXPECT_EQ(BaseNode::INIT_OK,
1940 node.InitByClientTagLookup(PASSWORDS, client_tag));
1941 node.SetEntitySpecifics(entity_specifics);
1943 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1946 // Passwords have their own handling for encryption. Verify it does not result
1947 // in unnecessary writes via SetPasswordSpecifics.
1948 TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) {
1949 std::string client_tag = "title";
1950 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1951 sync_pb::EntitySpecifics entity_specifics;
1953 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1954 Cryptographer* cryptographer = trans.GetCryptographer();
1955 sync_pb::PasswordSpecificsData data;
1956 data.set_password_value("secret");
1957 cryptographer->Encrypt(
1958 data,
1959 entity_specifics.mutable_password()->
1960 mutable_encrypted());
1962 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1963 syncable::GenerateSyncableHash(PASSWORDS,
1964 client_tag),
1965 entity_specifics);
1966 // New node shouldn't start off unsynced.
1967 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1969 // Manually change to the same data via SetPasswordSpecifics. Should not set
1970 // is_unsynced.
1972 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1973 WriteNode node(&trans);
1974 EXPECT_EQ(BaseNode::INIT_OK,
1975 node.InitByClientTagLookup(PASSWORDS, client_tag));
1976 node.SetPasswordSpecifics(node.GetPasswordSpecifics());
1978 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1980 // Manually change to different data. Should set is_unsynced.
1982 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1983 WriteNode node(&trans);
1984 EXPECT_EQ(BaseNode::INIT_OK,
1985 node.InitByClientTagLookup(PASSWORDS, client_tag));
1986 Cryptographer* cryptographer = trans.GetCryptographer();
1987 sync_pb::PasswordSpecificsData data;
1988 data.set_password_value("secret2");
1989 cryptographer->Encrypt(
1990 data,
1991 entity_specifics.mutable_password()->mutable_encrypted());
1992 node.SetPasswordSpecifics(data);
1993 const syncable::Entry* node_entry = node.GetEntry();
1994 EXPECT_TRUE(node_entry->GetIsUnsynced());
1998 // Passwords have their own handling for encryption. Verify setting a new
1999 // passphrase updates the data.
2000 TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) {
2001 std::string client_tag = "title";
2002 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2003 sync_pb::EntitySpecifics entity_specifics;
2005 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2006 Cryptographer* cryptographer = trans.GetCryptographer();
2007 sync_pb::PasswordSpecificsData data;
2008 data.set_password_value("secret");
2009 cryptographer->Encrypt(
2010 data,
2011 entity_specifics.mutable_password()->mutable_encrypted());
2013 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2014 syncable::GenerateSyncableHash(PASSWORDS,
2015 client_tag),
2016 entity_specifics);
2017 // New node shouldn't start off unsynced.
2018 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2020 // Set a new passphrase. Should set is_unsynced.
2021 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2022 EXPECT_CALL(encryption_observer_,
2023 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
2024 ExpectPassphraseAcceptance();
2025 SetCustomPassphraseAndCheck("new_passphrase");
2026 EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2029 // Passwords have their own handling for encryption. Verify it does not result
2030 // in unnecessary writes via ReencryptEverything.
2031 TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) {
2032 std::string client_tag = "title";
2033 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2034 sync_pb::EntitySpecifics entity_specifics;
2036 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2037 Cryptographer* cryptographer = trans.GetCryptographer();
2038 sync_pb::PasswordSpecificsData data;
2039 data.set_password_value("secret");
2040 cryptographer->Encrypt(
2041 data,
2042 entity_specifics.mutable_password()->mutable_encrypted());
2044 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2045 syncable::GenerateSyncableHash(PASSWORDS,
2046 client_tag),
2047 entity_specifics);
2048 // New node shouldn't start off unsynced.
2049 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2051 // Force a re-encrypt everything. Should not set is_unsynced.
2052 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2053 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2054 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2055 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
2056 sync_manager_.GetEncryptionHandler()->Init();
2057 PumpLoop();
2058 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2061 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2062 // when we write the same data, but does set it when we write new data.
2063 TEST_F(SyncManagerTest, SetBookmarkTitle) {
2064 std::string client_tag = "title";
2065 sync_pb::EntitySpecifics entity_specifics;
2066 entity_specifics.mutable_bookmark()->set_url("url");
2067 entity_specifics.mutable_bookmark()->set_title("title");
2068 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2069 syncable::GenerateSyncableHash(BOOKMARKS,
2070 client_tag),
2071 entity_specifics);
2072 // New node shouldn't start off unsynced.
2073 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2075 // Manually change to the same title. Should not set is_unsynced.
2077 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2078 WriteNode node(&trans);
2079 EXPECT_EQ(BaseNode::INIT_OK,
2080 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2081 node.SetTitle(client_tag);
2083 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2085 // Manually change to new title. Should set is_unsynced.
2087 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2088 WriteNode node(&trans);
2089 EXPECT_EQ(BaseNode::INIT_OK,
2090 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2091 node.SetTitle("title2");
2093 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2096 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2097 // bookmarks when we write the same data, but does set it when we write new
2098 // data.
2099 TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) {
2100 std::string client_tag = "title";
2101 sync_pb::EntitySpecifics entity_specifics;
2102 entity_specifics.mutable_bookmark()->set_url("url");
2103 entity_specifics.mutable_bookmark()->set_title("title");
2104 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2105 syncable::GenerateSyncableHash(BOOKMARKS,
2106 client_tag),
2107 entity_specifics);
2108 // New node shouldn't start off unsynced.
2109 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2111 // Encrypt the datatatype, should set is_unsynced.
2112 EXPECT_CALL(encryption_observer_,
2113 OnEncryptedTypesChanged(
2114 HasModelTypes(EncryptableUserTypes()), true));
2115 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2116 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2117 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2118 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2119 sync_manager_.GetEncryptionHandler()->Init();
2120 PumpLoop();
2121 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2123 // Manually change to the same title. Should not set is_unsynced.
2124 // NON_UNIQUE_NAME should be kEncryptedString.
2126 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2127 WriteNode node(&trans);
2128 EXPECT_EQ(BaseNode::INIT_OK,
2129 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2130 node.SetTitle(client_tag);
2131 const syncable::Entry* node_entry = node.GetEntry();
2132 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2133 EXPECT_TRUE(specifics.has_encrypted());
2134 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2136 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2138 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2139 // should still be kEncryptedString.
2141 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2142 WriteNode node(&trans);
2143 EXPECT_EQ(BaseNode::INIT_OK,
2144 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2145 node.SetTitle("title2");
2146 const syncable::Entry* node_entry = node.GetEntry();
2147 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2148 EXPECT_TRUE(specifics.has_encrypted());
2149 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2151 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2154 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2155 // when we write the same data, but does set it when we write new data.
2156 TEST_F(SyncManagerTest, SetNonBookmarkTitle) {
2157 std::string client_tag = "title";
2158 sync_pb::EntitySpecifics entity_specifics;
2159 entity_specifics.mutable_preference()->set_name("name");
2160 entity_specifics.mutable_preference()->set_value("value");
2161 MakeServerNode(sync_manager_.GetUserShare(),
2162 PREFERENCES,
2163 client_tag,
2164 syncable::GenerateSyncableHash(PREFERENCES,
2165 client_tag),
2166 entity_specifics);
2167 // New node shouldn't start off unsynced.
2168 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2170 // Manually change to the same title. Should not set is_unsynced.
2172 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2173 WriteNode node(&trans);
2174 EXPECT_EQ(BaseNode::INIT_OK,
2175 node.InitByClientTagLookup(PREFERENCES, client_tag));
2176 node.SetTitle(client_tag);
2178 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2180 // Manually change to new title. Should set is_unsynced.
2182 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2183 WriteNode node(&trans);
2184 EXPECT_EQ(BaseNode::INIT_OK,
2185 node.InitByClientTagLookup(PREFERENCES, client_tag));
2186 node.SetTitle("title2");
2188 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2191 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2192 // non-bookmarks when we write the same data or when we write new data
2193 // data (should remained kEncryptedString).
2194 TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) {
2195 std::string client_tag = "title";
2196 sync_pb::EntitySpecifics entity_specifics;
2197 entity_specifics.mutable_preference()->set_name("name");
2198 entity_specifics.mutable_preference()->set_value("value");
2199 MakeServerNode(sync_manager_.GetUserShare(),
2200 PREFERENCES,
2201 client_tag,
2202 syncable::GenerateSyncableHash(PREFERENCES,
2203 client_tag),
2204 entity_specifics);
2205 // New node shouldn't start off unsynced.
2206 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2208 // Encrypt the datatatype, should set is_unsynced.
2209 EXPECT_CALL(encryption_observer_,
2210 OnEncryptedTypesChanged(
2211 HasModelTypes(EncryptableUserTypes()), true));
2212 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2213 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2214 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2215 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2216 sync_manager_.GetEncryptionHandler()->Init();
2217 PumpLoop();
2218 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2220 // Manually change to the same title. Should not set is_unsynced.
2221 // NON_UNIQUE_NAME should be kEncryptedString.
2223 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2224 WriteNode node(&trans);
2225 EXPECT_EQ(BaseNode::INIT_OK,
2226 node.InitByClientTagLookup(PREFERENCES, client_tag));
2227 node.SetTitle(client_tag);
2228 const syncable::Entry* node_entry = node.GetEntry();
2229 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2230 EXPECT_TRUE(specifics.has_encrypted());
2231 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2233 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2235 // Manually change to new title. Should not set is_unsynced because the
2236 // NON_UNIQUE_NAME should still be kEncryptedString.
2238 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2239 WriteNode node(&trans);
2240 EXPECT_EQ(BaseNode::INIT_OK,
2241 node.InitByClientTagLookup(PREFERENCES, client_tag));
2242 node.SetTitle("title2");
2243 const syncable::Entry* node_entry = node.GetEntry();
2244 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2245 EXPECT_TRUE(specifics.has_encrypted());
2246 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2247 EXPECT_FALSE(node_entry->GetIsUnsynced());
2251 // Ensure that titles are truncated to 255 bytes, and attempting to reset
2252 // them to their longer version does not set IS_UNSYNCED.
2253 TEST_F(SyncManagerTest, SetLongTitle) {
2254 const int kNumChars = 512;
2255 const std::string kClientTag = "tag";
2256 std::string title(kNumChars, '0');
2257 sync_pb::EntitySpecifics entity_specifics;
2258 entity_specifics.mutable_preference()->set_name("name");
2259 entity_specifics.mutable_preference()->set_value("value");
2260 MakeServerNode(sync_manager_.GetUserShare(),
2261 PREFERENCES,
2262 "short_title",
2263 syncable::GenerateSyncableHash(PREFERENCES,
2264 kClientTag),
2265 entity_specifics);
2266 // New node shouldn't start off unsynced.
2267 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2269 // Manually change to the long title. Should set is_unsynced.
2271 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2272 WriteNode node(&trans);
2273 EXPECT_EQ(BaseNode::INIT_OK,
2274 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2275 node.SetTitle(title);
2276 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2278 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2280 // Manually change to the same title. Should not set is_unsynced.
2282 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2283 WriteNode node(&trans);
2284 EXPECT_EQ(BaseNode::INIT_OK,
2285 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2286 node.SetTitle(title);
2287 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2289 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2291 // Manually change to new title. Should set is_unsynced.
2293 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2294 WriteNode node(&trans);
2295 EXPECT_EQ(BaseNode::INIT_OK,
2296 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2297 node.SetTitle("title2");
2299 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2302 // Create an encrypted entry when the cryptographer doesn't think the type is
2303 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2304 // the data.
2305 TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) {
2306 std::string client_tag = "tag";
2307 std::string url = "url";
2308 std::string url2 = "new_url";
2309 std::string title = "title";
2310 sync_pb::EntitySpecifics entity_specifics;
2311 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2313 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2314 Cryptographer* crypto = trans.GetCryptographer();
2315 sync_pb::EntitySpecifics bm_specifics;
2316 bm_specifics.mutable_bookmark()->set_title("title");
2317 bm_specifics.mutable_bookmark()->set_url("url");
2318 sync_pb::EncryptedData encrypted;
2319 crypto->Encrypt(bm_specifics, &encrypted);
2320 entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
2321 AddDefaultFieldValue(BOOKMARKS, &entity_specifics);
2323 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2324 syncable::GenerateSyncableHash(BOOKMARKS,
2325 client_tag),
2326 entity_specifics);
2329 // Verify the data.
2330 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2331 ReadNode node(&trans);
2332 EXPECT_EQ(BaseNode::INIT_OK,
2333 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2334 EXPECT_EQ(title, node.GetTitle());
2335 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
2339 // Overwrite the url (which overwrites the specifics).
2340 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2341 WriteNode node(&trans);
2342 EXPECT_EQ(BaseNode::INIT_OK,
2343 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2345 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
2346 bookmark_specifics.set_url(url2);
2347 node.SetBookmarkSpecifics(bookmark_specifics);
2351 // Verify it's still encrypted and it has the most recent url.
2352 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2353 ReadNode node(&trans);
2354 EXPECT_EQ(BaseNode::INIT_OK,
2355 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2356 EXPECT_EQ(title, node.GetTitle());
2357 EXPECT_EQ(url2, node.GetBookmarkSpecifics().url());
2358 const syncable::Entry* node_entry = node.GetEntry();
2359 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2360 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2361 EXPECT_TRUE(specifics.has_encrypted());
2365 // Verify transaction version of a model type is incremented when node of
2366 // that type is updated.
2367 TEST_F(SyncManagerTest, IncrementTransactionVersion) {
2368 ModelSafeRoutingInfo routing_info;
2369 GetModelSafeRoutingInfo(&routing_info);
2372 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2373 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2374 i != routing_info.end(); ++i) {
2375 // Transaction version is incremented when SyncManagerTest::SetUp()
2376 // creates a node of each type.
2377 EXPECT_EQ(1,
2378 sync_manager_.GetUserShare()->directory->
2379 GetTransactionVersion(i->first));
2383 // Create bookmark node to increment transaction version of bookmark model.
2384 std::string client_tag = "title";
2385 sync_pb::EntitySpecifics entity_specifics;
2386 entity_specifics.mutable_bookmark()->set_url("url");
2387 entity_specifics.mutable_bookmark()->set_title("title");
2388 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2389 syncable::GenerateSyncableHash(BOOKMARKS,
2390 client_tag),
2391 entity_specifics);
2394 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2395 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2396 i != routing_info.end(); ++i) {
2397 EXPECT_EQ(i->first == BOOKMARKS ? 2 : 1,
2398 sync_manager_.GetUserShare()->directory->
2399 GetTransactionVersion(i->first));
2404 class MockSyncScheduler : public FakeSyncScheduler {
2405 public:
2406 MockSyncScheduler() : FakeSyncScheduler() {}
2407 virtual ~MockSyncScheduler() {}
2409 MOCK_METHOD2(Start, void(SyncScheduler::Mode, base::Time));
2410 MOCK_METHOD1(ScheduleConfiguration, void(const ConfigurationParams&));
2413 class ComponentsFactory : public TestInternalComponentsFactory {
2414 public:
2415 ComponentsFactory(const Switches& switches,
2416 SyncScheduler* scheduler_to_use,
2417 sessions::SyncSessionContext** session_context,
2418 InternalComponentsFactory::StorageOption* storage_used)
2419 : TestInternalComponentsFactory(
2420 switches, InternalComponentsFactory::STORAGE_IN_MEMORY, storage_used),
2421 scheduler_to_use_(scheduler_to_use),
2422 session_context_(session_context) {}
2423 ~ComponentsFactory() override {}
2425 scoped_ptr<SyncScheduler> BuildScheduler(
2426 const std::string& name,
2427 sessions::SyncSessionContext* context,
2428 CancelationSignal* stop_handle) override {
2429 *session_context_ = context;
2430 return scheduler_to_use_.Pass();
2433 private:
2434 scoped_ptr<SyncScheduler> scheduler_to_use_;
2435 sessions::SyncSessionContext** session_context_;
2438 class SyncManagerTestWithMockScheduler : public SyncManagerTest {
2439 public:
2440 SyncManagerTestWithMockScheduler() : scheduler_(NULL) {}
2441 InternalComponentsFactory* GetFactory() override {
2442 scheduler_ = new MockSyncScheduler();
2443 return new ComponentsFactory(GetSwitches(), scheduler_, &session_context_,
2444 &storage_used_);
2447 MockSyncScheduler* scheduler() { return scheduler_; }
2448 sessions::SyncSessionContext* session_context() {
2449 return session_context_;
2452 private:
2453 MockSyncScheduler* scheduler_;
2454 sessions::SyncSessionContext* session_context_;
2457 // Test that the configuration params are properly created and sent to
2458 // ScheduleConfigure. No callback should be invoked. Any disabled datatypes
2459 // should be purged.
2460 TEST_F(SyncManagerTestWithMockScheduler, BasicConfiguration) {
2461 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2462 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2463 ModelSafeRoutingInfo new_routing_info;
2464 GetModelSafeRoutingInfo(&new_routing_info);
2465 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2466 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2468 ConfigurationParams params;
2469 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE, _));
2470 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2471 WillOnce(SaveArg<0>(&params));
2473 // Set data for all types.
2474 ModelTypeSet protocol_types = ProtocolTypes();
2475 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2476 iter.Inc()) {
2477 SetProgressMarkerForType(iter.Get(), true);
2480 CallbackCounter ready_task_counter, retry_task_counter;
2481 sync_manager_.ConfigureSyncer(
2482 reason,
2483 types_to_download,
2484 disabled_types,
2485 ModelTypeSet(),
2486 ModelTypeSet(),
2487 new_routing_info,
2488 base::Bind(&CallbackCounter::Callback,
2489 base::Unretained(&ready_task_counter)),
2490 base::Bind(&CallbackCounter::Callback,
2491 base::Unretained(&retry_task_counter)));
2492 EXPECT_EQ(0, ready_task_counter.times_called());
2493 EXPECT_EQ(0, retry_task_counter.times_called());
2494 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2495 params.source);
2496 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2497 EXPECT_EQ(new_routing_info, params.routing_info);
2499 // Verify all the disabled types were purged.
2500 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().Equals(
2501 enabled_types));
2502 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2503 ModelTypeSet::All()).Equals(disabled_types));
2506 // Test that on a reconfiguration (configuration where the session context
2507 // already has routing info), only those recently disabled types are purged.
2508 TEST_F(SyncManagerTestWithMockScheduler, ReConfiguration) {
2509 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2510 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2511 ModelTypeSet disabled_types = ModelTypeSet(THEMES, SESSIONS);
2512 ModelSafeRoutingInfo old_routing_info;
2513 ModelSafeRoutingInfo new_routing_info;
2514 GetModelSafeRoutingInfo(&old_routing_info);
2515 new_routing_info = old_routing_info;
2516 new_routing_info.erase(THEMES);
2517 new_routing_info.erase(SESSIONS);
2518 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2520 ConfigurationParams params;
2521 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE, _));
2522 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2523 WillOnce(SaveArg<0>(&params));
2525 // Set data for all types except those recently disabled (so we can verify
2526 // only those recently disabled are purged) .
2527 ModelTypeSet protocol_types = ProtocolTypes();
2528 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2529 iter.Inc()) {
2530 if (!disabled_types.Has(iter.Get())) {
2531 SetProgressMarkerForType(iter.Get(), true);
2532 } else {
2533 SetProgressMarkerForType(iter.Get(), false);
2537 // Set the context to have the old routing info.
2538 session_context()->SetRoutingInfo(old_routing_info);
2540 CallbackCounter ready_task_counter, retry_task_counter;
2541 sync_manager_.ConfigureSyncer(
2542 reason,
2543 types_to_download,
2544 ModelTypeSet(),
2545 ModelTypeSet(),
2546 ModelTypeSet(),
2547 new_routing_info,
2548 base::Bind(&CallbackCounter::Callback,
2549 base::Unretained(&ready_task_counter)),
2550 base::Bind(&CallbackCounter::Callback,
2551 base::Unretained(&retry_task_counter)));
2552 EXPECT_EQ(0, ready_task_counter.times_called());
2553 EXPECT_EQ(0, retry_task_counter.times_called());
2554 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2555 params.source);
2556 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2557 EXPECT_EQ(new_routing_info, params.routing_info);
2559 // Verify only the recently disabled types were purged.
2560 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2561 ProtocolTypes()).Equals(disabled_types));
2564 // Test that PurgePartiallySyncedTypes purges only those types that have not
2565 // fully completed their initial download and apply.
2566 TEST_F(SyncManagerTest, PurgePartiallySyncedTypes) {
2567 ModelSafeRoutingInfo routing_info;
2568 GetModelSafeRoutingInfo(&routing_info);
2569 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2571 UserShare* share = sync_manager_.GetUserShare();
2573 // The test harness automatically initializes all types in the routing info.
2574 // Check that autofill is not among them.
2575 ASSERT_FALSE(enabled_types.Has(AUTOFILL));
2577 // Further ensure that the test harness did not create its root node.
2579 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2580 syncable::Entry autofill_root_node(&trans,
2581 syncable::GET_TYPE_ROOT,
2582 AUTOFILL);
2583 ASSERT_FALSE(autofill_root_node.good());
2586 // One more redundant check.
2587 ASSERT_FALSE(sync_manager_.InitialSyncEndedTypes().Has(AUTOFILL));
2589 // Give autofill a progress marker.
2590 sync_pb::DataTypeProgressMarker autofill_marker;
2591 autofill_marker.set_data_type_id(
2592 GetSpecificsFieldNumberFromModelType(AUTOFILL));
2593 autofill_marker.set_token("token");
2594 share->directory->SetDownloadProgress(AUTOFILL, autofill_marker);
2596 // Also add a pending autofill root node update from the server.
2597 TestEntryFactory factory_(share->directory.get());
2598 int autofill_meta = factory_.CreateUnappliedRootNode(AUTOFILL);
2600 // Preferences is an enabled type. Check that the harness initialized it.
2601 ASSERT_TRUE(enabled_types.Has(PREFERENCES));
2602 ASSERT_TRUE(sync_manager_.InitialSyncEndedTypes().Has(PREFERENCES));
2604 // Give preferencse a progress marker.
2605 sync_pb::DataTypeProgressMarker prefs_marker;
2606 prefs_marker.set_data_type_id(
2607 GetSpecificsFieldNumberFromModelType(PREFERENCES));
2608 prefs_marker.set_token("token");
2609 share->directory->SetDownloadProgress(PREFERENCES, prefs_marker);
2611 // Add a fully synced preferences node under the root.
2612 std::string pref_client_tag = "prefABC";
2613 std::string pref_hashed_tag = "hashXYZ";
2614 sync_pb::EntitySpecifics pref_specifics;
2615 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2616 int pref_meta = MakeServerNode(
2617 share, PREFERENCES, pref_client_tag, pref_hashed_tag, pref_specifics);
2619 // And now, the purge.
2620 EXPECT_TRUE(sync_manager_.PurgePartiallySyncedTypes());
2622 // Ensure that autofill lost its progress marker, but preferences did not.
2623 ModelTypeSet empty_tokens =
2624 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
2625 EXPECT_TRUE(empty_tokens.Has(AUTOFILL));
2626 EXPECT_FALSE(empty_tokens.Has(PREFERENCES));
2628 // Ensure that autofill lots its node, but preferences did not.
2630 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2631 syncable::Entry autofill_node(&trans, GET_BY_HANDLE, autofill_meta);
2632 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref_meta);
2633 EXPECT_FALSE(autofill_node.good());
2634 EXPECT_TRUE(pref_node.good());
2638 // Test CleanupDisabledTypes properly purges all disabled types as specified
2639 // by the previous and current enabled params.
2640 TEST_F(SyncManagerTest, PurgeDisabledTypes) {
2641 ModelSafeRoutingInfo routing_info;
2642 GetModelSafeRoutingInfo(&routing_info);
2643 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2644 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2646 // The harness should have initialized the enabled_types for us.
2647 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2649 // Set progress markers for all types.
2650 ModelTypeSet protocol_types = ProtocolTypes();
2651 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2652 iter.Inc()) {
2653 SetProgressMarkerForType(iter.Get(), true);
2656 // Verify all the enabled types remain after cleanup, and all the disabled
2657 // types were purged.
2658 sync_manager_.PurgeDisabledTypes(disabled_types,
2659 ModelTypeSet(),
2660 ModelTypeSet());
2661 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2662 EXPECT_TRUE(disabled_types.Equals(
2663 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2665 // Disable some more types.
2666 disabled_types.Put(BOOKMARKS);
2667 disabled_types.Put(PREFERENCES);
2668 ModelTypeSet new_enabled_types =
2669 Difference(ModelTypeSet::All(), disabled_types);
2671 // Verify only the non-disabled types remain after cleanup.
2672 sync_manager_.PurgeDisabledTypes(disabled_types,
2673 ModelTypeSet(),
2674 ModelTypeSet());
2675 EXPECT_TRUE(new_enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2676 EXPECT_TRUE(disabled_types.Equals(
2677 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2680 // Test PurgeDisabledTypes properly unapplies types by deleting their local data
2681 // and preserving their server data and progress marker.
2682 TEST_F(SyncManagerTest, PurgeUnappliedTypes) {
2683 ModelSafeRoutingInfo routing_info;
2684 GetModelSafeRoutingInfo(&routing_info);
2685 ModelTypeSet unapplied_types = ModelTypeSet(BOOKMARKS, PREFERENCES);
2686 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2687 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2689 // The harness should have initialized the enabled_types for us.
2690 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2692 // Set progress markers for all types.
2693 ModelTypeSet protocol_types = ProtocolTypes();
2694 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2695 iter.Inc()) {
2696 SetProgressMarkerForType(iter.Get(), true);
2699 // Add the following kinds of items:
2700 // 1. Fully synced preference.
2701 // 2. Locally created preference, server unknown, unsynced
2702 // 3. Locally deleted preference, server known, unsynced
2703 // 4. Server deleted preference, locally known.
2704 // 5. Server created preference, locally unknown, unapplied.
2705 // 6. A fully synced bookmark (no unique_client_tag).
2706 UserShare* share = sync_manager_.GetUserShare();
2707 sync_pb::EntitySpecifics pref_specifics;
2708 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2709 sync_pb::EntitySpecifics bm_specifics;
2710 AddDefaultFieldValue(BOOKMARKS, &bm_specifics);
2711 int pref1_meta = MakeServerNode(
2712 share, PREFERENCES, "pref1", "hash1", pref_specifics);
2713 int64 pref2_meta = MakeNodeWithRoot(share, PREFERENCES, "pref2");
2714 int pref3_meta = MakeServerNode(
2715 share, PREFERENCES, "pref3", "hash3", pref_specifics);
2716 int pref4_meta = MakeServerNode(
2717 share, PREFERENCES, "pref4", "hash4", pref_specifics);
2718 int pref5_meta = MakeServerNode(
2719 share, PREFERENCES, "pref5", "hash5", pref_specifics);
2720 int bookmark_meta = MakeServerNode(
2721 share, BOOKMARKS, "bookmark", "", bm_specifics);
2724 syncable::WriteTransaction trans(FROM_HERE,
2725 syncable::SYNCER,
2726 share->directory.get());
2727 // Pref's 1 and 2 are already set up properly.
2728 // Locally delete pref 3.
2729 syncable::MutableEntry pref3(&trans, GET_BY_HANDLE, pref3_meta);
2730 pref3.PutIsDel(true);
2731 pref3.PutIsUnsynced(true);
2732 // Delete pref 4 at the server.
2733 syncable::MutableEntry pref4(&trans, GET_BY_HANDLE, pref4_meta);
2734 pref4.PutServerIsDel(true);
2735 pref4.PutIsUnappliedUpdate(true);
2736 pref4.PutServerVersion(2);
2737 // Pref 5 is an new unapplied update.
2738 syncable::MutableEntry pref5(&trans, GET_BY_HANDLE, pref5_meta);
2739 pref5.PutIsUnappliedUpdate(true);
2740 pref5.PutIsDel(true);
2741 pref5.PutBaseVersion(-1);
2742 // Bookmark is already set up properly
2745 // Take a snapshot to clear all the dirty bits.
2746 share->directory.get()->SaveChanges();
2748 // Now request a purge for the unapplied types.
2749 disabled_types.PutAll(unapplied_types);
2750 sync_manager_.PurgeDisabledTypes(disabled_types,
2751 ModelTypeSet(),
2752 unapplied_types);
2754 // Verify the unapplied types still have progress markers and initial sync
2755 // ended after cleanup.
2756 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().HasAll(unapplied_types));
2757 EXPECT_TRUE(
2758 sync_manager_.GetTypesWithEmptyProgressMarkerToken(unapplied_types).
2759 Empty());
2761 // Ensure the items were unapplied as necessary.
2763 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2764 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref1_meta);
2765 ASSERT_TRUE(pref_node.good());
2766 EXPECT_TRUE(pref_node.GetKernelCopy().is_dirty());
2767 EXPECT_FALSE(pref_node.GetIsUnsynced());
2768 EXPECT_TRUE(pref_node.GetIsUnappliedUpdate());
2769 EXPECT_TRUE(pref_node.GetIsDel());
2770 EXPECT_GT(pref_node.GetServerVersion(), 0);
2771 EXPECT_EQ(pref_node.GetBaseVersion(), -1);
2773 // Pref 2 should just be locally deleted.
2774 syncable::Entry pref2_node(&trans, GET_BY_HANDLE, pref2_meta);
2775 ASSERT_TRUE(pref2_node.good());
2776 EXPECT_TRUE(pref2_node.GetKernelCopy().is_dirty());
2777 EXPECT_FALSE(pref2_node.GetIsUnsynced());
2778 EXPECT_TRUE(pref2_node.GetIsDel());
2779 EXPECT_FALSE(pref2_node.GetIsUnappliedUpdate());
2780 EXPECT_TRUE(pref2_node.GetIsDel());
2781 EXPECT_EQ(pref2_node.GetServerVersion(), 0);
2782 EXPECT_EQ(pref2_node.GetBaseVersion(), -1);
2784 syncable::Entry pref3_node(&trans, GET_BY_HANDLE, pref3_meta);
2785 ASSERT_TRUE(pref3_node.good());
2786 EXPECT_TRUE(pref3_node.GetKernelCopy().is_dirty());
2787 EXPECT_FALSE(pref3_node.GetIsUnsynced());
2788 EXPECT_TRUE(pref3_node.GetIsUnappliedUpdate());
2789 EXPECT_TRUE(pref3_node.GetIsDel());
2790 EXPECT_GT(pref3_node.GetServerVersion(), 0);
2791 EXPECT_EQ(pref3_node.GetBaseVersion(), -1);
2793 syncable::Entry pref4_node(&trans, GET_BY_HANDLE, pref4_meta);
2794 ASSERT_TRUE(pref4_node.good());
2795 EXPECT_TRUE(pref4_node.GetKernelCopy().is_dirty());
2796 EXPECT_FALSE(pref4_node.GetIsUnsynced());
2797 EXPECT_TRUE(pref4_node.GetIsUnappliedUpdate());
2798 EXPECT_TRUE(pref4_node.GetIsDel());
2799 EXPECT_GT(pref4_node.GetServerVersion(), 0);
2800 EXPECT_EQ(pref4_node.GetBaseVersion(), -1);
2802 // Pref 5 should remain untouched.
2803 syncable::Entry pref5_node(&trans, GET_BY_HANDLE, pref5_meta);
2804 ASSERT_TRUE(pref5_node.good());
2805 EXPECT_FALSE(pref5_node.GetKernelCopy().is_dirty());
2806 EXPECT_FALSE(pref5_node.GetIsUnsynced());
2807 EXPECT_TRUE(pref5_node.GetIsUnappliedUpdate());
2808 EXPECT_TRUE(pref5_node.GetIsDel());
2809 EXPECT_GT(pref5_node.GetServerVersion(), 0);
2810 EXPECT_EQ(pref5_node.GetBaseVersion(), -1);
2812 syncable::Entry bookmark_node(&trans, GET_BY_HANDLE, bookmark_meta);
2813 ASSERT_TRUE(bookmark_node.good());
2814 EXPECT_TRUE(bookmark_node.GetKernelCopy().is_dirty());
2815 EXPECT_FALSE(bookmark_node.GetIsUnsynced());
2816 EXPECT_TRUE(bookmark_node.GetIsUnappliedUpdate());
2817 EXPECT_TRUE(bookmark_node.GetIsDel());
2818 EXPECT_GT(bookmark_node.GetServerVersion(), 0);
2819 EXPECT_EQ(bookmark_node.GetBaseVersion(), -1);
2823 // A test harness to exercise the code that processes and passes changes from
2824 // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
2825 // ChangeProcessor.
2826 class SyncManagerChangeProcessingTest : public SyncManagerTest {
2827 public:
2828 void OnChangesApplied(ModelType model_type,
2829 int64 model_version,
2830 const BaseTransaction* trans,
2831 const ImmutableChangeRecordList& changes) override {
2832 last_changes_ = changes;
2835 void OnChangesComplete(ModelType model_type) override {}
2837 const ImmutableChangeRecordList& GetRecentChangeList() {
2838 return last_changes_;
2841 UserShare* share() {
2842 return sync_manager_.GetUserShare();
2845 // Set some flags so our nodes reasonably approximate the real world scenario
2846 // and can get past CheckTreeInvariants.
2848 // It's never going to be truly accurate, since we're squashing update
2849 // receipt, processing and application into a single transaction.
2850 void SetNodeProperties(syncable::MutableEntry *entry) {
2851 entry->PutId(id_factory_.NewServerId());
2852 entry->PutBaseVersion(10);
2853 entry->PutServerVersion(10);
2856 // Looks for the given change in the list. Returns the index at which it was
2857 // found. Returns -1 on lookup failure.
2858 size_t FindChangeInList(int64 id, ChangeRecord::Action action) {
2859 SCOPED_TRACE(id);
2860 for (size_t i = 0; i < last_changes_.Get().size(); ++i) {
2861 if (last_changes_.Get()[i].id == id
2862 && last_changes_.Get()[i].action == action) {
2863 return i;
2866 ADD_FAILURE() << "Failed to find specified change";
2867 return static_cast<size_t>(-1);
2870 // Returns the current size of the change list.
2872 // Note that spurious changes do not necessarily indicate a problem.
2873 // Assertions on change list size can help detect problems, but it may be
2874 // necessary to reduce their strictness if the implementation changes.
2875 size_t GetChangeListSize() {
2876 return last_changes_.Get().size();
2879 void ClearChangeList() { last_changes_ = ImmutableChangeRecordList(); }
2881 protected:
2882 ImmutableChangeRecordList last_changes_;
2883 TestIdFactory id_factory_;
2886 // Test creation of a folder and a bookmark.
2887 TEST_F(SyncManagerChangeProcessingTest, AddBookmarks) {
2888 int64 type_root = GetIdForDataType(BOOKMARKS);
2889 int64 folder_id = kInvalidId;
2890 int64 child_id = kInvalidId;
2892 // Create a folder and a bookmark under it.
2894 syncable::WriteTransaction trans(
2895 FROM_HERE, syncable::SYNCER, share()->directory.get());
2896 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
2897 ASSERT_TRUE(root.good());
2899 syncable::MutableEntry folder(&trans, syncable::CREATE,
2900 BOOKMARKS, root.GetId(), "folder");
2901 ASSERT_TRUE(folder.good());
2902 SetNodeProperties(&folder);
2903 folder.PutIsDir(true);
2904 folder_id = folder.GetMetahandle();
2906 syncable::MutableEntry child(&trans, syncable::CREATE,
2907 BOOKMARKS, folder.GetId(), "child");
2908 ASSERT_TRUE(child.good());
2909 SetNodeProperties(&child);
2910 child_id = child.GetMetahandle();
2913 // The closing of the above scope will delete the transaction. Its processed
2914 // changes should be waiting for us in a member of the test harness.
2915 EXPECT_EQ(2UL, GetChangeListSize());
2917 // We don't need to check these return values here. The function will add a
2918 // non-fatal failure if these changes are not found.
2919 size_t folder_change_pos =
2920 FindChangeInList(folder_id, ChangeRecord::ACTION_ADD);
2921 size_t child_change_pos =
2922 FindChangeInList(child_id, ChangeRecord::ACTION_ADD);
2924 // Parents are delivered before children.
2925 EXPECT_LT(folder_change_pos, child_change_pos);
2928 // Test creation of a preferences (with implicit parent Id)
2929 TEST_F(SyncManagerChangeProcessingTest, AddPreferences) {
2930 int64 item1_id = kInvalidId;
2931 int64 item2_id = kInvalidId;
2933 // Create two preferences.
2935 syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
2936 share()->directory.get());
2938 syncable::MutableEntry item1(&trans, syncable::CREATE, PREFERENCES,
2939 "test_item_1");
2940 ASSERT_TRUE(item1.good());
2941 SetNodeProperties(&item1);
2942 item1_id = item1.GetMetahandle();
2944 // Need at least two items to ensure hitting all possible codepaths in
2945 // ChangeReorderBuffer::Traversal::ExpandToInclude.
2946 syncable::MutableEntry item2(&trans, syncable::CREATE, PREFERENCES,
2947 "test_item_2");
2948 ASSERT_TRUE(item2.good());
2949 SetNodeProperties(&item2);
2950 item2_id = item2.GetMetahandle();
2953 // The closing of the above scope will delete the transaction. Its processed
2954 // changes should be waiting for us in a member of the test harness.
2955 EXPECT_EQ(2UL, GetChangeListSize());
2957 FindChangeInList(item1_id, ChangeRecord::ACTION_ADD);
2958 FindChangeInList(item2_id, ChangeRecord::ACTION_ADD);
2961 // Test moving a bookmark into an empty folder.
2962 TEST_F(SyncManagerChangeProcessingTest, MoveBookmarkIntoEmptyFolder) {
2963 int64 type_root = GetIdForDataType(BOOKMARKS);
2964 int64 folder_b_id = kInvalidId;
2965 int64 child_id = kInvalidId;
2967 // Create two folders. Place a child under folder A.
2969 syncable::WriteTransaction trans(
2970 FROM_HERE, syncable::SYNCER, share()->directory.get());
2971 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
2972 ASSERT_TRUE(root.good());
2974 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
2975 BOOKMARKS, root.GetId(), "folderA");
2976 ASSERT_TRUE(folder_a.good());
2977 SetNodeProperties(&folder_a);
2978 folder_a.PutIsDir(true);
2980 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
2981 BOOKMARKS, root.GetId(), "folderB");
2982 ASSERT_TRUE(folder_b.good());
2983 SetNodeProperties(&folder_b);
2984 folder_b.PutIsDir(true);
2985 folder_b_id = folder_b.GetMetahandle();
2987 syncable::MutableEntry child(&trans, syncable::CREATE,
2988 BOOKMARKS, folder_a.GetId(),
2989 "child");
2990 ASSERT_TRUE(child.good());
2991 SetNodeProperties(&child);
2992 child_id = child.GetMetahandle();
2995 // Close that transaction. The above was to setup the initial scenario. The
2996 // real test starts now.
2998 // Move the child from folder A to folder B.
3000 syncable::WriteTransaction trans(
3001 FROM_HERE, syncable::SYNCER, share()->directory.get());
3003 syncable::Entry folder_b(&trans, syncable::GET_BY_HANDLE, folder_b_id);
3004 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3006 child.PutParentId(folder_b.GetId());
3009 EXPECT_EQ(1UL, GetChangeListSize());
3011 // Verify that this was detected as a real change. An early version of the
3012 // UniquePosition code had a bug where moves from one folder to another were
3013 // ignored unless the moved node's UniquePosition value was also changed in
3014 // some way.
3015 FindChangeInList(child_id, ChangeRecord::ACTION_UPDATE);
3018 // Test moving a bookmark into a non-empty folder.
3019 TEST_F(SyncManagerChangeProcessingTest, MoveIntoPopulatedFolder) {
3020 int64 type_root = GetIdForDataType(BOOKMARKS);
3021 int64 child_a_id = kInvalidId;
3022 int64 child_b_id = kInvalidId;
3024 // Create two folders. Place one child each under folder A and folder B.
3026 syncable::WriteTransaction trans(
3027 FROM_HERE, syncable::SYNCER, share()->directory.get());
3028 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3029 ASSERT_TRUE(root.good());
3031 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3032 BOOKMARKS, root.GetId(), "folderA");
3033 ASSERT_TRUE(folder_a.good());
3034 SetNodeProperties(&folder_a);
3035 folder_a.PutIsDir(true);
3037 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3038 BOOKMARKS, root.GetId(), "folderB");
3039 ASSERT_TRUE(folder_b.good());
3040 SetNodeProperties(&folder_b);
3041 folder_b.PutIsDir(true);
3043 syncable::MutableEntry child_a(&trans, syncable::CREATE,
3044 BOOKMARKS, folder_a.GetId(),
3045 "childA");
3046 ASSERT_TRUE(child_a.good());
3047 SetNodeProperties(&child_a);
3048 child_a_id = child_a.GetMetahandle();
3050 syncable::MutableEntry child_b(&trans, syncable::CREATE,
3051 BOOKMARKS, folder_b.GetId(),
3052 "childB");
3053 SetNodeProperties(&child_b);
3054 child_b_id = child_b.GetMetahandle();
3057 // Close that transaction. The above was to setup the initial scenario. The
3058 // real test starts now.
3061 syncable::WriteTransaction trans(
3062 FROM_HERE, syncable::SYNCER, share()->directory.get());
3064 syncable::MutableEntry child_a(&trans, syncable::GET_BY_HANDLE, child_a_id);
3065 syncable::MutableEntry child_b(&trans, syncable::GET_BY_HANDLE, child_b_id);
3067 // Move child A from folder A to folder B and update its position.
3068 child_a.PutParentId(child_b.GetParentId());
3069 child_a.PutPredecessor(child_b.GetId());
3072 EXPECT_EQ(1UL, GetChangeListSize());
3074 // Verify that only child a is in the change list.
3075 // (This function will add a failure if the lookup fails.)
3076 FindChangeInList(child_a_id, ChangeRecord::ACTION_UPDATE);
3079 // Tests the ordering of deletion changes.
3080 TEST_F(SyncManagerChangeProcessingTest, DeletionsAndChanges) {
3081 int64 type_root = GetIdForDataType(BOOKMARKS);
3082 int64 folder_a_id = kInvalidId;
3083 int64 folder_b_id = kInvalidId;
3084 int64 child_id = kInvalidId;
3086 // Create two folders. Place a child under folder A.
3088 syncable::WriteTransaction trans(
3089 FROM_HERE, syncable::SYNCER, share()->directory.get());
3090 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3091 ASSERT_TRUE(root.good());
3093 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3094 BOOKMARKS, root.GetId(), "folderA");
3095 ASSERT_TRUE(folder_a.good());
3096 SetNodeProperties(&folder_a);
3097 folder_a.PutIsDir(true);
3098 folder_a_id = folder_a.GetMetahandle();
3100 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3101 BOOKMARKS, root.GetId(), "folderB");
3102 ASSERT_TRUE(folder_b.good());
3103 SetNodeProperties(&folder_b);
3104 folder_b.PutIsDir(true);
3105 folder_b_id = folder_b.GetMetahandle();
3107 syncable::MutableEntry child(&trans, syncable::CREATE,
3108 BOOKMARKS, folder_a.GetId(),
3109 "child");
3110 ASSERT_TRUE(child.good());
3111 SetNodeProperties(&child);
3112 child_id = child.GetMetahandle();
3115 // Close that transaction. The above was to setup the initial scenario. The
3116 // real test starts now.
3119 syncable::WriteTransaction trans(
3120 FROM_HERE, syncable::SYNCER, share()->directory.get());
3122 syncable::MutableEntry folder_a(
3123 &trans, syncable::GET_BY_HANDLE, folder_a_id);
3124 syncable::MutableEntry folder_b(
3125 &trans, syncable::GET_BY_HANDLE, folder_b_id);
3126 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3128 // Delete folder B and its child.
3129 child.PutIsDel(true);
3130 folder_b.PutIsDel(true);
3132 // Make an unrelated change to folder A.
3133 folder_a.PutNonUniqueName("NewNameA");
3136 EXPECT_EQ(3UL, GetChangeListSize());
3138 size_t folder_a_pos =
3139 FindChangeInList(folder_a_id, ChangeRecord::ACTION_UPDATE);
3140 size_t folder_b_pos =
3141 FindChangeInList(folder_b_id, ChangeRecord::ACTION_DELETE);
3142 size_t child_pos = FindChangeInList(child_id, ChangeRecord::ACTION_DELETE);
3144 // Deletes should appear before updates.
3145 EXPECT_LT(child_pos, folder_a_pos);
3146 EXPECT_LT(folder_b_pos, folder_a_pos);
3149 // See that attachment metadata changes are not filtered out by
3150 // SyncManagerImpl::VisiblePropertiesDiffer.
3151 TEST_F(SyncManagerChangeProcessingTest, AttachmentMetadataOnlyChanges) {
3152 // Create an article with no attachments. See that a change is generated.
3153 int64 article_id = kInvalidId;
3155 syncable::WriteTransaction trans(
3156 FROM_HERE, syncable::SYNCER, share()->directory.get());
3157 int64 type_root = GetIdForDataType(ARTICLES);
3158 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3159 ASSERT_TRUE(root.good());
3160 syncable::MutableEntry article(
3161 &trans, syncable::CREATE, ARTICLES, root.GetId(), "article");
3162 ASSERT_TRUE(article.good());
3163 SetNodeProperties(&article);
3164 article_id = article.GetMetahandle();
3166 ASSERT_EQ(1UL, GetChangeListSize());
3167 FindChangeInList(article_id, ChangeRecord::ACTION_ADD);
3168 ClearChangeList();
3170 // Modify the article by adding one attachment. Don't touch anything else.
3171 // See that a change is generated.
3173 syncable::WriteTransaction trans(
3174 FROM_HERE, syncable::SYNCER, share()->directory.get());
3175 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3176 sync_pb::AttachmentMetadata metadata;
3177 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3178 article.PutAttachmentMetadata(metadata);
3180 ASSERT_EQ(1UL, GetChangeListSize());
3181 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3182 ClearChangeList();
3184 // Modify the article by replacing its attachment with a different one. See
3185 // that a change is generated.
3187 syncable::WriteTransaction trans(
3188 FROM_HERE, syncable::SYNCER, share()->directory.get());
3189 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3190 sync_pb::AttachmentMetadata metadata = article.GetAttachmentMetadata();
3191 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3192 article.PutAttachmentMetadata(metadata);
3194 ASSERT_EQ(1UL, GetChangeListSize());
3195 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3196 ClearChangeList();
3198 // Modify the article by replacing its attachment metadata with the same
3199 // attachment metadata. No change should be generated.
3201 syncable::WriteTransaction trans(
3202 FROM_HERE, syncable::SYNCER, share()->directory.get());
3203 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3204 article.PutAttachmentMetadata(article.GetAttachmentMetadata());
3206 ASSERT_EQ(0UL, GetChangeListSize());
3209 // During initialization SyncManagerImpl loads sqlite database. If it fails to
3210 // do so it should fail initialization. This test verifies this behavior.
3211 // Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
3212 // InternalComponentsFactory to return DirectoryBackingStore that always fails
3213 // to load.
3214 class SyncManagerInitInvalidStorageTest : public SyncManagerTest {
3215 public:
3216 SyncManagerInitInvalidStorageTest() {
3219 InternalComponentsFactory* GetFactory() override {
3220 return new TestInternalComponentsFactory(
3221 GetSwitches(), InternalComponentsFactory::STORAGE_INVALID,
3222 &storage_used_);
3226 // SyncManagerInitInvalidStorageTest::GetFactory will return
3227 // DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
3228 // SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
3229 // task is to ensure that SyncManagerImpl reported initialization failure in
3230 // OnInitializationComplete callback.
3231 TEST_F(SyncManagerInitInvalidStorageTest, FailToOpenDatabase) {
3232 EXPECT_FALSE(initialization_succeeded_);
3235 } // namespace syncer