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.
12 #include "base/basictypes.h"
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/files/scoped_temp_dir.h"
16 #include "base/format_macros.h"
17 #include "base/location.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/run_loop.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/test/values_test_util.h"
24 #include "base/values.h"
25 #include "google_apis/gaia/gaia_constants.h"
26 #include "sync/engine/sync_scheduler.h"
27 #include "sync/internal_api/public/base/attachment_id_proto.h"
28 #include "sync/internal_api/public/base/cancelation_signal.h"
29 #include "sync/internal_api/public/base/model_type_test_util.h"
30 #include "sync/internal_api/public/change_record.h"
31 #include "sync/internal_api/public/engine/model_safe_worker.h"
32 #include "sync/internal_api/public/engine/polling_constants.h"
33 #include "sync/internal_api/public/events/protocol_event.h"
34 #include "sync/internal_api/public/http_post_provider_factory.h"
35 #include "sync/internal_api/public/http_post_provider_interface.h"
36 #include "sync/internal_api/public/read_node.h"
37 #include "sync/internal_api/public/read_transaction.h"
38 #include "sync/internal_api/public/test/test_entry_factory.h"
39 #include "sync/internal_api/public/test/test_internal_components_factory.h"
40 #include "sync/internal_api/public/test/test_user_share.h"
41 #include "sync/internal_api/public/write_node.h"
42 #include "sync/internal_api/public/write_transaction.h"
43 #include "sync/internal_api/sync_encryption_handler_impl.h"
44 #include "sync/internal_api/sync_manager_impl.h"
45 #include "sync/internal_api/syncapi_internal.h"
46 #include "sync/js/js_backend.h"
47 #include "sync/js/js_event_handler.h"
48 #include "sync/js/js_test_util.h"
49 #include "sync/protocol/bookmark_specifics.pb.h"
50 #include "sync/protocol/encryption.pb.h"
51 #include "sync/protocol/extension_specifics.pb.h"
52 #include "sync/protocol/password_specifics.pb.h"
53 #include "sync/protocol/preference_specifics.pb.h"
54 #include "sync/protocol/proto_value_conversions.h"
55 #include "sync/protocol/sync.pb.h"
56 #include "sync/sessions/sync_session.h"
57 #include "sync/syncable/directory.h"
58 #include "sync/syncable/entry.h"
59 #include "sync/syncable/mutable_entry.h"
60 #include "sync/syncable/nigori_util.h"
61 #include "sync/syncable/syncable_id.h"
62 #include "sync/syncable/syncable_read_transaction.h"
63 #include "sync/syncable/syncable_util.h"
64 #include "sync/syncable/syncable_write_transaction.h"
65 #include "sync/test/callback_counter.h"
66 #include "sync/test/engine/fake_model_worker.h"
67 #include "sync/test/engine/fake_sync_scheduler.h"
68 #include "sync/test/engine/test_id_factory.h"
69 #include "sync/test/fake_encryptor.h"
70 #include "sync/util/cryptographer.h"
71 #include "sync/util/extensions_activity.h"
72 #include "sync/util/mock_unrecoverable_error_handler.h"
73 #include "sync/util/time.h"
74 #include "testing/gmock/include/gmock/gmock.h"
75 #include "testing/gtest/include/gtest/gtest.h"
78 using base::ExpectDictStringValue
;
81 using testing::InSequence
;
82 using testing::Return
;
83 using testing::SaveArg
;
84 using testing::StrictMock
;
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
;
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);
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);
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
,
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);
143 int64
MakeBookmarkWithParent(UserShare
* share
,
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
));
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
,
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
,
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();
214 class SyncApiTest
: public testing::Test
{
216 void SetUp() override
{ test_user_share_
.SetUp(); }
218 void TearDown() override
{ test_user_share_
.TearDown(); }
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
236 void ReplaceWithTombstone(const ModelType
& model_type
,
237 const std::string
& client_tag
);
239 // Save changes to the Directory, destroy it then reload it.
242 UserShare
* user_share();
243 syncable::Directory
* dir();
244 SyncEncryptionHandler
* encryption_handler();
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
);
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
,
383 ReadNode
prefnode(&trans
);
384 EXPECT_EQ(BaseNode::INIT_OK
,
385 prefnode
.InitByClientTagLookup(PREFERENCES
,
388 ReadNode
autofillnode(&trans
);
389 EXPECT_EQ(BaseNode::INIT_OK
,
390 autofillnode
.InitByClientTagLookup(AUTOFILL
,
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
,
408 WriteTransaction
trans(FROM_HERE
, user_share());
409 WriteNode
node(&trans
);
410 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD
,
411 node
.InitByClientTagLookup(BOOKMARKS
,
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
) {
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
,
450 EXPECT_FALSE(wnode
.GetIsFolder());
451 EXPECT_EQ(wnode
.GetTitle(), test_title
);
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
,
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
,
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
,
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();
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
,
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
) {
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
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()));
756 class TestHttpPostProviderInterface
: public HttpPostProviderInterface
{
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
,
764 const char* content
) override
{}
765 bool MakeSynchronousPost(int* error_code
, int* response_code
) override
{
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
{
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
{
791 MOCK_METHOD1(OnSyncCycleCompleted
,
792 void(const SyncSessionSnapshot
&)); // NOLINT
793 MOCK_METHOD4(OnInitializationComplete
,
794 void(const WeakHandle
<JsBackend
>&,
795 const WeakHandle
<DataTypeDebugInfoListener
>&,
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
{
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
820 MOCK_METHOD1(OnLocalSetPassphraseEncryption
,
821 void(const SyncEncryptionHandler::NigoriState
&)); // NOLINT
826 class SyncManagerTest
: public testing::Test
,
827 public SyncManager::ChangeDelegate
{
834 enum EncryptionStatus
{
841 : sync_manager_("Test sync manager"),
842 mock_unrecoverable_error_handler_(NULL
) {
843 switches_
.encryption_method
=
844 InternalComponentsFactory::ENCRYPTION_KEYSTORE
;
847 virtual ~SyncManagerTest() {
850 // Test implementation.
852 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
854 extensions_activity_
= new ExtensionsActivity();
856 SyncCredentials credentials
;
857 credentials
.email
= "foo@bar.com";
858 credentials
.sync_token
= "sometoken";
859 OAuth2TokenService::ScopeSet scope_set
;
860 scope_set
.insert(GaiaConstants::kChromeSyncOAuth2Scope
);
861 credentials
.scope_set
= scope_set
;
863 sync_manager_
.AddObserver(&manager_observer_
);
864 EXPECT_CALL(manager_observer_
, OnInitializationComplete(_
, _
, _
, _
)).
865 WillOnce(DoAll(SaveArg
<0>(&js_backend_
),
866 SaveArg
<2>(&initialization_succeeded_
)));
868 EXPECT_FALSE(js_backend_
.IsInitialized());
870 std::vector
<scoped_refptr
<ModelSafeWorker
> > workers
;
871 ModelSafeRoutingInfo routing_info
;
872 GetModelSafeRoutingInfo(&routing_info
);
874 // This works only because all routing info types are GROUP_PASSIVE.
875 // If we had types in other groups, we would need additional workers
877 scoped_refptr
<ModelSafeWorker
> worker
= new FakeModelWorker(GROUP_PASSIVE
);
878 workers
.push_back(worker
);
880 SyncManager::InitArgs args
;
881 args
.database_location
= temp_dir_
.path();
882 args
.service_url
= GURL("https://example.com/");
884 scoped_ptr
<HttpPostProviderFactory
>(new TestHttpPostProviderFactory());
885 args
.workers
= workers
;
886 args
.extensions_activity
= extensions_activity_
.get(),
887 args
.change_delegate
= this;
888 args
.credentials
= credentials
;
889 args
.invalidator_client_id
= "fake_invalidator_client_id";
890 args
.internal_components_factory
.reset(GetFactory());
891 args
.encryptor
= &encryptor_
;
892 mock_unrecoverable_error_handler_
= new MockUnrecoverableErrorHandler();
893 args
.unrecoverable_error_handler
.reset(mock_unrecoverable_error_handler_
);
894 args
.cancelation_signal
= &cancelation_signal_
;
895 sync_manager_
.Init(&args
);
897 sync_manager_
.GetEncryptionHandler()->AddObserver(&encryption_observer_
);
899 EXPECT_TRUE(js_backend_
.IsInitialized());
900 EXPECT_EQ(InternalComponentsFactory::STORAGE_ON_DISK
,
903 if (initialization_succeeded_
) {
904 for (ModelSafeRoutingInfo::iterator i
= routing_info
.begin();
905 i
!= routing_info
.end(); ++i
) {
906 type_roots_
[i
->first
] =
907 MakeTypeRoot(sync_manager_
.GetUserShare(), i
->first
);
915 sync_manager_
.RemoveObserver(&manager_observer_
);
916 sync_manager_
.ShutdownOnSyncThread(STOP_SYNC
);
920 void GetModelSafeRoutingInfo(ModelSafeRoutingInfo
* out
) {
921 (*out
)[NIGORI
] = GROUP_PASSIVE
;
922 (*out
)[DEVICE_INFO
] = GROUP_PASSIVE
;
923 (*out
)[EXPERIMENTS
] = GROUP_PASSIVE
;
924 (*out
)[BOOKMARKS
] = GROUP_PASSIVE
;
925 (*out
)[THEMES
] = GROUP_PASSIVE
;
926 (*out
)[SESSIONS
] = GROUP_PASSIVE
;
927 (*out
)[PASSWORDS
] = GROUP_PASSIVE
;
928 (*out
)[PREFERENCES
] = GROUP_PASSIVE
;
929 (*out
)[PRIORITY_PREFERENCES
] = GROUP_PASSIVE
;
930 (*out
)[ARTICLES
] = GROUP_PASSIVE
;
933 ModelTypeSet
GetEnabledTypes() {
934 ModelSafeRoutingInfo routing_info
;
935 GetModelSafeRoutingInfo(&routing_info
);
936 return GetRoutingInfoTypes(routing_info
);
939 void OnChangesApplied(
940 ModelType model_type
,
942 const BaseTransaction
* trans
,
943 const ImmutableChangeRecordList
& changes
) override
{}
945 void OnChangesComplete(ModelType model_type
) override
{}
948 bool SetUpEncryption(NigoriStatus nigori_status
,
949 EncryptionStatus encryption_status
) {
950 UserShare
* share
= sync_manager_
.GetUserShare();
952 // We need to create the nigori node as if it were an applied server update.
953 int64 nigori_id
= GetIdForDataType(NIGORI
);
954 if (nigori_id
== kInvalidId
)
957 // Set the nigori cryptographer information.
958 if (encryption_status
== FULL_ENCRYPTION
)
959 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
961 WriteTransaction
trans(FROM_HERE
, share
);
962 Cryptographer
* cryptographer
= trans
.GetCryptographer();
965 if (encryption_status
!= UNINITIALIZED
) {
966 KeyParams params
= {"localhost", "dummy", "foobar"};
967 cryptographer
->AddKey(params
);
969 DCHECK_NE(nigori_status
, WRITE_TO_NIGORI
);
971 if (nigori_status
== WRITE_TO_NIGORI
) {
972 sync_pb::NigoriSpecifics nigori
;
973 cryptographer
->GetKeys(nigori
.mutable_encryption_keybag());
974 share
->directory
->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
976 trans
.GetWrappedTrans());
977 WriteNode
node(&trans
);
978 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(nigori_id
));
979 node
.SetNigoriSpecifics(nigori
);
981 return cryptographer
->is_ready();
984 int64
GetIdForDataType(ModelType type
) {
985 if (type_roots_
.count(type
) == 0)
987 return type_roots_
[type
];
991 base::RunLoop().RunUntilIdle();
994 void SetJsEventHandler(const WeakHandle
<JsEventHandler
>& event_handler
) {
995 js_backend_
.Call(FROM_HERE
, &JsBackend::SetJsEventHandler
,
1000 // Looks up an entry by client tag and resets IS_UNSYNCED value to false.
1001 // Returns true if entry was previously unsynced, false if IS_UNSYNCED was
1003 bool ResetUnsyncedEntry(ModelType type
,
1004 const std::string
& client_tag
) {
1005 UserShare
* share
= sync_manager_
.GetUserShare();
1006 syncable::WriteTransaction
trans(
1007 FROM_HERE
, syncable::UNITTEST
, share
->directory
.get());
1008 const std::string hash
= syncable::GenerateSyncableHash(type
, client_tag
);
1009 syncable::MutableEntry
entry(&trans
, syncable::GET_BY_CLIENT_TAG
,
1011 EXPECT_TRUE(entry
.good());
1012 if (!entry
.GetIsUnsynced())
1014 entry
.PutIsUnsynced(false);
1018 virtual InternalComponentsFactory
* GetFactory() {
1019 return new TestInternalComponentsFactory(
1020 GetSwitches(), InternalComponentsFactory::STORAGE_IN_MEMORY
,
1024 // Returns true if we are currently encrypting all sync data. May
1025 // be called on any thread.
1026 bool EncryptEverythingEnabledForTest() {
1027 return sync_manager_
.GetEncryptionHandler()->EncryptEverythingEnabled();
1030 // Gets the set of encrypted types from the cryptographer
1031 // Note: opens a transaction. May be called from any thread.
1032 ModelTypeSet
GetEncryptedTypes() {
1033 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1034 return GetEncryptedTypesWithTrans(&trans
);
1037 ModelTypeSet
GetEncryptedTypesWithTrans(BaseTransaction
* trans
) {
1038 return trans
->GetDirectory()->GetNigoriHandler()->
1039 GetEncryptedTypes(trans
->GetWrappedTrans());
1042 void SimulateInvalidatorEnabledForTest(bool is_enabled
) {
1043 DCHECK(sync_manager_
.thread_checker_
.CalledOnValidThread());
1044 sync_manager_
.SetInvalidatorEnabled(is_enabled
);
1047 void SetProgressMarkerForType(ModelType type
, bool set
) {
1049 sync_pb::DataTypeProgressMarker marker
;
1050 marker
.set_token("token");
1051 marker
.set_data_type_id(GetSpecificsFieldNumberFromModelType(type
));
1052 sync_manager_
.directory()->SetDownloadProgress(type
, marker
);
1054 sync_pb::DataTypeProgressMarker marker
;
1055 sync_manager_
.directory()->SetDownloadProgress(type
, marker
);
1059 InternalComponentsFactory::Switches
GetSwitches() const {
1063 void ExpectPassphraseAcceptance() {
1064 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1065 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1066 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1069 void SetImplicitPassphraseAndCheck(const std::string
& passphrase
) {
1070 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1073 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1074 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1077 void SetCustomPassphraseAndCheck(const std::string
& passphrase
) {
1078 EXPECT_CALL(encryption_observer_
,
1079 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1080 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1083 EXPECT_EQ(CUSTOM_PASSPHRASE
,
1084 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1087 bool HasUnrecoverableError() {
1088 if (mock_unrecoverable_error_handler_
)
1089 return mock_unrecoverable_error_handler_
->invocation_count() > 0;
1094 // Needed by |sync_manager_|.
1095 base::MessageLoop message_loop_
;
1096 // Needed by |sync_manager_|.
1097 base::ScopedTempDir temp_dir_
;
1098 // Sync Id's for the roots of the enabled datatypes.
1099 std::map
<ModelType
, int64
> type_roots_
;
1100 scoped_refptr
<ExtensionsActivity
> extensions_activity_
;
1103 FakeEncryptor encryptor_
;
1104 SyncManagerImpl sync_manager_
;
1105 CancelationSignal cancelation_signal_
;
1106 WeakHandle
<JsBackend
> js_backend_
;
1107 bool initialization_succeeded_
;
1108 StrictMock
<SyncManagerObserverMock
> manager_observer_
;
1109 StrictMock
<SyncEncryptionHandlerObserverMock
> encryption_observer_
;
1110 InternalComponentsFactory::Switches switches_
;
1111 InternalComponentsFactory::StorageOption storage_used_
;
1113 // Not owned (ownership is passed to the SyncManager).
1114 MockUnrecoverableErrorHandler
* mock_unrecoverable_error_handler_
;
1117 TEST_F(SyncManagerTest
, GetAllNodesForTypeTest
) {
1118 ModelSafeRoutingInfo routing_info
;
1119 GetModelSafeRoutingInfo(&routing_info
);
1120 sync_manager_
.StartSyncingNormally(routing_info
, base::Time());
1122 scoped_ptr
<base::ListValue
> node_list(
1123 sync_manager_
.GetAllNodesForType(syncer::PREFERENCES
));
1125 // Should have one node: the type root node.
1126 ASSERT_EQ(1U, node_list
->GetSize());
1128 const base::DictionaryValue
* first_result
;
1129 ASSERT_TRUE(node_list
->GetDictionary(0, &first_result
));
1130 EXPECT_TRUE(first_result
->HasKey("ID"));
1131 EXPECT_TRUE(first_result
->HasKey("NON_UNIQUE_NAME"));
1134 TEST_F(SyncManagerTest
, RefreshEncryptionReady
) {
1135 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1136 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1137 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1138 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1140 sync_manager_
.GetEncryptionHandler()->Init();
1143 const ModelTypeSet encrypted_types
= GetEncryptedTypes();
1144 EXPECT_TRUE(encrypted_types
.Has(PASSWORDS
));
1145 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1148 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1149 ReadNode
node(&trans
);
1150 EXPECT_EQ(BaseNode::INIT_OK
,
1151 node
.InitByIdLookup(GetIdForDataType(NIGORI
)));
1152 sync_pb::NigoriSpecifics nigori
= node
.GetNigoriSpecifics();
1153 EXPECT_TRUE(nigori
.has_encryption_keybag());
1154 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1155 EXPECT_TRUE(cryptographer
->is_ready());
1156 EXPECT_TRUE(cryptographer
->CanDecrypt(nigori
.encryption_keybag()));
1160 // Attempt to refresh encryption when nigori not downloaded.
1161 TEST_F(SyncManagerTest
, RefreshEncryptionNotReady
) {
1162 // Don't set up encryption (no nigori node created).
1164 // Should fail. Triggers an OnPassphraseRequired because the cryptographer
1166 EXPECT_CALL(encryption_observer_
, OnPassphraseRequired(_
, _
)).Times(1);
1167 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1168 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1169 sync_manager_
.GetEncryptionHandler()->Init();
1172 const ModelTypeSet encrypted_types
= GetEncryptedTypes();
1173 EXPECT_TRUE(encrypted_types
.Has(PASSWORDS
)); // Hardcoded.
1174 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1177 // Attempt to refresh encryption when nigori is empty.
1178 TEST_F(SyncManagerTest
, RefreshEncryptionEmptyNigori
) {
1179 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI
, DEFAULT_ENCRYPTION
));
1180 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete()).Times(1);
1181 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1182 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1184 // Should write to nigori.
1185 sync_manager_
.GetEncryptionHandler()->Init();
1188 const ModelTypeSet encrypted_types
= GetEncryptedTypes();
1189 EXPECT_TRUE(encrypted_types
.Has(PASSWORDS
)); // Hardcoded.
1190 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1193 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1194 ReadNode
node(&trans
);
1195 EXPECT_EQ(BaseNode::INIT_OK
,
1196 node
.InitByIdLookup(GetIdForDataType(NIGORI
)));
1197 sync_pb::NigoriSpecifics nigori
= node
.GetNigoriSpecifics();
1198 EXPECT_TRUE(nigori
.has_encryption_keybag());
1199 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1200 EXPECT_TRUE(cryptographer
->is_ready());
1201 EXPECT_TRUE(cryptographer
->CanDecrypt(nigori
.encryption_keybag()));
1205 TEST_F(SyncManagerTest
, EncryptDataTypesWithNoData
) {
1206 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1207 EXPECT_CALL(encryption_observer_
,
1208 OnEncryptedTypesChanged(
1209 HasModelTypes(EncryptableUserTypes()), true));
1210 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1211 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1212 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1215 TEST_F(SyncManagerTest
, EncryptDataTypesWithData
) {
1216 size_t batch_size
= 5;
1217 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1219 // Create some unencrypted unsynced data.
1220 int64 folder
= MakeFolderWithParent(sync_manager_
.GetUserShare(),
1222 GetIdForDataType(BOOKMARKS
),
1224 // First batch_size nodes are children of folder.
1226 for (i
= 0; i
< batch_size
; ++i
) {
1227 MakeBookmarkWithParent(sync_manager_
.GetUserShare(), folder
, NULL
);
1229 // Next batch_size nodes are a different type and on their own.
1230 for (; i
< 2*batch_size
; ++i
) {
1231 MakeNodeWithRoot(sync_manager_
.GetUserShare(), SESSIONS
,
1232 base::StringPrintf("%" PRIuS
"", i
));
1234 // Last batch_size nodes are a third type that will not need encryption.
1235 for (; i
< 3*batch_size
; ++i
) {
1236 MakeNodeWithRoot(sync_manager_
.GetUserShare(), THEMES
,
1237 base::StringPrintf("%" PRIuS
"", i
));
1241 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1242 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1243 SyncEncryptionHandler::SensitiveTypes()));
1244 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1245 trans
.GetWrappedTrans(),
1247 false /* not encrypted */));
1248 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1249 trans
.GetWrappedTrans(),
1251 false /* not encrypted */));
1252 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1253 trans
.GetWrappedTrans(),
1255 false /* not encrypted */));
1258 EXPECT_CALL(encryption_observer_
,
1259 OnEncryptedTypesChanged(
1260 HasModelTypes(EncryptableUserTypes()), true));
1261 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1262 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1263 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1265 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1266 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1267 EncryptableUserTypes()));
1268 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1269 trans
.GetWrappedTrans(),
1271 true /* is encrypted */));
1272 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1273 trans
.GetWrappedTrans(),
1275 true /* is encrypted */));
1276 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1277 trans
.GetWrappedTrans(),
1279 true /* is encrypted */));
1282 // Trigger's a ReEncryptEverything with new passphrase.
1283 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1284 EXPECT_CALL(encryption_observer_
,
1285 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1286 ExpectPassphraseAcceptance();
1287 SetCustomPassphraseAndCheck("new_passphrase");
1288 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1290 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1291 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1292 EncryptableUserTypes()));
1293 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1294 trans
.GetWrappedTrans(),
1296 true /* is encrypted */));
1297 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1298 trans
.GetWrappedTrans(),
1300 true /* is encrypted */));
1301 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1302 trans
.GetWrappedTrans(),
1304 true /* is encrypted */));
1306 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1307 // a reencryption and should just notify immediately.
1308 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1309 EXPECT_CALL(encryption_observer_
,
1310 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
)).Times(0);
1311 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted()).Times(0);
1312 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete()).Times(0);
1313 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1316 // Test that when there are no pending keys and the cryptographer is not
1317 // initialized, we add a key based on the current GAIA password.
1318 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1319 TEST_F(SyncManagerTest
, SetInitialGaiaPass
) {
1320 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI
, UNINITIALIZED
));
1321 EXPECT_CALL(encryption_observer_
,
1322 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1323 ExpectPassphraseAcceptance();
1324 SetImplicitPassphraseAndCheck("new_passphrase");
1325 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1327 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1328 ReadNode
node(&trans
);
1329 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1330 sync_pb::NigoriSpecifics nigori
= node
.GetNigoriSpecifics();
1331 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1332 EXPECT_TRUE(cryptographer
->is_ready());
1333 EXPECT_TRUE(cryptographer
->CanDecrypt(nigori
.encryption_keybag()));
1337 // Test that when there are no pending keys and we have on the old GAIA
1338 // password, we update and re-encrypt everything with the new GAIA password.
1339 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1340 TEST_F(SyncManagerTest
, UpdateGaiaPass
) {
1341 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1342 Cryptographer
verifier(&encryptor_
);
1344 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1345 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1346 std::string bootstrap_token
;
1347 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1348 verifier
.Bootstrap(bootstrap_token
);
1350 EXPECT_CALL(encryption_observer_
,
1351 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1352 ExpectPassphraseAcceptance();
1353 SetImplicitPassphraseAndCheck("new_passphrase");
1354 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1356 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1357 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1358 EXPECT_TRUE(cryptographer
->is_ready());
1359 // Verify the default key has changed.
1360 sync_pb::EncryptedData encrypted
;
1361 cryptographer
->GetKeys(&encrypted
);
1362 EXPECT_FALSE(verifier
.CanDecrypt(encrypted
));
1366 // Sets a new explicit passphrase. This should update the bootstrap token
1367 // and re-encrypt everything.
1368 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1369 TEST_F(SyncManagerTest
, SetPassphraseWithPassword
) {
1370 Cryptographer
verifier(&encryptor_
);
1371 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1373 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1374 // Store the default (soon to be old) key.
1375 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1376 std::string bootstrap_token
;
1377 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1378 verifier
.Bootstrap(bootstrap_token
);
1380 ReadNode
root_node(&trans
);
1381 root_node
.InitByRootLookup();
1383 WriteNode
password_node(&trans
);
1384 WriteNode::InitUniqueByCreationResult result
=
1385 password_node
.InitUniqueByCreation(PASSWORDS
,
1387 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
1388 sync_pb::PasswordSpecificsData data
;
1389 data
.set_password_value("secret");
1390 password_node
.SetPasswordSpecifics(data
);
1392 EXPECT_CALL(encryption_observer_
,
1393 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1394 ExpectPassphraseAcceptance();
1395 SetCustomPassphraseAndCheck("new_passphrase");
1396 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1398 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1399 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1400 EXPECT_TRUE(cryptographer
->is_ready());
1401 // Verify the default key has changed.
1402 sync_pb::EncryptedData encrypted
;
1403 cryptographer
->GetKeys(&encrypted
);
1404 EXPECT_FALSE(verifier
.CanDecrypt(encrypted
));
1406 ReadNode
password_node(&trans
);
1407 EXPECT_EQ(BaseNode::INIT_OK
,
1408 password_node
.InitByClientTagLookup(PASSWORDS
,
1410 const sync_pb::PasswordSpecificsData
& data
=
1411 password_node
.GetPasswordSpecifics();
1412 EXPECT_EQ("secret", data
.password_value());
1416 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1417 // being encrypted with a new (unprovided) GAIA password, then supply the
1419 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1420 TEST_F(SyncManagerTest
, SupplyPendingGAIAPass
) {
1421 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1422 Cryptographer
other_cryptographer(&encryptor_
);
1424 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1425 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1426 std::string bootstrap_token
;
1427 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1428 other_cryptographer
.Bootstrap(bootstrap_token
);
1430 // Now update the nigori to reflect the new keys, and update the
1431 // cryptographer to have pending keys.
1432 KeyParams params
= {"localhost", "dummy", "passphrase2"};
1433 other_cryptographer
.AddKey(params
);
1434 WriteNode
node(&trans
);
1435 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1436 sync_pb::NigoriSpecifics nigori
;
1437 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1438 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1439 EXPECT_TRUE(cryptographer
->has_pending_keys());
1440 node
.SetNigoriSpecifics(nigori
);
1442 EXPECT_CALL(encryption_observer_
,
1443 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1444 ExpectPassphraseAcceptance();
1445 sync_manager_
.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
1446 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1447 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1448 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1450 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1451 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1452 EXPECT_TRUE(cryptographer
->is_ready());
1453 // Verify we're encrypting with the new key.
1454 sync_pb::EncryptedData encrypted
;
1455 cryptographer
->GetKeys(&encrypted
);
1456 EXPECT_TRUE(other_cryptographer
.CanDecrypt(encrypted
));
1460 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1461 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1462 // the current GAIA password and verify the bootstrap token is updated. Then
1463 // supply the old GAIA password, and verify we re-encrypt all data with the
1464 // new GAIA password.
1465 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1466 TEST_F(SyncManagerTest
, SupplyPendingOldGAIAPass
) {
1467 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1468 Cryptographer
other_cryptographer(&encryptor_
);
1470 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1471 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1472 std::string bootstrap_token
;
1473 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1474 other_cryptographer
.Bootstrap(bootstrap_token
);
1476 // Now update the nigori to reflect the new keys, and update the
1477 // cryptographer to have pending keys.
1478 KeyParams params
= {"localhost", "dummy", "old_gaia"};
1479 other_cryptographer
.AddKey(params
);
1480 WriteNode
node(&trans
);
1481 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1482 sync_pb::NigoriSpecifics nigori
;
1483 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1484 node
.SetNigoriSpecifics(nigori
);
1485 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1487 // other_cryptographer now contains all encryption keys, and is encrypting
1488 // with the newest gaia.
1489 KeyParams new_params
= {"localhost", "dummy", "new_gaia"};
1490 other_cryptographer
.AddKey(new_params
);
1492 // The bootstrap token should have been updated. Save it to ensure it's based
1493 // on the new GAIA password.
1494 std::string bootstrap_token
;
1495 EXPECT_CALL(encryption_observer_
,
1496 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
))
1497 .WillOnce(SaveArg
<0>(&bootstrap_token
));
1498 EXPECT_CALL(encryption_observer_
, OnPassphraseRequired(_
,_
));
1499 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1500 SetImplicitPassphraseAndCheck("new_gaia");
1501 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1502 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1504 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1505 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1506 EXPECT_TRUE(cryptographer
->is_initialized());
1507 EXPECT_FALSE(cryptographer
->is_ready());
1508 // Verify we're encrypting with the new key, even though we have pending
1510 sync_pb::EncryptedData encrypted
;
1511 other_cryptographer
.GetKeys(&encrypted
);
1512 EXPECT_TRUE(cryptographer
->CanDecrypt(encrypted
));
1514 EXPECT_CALL(encryption_observer_
,
1515 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1516 ExpectPassphraseAcceptance();
1517 SetImplicitPassphraseAndCheck("old_gaia");
1519 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1520 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1521 EXPECT_TRUE(cryptographer
->is_ready());
1523 // Verify we're encrypting with the new key.
1524 sync_pb::EncryptedData encrypted
;
1525 other_cryptographer
.GetKeys(&encrypted
);
1526 EXPECT_TRUE(cryptographer
->CanDecrypt(encrypted
));
1528 // Verify the saved bootstrap token is based on the new gaia password.
1529 Cryptographer
temp_cryptographer(&encryptor_
);
1530 temp_cryptographer
.Bootstrap(bootstrap_token
);
1531 EXPECT_TRUE(temp_cryptographer
.CanDecrypt(encrypted
));
1535 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1536 // being encrypted with an explicit (unprovided) passphrase, then supply the
1538 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1539 TEST_F(SyncManagerTest
, SupplyPendingExplicitPass
) {
1540 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1541 Cryptographer
other_cryptographer(&encryptor_
);
1543 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1544 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1545 std::string bootstrap_token
;
1546 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1547 other_cryptographer
.Bootstrap(bootstrap_token
);
1549 // Now update the nigori to reflect the new keys, and update the
1550 // cryptographer to have pending keys.
1551 KeyParams params
= {"localhost", "dummy", "explicit"};
1552 other_cryptographer
.AddKey(params
);
1553 WriteNode
node(&trans
);
1554 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1555 sync_pb::NigoriSpecifics nigori
;
1556 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1557 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1558 EXPECT_TRUE(cryptographer
->has_pending_keys());
1559 nigori
.set_keybag_is_frozen(true);
1560 node
.SetNigoriSpecifics(nigori
);
1562 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1563 EXPECT_CALL(encryption_observer_
,
1564 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1565 EXPECT_CALL(encryption_observer_
, OnPassphraseRequired(_
, _
));
1566 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1567 sync_manager_
.GetEncryptionHandler()->Init();
1568 EXPECT_CALL(encryption_observer_
,
1569 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1570 ExpectPassphraseAcceptance();
1571 sync_manager_
.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
1572 EXPECT_EQ(CUSTOM_PASSPHRASE
,
1573 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1574 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1576 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1577 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1578 EXPECT_TRUE(cryptographer
->is_ready());
1579 // Verify we're encrypting with the new key.
1580 sync_pb::EncryptedData encrypted
;
1581 cryptographer
->GetKeys(&encrypted
);
1582 EXPECT_TRUE(other_cryptographer
.CanDecrypt(encrypted
));
1586 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1587 // being encrypted with a new (unprovided) GAIA password, then supply the
1588 // password as a user-provided password.
1589 // This is the android case 7/8.
1590 TEST_F(SyncManagerTest
, SupplyPendingGAIAPassUserProvided
) {
1591 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI
, UNINITIALIZED
));
1592 Cryptographer
other_cryptographer(&encryptor_
);
1594 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1595 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1596 // Now update the nigori to reflect the new keys, and update the
1597 // cryptographer to have pending keys.
1598 KeyParams params
= {"localhost", "dummy", "passphrase"};
1599 other_cryptographer
.AddKey(params
);
1600 WriteNode
node(&trans
);
1601 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1602 sync_pb::NigoriSpecifics nigori
;
1603 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1604 node
.SetNigoriSpecifics(nigori
);
1605 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1606 EXPECT_FALSE(cryptographer
->is_ready());
1608 EXPECT_CALL(encryption_observer_
,
1609 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1610 ExpectPassphraseAcceptance();
1611 SetImplicitPassphraseAndCheck("passphrase");
1612 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1614 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1615 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1616 EXPECT_TRUE(cryptographer
->is_ready());
1620 TEST_F(SyncManagerTest
, SetPassphraseWithEmptyPasswordNode
) {
1621 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1623 std::string tag
= "foo";
1625 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1626 ReadNode
root_node(&trans
);
1627 root_node
.InitByRootLookup();
1629 WriteNode
password_node(&trans
);
1630 WriteNode::InitUniqueByCreationResult result
=
1631 password_node
.InitUniqueByCreation(PASSWORDS
, root_node
, tag
);
1632 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
1633 node_id
= password_node
.GetId();
1635 EXPECT_CALL(encryption_observer_
,
1636 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1637 ExpectPassphraseAcceptance();
1638 SetCustomPassphraseAndCheck("new_passphrase");
1639 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1641 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1642 ReadNode
password_node(&trans
);
1643 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY
,
1644 password_node
.InitByClientTagLookup(PASSWORDS
,
1648 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1649 ReadNode
password_node(&trans
);
1650 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY
,
1651 password_node
.InitByIdLookup(node_id
));
1655 // Friended by WriteNode, so can't be in an anonymouse namespace.
1656 TEST_F(SyncManagerTest
, EncryptBookmarksWithLegacyData
) {
1657 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1659 SyncAPINameToServerName("Google", &title
);
1660 std::string url
= "http://www.google.com";
1661 std::string raw_title2
= ".."; // An invalid cosmo title.
1663 SyncAPINameToServerName(raw_title2
, &title2
);
1664 std::string url2
= "http://www.bla.com";
1666 // Create a bookmark using the legacy format.
1668 MakeNodeWithRoot(sync_manager_
.GetUserShare(), BOOKMARKS
, "testtag");
1670 MakeNodeWithRoot(sync_manager_
.GetUserShare(), BOOKMARKS
, "testtag2");
1672 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1673 WriteNode
node(&trans
);
1674 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(node_id1
));
1676 sync_pb::EntitySpecifics entity_specifics
;
1677 entity_specifics
.mutable_bookmark()->set_url(url
);
1678 node
.SetEntitySpecifics(entity_specifics
);
1680 // Set the old style title.
1681 syncable::MutableEntry
* node_entry
= node
.entry_
;
1682 node_entry
->PutNonUniqueName(title
);
1684 WriteNode
node2(&trans
);
1685 EXPECT_EQ(BaseNode::INIT_OK
, node2
.InitByIdLookup(node_id2
));
1687 sync_pb::EntitySpecifics entity_specifics2
;
1688 entity_specifics2
.mutable_bookmark()->set_url(url2
);
1689 node2
.SetEntitySpecifics(entity_specifics2
);
1691 // Set the old style title.
1692 syncable::MutableEntry
* node_entry2
= node2
.entry_
;
1693 node_entry2
->PutNonUniqueName(title2
);
1697 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1698 ReadNode
node(&trans
);
1699 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(node_id1
));
1700 EXPECT_EQ(BOOKMARKS
, node
.GetModelType());
1701 EXPECT_EQ(title
, node
.GetTitle());
1702 EXPECT_EQ(title
, node
.GetBookmarkSpecifics().title());
1703 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
1705 ReadNode
node2(&trans
);
1706 EXPECT_EQ(BaseNode::INIT_OK
, node2
.InitByIdLookup(node_id2
));
1707 EXPECT_EQ(BOOKMARKS
, node2
.GetModelType());
1708 // We should de-canonicalize the title in GetTitle(), but the title in the
1709 // specifics should be stored in the server legal form.
1710 EXPECT_EQ(raw_title2
, node2
.GetTitle());
1711 EXPECT_EQ(title2
, node2
.GetBookmarkSpecifics().title());
1712 EXPECT_EQ(url2
, node2
.GetBookmarkSpecifics().url());
1716 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1717 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1718 trans
.GetWrappedTrans(),
1720 false /* not encrypted */));
1723 EXPECT_CALL(encryption_observer_
,
1724 OnEncryptedTypesChanged(
1725 HasModelTypes(EncryptableUserTypes()), true));
1726 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1727 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1728 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1731 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1732 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1733 EncryptableUserTypes()));
1734 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1735 trans
.GetWrappedTrans(),
1737 true /* is encrypted */));
1739 ReadNode
node(&trans
);
1740 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(node_id1
));
1741 EXPECT_EQ(BOOKMARKS
, node
.GetModelType());
1742 EXPECT_EQ(title
, node
.GetTitle());
1743 EXPECT_EQ(title
, node
.GetBookmarkSpecifics().title());
1744 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
1746 ReadNode
node2(&trans
);
1747 EXPECT_EQ(BaseNode::INIT_OK
, node2
.InitByIdLookup(node_id2
));
1748 EXPECT_EQ(BOOKMARKS
, node2
.GetModelType());
1749 // We should de-canonicalize the title in GetTitle(), but the title in the
1750 // specifics should be stored in the server legal form.
1751 EXPECT_EQ(raw_title2
, node2
.GetTitle());
1752 EXPECT_EQ(title2
, node2
.GetBookmarkSpecifics().title());
1753 EXPECT_EQ(url2
, node2
.GetBookmarkSpecifics().url());
1757 // Create a bookmark and set the title/url, then verify the data was properly
1758 // set. This replicates the unique way bookmarks have of creating sync nodes.
1759 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1760 TEST_F(SyncManagerTest
, CreateLocalBookmark
) {
1761 std::string title
= "title";
1762 std::string url
= "url";
1764 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1765 ReadNode
bookmark_root(&trans
);
1766 ASSERT_EQ(BaseNode::INIT_OK
, bookmark_root
.InitTypeRoot(BOOKMARKS
));
1767 WriteNode
node(&trans
);
1768 ASSERT_TRUE(node
.InitBookmarkByCreation(bookmark_root
, NULL
));
1769 node
.SetIsFolder(false);
1770 node
.SetTitle(title
);
1772 sync_pb::BookmarkSpecifics
bookmark_specifics(node
.GetBookmarkSpecifics());
1773 bookmark_specifics
.set_url(url
);
1774 node
.SetBookmarkSpecifics(bookmark_specifics
);
1777 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1778 ReadNode
bookmark_root(&trans
);
1779 ASSERT_EQ(BaseNode::INIT_OK
, bookmark_root
.InitTypeRoot(BOOKMARKS
));
1780 int64 child_id
= bookmark_root
.GetFirstChildId();
1782 ReadNode
node(&trans
);
1783 ASSERT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(child_id
));
1784 EXPECT_FALSE(node
.GetIsFolder());
1785 EXPECT_EQ(title
, node
.GetTitle());
1786 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
1790 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1792 TEST_F(SyncManagerTest
, UpdateEntryWithEncryption
) {
1793 std::string client_tag
= "title";
1794 sync_pb::EntitySpecifics entity_specifics
;
1795 entity_specifics
.mutable_bookmark()->set_url("url");
1796 entity_specifics
.mutable_bookmark()->set_title("title");
1797 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
1798 syncable::GenerateSyncableHash(BOOKMARKS
,
1801 // New node shouldn't start off unsynced.
1802 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1803 // Manually change to the same data. Should not set is_unsynced.
1805 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1806 WriteNode
node(&trans
);
1807 EXPECT_EQ(BaseNode::INIT_OK
,
1808 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1809 node
.SetEntitySpecifics(entity_specifics
);
1811 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1813 // Encrypt the datatatype, should set is_unsynced.
1814 EXPECT_CALL(encryption_observer_
,
1815 OnEncryptedTypesChanged(
1816 HasModelTypes(EncryptableUserTypes()), true));
1817 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1818 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
1820 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1821 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
1822 sync_manager_
.GetEncryptionHandler()->Init();
1825 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1826 ReadNode
node(&trans
);
1827 EXPECT_EQ(BaseNode::INIT_OK
,
1828 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1829 const syncable::Entry
* node_entry
= node
.GetEntry();
1830 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1831 EXPECT_TRUE(specifics
.has_encrypted());
1832 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1833 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1834 EXPECT_TRUE(cryptographer
->is_ready());
1835 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1836 specifics
.encrypted()));
1838 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1840 // Set a new passphrase. Should set is_unsynced.
1841 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1842 EXPECT_CALL(encryption_observer_
,
1843 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1844 ExpectPassphraseAcceptance();
1845 SetCustomPassphraseAndCheck("new_passphrase");
1847 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1848 ReadNode
node(&trans
);
1849 EXPECT_EQ(BaseNode::INIT_OK
,
1850 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1851 const syncable::Entry
* node_entry
= node
.GetEntry();
1852 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1853 EXPECT_TRUE(specifics
.has_encrypted());
1854 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1855 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1856 EXPECT_TRUE(cryptographer
->is_ready());
1857 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1858 specifics
.encrypted()));
1860 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1862 // Force a re-encrypt everything. Should not set is_unsynced.
1863 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1864 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1865 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1866 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
1868 sync_manager_
.GetEncryptionHandler()->Init();
1872 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1873 ReadNode
node(&trans
);
1874 EXPECT_EQ(BaseNode::INIT_OK
,
1875 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1876 const syncable::Entry
* node_entry
= node
.GetEntry();
1877 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1878 EXPECT_TRUE(specifics
.has_encrypted());
1879 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1880 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1881 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1882 specifics
.encrypted()));
1884 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1886 // Manually change to the same data. Should not set is_unsynced.
1888 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1889 WriteNode
node(&trans
);
1890 EXPECT_EQ(BaseNode::INIT_OK
,
1891 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1892 node
.SetEntitySpecifics(entity_specifics
);
1893 const syncable::Entry
* node_entry
= node
.GetEntry();
1894 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1895 EXPECT_TRUE(specifics
.has_encrypted());
1896 EXPECT_FALSE(node_entry
->GetIsUnsynced());
1897 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1898 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1899 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1900 specifics
.encrypted()));
1902 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1904 // Manually change to different data. Should set is_unsynced.
1906 entity_specifics
.mutable_bookmark()->set_url("url2");
1907 entity_specifics
.mutable_bookmark()->set_title("title2");
1908 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1909 WriteNode
node(&trans
);
1910 EXPECT_EQ(BaseNode::INIT_OK
,
1911 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1912 node
.SetEntitySpecifics(entity_specifics
);
1913 const syncable::Entry
* node_entry
= node
.GetEntry();
1914 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1915 EXPECT_TRUE(specifics
.has_encrypted());
1916 EXPECT_TRUE(node_entry
->GetIsUnsynced());
1917 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1918 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1919 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1920 specifics
.encrypted()));
1924 // Passwords have their own handling for encryption. Verify it does not result
1925 // in unnecessary writes via SetEntitySpecifics.
1926 TEST_F(SyncManagerTest
, UpdatePasswordSetEntitySpecificsNoChange
) {
1927 std::string client_tag
= "title";
1928 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1929 sync_pb::EntitySpecifics entity_specifics
;
1931 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1932 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1933 sync_pb::PasswordSpecificsData data
;
1934 data
.set_password_value("secret");
1935 cryptographer
->Encrypt(
1937 entity_specifics
.mutable_password()->
1938 mutable_encrypted());
1940 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
1941 syncable::GenerateSyncableHash(PASSWORDS
,
1944 // New node shouldn't start off unsynced.
1945 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1947 // Manually change to the same data via SetEntitySpecifics. Should not set
1950 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1951 WriteNode
node(&trans
);
1952 EXPECT_EQ(BaseNode::INIT_OK
,
1953 node
.InitByClientTagLookup(PASSWORDS
, client_tag
));
1954 node
.SetEntitySpecifics(entity_specifics
);
1956 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1959 // Passwords have their own handling for encryption. Verify it does not result
1960 // in unnecessary writes via SetPasswordSpecifics.
1961 TEST_F(SyncManagerTest
, UpdatePasswordSetPasswordSpecifics
) {
1962 std::string client_tag
= "title";
1963 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1964 sync_pb::EntitySpecifics entity_specifics
;
1966 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1967 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1968 sync_pb::PasswordSpecificsData data
;
1969 data
.set_password_value("secret");
1970 cryptographer
->Encrypt(
1972 entity_specifics
.mutable_password()->
1973 mutable_encrypted());
1975 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
1976 syncable::GenerateSyncableHash(PASSWORDS
,
1979 // New node shouldn't start off unsynced.
1980 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1982 // Manually change to the same data via SetPasswordSpecifics. Should not set
1985 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1986 WriteNode
node(&trans
);
1987 EXPECT_EQ(BaseNode::INIT_OK
,
1988 node
.InitByClientTagLookup(PASSWORDS
, client_tag
));
1989 node
.SetPasswordSpecifics(node
.GetPasswordSpecifics());
1991 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1993 // Manually change to different data. Should set is_unsynced.
1995 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1996 WriteNode
node(&trans
);
1997 EXPECT_EQ(BaseNode::INIT_OK
,
1998 node
.InitByClientTagLookup(PASSWORDS
, client_tag
));
1999 Cryptographer
* cryptographer
= trans
.GetCryptographer();
2000 sync_pb::PasswordSpecificsData data
;
2001 data
.set_password_value("secret2");
2002 cryptographer
->Encrypt(
2004 entity_specifics
.mutable_password()->mutable_encrypted());
2005 node
.SetPasswordSpecifics(data
);
2006 const syncable::Entry
* node_entry
= node
.GetEntry();
2007 EXPECT_TRUE(node_entry
->GetIsUnsynced());
2011 // Passwords have their own handling for encryption. Verify setting a new
2012 // passphrase updates the data.
2013 TEST_F(SyncManagerTest
, UpdatePasswordNewPassphrase
) {
2014 std::string client_tag
= "title";
2015 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
2016 sync_pb::EntitySpecifics entity_specifics
;
2018 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2019 Cryptographer
* cryptographer
= trans
.GetCryptographer();
2020 sync_pb::PasswordSpecificsData data
;
2021 data
.set_password_value("secret");
2022 cryptographer
->Encrypt(
2024 entity_specifics
.mutable_password()->mutable_encrypted());
2026 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
2027 syncable::GenerateSyncableHash(PASSWORDS
,
2030 // New node shouldn't start off unsynced.
2031 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2033 // Set a new passphrase. Should set is_unsynced.
2034 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
2035 EXPECT_CALL(encryption_observer_
,
2036 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
2037 ExpectPassphraseAcceptance();
2038 SetCustomPassphraseAndCheck("new_passphrase");
2039 EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2042 // Passwords have their own handling for encryption. Verify it does not result
2043 // in unnecessary writes via ReencryptEverything.
2044 TEST_F(SyncManagerTest
, UpdatePasswordReencryptEverything
) {
2045 std::string client_tag
= "title";
2046 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
2047 sync_pb::EntitySpecifics entity_specifics
;
2049 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2050 Cryptographer
* cryptographer
= trans
.GetCryptographer();
2051 sync_pb::PasswordSpecificsData data
;
2052 data
.set_password_value("secret");
2053 cryptographer
->Encrypt(
2055 entity_specifics
.mutable_password()->mutable_encrypted());
2057 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
2058 syncable::GenerateSyncableHash(PASSWORDS
,
2061 // New node shouldn't start off unsynced.
2062 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2064 // Force a re-encrypt everything. Should not set is_unsynced.
2065 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
2066 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2067 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2068 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
2069 sync_manager_
.GetEncryptionHandler()->Init();
2071 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2074 // Test that attempting to start up with corrupted password data triggers
2075 // an unrecoverable error (rather than crashing).
2076 TEST_F(SyncManagerTest
, ReencryptEverythingWithUnrecoverableErrorPasswords
) {
2077 const char kClientTag
[] = "client_tag";
2079 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
2080 sync_pb::EntitySpecifics entity_specifics
;
2082 // Create a synced bookmark with undecryptable data.
2083 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2085 Cryptographer
other_cryptographer(&encryptor_
);
2086 KeyParams fake_params
= {"localhost", "dummy", "fake_key"};
2087 other_cryptographer
.AddKey(fake_params
);
2088 sync_pb::PasswordSpecificsData data
;
2089 data
.set_password_value("secret");
2090 other_cryptographer
.Encrypt(
2092 entity_specifics
.mutable_password()->mutable_encrypted());
2094 // Set up the real cryptographer with a different key.
2095 KeyParams real_params
= {"localhost", "username", "real_key"};
2096 trans
.GetCryptographer()->AddKey(real_params
);
2098 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, kClientTag
,
2099 syncable::GenerateSyncableHash(PASSWORDS
,
2102 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, kClientTag
));
2104 // Force a re-encrypt everything. Should trigger an unrecoverable error due
2105 // to being unable to decrypt the data that was previously applied.
2106 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
2107 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2108 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2109 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
2110 EXPECT_FALSE(HasUnrecoverableError());
2111 sync_manager_
.GetEncryptionHandler()->Init();
2113 EXPECT_TRUE(HasUnrecoverableError());
2116 // Test that attempting to start up with corrupted bookmark data triggers
2117 // an unrecoverable error (rather than crashing).
2118 TEST_F(SyncManagerTest
, ReencryptEverythingWithUnrecoverableErrorBookmarks
) {
2119 const char kClientTag
[] = "client_tag";
2120 EXPECT_CALL(encryption_observer_
,
2121 OnEncryptedTypesChanged(
2122 HasModelTypes(EncryptableUserTypes()), true));
2123 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
2124 sync_pb::EntitySpecifics entity_specifics
;
2126 // Create a synced bookmark with undecryptable data.
2127 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2129 Cryptographer
other_cryptographer(&encryptor_
);
2130 KeyParams fake_params
= {"localhost", "dummy", "fake_key"};
2131 other_cryptographer
.AddKey(fake_params
);
2132 sync_pb::EntitySpecifics bm_specifics
;
2133 bm_specifics
.mutable_bookmark()->set_title("title");
2134 bm_specifics
.mutable_bookmark()->set_url("url");
2135 sync_pb::EncryptedData encrypted
;
2136 other_cryptographer
.Encrypt(bm_specifics
, &encrypted
);
2137 entity_specifics
.mutable_encrypted()->CopyFrom(encrypted
);
2139 // Set up the real cryptographer with a different key.
2140 KeyParams real_params
= {"localhost", "username", "real_key"};
2141 trans
.GetCryptographer()->AddKey(real_params
);
2143 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, kClientTag
,
2144 syncable::GenerateSyncableHash(BOOKMARKS
,
2147 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, kClientTag
));
2149 // Force a re-encrypt everything. Should trigger an unrecoverable error due
2150 // to being unable to decrypt the data that was previously applied.
2151 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
2152 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2153 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2154 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
2155 EXPECT_FALSE(HasUnrecoverableError());
2156 sync_manager_
.GetEncryptionHandler()->Init();
2158 EXPECT_TRUE(HasUnrecoverableError());
2161 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2162 // when we write the same data, but does set it when we write new data.
2163 TEST_F(SyncManagerTest
, SetBookmarkTitle
) {
2164 std::string client_tag
= "title";
2165 sync_pb::EntitySpecifics entity_specifics
;
2166 entity_specifics
.mutable_bookmark()->set_url("url");
2167 entity_specifics
.mutable_bookmark()->set_title("title");
2168 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2169 syncable::GenerateSyncableHash(BOOKMARKS
,
2172 // New node shouldn't start off unsynced.
2173 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2175 // Manually change to the same title. Should not set is_unsynced.
2177 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2178 WriteNode
node(&trans
);
2179 EXPECT_EQ(BaseNode::INIT_OK
,
2180 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2181 node
.SetTitle(client_tag
);
2183 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2185 // Manually change to new title. Should set is_unsynced.
2187 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2188 WriteNode
node(&trans
);
2189 EXPECT_EQ(BaseNode::INIT_OK
,
2190 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2191 node
.SetTitle("title2");
2193 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2196 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2197 // bookmarks when we write the same data, but does set it when we write new
2199 TEST_F(SyncManagerTest
, SetBookmarkTitleWithEncryption
) {
2200 std::string client_tag
= "title";
2201 sync_pb::EntitySpecifics entity_specifics
;
2202 entity_specifics
.mutable_bookmark()->set_url("url");
2203 entity_specifics
.mutable_bookmark()->set_title("title");
2204 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2205 syncable::GenerateSyncableHash(BOOKMARKS
,
2208 // New node shouldn't start off unsynced.
2209 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2211 // Encrypt the datatatype, should set is_unsynced.
2212 EXPECT_CALL(encryption_observer_
,
2213 OnEncryptedTypesChanged(
2214 HasModelTypes(EncryptableUserTypes()), true));
2215 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2216 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
2217 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2218 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
2219 sync_manager_
.GetEncryptionHandler()->Init();
2221 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2223 // Manually change to the same title. Should not set is_unsynced.
2224 // NON_UNIQUE_NAME should be kEncryptedString.
2226 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2227 WriteNode
node(&trans
);
2228 EXPECT_EQ(BaseNode::INIT_OK
,
2229 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2230 node
.SetTitle(client_tag
);
2231 const syncable::Entry
* node_entry
= node
.GetEntry();
2232 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2233 EXPECT_TRUE(specifics
.has_encrypted());
2234 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2236 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2238 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2239 // should still be kEncryptedString.
2241 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2242 WriteNode
node(&trans
);
2243 EXPECT_EQ(BaseNode::INIT_OK
,
2244 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2245 node
.SetTitle("title2");
2246 const syncable::Entry
* node_entry
= node
.GetEntry();
2247 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2248 EXPECT_TRUE(specifics
.has_encrypted());
2249 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2251 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2254 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2255 // when we write the same data, but does set it when we write new data.
2256 TEST_F(SyncManagerTest
, SetNonBookmarkTitle
) {
2257 std::string client_tag
= "title";
2258 sync_pb::EntitySpecifics entity_specifics
;
2259 entity_specifics
.mutable_preference()->set_name("name");
2260 entity_specifics
.mutable_preference()->set_value("value");
2261 MakeServerNode(sync_manager_
.GetUserShare(),
2264 syncable::GenerateSyncableHash(PREFERENCES
,
2267 // New node shouldn't start off unsynced.
2268 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2270 // Manually change to the same title. Should not set is_unsynced.
2272 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2273 WriteNode
node(&trans
);
2274 EXPECT_EQ(BaseNode::INIT_OK
,
2275 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2276 node
.SetTitle(client_tag
);
2278 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2280 // Manually change to new title. Should 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
, client_tag
));
2286 node
.SetTitle("title2");
2288 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2291 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2292 // non-bookmarks when we write the same data or when we write new data
2293 // data (should remained kEncryptedString).
2294 TEST_F(SyncManagerTest
, SetNonBookmarkTitleWithEncryption
) {
2295 std::string client_tag
= "title";
2296 sync_pb::EntitySpecifics entity_specifics
;
2297 entity_specifics
.mutable_preference()->set_name("name");
2298 entity_specifics
.mutable_preference()->set_value("value");
2299 MakeServerNode(sync_manager_
.GetUserShare(),
2302 syncable::GenerateSyncableHash(PREFERENCES
,
2305 // New node shouldn't start off unsynced.
2306 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2308 // Encrypt the datatatype, should set is_unsynced.
2309 EXPECT_CALL(encryption_observer_
,
2310 OnEncryptedTypesChanged(
2311 HasModelTypes(EncryptableUserTypes()), true));
2312 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2313 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
2314 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2315 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
2316 sync_manager_
.GetEncryptionHandler()->Init();
2318 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2320 // Manually change to the same title. Should not set is_unsynced.
2321 // NON_UNIQUE_NAME should be kEncryptedString.
2323 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2324 WriteNode
node(&trans
);
2325 EXPECT_EQ(BaseNode::INIT_OK
,
2326 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2327 node
.SetTitle(client_tag
);
2328 const syncable::Entry
* node_entry
= node
.GetEntry();
2329 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2330 EXPECT_TRUE(specifics
.has_encrypted());
2331 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2333 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2335 // Manually change to new title. Should not set is_unsynced because the
2336 // NON_UNIQUE_NAME should still be kEncryptedString.
2338 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2339 WriteNode
node(&trans
);
2340 EXPECT_EQ(BaseNode::INIT_OK
,
2341 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2342 node
.SetTitle("title2");
2343 const syncable::Entry
* node_entry
= node
.GetEntry();
2344 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2345 EXPECT_TRUE(specifics
.has_encrypted());
2346 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2347 EXPECT_FALSE(node_entry
->GetIsUnsynced());
2351 // Ensure that titles are truncated to 255 bytes, and attempting to reset
2352 // them to their longer version does not set IS_UNSYNCED.
2353 TEST_F(SyncManagerTest
, SetLongTitle
) {
2354 const int kNumChars
= 512;
2355 const std::string kClientTag
= "tag";
2356 std::string
title(kNumChars
, '0');
2357 sync_pb::EntitySpecifics entity_specifics
;
2358 entity_specifics
.mutable_preference()->set_name("name");
2359 entity_specifics
.mutable_preference()->set_value("value");
2360 MakeServerNode(sync_manager_
.GetUserShare(),
2363 syncable::GenerateSyncableHash(PREFERENCES
,
2366 // New node shouldn't start off unsynced.
2367 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2369 // Manually change to the long title. Should set is_unsynced.
2371 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2372 WriteNode
node(&trans
);
2373 EXPECT_EQ(BaseNode::INIT_OK
,
2374 node
.InitByClientTagLookup(PREFERENCES
, kClientTag
));
2375 node
.SetTitle(title
);
2376 EXPECT_EQ(node
.GetTitle(), title
.substr(0, 255));
2378 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2380 // Manually change to the same title. Should not set is_unsynced.
2382 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2383 WriteNode
node(&trans
);
2384 EXPECT_EQ(BaseNode::INIT_OK
,
2385 node
.InitByClientTagLookup(PREFERENCES
, kClientTag
));
2386 node
.SetTitle(title
);
2387 EXPECT_EQ(node
.GetTitle(), title
.substr(0, 255));
2389 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2391 // Manually change to new title. Should set is_unsynced.
2393 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2394 WriteNode
node(&trans
);
2395 EXPECT_EQ(BaseNode::INIT_OK
,
2396 node
.InitByClientTagLookup(PREFERENCES
, kClientTag
));
2397 node
.SetTitle("title2");
2399 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2402 // Create an encrypted entry when the cryptographer doesn't think the type is
2403 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2405 TEST_F(SyncManagerTest
, SetPreviouslyEncryptedSpecifics
) {
2406 std::string client_tag
= "tag";
2407 std::string url
= "url";
2408 std::string url2
= "new_url";
2409 std::string title
= "title";
2410 sync_pb::EntitySpecifics entity_specifics
;
2411 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
2413 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2414 Cryptographer
* crypto
= trans
.GetCryptographer();
2415 sync_pb::EntitySpecifics bm_specifics
;
2416 bm_specifics
.mutable_bookmark()->set_title("title");
2417 bm_specifics
.mutable_bookmark()->set_url("url");
2418 sync_pb::EncryptedData encrypted
;
2419 crypto
->Encrypt(bm_specifics
, &encrypted
);
2420 entity_specifics
.mutable_encrypted()->CopyFrom(encrypted
);
2421 AddDefaultFieldValue(BOOKMARKS
, &entity_specifics
);
2423 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2424 syncable::GenerateSyncableHash(BOOKMARKS
,
2430 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2431 ReadNode
node(&trans
);
2432 EXPECT_EQ(BaseNode::INIT_OK
,
2433 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2434 EXPECT_EQ(title
, node
.GetTitle());
2435 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
2439 // Overwrite the url (which overwrites the specifics).
2440 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2441 WriteNode
node(&trans
);
2442 EXPECT_EQ(BaseNode::INIT_OK
,
2443 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2445 sync_pb::BookmarkSpecifics
bookmark_specifics(node
.GetBookmarkSpecifics());
2446 bookmark_specifics
.set_url(url2
);
2447 node
.SetBookmarkSpecifics(bookmark_specifics
);
2451 // Verify it's still encrypted and it has the most recent url.
2452 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2453 ReadNode
node(&trans
);
2454 EXPECT_EQ(BaseNode::INIT_OK
,
2455 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2456 EXPECT_EQ(title
, node
.GetTitle());
2457 EXPECT_EQ(url2
, node
.GetBookmarkSpecifics().url());
2458 const syncable::Entry
* node_entry
= node
.GetEntry();
2459 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2460 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2461 EXPECT_TRUE(specifics
.has_encrypted());
2465 // Verify transaction version of a model type is incremented when node of
2466 // that type is updated.
2467 TEST_F(SyncManagerTest
, IncrementTransactionVersion
) {
2468 ModelSafeRoutingInfo routing_info
;
2469 GetModelSafeRoutingInfo(&routing_info
);
2472 ReadTransaction
read_trans(FROM_HERE
, sync_manager_
.GetUserShare());
2473 for (ModelSafeRoutingInfo::iterator i
= routing_info
.begin();
2474 i
!= routing_info
.end(); ++i
) {
2475 // Transaction version is incremented when SyncManagerTest::SetUp()
2476 // creates a node of each type.
2478 sync_manager_
.GetUserShare()->directory
->
2479 GetTransactionVersion(i
->first
));
2483 // Create bookmark node to increment transaction version of bookmark model.
2484 std::string client_tag
= "title";
2485 sync_pb::EntitySpecifics entity_specifics
;
2486 entity_specifics
.mutable_bookmark()->set_url("url");
2487 entity_specifics
.mutable_bookmark()->set_title("title");
2488 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2489 syncable::GenerateSyncableHash(BOOKMARKS
,
2494 ReadTransaction
read_trans(FROM_HERE
, sync_manager_
.GetUserShare());
2495 for (ModelSafeRoutingInfo::iterator i
= routing_info
.begin();
2496 i
!= routing_info
.end(); ++i
) {
2497 EXPECT_EQ(i
->first
== BOOKMARKS
? 2 : 1,
2498 sync_manager_
.GetUserShare()->directory
->
2499 GetTransactionVersion(i
->first
));
2504 class MockSyncScheduler
: public FakeSyncScheduler
{
2506 MockSyncScheduler() : FakeSyncScheduler() {}
2507 virtual ~MockSyncScheduler() {}
2509 MOCK_METHOD2(Start
, void(SyncScheduler::Mode
, base::Time
));
2510 MOCK_METHOD1(ScheduleConfiguration
, void(const ConfigurationParams
&));
2513 class ComponentsFactory
: public TestInternalComponentsFactory
{
2515 ComponentsFactory(const Switches
& switches
,
2516 SyncScheduler
* scheduler_to_use
,
2517 sessions::SyncSessionContext
** session_context
,
2518 InternalComponentsFactory::StorageOption
* storage_used
)
2519 : TestInternalComponentsFactory(
2520 switches
, InternalComponentsFactory::STORAGE_IN_MEMORY
, storage_used
),
2521 scheduler_to_use_(scheduler_to_use
),
2522 session_context_(session_context
) {}
2523 ~ComponentsFactory() override
{}
2525 scoped_ptr
<SyncScheduler
> BuildScheduler(
2526 const std::string
& name
,
2527 sessions::SyncSessionContext
* context
,
2528 CancelationSignal
* stop_handle
) override
{
2529 *session_context_
= context
;
2530 return scheduler_to_use_
.Pass();
2534 scoped_ptr
<SyncScheduler
> scheduler_to_use_
;
2535 sessions::SyncSessionContext
** session_context_
;
2538 class SyncManagerTestWithMockScheduler
: public SyncManagerTest
{
2540 SyncManagerTestWithMockScheduler() : scheduler_(NULL
) {}
2541 InternalComponentsFactory
* GetFactory() override
{
2542 scheduler_
= new MockSyncScheduler();
2543 return new ComponentsFactory(GetSwitches(), scheduler_
, &session_context_
,
2547 MockSyncScheduler
* scheduler() { return scheduler_
; }
2548 sessions::SyncSessionContext
* session_context() {
2549 return session_context_
;
2553 MockSyncScheduler
* scheduler_
;
2554 sessions::SyncSessionContext
* session_context_
;
2557 // Test that the configuration params are properly created and sent to
2558 // ScheduleConfigure. No callback should be invoked. Any disabled datatypes
2559 // should be purged.
2560 TEST_F(SyncManagerTestWithMockScheduler
, BasicConfiguration
) {
2561 ConfigureReason reason
= CONFIGURE_REASON_RECONFIGURATION
;
2562 ModelTypeSet
types_to_download(BOOKMARKS
, PREFERENCES
);
2563 ModelSafeRoutingInfo new_routing_info
;
2564 GetModelSafeRoutingInfo(&new_routing_info
);
2565 ModelTypeSet enabled_types
= GetRoutingInfoTypes(new_routing_info
);
2566 ModelTypeSet disabled_types
= Difference(ModelTypeSet::All(), enabled_types
);
2568 ConfigurationParams params
;
2569 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE
, _
));
2570 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_
)).
2571 WillOnce(SaveArg
<0>(¶ms
));
2573 // Set data for all types.
2574 ModelTypeSet protocol_types
= ProtocolTypes();
2575 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2577 SetProgressMarkerForType(iter
.Get(), true);
2580 CallbackCounter ready_task_counter
, retry_task_counter
;
2581 sync_manager_
.ConfigureSyncer(
2588 base::Bind(&CallbackCounter::Callback
,
2589 base::Unretained(&ready_task_counter
)),
2590 base::Bind(&CallbackCounter::Callback
,
2591 base::Unretained(&retry_task_counter
)));
2592 EXPECT_EQ(0, ready_task_counter
.times_called());
2593 EXPECT_EQ(0, retry_task_counter
.times_called());
2594 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION
,
2596 EXPECT_TRUE(types_to_download
.Equals(params
.types_to_download
));
2597 EXPECT_EQ(new_routing_info
, params
.routing_info
);
2599 // Verify all the disabled types were purged.
2600 EXPECT_TRUE(sync_manager_
.InitialSyncEndedTypes().Equals(
2602 EXPECT_TRUE(sync_manager_
.GetTypesWithEmptyProgressMarkerToken(
2603 ModelTypeSet::All()).Equals(disabled_types
));
2606 // Test that on a reconfiguration (configuration where the session context
2607 // already has routing info), only those recently disabled types are purged.
2608 TEST_F(SyncManagerTestWithMockScheduler
, ReConfiguration
) {
2609 ConfigureReason reason
= CONFIGURE_REASON_RECONFIGURATION
;
2610 ModelTypeSet
types_to_download(BOOKMARKS
, PREFERENCES
);
2611 ModelTypeSet disabled_types
= ModelTypeSet(THEMES
, SESSIONS
);
2612 ModelSafeRoutingInfo old_routing_info
;
2613 ModelSafeRoutingInfo new_routing_info
;
2614 GetModelSafeRoutingInfo(&old_routing_info
);
2615 new_routing_info
= old_routing_info
;
2616 new_routing_info
.erase(THEMES
);
2617 new_routing_info
.erase(SESSIONS
);
2618 ModelTypeSet enabled_types
= GetRoutingInfoTypes(new_routing_info
);
2620 ConfigurationParams params
;
2621 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE
, _
));
2622 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_
)).
2623 WillOnce(SaveArg
<0>(¶ms
));
2625 // Set data for all types except those recently disabled (so we can verify
2626 // only those recently disabled are purged) .
2627 ModelTypeSet protocol_types
= ProtocolTypes();
2628 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2630 if (!disabled_types
.Has(iter
.Get())) {
2631 SetProgressMarkerForType(iter
.Get(), true);
2633 SetProgressMarkerForType(iter
.Get(), false);
2637 // Set the context to have the old routing info.
2638 session_context()->SetRoutingInfo(old_routing_info
);
2640 CallbackCounter ready_task_counter
, retry_task_counter
;
2641 sync_manager_
.ConfigureSyncer(
2648 base::Bind(&CallbackCounter::Callback
,
2649 base::Unretained(&ready_task_counter
)),
2650 base::Bind(&CallbackCounter::Callback
,
2651 base::Unretained(&retry_task_counter
)));
2652 EXPECT_EQ(0, ready_task_counter
.times_called());
2653 EXPECT_EQ(0, retry_task_counter
.times_called());
2654 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION
,
2656 EXPECT_TRUE(types_to_download
.Equals(params
.types_to_download
));
2657 EXPECT_EQ(new_routing_info
, params
.routing_info
);
2659 // Verify only the recently disabled types were purged.
2660 EXPECT_TRUE(sync_manager_
.GetTypesWithEmptyProgressMarkerToken(
2661 ProtocolTypes()).Equals(disabled_types
));
2664 // Test that PurgePartiallySyncedTypes purges only those types that have not
2665 // fully completed their initial download and apply.
2666 TEST_F(SyncManagerTest
, PurgePartiallySyncedTypes
) {
2667 ModelSafeRoutingInfo routing_info
;
2668 GetModelSafeRoutingInfo(&routing_info
);
2669 ModelTypeSet enabled_types
= GetRoutingInfoTypes(routing_info
);
2671 UserShare
* share
= sync_manager_
.GetUserShare();
2673 // The test harness automatically initializes all types in the routing info.
2674 // Check that autofill is not among them.
2675 ASSERT_FALSE(enabled_types
.Has(AUTOFILL
));
2677 // Further ensure that the test harness did not create its root node.
2679 syncable::ReadTransaction
trans(FROM_HERE
, share
->directory
.get());
2680 syncable::Entry
autofill_root_node(&trans
,
2681 syncable::GET_TYPE_ROOT
,
2683 ASSERT_FALSE(autofill_root_node
.good());
2686 // One more redundant check.
2687 ASSERT_FALSE(sync_manager_
.InitialSyncEndedTypes().Has(AUTOFILL
));
2689 // Give autofill a progress marker.
2690 sync_pb::DataTypeProgressMarker autofill_marker
;
2691 autofill_marker
.set_data_type_id(
2692 GetSpecificsFieldNumberFromModelType(AUTOFILL
));
2693 autofill_marker
.set_token("token");
2694 share
->directory
->SetDownloadProgress(AUTOFILL
, autofill_marker
);
2696 // Also add a pending autofill root node update from the server.
2697 TestEntryFactory
factory_(share
->directory
.get());
2698 int autofill_meta
= factory_
.CreateUnappliedRootNode(AUTOFILL
);
2700 // Preferences is an enabled type. Check that the harness initialized it.
2701 ASSERT_TRUE(enabled_types
.Has(PREFERENCES
));
2702 ASSERT_TRUE(sync_manager_
.InitialSyncEndedTypes().Has(PREFERENCES
));
2704 // Give preferencse a progress marker.
2705 sync_pb::DataTypeProgressMarker prefs_marker
;
2706 prefs_marker
.set_data_type_id(
2707 GetSpecificsFieldNumberFromModelType(PREFERENCES
));
2708 prefs_marker
.set_token("token");
2709 share
->directory
->SetDownloadProgress(PREFERENCES
, prefs_marker
);
2711 // Add a fully synced preferences node under the root.
2712 std::string pref_client_tag
= "prefABC";
2713 std::string pref_hashed_tag
= "hashXYZ";
2714 sync_pb::EntitySpecifics pref_specifics
;
2715 AddDefaultFieldValue(PREFERENCES
, &pref_specifics
);
2716 int pref_meta
= MakeServerNode(
2717 share
, PREFERENCES
, pref_client_tag
, pref_hashed_tag
, pref_specifics
);
2719 // And now, the purge.
2720 EXPECT_TRUE(sync_manager_
.PurgePartiallySyncedTypes());
2722 // Ensure that autofill lost its progress marker, but preferences did not.
2723 ModelTypeSet empty_tokens
=
2724 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
2725 EXPECT_TRUE(empty_tokens
.Has(AUTOFILL
));
2726 EXPECT_FALSE(empty_tokens
.Has(PREFERENCES
));
2728 // Ensure that autofill lots its node, but preferences did not.
2730 syncable::ReadTransaction
trans(FROM_HERE
, share
->directory
.get());
2731 syncable::Entry
autofill_node(&trans
, GET_BY_HANDLE
, autofill_meta
);
2732 syncable::Entry
pref_node(&trans
, GET_BY_HANDLE
, pref_meta
);
2733 EXPECT_FALSE(autofill_node
.good());
2734 EXPECT_TRUE(pref_node
.good());
2738 // Test CleanupDisabledTypes properly purges all disabled types as specified
2739 // by the previous and current enabled params.
2740 TEST_F(SyncManagerTest
, PurgeDisabledTypes
) {
2741 ModelSafeRoutingInfo routing_info
;
2742 GetModelSafeRoutingInfo(&routing_info
);
2743 ModelTypeSet enabled_types
= GetRoutingInfoTypes(routing_info
);
2744 ModelTypeSet disabled_types
= Difference(ModelTypeSet::All(), enabled_types
);
2746 // The harness should have initialized the enabled_types for us.
2747 EXPECT_TRUE(enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2749 // Set progress markers for all types.
2750 ModelTypeSet protocol_types
= ProtocolTypes();
2751 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2753 SetProgressMarkerForType(iter
.Get(), true);
2756 // Verify all the enabled types remain after cleanup, and all the disabled
2757 // types were purged.
2758 sync_manager_
.PurgeDisabledTypes(disabled_types
,
2761 EXPECT_TRUE(enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2762 EXPECT_TRUE(disabled_types
.Equals(
2763 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2765 // Disable some more types.
2766 disabled_types
.Put(BOOKMARKS
);
2767 disabled_types
.Put(PREFERENCES
);
2768 ModelTypeSet new_enabled_types
=
2769 Difference(ModelTypeSet::All(), disabled_types
);
2771 // Verify only the non-disabled types remain after cleanup.
2772 sync_manager_
.PurgeDisabledTypes(disabled_types
,
2775 EXPECT_TRUE(new_enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2776 EXPECT_TRUE(disabled_types
.Equals(
2777 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2780 // Test PurgeDisabledTypes properly unapplies types by deleting their local data
2781 // and preserving their server data and progress marker.
2782 TEST_F(SyncManagerTest
, PurgeUnappliedTypes
) {
2783 ModelSafeRoutingInfo routing_info
;
2784 GetModelSafeRoutingInfo(&routing_info
);
2785 ModelTypeSet unapplied_types
= ModelTypeSet(BOOKMARKS
, PREFERENCES
);
2786 ModelTypeSet enabled_types
= GetRoutingInfoTypes(routing_info
);
2787 ModelTypeSet disabled_types
= Difference(ModelTypeSet::All(), enabled_types
);
2789 // The harness should have initialized the enabled_types for us.
2790 EXPECT_TRUE(enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2792 // Set progress markers for all types.
2793 ModelTypeSet protocol_types
= ProtocolTypes();
2794 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2796 SetProgressMarkerForType(iter
.Get(), true);
2799 // Add the following kinds of items:
2800 // 1. Fully synced preference.
2801 // 2. Locally created preference, server unknown, unsynced
2802 // 3. Locally deleted preference, server known, unsynced
2803 // 4. Server deleted preference, locally known.
2804 // 5. Server created preference, locally unknown, unapplied.
2805 // 6. A fully synced bookmark (no unique_client_tag).
2806 UserShare
* share
= sync_manager_
.GetUserShare();
2807 sync_pb::EntitySpecifics pref_specifics
;
2808 AddDefaultFieldValue(PREFERENCES
, &pref_specifics
);
2809 sync_pb::EntitySpecifics bm_specifics
;
2810 AddDefaultFieldValue(BOOKMARKS
, &bm_specifics
);
2811 int pref1_meta
= MakeServerNode(
2812 share
, PREFERENCES
, "pref1", "hash1", pref_specifics
);
2813 int64 pref2_meta
= MakeNodeWithRoot(share
, PREFERENCES
, "pref2");
2814 int pref3_meta
= MakeServerNode(
2815 share
, PREFERENCES
, "pref3", "hash3", pref_specifics
);
2816 int pref4_meta
= MakeServerNode(
2817 share
, PREFERENCES
, "pref4", "hash4", pref_specifics
);
2818 int pref5_meta
= MakeServerNode(
2819 share
, PREFERENCES
, "pref5", "hash5", pref_specifics
);
2820 int bookmark_meta
= MakeServerNode(
2821 share
, BOOKMARKS
, "bookmark", "", bm_specifics
);
2824 syncable::WriteTransaction
trans(FROM_HERE
,
2826 share
->directory
.get());
2827 // Pref's 1 and 2 are already set up properly.
2828 // Locally delete pref 3.
2829 syncable::MutableEntry
pref3(&trans
, GET_BY_HANDLE
, pref3_meta
);
2830 pref3
.PutIsDel(true);
2831 pref3
.PutIsUnsynced(true);
2832 // Delete pref 4 at the server.
2833 syncable::MutableEntry
pref4(&trans
, GET_BY_HANDLE
, pref4_meta
);
2834 pref4
.PutServerIsDel(true);
2835 pref4
.PutIsUnappliedUpdate(true);
2836 pref4
.PutServerVersion(2);
2837 // Pref 5 is an new unapplied update.
2838 syncable::MutableEntry
pref5(&trans
, GET_BY_HANDLE
, pref5_meta
);
2839 pref5
.PutIsUnappliedUpdate(true);
2840 pref5
.PutIsDel(true);
2841 pref5
.PutBaseVersion(-1);
2842 // Bookmark is already set up properly
2845 // Take a snapshot to clear all the dirty bits.
2846 share
->directory
.get()->SaveChanges();
2848 // Now request a purge for the unapplied types.
2849 disabled_types
.PutAll(unapplied_types
);
2850 sync_manager_
.PurgeDisabledTypes(disabled_types
,
2854 // Verify the unapplied types still have progress markers and initial sync
2855 // ended after cleanup.
2856 EXPECT_TRUE(sync_manager_
.InitialSyncEndedTypes().HasAll(unapplied_types
));
2858 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(unapplied_types
).
2861 // Ensure the items were unapplied as necessary.
2863 syncable::ReadTransaction
trans(FROM_HERE
, share
->directory
.get());
2864 syncable::Entry
pref_node(&trans
, GET_BY_HANDLE
, pref1_meta
);
2865 ASSERT_TRUE(pref_node
.good());
2866 EXPECT_TRUE(pref_node
.GetKernelCopy().is_dirty());
2867 EXPECT_FALSE(pref_node
.GetIsUnsynced());
2868 EXPECT_TRUE(pref_node
.GetIsUnappliedUpdate());
2869 EXPECT_TRUE(pref_node
.GetIsDel());
2870 EXPECT_GT(pref_node
.GetServerVersion(), 0);
2871 EXPECT_EQ(pref_node
.GetBaseVersion(), -1);
2873 // Pref 2 should just be locally deleted.
2874 syncable::Entry
pref2_node(&trans
, GET_BY_HANDLE
, pref2_meta
);
2875 ASSERT_TRUE(pref2_node
.good());
2876 EXPECT_TRUE(pref2_node
.GetKernelCopy().is_dirty());
2877 EXPECT_FALSE(pref2_node
.GetIsUnsynced());
2878 EXPECT_TRUE(pref2_node
.GetIsDel());
2879 EXPECT_FALSE(pref2_node
.GetIsUnappliedUpdate());
2880 EXPECT_TRUE(pref2_node
.GetIsDel());
2881 EXPECT_EQ(pref2_node
.GetServerVersion(), 0);
2882 EXPECT_EQ(pref2_node
.GetBaseVersion(), -1);
2884 syncable::Entry
pref3_node(&trans
, GET_BY_HANDLE
, pref3_meta
);
2885 ASSERT_TRUE(pref3_node
.good());
2886 EXPECT_TRUE(pref3_node
.GetKernelCopy().is_dirty());
2887 EXPECT_FALSE(pref3_node
.GetIsUnsynced());
2888 EXPECT_TRUE(pref3_node
.GetIsUnappliedUpdate());
2889 EXPECT_TRUE(pref3_node
.GetIsDel());
2890 EXPECT_GT(pref3_node
.GetServerVersion(), 0);
2891 EXPECT_EQ(pref3_node
.GetBaseVersion(), -1);
2893 syncable::Entry
pref4_node(&trans
, GET_BY_HANDLE
, pref4_meta
);
2894 ASSERT_TRUE(pref4_node
.good());
2895 EXPECT_TRUE(pref4_node
.GetKernelCopy().is_dirty());
2896 EXPECT_FALSE(pref4_node
.GetIsUnsynced());
2897 EXPECT_TRUE(pref4_node
.GetIsUnappliedUpdate());
2898 EXPECT_TRUE(pref4_node
.GetIsDel());
2899 EXPECT_GT(pref4_node
.GetServerVersion(), 0);
2900 EXPECT_EQ(pref4_node
.GetBaseVersion(), -1);
2902 // Pref 5 should remain untouched.
2903 syncable::Entry
pref5_node(&trans
, GET_BY_HANDLE
, pref5_meta
);
2904 ASSERT_TRUE(pref5_node
.good());
2905 EXPECT_FALSE(pref5_node
.GetKernelCopy().is_dirty());
2906 EXPECT_FALSE(pref5_node
.GetIsUnsynced());
2907 EXPECT_TRUE(pref5_node
.GetIsUnappliedUpdate());
2908 EXPECT_TRUE(pref5_node
.GetIsDel());
2909 EXPECT_GT(pref5_node
.GetServerVersion(), 0);
2910 EXPECT_EQ(pref5_node
.GetBaseVersion(), -1);
2912 syncable::Entry
bookmark_node(&trans
, GET_BY_HANDLE
, bookmark_meta
);
2913 ASSERT_TRUE(bookmark_node
.good());
2914 EXPECT_TRUE(bookmark_node
.GetKernelCopy().is_dirty());
2915 EXPECT_FALSE(bookmark_node
.GetIsUnsynced());
2916 EXPECT_TRUE(bookmark_node
.GetIsUnappliedUpdate());
2917 EXPECT_TRUE(bookmark_node
.GetIsDel());
2918 EXPECT_GT(bookmark_node
.GetServerVersion(), 0);
2919 EXPECT_EQ(bookmark_node
.GetBaseVersion(), -1);
2923 // A test harness to exercise the code that processes and passes changes from
2924 // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
2926 class SyncManagerChangeProcessingTest
: public SyncManagerTest
{
2928 void OnChangesApplied(ModelType model_type
,
2929 int64 model_version
,
2930 const BaseTransaction
* trans
,
2931 const ImmutableChangeRecordList
& changes
) override
{
2932 last_changes_
= changes
;
2935 void OnChangesComplete(ModelType model_type
) override
{}
2937 const ImmutableChangeRecordList
& GetRecentChangeList() {
2938 return last_changes_
;
2941 UserShare
* share() {
2942 return sync_manager_
.GetUserShare();
2945 // Set some flags so our nodes reasonably approximate the real world scenario
2946 // and can get past CheckTreeInvariants.
2948 // It's never going to be truly accurate, since we're squashing update
2949 // receipt, processing and application into a single transaction.
2950 void SetNodeProperties(syncable::MutableEntry
*entry
) {
2951 entry
->PutId(id_factory_
.NewServerId());
2952 entry
->PutBaseVersion(10);
2953 entry
->PutServerVersion(10);
2956 // Looks for the given change in the list. Returns the index at which it was
2957 // found. Returns -1 on lookup failure.
2958 size_t FindChangeInList(int64 id
, ChangeRecord::Action action
) {
2960 for (size_t i
= 0; i
< last_changes_
.Get().size(); ++i
) {
2961 if (last_changes_
.Get()[i
].id
== id
2962 && last_changes_
.Get()[i
].action
== action
) {
2966 ADD_FAILURE() << "Failed to find specified change";
2967 return static_cast<size_t>(-1);
2970 // Returns the current size of the change list.
2972 // Note that spurious changes do not necessarily indicate a problem.
2973 // Assertions on change list size can help detect problems, but it may be
2974 // necessary to reduce their strictness if the implementation changes.
2975 size_t GetChangeListSize() {
2976 return last_changes_
.Get().size();
2979 void ClearChangeList() { last_changes_
= ImmutableChangeRecordList(); }
2982 ImmutableChangeRecordList last_changes_
;
2983 TestIdFactory id_factory_
;
2986 // Test creation of a folder and a bookmark.
2987 TEST_F(SyncManagerChangeProcessingTest
, AddBookmarks
) {
2988 int64 type_root
= GetIdForDataType(BOOKMARKS
);
2989 int64 folder_id
= kInvalidId
;
2990 int64 child_id
= kInvalidId
;
2992 // Create a folder and a bookmark under it.
2994 syncable::WriteTransaction
trans(
2995 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
2996 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
2997 ASSERT_TRUE(root
.good());
2999 syncable::MutableEntry
folder(&trans
, syncable::CREATE
,
3000 BOOKMARKS
, root
.GetId(), "folder");
3001 ASSERT_TRUE(folder
.good());
3002 SetNodeProperties(&folder
);
3003 folder
.PutIsDir(true);
3004 folder_id
= folder
.GetMetahandle();
3006 syncable::MutableEntry
child(&trans
, syncable::CREATE
,
3007 BOOKMARKS
, folder
.GetId(), "child");
3008 ASSERT_TRUE(child
.good());
3009 SetNodeProperties(&child
);
3010 child_id
= child
.GetMetahandle();
3013 // The closing of the above scope will delete the transaction. Its processed
3014 // changes should be waiting for us in a member of the test harness.
3015 EXPECT_EQ(2UL, GetChangeListSize());
3017 // We don't need to check these return values here. The function will add a
3018 // non-fatal failure if these changes are not found.
3019 size_t folder_change_pos
=
3020 FindChangeInList(folder_id
, ChangeRecord::ACTION_ADD
);
3021 size_t child_change_pos
=
3022 FindChangeInList(child_id
, ChangeRecord::ACTION_ADD
);
3024 // Parents are delivered before children.
3025 EXPECT_LT(folder_change_pos
, child_change_pos
);
3028 // Test creation of a preferences (with implicit parent Id)
3029 TEST_F(SyncManagerChangeProcessingTest
, AddPreferences
) {
3030 int64 item1_id
= kInvalidId
;
3031 int64 item2_id
= kInvalidId
;
3033 // Create two preferences.
3035 syncable::WriteTransaction
trans(FROM_HERE
, syncable::SYNCER
,
3036 share()->directory
.get());
3038 syncable::MutableEntry
item1(&trans
, syncable::CREATE
, PREFERENCES
,
3040 ASSERT_TRUE(item1
.good());
3041 SetNodeProperties(&item1
);
3042 item1_id
= item1
.GetMetahandle();
3044 // Need at least two items to ensure hitting all possible codepaths in
3045 // ChangeReorderBuffer::Traversal::ExpandToInclude.
3046 syncable::MutableEntry
item2(&trans
, syncable::CREATE
, PREFERENCES
,
3048 ASSERT_TRUE(item2
.good());
3049 SetNodeProperties(&item2
);
3050 item2_id
= item2
.GetMetahandle();
3053 // The closing of the above scope will delete the transaction. Its processed
3054 // changes should be waiting for us in a member of the test harness.
3055 EXPECT_EQ(2UL, GetChangeListSize());
3057 FindChangeInList(item1_id
, ChangeRecord::ACTION_ADD
);
3058 FindChangeInList(item2_id
, ChangeRecord::ACTION_ADD
);
3061 // Test moving a bookmark into an empty folder.
3062 TEST_F(SyncManagerChangeProcessingTest
, MoveBookmarkIntoEmptyFolder
) {
3063 int64 type_root
= GetIdForDataType(BOOKMARKS
);
3064 int64 folder_b_id
= kInvalidId
;
3065 int64 child_id
= kInvalidId
;
3067 // Create two folders. Place a child under folder A.
3069 syncable::WriteTransaction
trans(
3070 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3071 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
3072 ASSERT_TRUE(root
.good());
3074 syncable::MutableEntry
folder_a(&trans
, syncable::CREATE
,
3075 BOOKMARKS
, root
.GetId(), "folderA");
3076 ASSERT_TRUE(folder_a
.good());
3077 SetNodeProperties(&folder_a
);
3078 folder_a
.PutIsDir(true);
3080 syncable::MutableEntry
folder_b(&trans
, syncable::CREATE
,
3081 BOOKMARKS
, root
.GetId(), "folderB");
3082 ASSERT_TRUE(folder_b
.good());
3083 SetNodeProperties(&folder_b
);
3084 folder_b
.PutIsDir(true);
3085 folder_b_id
= folder_b
.GetMetahandle();
3087 syncable::MutableEntry
child(&trans
, syncable::CREATE
,
3088 BOOKMARKS
, folder_a
.GetId(),
3090 ASSERT_TRUE(child
.good());
3091 SetNodeProperties(&child
);
3092 child_id
= child
.GetMetahandle();
3095 // Close that transaction. The above was to setup the initial scenario. The
3096 // real test starts now.
3098 // Move the child from folder A to folder B.
3100 syncable::WriteTransaction
trans(
3101 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3103 syncable::Entry
folder_b(&trans
, syncable::GET_BY_HANDLE
, folder_b_id
);
3104 syncable::MutableEntry
child(&trans
, syncable::GET_BY_HANDLE
, child_id
);
3106 child
.PutParentId(folder_b
.GetId());
3109 EXPECT_EQ(1UL, GetChangeListSize());
3111 // Verify that this was detected as a real change. An early version of the
3112 // UniquePosition code had a bug where moves from one folder to another were
3113 // ignored unless the moved node's UniquePosition value was also changed in
3115 FindChangeInList(child_id
, ChangeRecord::ACTION_UPDATE
);
3118 // Test moving a bookmark into a non-empty folder.
3119 TEST_F(SyncManagerChangeProcessingTest
, MoveIntoPopulatedFolder
) {
3120 int64 type_root
= GetIdForDataType(BOOKMARKS
);
3121 int64 child_a_id
= kInvalidId
;
3122 int64 child_b_id
= kInvalidId
;
3124 // Create two folders. Place one child each under folder A and folder B.
3126 syncable::WriteTransaction
trans(
3127 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3128 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
3129 ASSERT_TRUE(root
.good());
3131 syncable::MutableEntry
folder_a(&trans
, syncable::CREATE
,
3132 BOOKMARKS
, root
.GetId(), "folderA");
3133 ASSERT_TRUE(folder_a
.good());
3134 SetNodeProperties(&folder_a
);
3135 folder_a
.PutIsDir(true);
3137 syncable::MutableEntry
folder_b(&trans
, syncable::CREATE
,
3138 BOOKMARKS
, root
.GetId(), "folderB");
3139 ASSERT_TRUE(folder_b
.good());
3140 SetNodeProperties(&folder_b
);
3141 folder_b
.PutIsDir(true);
3143 syncable::MutableEntry
child_a(&trans
, syncable::CREATE
,
3144 BOOKMARKS
, folder_a
.GetId(),
3146 ASSERT_TRUE(child_a
.good());
3147 SetNodeProperties(&child_a
);
3148 child_a_id
= child_a
.GetMetahandle();
3150 syncable::MutableEntry
child_b(&trans
, syncable::CREATE
,
3151 BOOKMARKS
, folder_b
.GetId(),
3153 SetNodeProperties(&child_b
);
3154 child_b_id
= child_b
.GetMetahandle();
3157 // Close that transaction. The above was to setup the initial scenario. The
3158 // real test starts now.
3161 syncable::WriteTransaction
trans(
3162 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3164 syncable::MutableEntry
child_a(&trans
, syncable::GET_BY_HANDLE
, child_a_id
);
3165 syncable::MutableEntry
child_b(&trans
, syncable::GET_BY_HANDLE
, child_b_id
);
3167 // Move child A from folder A to folder B and update its position.
3168 child_a
.PutParentId(child_b
.GetParentId());
3169 child_a
.PutPredecessor(child_b
.GetId());
3172 EXPECT_EQ(1UL, GetChangeListSize());
3174 // Verify that only child a is in the change list.
3175 // (This function will add a failure if the lookup fails.)
3176 FindChangeInList(child_a_id
, ChangeRecord::ACTION_UPDATE
);
3179 // Tests the ordering of deletion changes.
3180 TEST_F(SyncManagerChangeProcessingTest
, DeletionsAndChanges
) {
3181 int64 type_root
= GetIdForDataType(BOOKMARKS
);
3182 int64 folder_a_id
= kInvalidId
;
3183 int64 folder_b_id
= kInvalidId
;
3184 int64 child_id
= kInvalidId
;
3186 // Create two folders. Place a child under folder A.
3188 syncable::WriteTransaction
trans(
3189 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3190 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
3191 ASSERT_TRUE(root
.good());
3193 syncable::MutableEntry
folder_a(&trans
, syncable::CREATE
,
3194 BOOKMARKS
, root
.GetId(), "folderA");
3195 ASSERT_TRUE(folder_a
.good());
3196 SetNodeProperties(&folder_a
);
3197 folder_a
.PutIsDir(true);
3198 folder_a_id
= folder_a
.GetMetahandle();
3200 syncable::MutableEntry
folder_b(&trans
, syncable::CREATE
,
3201 BOOKMARKS
, root
.GetId(), "folderB");
3202 ASSERT_TRUE(folder_b
.good());
3203 SetNodeProperties(&folder_b
);
3204 folder_b
.PutIsDir(true);
3205 folder_b_id
= folder_b
.GetMetahandle();
3207 syncable::MutableEntry
child(&trans
, syncable::CREATE
,
3208 BOOKMARKS
, folder_a
.GetId(),
3210 ASSERT_TRUE(child
.good());
3211 SetNodeProperties(&child
);
3212 child_id
= child
.GetMetahandle();
3215 // Close that transaction. The above was to setup the initial scenario. The
3216 // real test starts now.
3219 syncable::WriteTransaction
trans(
3220 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3222 syncable::MutableEntry
folder_a(
3223 &trans
, syncable::GET_BY_HANDLE
, folder_a_id
);
3224 syncable::MutableEntry
folder_b(
3225 &trans
, syncable::GET_BY_HANDLE
, folder_b_id
);
3226 syncable::MutableEntry
child(&trans
, syncable::GET_BY_HANDLE
, child_id
);
3228 // Delete folder B and its child.
3229 child
.PutIsDel(true);
3230 folder_b
.PutIsDel(true);
3232 // Make an unrelated change to folder A.
3233 folder_a
.PutNonUniqueName("NewNameA");
3236 EXPECT_EQ(3UL, GetChangeListSize());
3238 size_t folder_a_pos
=
3239 FindChangeInList(folder_a_id
, ChangeRecord::ACTION_UPDATE
);
3240 size_t folder_b_pos
=
3241 FindChangeInList(folder_b_id
, ChangeRecord::ACTION_DELETE
);
3242 size_t child_pos
= FindChangeInList(child_id
, ChangeRecord::ACTION_DELETE
);
3244 // Deletes should appear before updates.
3245 EXPECT_LT(child_pos
, folder_a_pos
);
3246 EXPECT_LT(folder_b_pos
, folder_a_pos
);
3249 // See that attachment metadata changes are not filtered out by
3250 // SyncManagerImpl::VisiblePropertiesDiffer.
3251 TEST_F(SyncManagerChangeProcessingTest
, AttachmentMetadataOnlyChanges
) {
3252 // Create an article with no attachments. See that a change is generated.
3253 int64 article_id
= kInvalidId
;
3255 syncable::WriteTransaction
trans(
3256 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3257 int64 type_root
= GetIdForDataType(ARTICLES
);
3258 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
3259 ASSERT_TRUE(root
.good());
3260 syncable::MutableEntry
article(
3261 &trans
, syncable::CREATE
, ARTICLES
, root
.GetId(), "article");
3262 ASSERT_TRUE(article
.good());
3263 SetNodeProperties(&article
);
3264 article_id
= article
.GetMetahandle();
3266 ASSERT_EQ(1UL, GetChangeListSize());
3267 FindChangeInList(article_id
, ChangeRecord::ACTION_ADD
);
3270 // Modify the article by adding one attachment. Don't touch anything else.
3271 // See that a change is generated.
3273 syncable::WriteTransaction
trans(
3274 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3275 syncable::MutableEntry
article(&trans
, syncable::GET_BY_HANDLE
, article_id
);
3276 sync_pb::AttachmentMetadata metadata
;
3277 *metadata
.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3278 article
.PutAttachmentMetadata(metadata
);
3280 ASSERT_EQ(1UL, GetChangeListSize());
3281 FindChangeInList(article_id
, ChangeRecord::ACTION_UPDATE
);
3284 // Modify the article by replacing its attachment with a different one. See
3285 // that a change is generated.
3287 syncable::WriteTransaction
trans(
3288 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3289 syncable::MutableEntry
article(&trans
, syncable::GET_BY_HANDLE
, article_id
);
3290 sync_pb::AttachmentMetadata metadata
= article
.GetAttachmentMetadata();
3291 *metadata
.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3292 article
.PutAttachmentMetadata(metadata
);
3294 ASSERT_EQ(1UL, GetChangeListSize());
3295 FindChangeInList(article_id
, ChangeRecord::ACTION_UPDATE
);
3298 // Modify the article by replacing its attachment metadata with the same
3299 // attachment metadata. No change should be generated.
3301 syncable::WriteTransaction
trans(
3302 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3303 syncable::MutableEntry
article(&trans
, syncable::GET_BY_HANDLE
, article_id
);
3304 article
.PutAttachmentMetadata(article
.GetAttachmentMetadata());
3306 ASSERT_EQ(0UL, GetChangeListSize());
3309 // During initialization SyncManagerImpl loads sqlite database. If it fails to
3310 // do so it should fail initialization. This test verifies this behavior.
3311 // Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
3312 // InternalComponentsFactory to return DirectoryBackingStore that always fails
3314 class SyncManagerInitInvalidStorageTest
: public SyncManagerTest
{
3316 SyncManagerInitInvalidStorageTest() {
3319 InternalComponentsFactory
* GetFactory() override
{
3320 return new TestInternalComponentsFactory(
3321 GetSwitches(), InternalComponentsFactory::STORAGE_INVALID
,
3326 // SyncManagerInitInvalidStorageTest::GetFactory will return
3327 // DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
3328 // SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
3329 // task is to ensure that SyncManagerImpl reported initialization failure in
3330 // OnInitializationComplete callback.
3331 TEST_F(SyncManagerInitInvalidStorageTest
, FailToOpenDatabase
) {
3332 EXPECT_FALSE(initialization_succeeded_
);
3335 } // namespace syncer