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/message_loop/message_loop.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/test/values_test_util.h"
24 #include "base/values.h"
25 #include "google_apis/gaia/gaia_constants.h"
26 #include "sync/engine/sync_scheduler.h"
27 #include "sync/internal_api/public/base/attachment_id_proto.h"
28 #include "sync/internal_api/public/base/cancelation_signal.h"
29 #include "sync/internal_api/public/base/model_type_test_util.h"
30 #include "sync/internal_api/public/change_record.h"
31 #include "sync/internal_api/public/engine/model_safe_worker.h"
32 #include "sync/internal_api/public/engine/polling_constants.h"
33 #include "sync/internal_api/public/events/protocol_event.h"
34 #include "sync/internal_api/public/http_post_provider_factory.h"
35 #include "sync/internal_api/public/http_post_provider_interface.h"
36 #include "sync/internal_api/public/read_node.h"
37 #include "sync/internal_api/public/read_transaction.h"
38 #include "sync/internal_api/public/test/test_entry_factory.h"
39 #include "sync/internal_api/public/test/test_internal_components_factory.h"
40 #include "sync/internal_api/public/test/test_user_share.h"
41 #include "sync/internal_api/public/write_node.h"
42 #include "sync/internal_api/public/write_transaction.h"
43 #include "sync/internal_api/sync_encryption_handler_impl.h"
44 #include "sync/internal_api/sync_manager_impl.h"
45 #include "sync/internal_api/syncapi_internal.h"
46 #include "sync/js/js_backend.h"
47 #include "sync/js/js_event_handler.h"
48 #include "sync/js/js_test_util.h"
49 #include "sync/protocol/bookmark_specifics.pb.h"
50 #include "sync/protocol/encryption.pb.h"
51 #include "sync/protocol/extension_specifics.pb.h"
52 #include "sync/protocol/password_specifics.pb.h"
53 #include "sync/protocol/preference_specifics.pb.h"
54 #include "sync/protocol/proto_value_conversions.h"
55 #include "sync/protocol/sync.pb.h"
56 #include "sync/sessions/sync_session.h"
57 #include "sync/syncable/directory.h"
58 #include "sync/syncable/entry.h"
59 #include "sync/syncable/mutable_entry.h"
60 #include "sync/syncable/nigori_util.h"
61 #include "sync/syncable/syncable_id.h"
62 #include "sync/syncable/syncable_read_transaction.h"
63 #include "sync/syncable/syncable_util.h"
64 #include "sync/syncable/syncable_write_transaction.h"
65 #include "sync/test/callback_counter.h"
66 #include "sync/test/engine/fake_model_worker.h"
67 #include "sync/test/engine/fake_sync_scheduler.h"
68 #include "sync/test/engine/test_id_factory.h"
69 #include "sync/test/fake_encryptor.h"
70 #include "sync/util/cryptographer.h"
71 #include "sync/util/extensions_activity.h"
72 #include "sync/util/test_unrecoverable_error_handler.h"
73 #include "sync/util/time.h"
74 #include "testing/gmock/include/gmock/gmock.h"
75 #include "testing/gtest/include/gtest/gtest.h"
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 non-folder child of the root node. 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 ReadNode
root_node(&trans
);
105 root_node
.InitByRootLookup();
106 WriteNode
node(&trans
);
107 WriteNode::InitUniqueByCreationResult result
=
108 node
.InitUniqueByCreation(model_type
, root_node
, client_tag
);
109 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
110 node
.SetIsFolder(false);
114 // Makes a folder child of a non-root node. Returns the id of the
115 // newly-created node.
116 int64
MakeFolderWithParent(UserShare
* share
,
117 ModelType model_type
,
119 BaseNode
* predecessor
) {
120 WriteTransaction
trans(FROM_HERE
, share
);
121 ReadNode
parent_node(&trans
);
122 EXPECT_EQ(BaseNode::INIT_OK
, parent_node
.InitByIdLookup(parent_id
));
123 WriteNode
node(&trans
);
124 EXPECT_TRUE(node
.InitBookmarkByCreation(parent_node
, predecessor
));
125 node
.SetIsFolder(true);
129 int64
MakeBookmarkWithParent(UserShare
* share
,
131 BaseNode
* predecessor
) {
132 WriteTransaction
trans(FROM_HERE
, share
);
133 ReadNode
parent_node(&trans
);
134 EXPECT_EQ(BaseNode::INIT_OK
, parent_node
.InitByIdLookup(parent_id
));
135 WriteNode
node(&trans
);
136 EXPECT_TRUE(node
.InitBookmarkByCreation(parent_node
, predecessor
));
140 // Creates the "synced" root node for a particular datatype. We use the syncable
141 // methods here so that the syncer treats these nodes as if they were already
142 // received from the server.
143 int64
MakeServerNodeForType(UserShare
* share
,
144 ModelType model_type
) {
145 sync_pb::EntitySpecifics specifics
;
146 AddDefaultFieldValue(model_type
, &specifics
);
147 syncable::WriteTransaction
trans(
148 FROM_HERE
, syncable::UNITTEST
, share
->directory
.get());
149 // Attempt to lookup by nigori tag.
150 std::string type_tag
= ModelTypeToRootTag(model_type
);
151 syncable::Id node_id
= syncable::Id::CreateFromServerId(type_tag
);
152 syncable::MutableEntry
entry(&trans
, syncable::CREATE_NEW_UPDATE_ITEM
,
154 EXPECT_TRUE(entry
.good());
155 entry
.PutBaseVersion(1);
156 entry
.PutServerVersion(1);
157 entry
.PutIsUnappliedUpdate(false);
158 entry
.PutServerParentId(syncable::GetNullId());
159 entry
.PutServerIsDir(true);
160 entry
.PutIsDir(true);
161 entry
.PutServerSpecifics(specifics
);
162 entry
.PutUniqueServerTag(type_tag
);
163 entry
.PutNonUniqueName(type_tag
);
164 entry
.PutIsDel(false);
165 entry
.PutSpecifics(specifics
);
166 return entry
.GetMetahandle();
169 // Simulates creating a "synced" node as a child of the root datatype node.
170 int64
MakeServerNode(UserShare
* share
, ModelType model_type
,
171 const std::string
& client_tag
,
172 const std::string
& hashed_tag
,
173 const sync_pb::EntitySpecifics
& specifics
) {
174 syncable::WriteTransaction
trans(
175 FROM_HERE
, syncable::UNITTEST
, share
->directory
.get());
176 syncable::Entry
root_entry(&trans
, syncable::GET_TYPE_ROOT
, model_type
);
177 EXPECT_TRUE(root_entry
.good());
178 syncable::Id root_id
= root_entry
.GetId();
179 syncable::Id node_id
= syncable::Id::CreateFromServerId(client_tag
);
180 syncable::MutableEntry
entry(&trans
, syncable::CREATE_NEW_UPDATE_ITEM
,
182 EXPECT_TRUE(entry
.good());
183 entry
.PutBaseVersion(1);
184 entry
.PutServerVersion(1);
185 entry
.PutIsUnappliedUpdate(false);
186 entry
.PutServerParentId(root_id
);
187 entry
.PutParentId(root_id
);
188 entry
.PutServerIsDir(false);
189 entry
.PutIsDir(false);
190 entry
.PutServerSpecifics(specifics
);
191 entry
.PutNonUniqueName(client_tag
);
192 entry
.PutUniqueClientTag(hashed_tag
);
193 entry
.PutIsDel(false);
194 entry
.PutSpecifics(specifics
);
195 return entry
.GetMetahandle();
200 class SyncApiTest
: public testing::Test
{
202 virtual void SetUp() {
203 test_user_share_
.SetUp();
206 virtual void TearDown() {
207 test_user_share_
.TearDown();
211 // Create an entry with the given |model_type|, |client_tag| and
212 // |attachment_metadata|.
213 void CreateEntryWithAttachmentMetadata(
214 const ModelType
& model_type
,
215 const std::string
& client_tag
,
216 const sync_pb::AttachmentMetadata
& attachment_metadata
);
218 // Attempts to load the entry specified by |model_type| and |client_tag| and
219 // returns the lookup result code.
220 BaseNode::InitByLookupResult
LookupEntryByClientTag(
221 const ModelType
& model_type
,
222 const std::string
& client_tag
);
224 // Replace the entry specified by |model_type| and |client_tag| with a
226 void ReplaceWithTombstone(const ModelType
& model_type
,
227 const std::string
& client_tag
);
229 // Save changes to the Directory, destroy it then reload it.
232 UserShare
* user_share();
233 syncable::Directory
* dir();
234 SyncEncryptionHandler
* encryption_handler();
237 base::MessageLoop message_loop_
;
238 TestUserShare test_user_share_
;
241 UserShare
* SyncApiTest::user_share() {
242 return test_user_share_
.user_share();
245 syncable::Directory
* SyncApiTest::dir() {
246 return test_user_share_
.user_share()->directory
.get();
249 SyncEncryptionHandler
* SyncApiTest::encryption_handler() {
250 return test_user_share_
.encryption_handler();
253 bool SyncApiTest::ReloadDir() {
254 return test_user_share_
.Reload();
257 void SyncApiTest::CreateEntryWithAttachmentMetadata(
258 const ModelType
& model_type
,
259 const std::string
& client_tag
,
260 const sync_pb::AttachmentMetadata
& attachment_metadata
) {
261 syncer::WriteTransaction
trans(FROM_HERE
, user_share());
262 syncer::ReadNode
root_node(&trans
);
263 root_node
.InitByRootLookup();
264 syncer::WriteNode
node(&trans
);
265 ASSERT_EQ(node
.InitUniqueByCreation(model_type
, root_node
, client_tag
),
266 syncer::WriteNode::INIT_SUCCESS
);
267 node
.SetAttachmentMetadata(attachment_metadata
);
270 BaseNode::InitByLookupResult
SyncApiTest::LookupEntryByClientTag(
271 const ModelType
& model_type
,
272 const std::string
& client_tag
) {
273 syncer::ReadTransaction
trans(FROM_HERE
, user_share());
274 syncer::ReadNode
node(&trans
);
275 return node
.InitByClientTagLookup(model_type
, client_tag
);
278 void SyncApiTest::ReplaceWithTombstone(const ModelType
& model_type
,
279 const std::string
& client_tag
) {
280 syncer::WriteTransaction
trans(FROM_HERE
, user_share());
281 syncer::WriteNode
node(&trans
);
282 ASSERT_EQ(node
.InitByClientTagLookup(model_type
, client_tag
),
283 syncer::WriteNode::INIT_OK
);
287 TEST_F(SyncApiTest
, SanityCheckTest
) {
289 ReadTransaction
trans(FROM_HERE
, user_share());
290 EXPECT_TRUE(trans
.GetWrappedTrans());
293 WriteTransaction
trans(FROM_HERE
, user_share());
294 EXPECT_TRUE(trans
.GetWrappedTrans());
297 // No entries but root should exist
298 ReadTransaction
trans(FROM_HERE
, user_share());
299 ReadNode
node(&trans
);
300 // Metahandle 1 can be root, sanity check 2
301 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD
, node
.InitByIdLookup(2));
305 TEST_F(SyncApiTest
, BasicTagWrite
) {
307 ReadTransaction
trans(FROM_HERE
, user_share());
308 ReadNode
root_node(&trans
);
309 root_node
.InitByRootLookup();
310 EXPECT_EQ(root_node
.GetFirstChildId(), 0);
313 ignore_result(MakeNode(user_share(), BOOKMARKS
, "testtag"));
316 ReadTransaction
trans(FROM_HERE
, user_share());
317 ReadNode
node(&trans
);
318 EXPECT_EQ(BaseNode::INIT_OK
,
319 node
.InitByClientTagLookup(BOOKMARKS
, "testtag"));
321 ReadNode
root_node(&trans
);
322 root_node
.InitByRootLookup();
323 EXPECT_NE(node
.GetId(), 0);
324 EXPECT_EQ(node
.GetId(), root_node
.GetFirstChildId());
328 TEST_F(SyncApiTest
, ModelTypesSiloed
) {
330 WriteTransaction
trans(FROM_HERE
, user_share());
331 ReadNode
root_node(&trans
);
332 root_node
.InitByRootLookup();
333 EXPECT_EQ(root_node
.GetFirstChildId(), 0);
336 ignore_result(MakeNode(user_share(), BOOKMARKS
, "collideme"));
337 ignore_result(MakeNode(user_share(), PREFERENCES
, "collideme"));
338 ignore_result(MakeNode(user_share(), AUTOFILL
, "collideme"));
341 ReadTransaction
trans(FROM_HERE
, user_share());
343 ReadNode
bookmarknode(&trans
);
344 EXPECT_EQ(BaseNode::INIT_OK
,
345 bookmarknode
.InitByClientTagLookup(BOOKMARKS
,
348 ReadNode
prefnode(&trans
);
349 EXPECT_EQ(BaseNode::INIT_OK
,
350 prefnode
.InitByClientTagLookup(PREFERENCES
,
353 ReadNode
autofillnode(&trans
);
354 EXPECT_EQ(BaseNode::INIT_OK
,
355 autofillnode
.InitByClientTagLookup(AUTOFILL
,
358 EXPECT_NE(bookmarknode
.GetId(), prefnode
.GetId());
359 EXPECT_NE(autofillnode
.GetId(), prefnode
.GetId());
360 EXPECT_NE(bookmarknode
.GetId(), autofillnode
.GetId());
364 TEST_F(SyncApiTest
, ReadMissingTagsFails
) {
366 ReadTransaction
trans(FROM_HERE
, user_share());
367 ReadNode
node(&trans
);
368 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD
,
369 node
.InitByClientTagLookup(BOOKMARKS
,
373 WriteTransaction
trans(FROM_HERE
, user_share());
374 WriteNode
node(&trans
);
375 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD
,
376 node
.InitByClientTagLookup(BOOKMARKS
,
381 // TODO(chron): Hook this all up to the server and write full integration tests
382 // for update->undelete behavior.
383 TEST_F(SyncApiTest
, TestDeleteBehavior
) {
386 std::string
test_title("test1");
389 WriteTransaction
trans(FROM_HERE
, user_share());
390 ReadNode
root_node(&trans
);
391 root_node
.InitByRootLookup();
393 // we'll use this spare folder later
394 WriteNode
folder_node(&trans
);
395 EXPECT_TRUE(folder_node
.InitBookmarkByCreation(root_node
, NULL
));
396 folder_id
= folder_node
.GetId();
398 WriteNode
wnode(&trans
);
399 WriteNode::InitUniqueByCreationResult result
=
400 wnode
.InitUniqueByCreation(BOOKMARKS
, root_node
, "testtag");
401 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
402 wnode
.SetIsFolder(false);
403 wnode
.SetTitle(test_title
);
405 node_id
= wnode
.GetId();
408 // Ensure we can delete something with a tag.
410 WriteTransaction
trans(FROM_HERE
, user_share());
411 WriteNode
wnode(&trans
);
412 EXPECT_EQ(BaseNode::INIT_OK
,
413 wnode
.InitByClientTagLookup(BOOKMARKS
,
415 EXPECT_FALSE(wnode
.GetIsFolder());
416 EXPECT_EQ(wnode
.GetTitle(), test_title
);
421 // Lookup of a node which was deleted should return failure,
422 // but have found some data about the node.
424 ReadTransaction
trans(FROM_HERE
, user_share());
425 ReadNode
node(&trans
);
426 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL
,
427 node
.InitByClientTagLookup(BOOKMARKS
,
429 // Note that for proper function of this API this doesn't need to be
430 // filled, we're checking just to make sure the DB worked in this test.
431 EXPECT_EQ(node
.GetTitle(), test_title
);
435 WriteTransaction
trans(FROM_HERE
, user_share());
436 ReadNode
folder_node(&trans
);
437 EXPECT_EQ(BaseNode::INIT_OK
, folder_node
.InitByIdLookup(folder_id
));
439 WriteNode
wnode(&trans
);
440 // This will undelete the tag.
441 WriteNode::InitUniqueByCreationResult result
=
442 wnode
.InitUniqueByCreation(BOOKMARKS
, folder_node
, "testtag");
443 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
444 EXPECT_EQ(wnode
.GetIsFolder(), false);
445 EXPECT_EQ(wnode
.GetParentId(), folder_node
.GetId());
446 EXPECT_EQ(wnode
.GetId(), node_id
);
447 EXPECT_NE(wnode
.GetTitle(), test_title
); // Title should be cleared
448 wnode
.SetTitle(test_title
);
451 // Now look up should work.
453 ReadTransaction
trans(FROM_HERE
, user_share());
454 ReadNode
node(&trans
);
455 EXPECT_EQ(BaseNode::INIT_OK
,
456 node
.InitByClientTagLookup(BOOKMARKS
,
458 EXPECT_EQ(node
.GetTitle(), test_title
);
459 EXPECT_EQ(node
.GetModelType(), BOOKMARKS
);
463 TEST_F(SyncApiTest
, WriteAndReadPassword
) {
464 KeyParams params
= {"localhost", "username", "passphrase"};
466 ReadTransaction
trans(FROM_HERE
, user_share());
467 trans
.GetCryptographer()->AddKey(params
);
470 WriteTransaction
trans(FROM_HERE
, user_share());
471 ReadNode
root_node(&trans
);
472 root_node
.InitByRootLookup();
474 WriteNode
password_node(&trans
);
475 WriteNode::InitUniqueByCreationResult result
=
476 password_node
.InitUniqueByCreation(PASSWORDS
,
478 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
479 sync_pb::PasswordSpecificsData data
;
480 data
.set_password_value("secret");
481 password_node
.SetPasswordSpecifics(data
);
484 ReadTransaction
trans(FROM_HERE
, user_share());
485 ReadNode
root_node(&trans
);
486 root_node
.InitByRootLookup();
488 ReadNode
password_node(&trans
);
489 EXPECT_EQ(BaseNode::INIT_OK
,
490 password_node
.InitByClientTagLookup(PASSWORDS
, "foo"));
491 const sync_pb::PasswordSpecificsData
& data
=
492 password_node
.GetPasswordSpecifics();
493 EXPECT_EQ("secret", data
.password_value());
497 TEST_F(SyncApiTest
, WriteEncryptedTitle
) {
498 KeyParams params
= {"localhost", "username", "passphrase"};
500 ReadTransaction
trans(FROM_HERE
, user_share());
501 trans
.GetCryptographer()->AddKey(params
);
503 encryption_handler()->EnableEncryptEverything();
506 WriteTransaction
trans(FROM_HERE
, user_share());
507 ReadNode
root_node(&trans
);
508 root_node
.InitByRootLookup();
510 WriteNode
bookmark_node(&trans
);
511 ASSERT_TRUE(bookmark_node
.InitBookmarkByCreation(root_node
, NULL
));
512 bookmark_id
= bookmark_node
.GetId();
513 bookmark_node
.SetTitle("foo");
515 WriteNode
pref_node(&trans
);
516 WriteNode::InitUniqueByCreationResult result
=
517 pref_node
.InitUniqueByCreation(PREFERENCES
, root_node
, "bar");
518 ASSERT_EQ(WriteNode::INIT_SUCCESS
, result
);
519 pref_node
.SetTitle("bar");
522 ReadTransaction
trans(FROM_HERE
, user_share());
523 ReadNode
root_node(&trans
);
524 root_node
.InitByRootLookup();
526 ReadNode
bookmark_node(&trans
);
527 ASSERT_EQ(BaseNode::INIT_OK
, bookmark_node
.InitByIdLookup(bookmark_id
));
528 EXPECT_EQ("foo", bookmark_node
.GetTitle());
529 EXPECT_EQ(kEncryptedString
,
530 bookmark_node
.GetEntry()->GetNonUniqueName());
532 ReadNode
pref_node(&trans
);
533 ASSERT_EQ(BaseNode::INIT_OK
,
534 pref_node
.InitByClientTagLookup(PREFERENCES
,
536 EXPECT_EQ(kEncryptedString
, pref_node
.GetTitle());
540 TEST_F(SyncApiTest
, BaseNodeSetSpecifics
) {
541 int64 child_id
= MakeNode(user_share(), BOOKMARKS
, "testtag");
542 WriteTransaction
trans(FROM_HERE
, user_share());
543 WriteNode
node(&trans
);
544 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(child_id
));
546 sync_pb::EntitySpecifics entity_specifics
;
547 entity_specifics
.mutable_bookmark()->set_url("http://www.google.com");
549 EXPECT_NE(entity_specifics
.SerializeAsString(),
550 node
.GetEntitySpecifics().SerializeAsString());
551 node
.SetEntitySpecifics(entity_specifics
);
552 EXPECT_EQ(entity_specifics
.SerializeAsString(),
553 node
.GetEntitySpecifics().SerializeAsString());
556 TEST_F(SyncApiTest
, BaseNodeSetSpecificsPreservesUnknownFields
) {
557 int64 child_id
= MakeNode(user_share(), BOOKMARKS
, "testtag");
558 WriteTransaction
trans(FROM_HERE
, user_share());
559 WriteNode
node(&trans
);
560 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(child_id
));
561 EXPECT_TRUE(node
.GetEntitySpecifics().unknown_fields().empty());
563 sync_pb::EntitySpecifics entity_specifics
;
564 entity_specifics
.mutable_bookmark()->set_url("http://www.google.com");
565 entity_specifics
.mutable_unknown_fields()->AddFixed32(5, 100);
566 node
.SetEntitySpecifics(entity_specifics
);
567 EXPECT_FALSE(node
.GetEntitySpecifics().unknown_fields().empty());
569 entity_specifics
.mutable_unknown_fields()->Clear();
570 node
.SetEntitySpecifics(entity_specifics
);
571 EXPECT_FALSE(node
.GetEntitySpecifics().unknown_fields().empty());
574 TEST_F(SyncApiTest
, EmptyTags
) {
575 WriteTransaction
trans(FROM_HERE
, user_share());
576 ReadNode
root_node(&trans
);
577 root_node
.InitByRootLookup();
578 WriteNode
node(&trans
);
579 std::string empty_tag
;
580 WriteNode::InitUniqueByCreationResult result
=
581 node
.InitUniqueByCreation(TYPED_URLS
, root_node
, empty_tag
);
582 EXPECT_NE(WriteNode::INIT_SUCCESS
, result
);
583 EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION
,
584 node
.InitByClientTagLookup(TYPED_URLS
, empty_tag
));
587 // Test counting nodes when the type's root node has no children.
588 TEST_F(SyncApiTest
, GetTotalNodeCountEmpty
) {
589 int64 type_root
= MakeServerNodeForType(user_share(), BOOKMARKS
);
591 ReadTransaction
trans(FROM_HERE
, user_share());
592 ReadNode
type_root_node(&trans
);
593 EXPECT_EQ(BaseNode::INIT_OK
,
594 type_root_node
.InitByIdLookup(type_root
));
595 EXPECT_EQ(1, type_root_node
.GetTotalNodeCount());
599 // Test counting nodes when there is one child beneath the type's root.
600 TEST_F(SyncApiTest
, GetTotalNodeCountOneChild
) {
601 int64 type_root
= MakeServerNodeForType(user_share(), BOOKMARKS
);
602 int64 parent
= MakeFolderWithParent(user_share(), BOOKMARKS
, type_root
, NULL
);
604 ReadTransaction
trans(FROM_HERE
, user_share());
605 ReadNode
type_root_node(&trans
);
606 EXPECT_EQ(BaseNode::INIT_OK
,
607 type_root_node
.InitByIdLookup(type_root
));
608 EXPECT_EQ(2, type_root_node
.GetTotalNodeCount());
609 ReadNode
parent_node(&trans
);
610 EXPECT_EQ(BaseNode::INIT_OK
,
611 parent_node
.InitByIdLookup(parent
));
612 EXPECT_EQ(1, parent_node
.GetTotalNodeCount());
616 // Test counting nodes when there are multiple children beneath the type root,
617 // and one of those children has children of its own.
618 TEST_F(SyncApiTest
, GetTotalNodeCountMultipleChildren
) {
619 int64 type_root
= MakeServerNodeForType(user_share(), BOOKMARKS
);
620 int64 parent
= MakeFolderWithParent(user_share(), BOOKMARKS
, type_root
, NULL
);
621 ignore_result(MakeFolderWithParent(user_share(), BOOKMARKS
, type_root
, NULL
));
622 int64 child1
= MakeFolderWithParent(user_share(), BOOKMARKS
, parent
, NULL
);
623 ignore_result(MakeBookmarkWithParent(user_share(), parent
, NULL
));
624 ignore_result(MakeBookmarkWithParent(user_share(), child1
, NULL
));
627 ReadTransaction
trans(FROM_HERE
, user_share());
628 ReadNode
type_root_node(&trans
);
629 EXPECT_EQ(BaseNode::INIT_OK
,
630 type_root_node
.InitByIdLookup(type_root
));
631 EXPECT_EQ(6, type_root_node
.GetTotalNodeCount());
632 ReadNode
node(&trans
);
633 EXPECT_EQ(BaseNode::INIT_OK
,
634 node
.InitByIdLookup(parent
));
635 EXPECT_EQ(4, node
.GetTotalNodeCount());
639 // Verify that Directory keeps track of which attachments are referenced by
641 TEST_F(SyncApiTest
, AttachmentLinking
) {
642 // Add an entry with an attachment.
643 std::string
tag1("some tag");
644 syncer::AttachmentId
attachment_id(syncer::AttachmentId::Create());
645 sync_pb::AttachmentMetadata attachment_metadata
;
646 sync_pb::AttachmentMetadataRecord
* record
= attachment_metadata
.add_record();
647 *record
->mutable_id() = attachment_id
.GetProto();
648 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
649 CreateEntryWithAttachmentMetadata(PREFERENCES
, tag1
, attachment_metadata
);
651 // See that the directory knows it's linked.
652 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
654 // Add a second entry referencing the same attachment.
655 std::string
tag2("some other tag");
656 CreateEntryWithAttachmentMetadata(PREFERENCES
, tag2
, attachment_metadata
);
658 // See that the directory knows it's still linked.
659 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
661 // Tombstone the first entry.
662 ReplaceWithTombstone(syncer::PREFERENCES
, tag1
);
664 // See that the attachment is still considered linked because the entry hasn't
665 // been purged from the Directory.
666 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
668 // Save changes and see that the entry is truly gone.
669 ASSERT_TRUE(dir()->SaveChanges());
670 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES
, tag1
),
671 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD
);
673 // However, the attachment is still linked.
674 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
676 // Save, destroy, and recreate the directory. See that it's still linked.
677 ASSERT_TRUE(ReloadDir());
678 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
680 // Tombstone the second entry, save changes, see that it's truly gone.
681 ReplaceWithTombstone(syncer::PREFERENCES
, tag2
);
682 ASSERT_TRUE(dir()->SaveChanges());
683 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES
, tag2
),
684 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD
);
686 // Finally, the attachment is no longer linked.
687 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
692 class TestHttpPostProviderInterface
: public HttpPostProviderInterface
{
694 ~TestHttpPostProviderInterface() override
{}
696 void SetExtraRequestHeaders(const char* headers
) override
{}
697 void SetURL(const char* url
, int port
) override
{}
698 void SetPostPayload(const char* content_type
,
700 const char* content
) override
{}
701 bool MakeSynchronousPost(int* error_code
, int* response_code
) override
{
704 int GetResponseContentLength() const override
{ return 0; }
705 const char* GetResponseContent() const override
{ return ""; }
706 const std::string
GetResponseHeaderValue(
707 const std::string
& name
) const override
{
708 return std::string();
710 void Abort() override
{}
713 class TestHttpPostProviderFactory
: public HttpPostProviderFactory
{
715 ~TestHttpPostProviderFactory() override
{}
716 void Init(const std::string
& user_agent
) override
{}
717 HttpPostProviderInterface
* Create() override
{
718 return new TestHttpPostProviderInterface();
720 void Destroy(HttpPostProviderInterface
* http
) override
{
721 delete static_cast<TestHttpPostProviderInterface
*>(http
);
725 class SyncManagerObserverMock
: public SyncManager::Observer
{
727 MOCK_METHOD1(OnSyncCycleCompleted
,
728 void(const SyncSessionSnapshot
&)); // NOLINT
729 MOCK_METHOD4(OnInitializationComplete
,
730 void(const WeakHandle
<JsBackend
>&,
731 const WeakHandle
<DataTypeDebugInfoListener
>&,
733 syncer::ModelTypeSet
)); // NOLINT
734 MOCK_METHOD1(OnConnectionStatusChange
, void(ConnectionStatus
)); // NOLINT
735 MOCK_METHOD1(OnUpdatedToken
, void(const std::string
&)); // NOLINT
736 MOCK_METHOD1(OnActionableError
, void(const SyncProtocolError
&)); // NOLINT
737 MOCK_METHOD1(OnMigrationRequested
, void(syncer::ModelTypeSet
)); // NOLINT
738 MOCK_METHOD1(OnProtocolEvent
, void(const ProtocolEvent
&)); // NOLINT
741 class SyncEncryptionHandlerObserverMock
742 : public SyncEncryptionHandler::Observer
{
744 MOCK_METHOD2(OnPassphraseRequired
,
745 void(PassphraseRequiredReason
,
746 const sync_pb::EncryptedData
&)); // NOLINT
747 MOCK_METHOD0(OnPassphraseAccepted
, void()); // NOLINT
748 MOCK_METHOD2(OnBootstrapTokenUpdated
,
749 void(const std::string
&, BootstrapTokenType type
)); // NOLINT
750 MOCK_METHOD2(OnEncryptedTypesChanged
,
751 void(ModelTypeSet
, bool)); // NOLINT
752 MOCK_METHOD0(OnEncryptionComplete
, void()); // NOLINT
753 MOCK_METHOD1(OnCryptographerStateChanged
, void(Cryptographer
*)); // NOLINT
754 MOCK_METHOD2(OnPassphraseTypeChanged
, void(PassphraseType
,
755 base::Time
)); // NOLINT
760 class SyncManagerTest
: public testing::Test
,
761 public SyncManager::ChangeDelegate
{
768 enum EncryptionStatus
{
775 : sync_manager_("Test sync manager") {
776 switches_
.encryption_method
=
777 InternalComponentsFactory::ENCRYPTION_KEYSTORE
;
780 virtual ~SyncManagerTest() {
783 // Test implementation.
785 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
787 extensions_activity_
= new ExtensionsActivity();
789 SyncCredentials credentials
;
790 credentials
.email
= "foo@bar.com";
791 credentials
.sync_token
= "sometoken";
792 OAuth2TokenService::ScopeSet scope_set
;
793 scope_set
.insert(GaiaConstants::kChromeSyncOAuth2Scope
);
794 credentials
.scope_set
= scope_set
;
796 sync_manager_
.AddObserver(&manager_observer_
);
797 EXPECT_CALL(manager_observer_
, OnInitializationComplete(_
, _
, _
, _
)).
798 WillOnce(DoAll(SaveArg
<0>(&js_backend_
),
799 SaveArg
<2>(&initialization_succeeded_
)));
801 EXPECT_FALSE(js_backend_
.IsInitialized());
803 std::vector
<scoped_refptr
<ModelSafeWorker
> > workers
;
804 ModelSafeRoutingInfo routing_info
;
805 GetModelSafeRoutingInfo(&routing_info
);
807 // This works only because all routing info types are GROUP_PASSIVE.
808 // If we had types in other groups, we would need additional workers
810 scoped_refptr
<ModelSafeWorker
> worker
= new FakeModelWorker(GROUP_PASSIVE
);
811 workers
.push_back(worker
);
813 SyncManager::InitArgs args
;
814 args
.database_location
= temp_dir_
.path();
815 args
.service_url
= GURL("https://example.com/");
817 scoped_ptr
<HttpPostProviderFactory
>(new TestHttpPostProviderFactory());
818 args
.workers
= workers
;
819 args
.extensions_activity
= extensions_activity_
.get(),
820 args
.change_delegate
= this;
821 args
.credentials
= credentials
;
822 args
.invalidator_client_id
= "fake_invalidator_client_id";
823 args
.internal_components_factory
.reset(GetFactory());
824 args
.encryptor
= &encryptor_
;
825 args
.unrecoverable_error_handler
.reset(new TestUnrecoverableErrorHandler
);
826 args
.cancelation_signal
= &cancelation_signal_
;
827 sync_manager_
.Init(&args
);
829 sync_manager_
.GetEncryptionHandler()->AddObserver(&encryption_observer_
);
831 EXPECT_TRUE(js_backend_
.IsInitialized());
832 EXPECT_EQ(InternalComponentsFactory::STORAGE_ON_DISK
,
835 if (initialization_succeeded_
) {
836 for (ModelSafeRoutingInfo::iterator i
= routing_info
.begin();
837 i
!= routing_info
.end(); ++i
) {
838 type_roots_
[i
->first
] = MakeServerNodeForType(
839 sync_manager_
.GetUserShare(), i
->first
);
847 sync_manager_
.RemoveObserver(&manager_observer_
);
848 sync_manager_
.ShutdownOnSyncThread(STOP_SYNC
);
852 void GetModelSafeRoutingInfo(ModelSafeRoutingInfo
* out
) {
853 (*out
)[NIGORI
] = GROUP_PASSIVE
;
854 (*out
)[DEVICE_INFO
] = GROUP_PASSIVE
;
855 (*out
)[EXPERIMENTS
] = GROUP_PASSIVE
;
856 (*out
)[BOOKMARKS
] = GROUP_PASSIVE
;
857 (*out
)[THEMES
] = GROUP_PASSIVE
;
858 (*out
)[SESSIONS
] = GROUP_PASSIVE
;
859 (*out
)[PASSWORDS
] = GROUP_PASSIVE
;
860 (*out
)[PREFERENCES
] = GROUP_PASSIVE
;
861 (*out
)[PRIORITY_PREFERENCES
] = GROUP_PASSIVE
;
862 (*out
)[ARTICLES
] = GROUP_PASSIVE
;
865 ModelTypeSet
GetEnabledTypes() {
866 ModelSafeRoutingInfo routing_info
;
867 GetModelSafeRoutingInfo(&routing_info
);
868 return GetRoutingInfoTypes(routing_info
);
871 virtual void OnChangesApplied(
872 ModelType model_type
,
874 const BaseTransaction
* trans
,
875 const ImmutableChangeRecordList
& changes
) override
{}
877 virtual void OnChangesComplete(ModelType model_type
) override
{}
880 bool SetUpEncryption(NigoriStatus nigori_status
,
881 EncryptionStatus encryption_status
) {
882 UserShare
* share
= sync_manager_
.GetUserShare();
884 // We need to create the nigori node as if it were an applied server update.
885 int64 nigori_id
= GetIdForDataType(NIGORI
);
886 if (nigori_id
== kInvalidId
)
889 // Set the nigori cryptographer information.
890 if (encryption_status
== FULL_ENCRYPTION
)
891 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
893 WriteTransaction
trans(FROM_HERE
, share
);
894 Cryptographer
* cryptographer
= trans
.GetCryptographer();
897 if (encryption_status
!= UNINITIALIZED
) {
898 KeyParams params
= {"localhost", "dummy", "foobar"};
899 cryptographer
->AddKey(params
);
901 DCHECK_NE(nigori_status
, WRITE_TO_NIGORI
);
903 if (nigori_status
== WRITE_TO_NIGORI
) {
904 sync_pb::NigoriSpecifics nigori
;
905 cryptographer
->GetKeys(nigori
.mutable_encryption_keybag());
906 share
->directory
->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
908 trans
.GetWrappedTrans());
909 WriteNode
node(&trans
);
910 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(nigori_id
));
911 node
.SetNigoriSpecifics(nigori
);
913 return cryptographer
->is_ready();
916 int64
GetIdForDataType(ModelType type
) {
917 if (type_roots_
.count(type
) == 0)
919 return type_roots_
[type
];
923 message_loop_
.RunUntilIdle();
926 void SetJsEventHandler(const WeakHandle
<JsEventHandler
>& event_handler
) {
927 js_backend_
.Call(FROM_HERE
, &JsBackend::SetJsEventHandler
,
932 // Looks up an entry by client tag and resets IS_UNSYNCED value to false.
933 // Returns true if entry was previously unsynced, false if IS_UNSYNCED was
935 bool ResetUnsyncedEntry(ModelType type
,
936 const std::string
& client_tag
) {
937 UserShare
* share
= sync_manager_
.GetUserShare();
938 syncable::WriteTransaction
trans(
939 FROM_HERE
, syncable::UNITTEST
, share
->directory
.get());
940 const std::string hash
= syncable::GenerateSyncableHash(type
, client_tag
);
941 syncable::MutableEntry
entry(&trans
, syncable::GET_BY_CLIENT_TAG
,
943 EXPECT_TRUE(entry
.good());
944 if (!entry
.GetIsUnsynced())
946 entry
.PutIsUnsynced(false);
950 virtual InternalComponentsFactory
* GetFactory() {
951 return new TestInternalComponentsFactory(
952 GetSwitches(), InternalComponentsFactory::STORAGE_IN_MEMORY
,
956 // Returns true if we are currently encrypting all sync data. May
957 // be called on any thread.
958 bool EncryptEverythingEnabledForTest() {
959 return sync_manager_
.GetEncryptionHandler()->EncryptEverythingEnabled();
962 // Gets the set of encrypted types from the cryptographer
963 // Note: opens a transaction. May be called from any thread.
964 ModelTypeSet
GetEncryptedTypes() {
965 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
966 return GetEncryptedTypesWithTrans(&trans
);
969 ModelTypeSet
GetEncryptedTypesWithTrans(BaseTransaction
* trans
) {
970 return trans
->GetDirectory()->GetNigoriHandler()->
971 GetEncryptedTypes(trans
->GetWrappedTrans());
974 void SimulateInvalidatorEnabledForTest(bool is_enabled
) {
975 DCHECK(sync_manager_
.thread_checker_
.CalledOnValidThread());
976 sync_manager_
.SetInvalidatorEnabled(is_enabled
);
979 void SetProgressMarkerForType(ModelType type
, bool set
) {
981 sync_pb::DataTypeProgressMarker marker
;
982 marker
.set_token("token");
983 marker
.set_data_type_id(GetSpecificsFieldNumberFromModelType(type
));
984 sync_manager_
.directory()->SetDownloadProgress(type
, marker
);
986 sync_pb::DataTypeProgressMarker marker
;
987 sync_manager_
.directory()->SetDownloadProgress(type
, marker
);
991 InternalComponentsFactory::Switches
GetSwitches() const {
996 // Needed by |sync_manager_|.
997 base::MessageLoop message_loop_
;
998 // Needed by |sync_manager_|.
999 base::ScopedTempDir temp_dir_
;
1000 // Sync Id's for the roots of the enabled datatypes.
1001 std::map
<ModelType
, int64
> type_roots_
;
1002 scoped_refptr
<ExtensionsActivity
> extensions_activity_
;
1005 FakeEncryptor encryptor_
;
1006 SyncManagerImpl sync_manager_
;
1007 CancelationSignal cancelation_signal_
;
1008 WeakHandle
<JsBackend
> js_backend_
;
1009 bool initialization_succeeded_
;
1010 StrictMock
<SyncManagerObserverMock
> manager_observer_
;
1011 StrictMock
<SyncEncryptionHandlerObserverMock
> encryption_observer_
;
1012 InternalComponentsFactory::Switches switches_
;
1013 InternalComponentsFactory::StorageOption storage_used_
;
1016 TEST_F(SyncManagerTest
, GetAllNodesForTypeTest
) {
1017 ModelSafeRoutingInfo routing_info
;
1018 GetModelSafeRoutingInfo(&routing_info
);
1019 sync_manager_
.StartSyncingNormally(routing_info
);
1021 scoped_ptr
<base::ListValue
> node_list(
1022 sync_manager_
.GetAllNodesForType(syncer::PREFERENCES
));
1024 // Should have one node: the type root node.
1025 ASSERT_EQ(1U, node_list
->GetSize());
1027 const base::DictionaryValue
* first_result
;
1028 ASSERT_TRUE(node_list
->GetDictionary(0, &first_result
));
1029 EXPECT_TRUE(first_result
->HasKey("ID"));
1030 EXPECT_TRUE(first_result
->HasKey("NON_UNIQUE_NAME"));
1033 TEST_F(SyncManagerTest
, RefreshEncryptionReady
) {
1034 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1035 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1036 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1037 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1039 sync_manager_
.GetEncryptionHandler()->Init();
1042 const ModelTypeSet encrypted_types
= GetEncryptedTypes();
1043 EXPECT_TRUE(encrypted_types
.Has(PASSWORDS
));
1044 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1047 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1048 ReadNode
node(&trans
);
1049 EXPECT_EQ(BaseNode::INIT_OK
,
1050 node
.InitByIdLookup(GetIdForDataType(NIGORI
)));
1051 sync_pb::NigoriSpecifics nigori
= node
.GetNigoriSpecifics();
1052 EXPECT_TRUE(nigori
.has_encryption_keybag());
1053 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1054 EXPECT_TRUE(cryptographer
->is_ready());
1055 EXPECT_TRUE(cryptographer
->CanDecrypt(nigori
.encryption_keybag()));
1059 // Attempt to refresh encryption when nigori not downloaded.
1060 TEST_F(SyncManagerTest
, RefreshEncryptionNotReady
) {
1061 // Don't set up encryption (no nigori node created).
1063 // Should fail. Triggers an OnPassphraseRequired because the cryptographer
1065 EXPECT_CALL(encryption_observer_
, OnPassphraseRequired(_
, _
)).Times(1);
1066 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1067 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1068 sync_manager_
.GetEncryptionHandler()->Init();
1071 const ModelTypeSet encrypted_types
= GetEncryptedTypes();
1072 EXPECT_TRUE(encrypted_types
.Has(PASSWORDS
)); // Hardcoded.
1073 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1076 // Attempt to refresh encryption when nigori is empty.
1077 TEST_F(SyncManagerTest
, RefreshEncryptionEmptyNigori
) {
1078 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI
, DEFAULT_ENCRYPTION
));
1079 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete()).Times(1);
1080 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1081 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1083 // Should write to nigori.
1084 sync_manager_
.GetEncryptionHandler()->Init();
1087 const ModelTypeSet encrypted_types
= GetEncryptedTypes();
1088 EXPECT_TRUE(encrypted_types
.Has(PASSWORDS
)); // Hardcoded.
1089 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1092 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1093 ReadNode
node(&trans
);
1094 EXPECT_EQ(BaseNode::INIT_OK
,
1095 node
.InitByIdLookup(GetIdForDataType(NIGORI
)));
1096 sync_pb::NigoriSpecifics nigori
= node
.GetNigoriSpecifics();
1097 EXPECT_TRUE(nigori
.has_encryption_keybag());
1098 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1099 EXPECT_TRUE(cryptographer
->is_ready());
1100 EXPECT_TRUE(cryptographer
->CanDecrypt(nigori
.encryption_keybag()));
1104 TEST_F(SyncManagerTest
, EncryptDataTypesWithNoData
) {
1105 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1106 EXPECT_CALL(encryption_observer_
,
1107 OnEncryptedTypesChanged(
1108 HasModelTypes(EncryptableUserTypes()), true));
1109 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1110 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1111 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1114 TEST_F(SyncManagerTest
, EncryptDataTypesWithData
) {
1115 size_t batch_size
= 5;
1116 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1118 // Create some unencrypted unsynced data.
1119 int64 folder
= MakeFolderWithParent(sync_manager_
.GetUserShare(),
1121 GetIdForDataType(BOOKMARKS
),
1123 // First batch_size nodes are children of folder.
1125 for (i
= 0; i
< batch_size
; ++i
) {
1126 MakeBookmarkWithParent(sync_manager_
.GetUserShare(), folder
, NULL
);
1128 // Next batch_size nodes are a different type and on their own.
1129 for (; i
< 2*batch_size
; ++i
) {
1130 MakeNode(sync_manager_
.GetUserShare(), SESSIONS
,
1131 base::StringPrintf("%" PRIuS
"", i
));
1133 // Last batch_size nodes are a third type that will not need encryption.
1134 for (; i
< 3*batch_size
; ++i
) {
1135 MakeNode(sync_manager_
.GetUserShare(), THEMES
,
1136 base::StringPrintf("%" PRIuS
"", i
));
1140 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1141 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1142 SyncEncryptionHandler::SensitiveTypes()));
1143 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1144 trans
.GetWrappedTrans(),
1146 false /* not encrypted */));
1147 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1148 trans
.GetWrappedTrans(),
1150 false /* not encrypted */));
1151 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1152 trans
.GetWrappedTrans(),
1154 false /* not encrypted */));
1157 EXPECT_CALL(encryption_observer_
,
1158 OnEncryptedTypesChanged(
1159 HasModelTypes(EncryptableUserTypes()), true));
1160 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1161 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1162 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1164 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1165 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1166 EncryptableUserTypes()));
1167 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1168 trans
.GetWrappedTrans(),
1170 true /* is encrypted */));
1171 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1172 trans
.GetWrappedTrans(),
1174 true /* is encrypted */));
1175 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1176 trans
.GetWrappedTrans(),
1178 true /* is encrypted */));
1181 // Trigger's a ReEncryptEverything with new passphrase.
1182 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1183 EXPECT_CALL(encryption_observer_
,
1184 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1185 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1186 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1187 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1188 EXPECT_CALL(encryption_observer_
,
1189 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1190 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1191 "new_passphrase", true);
1192 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1194 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1195 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1196 EncryptableUserTypes()));
1197 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1198 trans
.GetWrappedTrans(),
1200 true /* is encrypted */));
1201 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1202 trans
.GetWrappedTrans(),
1204 true /* is encrypted */));
1205 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1206 trans
.GetWrappedTrans(),
1208 true /* is encrypted */));
1210 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1211 // a reencryption and should just notify immediately.
1212 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1213 EXPECT_CALL(encryption_observer_
,
1214 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
)).Times(0);
1215 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted()).Times(0);
1216 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete()).Times(0);
1217 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1220 // Test that when there are no pending keys and the cryptographer is not
1221 // initialized, we add a key based on the current GAIA password.
1222 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1223 TEST_F(SyncManagerTest
, SetInitialGaiaPass
) {
1224 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI
, UNINITIALIZED
));
1225 EXPECT_CALL(encryption_observer_
,
1226 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1227 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1228 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1229 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1230 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1233 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1234 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1235 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1237 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1238 ReadNode
node(&trans
);
1239 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1240 sync_pb::NigoriSpecifics nigori
= node
.GetNigoriSpecifics();
1241 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1242 EXPECT_TRUE(cryptographer
->is_ready());
1243 EXPECT_TRUE(cryptographer
->CanDecrypt(nigori
.encryption_keybag()));
1247 // Test that when there are no pending keys and we have on the old GAIA
1248 // password, we update and re-encrypt everything with the new GAIA password.
1249 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1250 TEST_F(SyncManagerTest
, UpdateGaiaPass
) {
1251 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1252 Cryptographer
verifier(&encryptor_
);
1254 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1255 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1256 std::string bootstrap_token
;
1257 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1258 verifier
.Bootstrap(bootstrap_token
);
1260 EXPECT_CALL(encryption_observer_
,
1261 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1262 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1263 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1264 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1265 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1268 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1269 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1270 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1272 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1273 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1274 EXPECT_TRUE(cryptographer
->is_ready());
1275 // Verify the default key has changed.
1276 sync_pb::EncryptedData encrypted
;
1277 cryptographer
->GetKeys(&encrypted
);
1278 EXPECT_FALSE(verifier
.CanDecrypt(encrypted
));
1282 // Sets a new explicit passphrase. This should update the bootstrap token
1283 // and re-encrypt everything.
1284 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1285 TEST_F(SyncManagerTest
, SetPassphraseWithPassword
) {
1286 Cryptographer
verifier(&encryptor_
);
1287 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1289 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1290 // Store the default (soon to be old) key.
1291 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1292 std::string bootstrap_token
;
1293 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1294 verifier
.Bootstrap(bootstrap_token
);
1296 ReadNode
root_node(&trans
);
1297 root_node
.InitByRootLookup();
1299 WriteNode
password_node(&trans
);
1300 WriteNode::InitUniqueByCreationResult result
=
1301 password_node
.InitUniqueByCreation(PASSWORDS
,
1303 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
1304 sync_pb::PasswordSpecificsData data
;
1305 data
.set_password_value("secret");
1306 password_node
.SetPasswordSpecifics(data
);
1308 EXPECT_CALL(encryption_observer_
,
1309 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1310 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1311 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1312 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1313 EXPECT_CALL(encryption_observer_
,
1314 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1315 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1318 EXPECT_EQ(CUSTOM_PASSPHRASE
,
1319 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1320 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1322 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1323 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1324 EXPECT_TRUE(cryptographer
->is_ready());
1325 // Verify the default key has changed.
1326 sync_pb::EncryptedData encrypted
;
1327 cryptographer
->GetKeys(&encrypted
);
1328 EXPECT_FALSE(verifier
.CanDecrypt(encrypted
));
1330 ReadNode
password_node(&trans
);
1331 EXPECT_EQ(BaseNode::INIT_OK
,
1332 password_node
.InitByClientTagLookup(PASSWORDS
,
1334 const sync_pb::PasswordSpecificsData
& data
=
1335 password_node
.GetPasswordSpecifics();
1336 EXPECT_EQ("secret", data
.password_value());
1340 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1341 // being encrypted with a new (unprovided) GAIA password, then supply the
1343 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1344 TEST_F(SyncManagerTest
, SupplyPendingGAIAPass
) {
1345 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1346 Cryptographer
other_cryptographer(&encryptor_
);
1348 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1349 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1350 std::string bootstrap_token
;
1351 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1352 other_cryptographer
.Bootstrap(bootstrap_token
);
1354 // Now update the nigori to reflect the new keys, and update the
1355 // cryptographer to have pending keys.
1356 KeyParams params
= {"localhost", "dummy", "passphrase2"};
1357 other_cryptographer
.AddKey(params
);
1358 WriteNode
node(&trans
);
1359 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1360 sync_pb::NigoriSpecifics nigori
;
1361 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1362 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1363 EXPECT_TRUE(cryptographer
->has_pending_keys());
1364 node
.SetNigoriSpecifics(nigori
);
1366 EXPECT_CALL(encryption_observer_
,
1367 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1368 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1369 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1370 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1371 sync_manager_
.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
1372 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1373 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1374 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1376 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1377 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1378 EXPECT_TRUE(cryptographer
->is_ready());
1379 // Verify we're encrypting with the new key.
1380 sync_pb::EncryptedData encrypted
;
1381 cryptographer
->GetKeys(&encrypted
);
1382 EXPECT_TRUE(other_cryptographer
.CanDecrypt(encrypted
));
1386 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1387 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1388 // the current GAIA password and verify the bootstrap token is updated. Then
1389 // supply the old GAIA password, and verify we re-encrypt all data with the
1390 // new GAIA password.
1391 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1392 TEST_F(SyncManagerTest
, SupplyPendingOldGAIAPass
) {
1393 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1394 Cryptographer
other_cryptographer(&encryptor_
);
1396 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1397 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1398 std::string bootstrap_token
;
1399 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1400 other_cryptographer
.Bootstrap(bootstrap_token
);
1402 // Now update the nigori to reflect the new keys, and update the
1403 // cryptographer to have pending keys.
1404 KeyParams params
= {"localhost", "dummy", "old_gaia"};
1405 other_cryptographer
.AddKey(params
);
1406 WriteNode
node(&trans
);
1407 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1408 sync_pb::NigoriSpecifics nigori
;
1409 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1410 node
.SetNigoriSpecifics(nigori
);
1411 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1413 // other_cryptographer now contains all encryption keys, and is encrypting
1414 // with the newest gaia.
1415 KeyParams new_params
= {"localhost", "dummy", "new_gaia"};
1416 other_cryptographer
.AddKey(new_params
);
1418 // The bootstrap token should have been updated. Save it to ensure it's based
1419 // on the new GAIA password.
1420 std::string bootstrap_token
;
1421 EXPECT_CALL(encryption_observer_
,
1422 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
))
1423 .WillOnce(SaveArg
<0>(&bootstrap_token
));
1424 EXPECT_CALL(encryption_observer_
, OnPassphraseRequired(_
,_
));
1425 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1426 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1429 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1430 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1431 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1432 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1434 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1435 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1436 EXPECT_TRUE(cryptographer
->is_initialized());
1437 EXPECT_FALSE(cryptographer
->is_ready());
1438 // Verify we're encrypting with the new key, even though we have pending
1440 sync_pb::EncryptedData encrypted
;
1441 other_cryptographer
.GetKeys(&encrypted
);
1442 EXPECT_TRUE(cryptographer
->CanDecrypt(encrypted
));
1444 EXPECT_CALL(encryption_observer_
,
1445 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1446 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1447 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1448 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1449 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1452 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1453 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1455 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1456 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1457 EXPECT_TRUE(cryptographer
->is_ready());
1459 // Verify we're encrypting with the new key.
1460 sync_pb::EncryptedData encrypted
;
1461 other_cryptographer
.GetKeys(&encrypted
);
1462 EXPECT_TRUE(cryptographer
->CanDecrypt(encrypted
));
1464 // Verify the saved bootstrap token is based on the new gaia password.
1465 Cryptographer
temp_cryptographer(&encryptor_
);
1466 temp_cryptographer
.Bootstrap(bootstrap_token
);
1467 EXPECT_TRUE(temp_cryptographer
.CanDecrypt(encrypted
));
1471 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1472 // being encrypted with an explicit (unprovided) passphrase, then supply the
1474 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1475 TEST_F(SyncManagerTest
, SupplyPendingExplicitPass
) {
1476 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1477 Cryptographer
other_cryptographer(&encryptor_
);
1479 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1480 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1481 std::string bootstrap_token
;
1482 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1483 other_cryptographer
.Bootstrap(bootstrap_token
);
1485 // Now update the nigori to reflect the new keys, and update the
1486 // cryptographer to have pending keys.
1487 KeyParams params
= {"localhost", "dummy", "explicit"};
1488 other_cryptographer
.AddKey(params
);
1489 WriteNode
node(&trans
);
1490 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1491 sync_pb::NigoriSpecifics nigori
;
1492 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1493 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1494 EXPECT_TRUE(cryptographer
->has_pending_keys());
1495 nigori
.set_keybag_is_frozen(true);
1496 node
.SetNigoriSpecifics(nigori
);
1498 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1499 EXPECT_CALL(encryption_observer_
,
1500 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1501 EXPECT_CALL(encryption_observer_
, OnPassphraseRequired(_
, _
));
1502 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1503 sync_manager_
.GetEncryptionHandler()->Init();
1504 EXPECT_CALL(encryption_observer_
,
1505 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1506 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1507 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1508 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1509 sync_manager_
.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
1510 EXPECT_EQ(CUSTOM_PASSPHRASE
,
1511 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1512 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1514 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1515 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1516 EXPECT_TRUE(cryptographer
->is_ready());
1517 // Verify we're encrypting with the new key.
1518 sync_pb::EncryptedData encrypted
;
1519 cryptographer
->GetKeys(&encrypted
);
1520 EXPECT_TRUE(other_cryptographer
.CanDecrypt(encrypted
));
1524 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1525 // being encrypted with a new (unprovided) GAIA password, then supply the
1526 // password as a user-provided password.
1527 // This is the android case 7/8.
1528 TEST_F(SyncManagerTest
, SupplyPendingGAIAPassUserProvided
) {
1529 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI
, UNINITIALIZED
));
1530 Cryptographer
other_cryptographer(&encryptor_
);
1532 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1533 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1534 // Now update the nigori to reflect the new keys, and update the
1535 // cryptographer to have pending keys.
1536 KeyParams params
= {"localhost", "dummy", "passphrase"};
1537 other_cryptographer
.AddKey(params
);
1538 WriteNode
node(&trans
);
1539 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1540 sync_pb::NigoriSpecifics nigori
;
1541 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1542 node
.SetNigoriSpecifics(nigori
);
1543 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1544 EXPECT_FALSE(cryptographer
->is_ready());
1546 EXPECT_CALL(encryption_observer_
,
1547 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1548 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1549 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1550 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1551 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1554 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1555 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1556 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1558 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1559 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1560 EXPECT_TRUE(cryptographer
->is_ready());
1564 TEST_F(SyncManagerTest
, SetPassphraseWithEmptyPasswordNode
) {
1565 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1567 std::string tag
= "foo";
1569 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1570 ReadNode
root_node(&trans
);
1571 root_node
.InitByRootLookup();
1573 WriteNode
password_node(&trans
);
1574 WriteNode::InitUniqueByCreationResult result
=
1575 password_node
.InitUniqueByCreation(PASSWORDS
, root_node
, tag
);
1576 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
1577 node_id
= password_node
.GetId();
1579 EXPECT_CALL(encryption_observer_
,
1580 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1581 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1582 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1583 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1584 EXPECT_CALL(encryption_observer_
,
1585 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1586 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1589 EXPECT_EQ(CUSTOM_PASSPHRASE
,
1590 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1591 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1593 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1594 ReadNode
password_node(&trans
);
1595 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY
,
1596 password_node
.InitByClientTagLookup(PASSWORDS
,
1600 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1601 ReadNode
password_node(&trans
);
1602 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY
,
1603 password_node
.InitByIdLookup(node_id
));
1607 // Friended by WriteNode, so can't be in an anonymouse namespace.
1608 TEST_F(SyncManagerTest
, EncryptBookmarksWithLegacyData
) {
1609 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1611 SyncAPINameToServerName("Google", &title
);
1612 std::string url
= "http://www.google.com";
1613 std::string raw_title2
= ".."; // An invalid cosmo title.
1615 SyncAPINameToServerName(raw_title2
, &title2
);
1616 std::string url2
= "http://www.bla.com";
1618 // Create a bookmark using the legacy format.
1619 int64 node_id1
= MakeNode(sync_manager_
.GetUserShare(),
1622 int64 node_id2
= MakeNode(sync_manager_
.GetUserShare(),
1626 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1627 WriteNode
node(&trans
);
1628 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(node_id1
));
1630 sync_pb::EntitySpecifics entity_specifics
;
1631 entity_specifics
.mutable_bookmark()->set_url(url
);
1632 node
.SetEntitySpecifics(entity_specifics
);
1634 // Set the old style title.
1635 syncable::MutableEntry
* node_entry
= node
.entry_
;
1636 node_entry
->PutNonUniqueName(title
);
1638 WriteNode
node2(&trans
);
1639 EXPECT_EQ(BaseNode::INIT_OK
, node2
.InitByIdLookup(node_id2
));
1641 sync_pb::EntitySpecifics entity_specifics2
;
1642 entity_specifics2
.mutable_bookmark()->set_url(url2
);
1643 node2
.SetEntitySpecifics(entity_specifics2
);
1645 // Set the old style title.
1646 syncable::MutableEntry
* node_entry2
= node2
.entry_
;
1647 node_entry2
->PutNonUniqueName(title2
);
1651 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1652 ReadNode
node(&trans
);
1653 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(node_id1
));
1654 EXPECT_EQ(BOOKMARKS
, node
.GetModelType());
1655 EXPECT_EQ(title
, node
.GetTitle());
1656 EXPECT_EQ(title
, node
.GetBookmarkSpecifics().title());
1657 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
1659 ReadNode
node2(&trans
);
1660 EXPECT_EQ(BaseNode::INIT_OK
, node2
.InitByIdLookup(node_id2
));
1661 EXPECT_EQ(BOOKMARKS
, node2
.GetModelType());
1662 // We should de-canonicalize the title in GetTitle(), but the title in the
1663 // specifics should be stored in the server legal form.
1664 EXPECT_EQ(raw_title2
, node2
.GetTitle());
1665 EXPECT_EQ(title2
, node2
.GetBookmarkSpecifics().title());
1666 EXPECT_EQ(url2
, node2
.GetBookmarkSpecifics().url());
1670 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1671 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1672 trans
.GetWrappedTrans(),
1674 false /* not encrypted */));
1677 EXPECT_CALL(encryption_observer_
,
1678 OnEncryptedTypesChanged(
1679 HasModelTypes(EncryptableUserTypes()), true));
1680 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1681 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1682 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1685 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1686 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1687 EncryptableUserTypes()));
1688 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1689 trans
.GetWrappedTrans(),
1691 true /* is encrypted */));
1693 ReadNode
node(&trans
);
1694 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(node_id1
));
1695 EXPECT_EQ(BOOKMARKS
, node
.GetModelType());
1696 EXPECT_EQ(title
, node
.GetTitle());
1697 EXPECT_EQ(title
, node
.GetBookmarkSpecifics().title());
1698 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
1700 ReadNode
node2(&trans
);
1701 EXPECT_EQ(BaseNode::INIT_OK
, node2
.InitByIdLookup(node_id2
));
1702 EXPECT_EQ(BOOKMARKS
, node2
.GetModelType());
1703 // We should de-canonicalize the title in GetTitle(), but the title in the
1704 // specifics should be stored in the server legal form.
1705 EXPECT_EQ(raw_title2
, node2
.GetTitle());
1706 EXPECT_EQ(title2
, node2
.GetBookmarkSpecifics().title());
1707 EXPECT_EQ(url2
, node2
.GetBookmarkSpecifics().url());
1711 // Create a bookmark and set the title/url, then verify the data was properly
1712 // set. This replicates the unique way bookmarks have of creating sync nodes.
1713 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1714 TEST_F(SyncManagerTest
, CreateLocalBookmark
) {
1715 std::string title
= "title";
1716 std::string url
= "url";
1718 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1719 ReadNode
bookmark_root(&trans
);
1720 ASSERT_EQ(BaseNode::INIT_OK
, bookmark_root
.InitTypeRoot(BOOKMARKS
));
1721 WriteNode
node(&trans
);
1722 ASSERT_TRUE(node
.InitBookmarkByCreation(bookmark_root
, NULL
));
1723 node
.SetIsFolder(false);
1724 node
.SetTitle(title
);
1726 sync_pb::BookmarkSpecifics
bookmark_specifics(node
.GetBookmarkSpecifics());
1727 bookmark_specifics
.set_url(url
);
1728 node
.SetBookmarkSpecifics(bookmark_specifics
);
1731 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1732 ReadNode
bookmark_root(&trans
);
1733 ASSERT_EQ(BaseNode::INIT_OK
, bookmark_root
.InitTypeRoot(BOOKMARKS
));
1734 int64 child_id
= bookmark_root
.GetFirstChildId();
1736 ReadNode
node(&trans
);
1737 ASSERT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(child_id
));
1738 EXPECT_FALSE(node
.GetIsFolder());
1739 EXPECT_EQ(title
, node
.GetTitle());
1740 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
1744 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1746 TEST_F(SyncManagerTest
, UpdateEntryWithEncryption
) {
1747 std::string client_tag
= "title";
1748 sync_pb::EntitySpecifics entity_specifics
;
1749 entity_specifics
.mutable_bookmark()->set_url("url");
1750 entity_specifics
.mutable_bookmark()->set_title("title");
1751 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
1752 syncable::GenerateSyncableHash(BOOKMARKS
,
1755 // New node shouldn't start off unsynced.
1756 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1757 // Manually change to the same data. Should not set is_unsynced.
1759 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1760 WriteNode
node(&trans
);
1761 EXPECT_EQ(BaseNode::INIT_OK
,
1762 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1763 node
.SetEntitySpecifics(entity_specifics
);
1765 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1767 // Encrypt the datatatype, should set is_unsynced.
1768 EXPECT_CALL(encryption_observer_
,
1769 OnEncryptedTypesChanged(
1770 HasModelTypes(EncryptableUserTypes()), true));
1771 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1772 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
1774 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1775 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
1776 sync_manager_
.GetEncryptionHandler()->Init();
1779 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1780 ReadNode
node(&trans
);
1781 EXPECT_EQ(BaseNode::INIT_OK
,
1782 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1783 const syncable::Entry
* node_entry
= node
.GetEntry();
1784 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1785 EXPECT_TRUE(specifics
.has_encrypted());
1786 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1787 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1788 EXPECT_TRUE(cryptographer
->is_ready());
1789 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1790 specifics
.encrypted()));
1792 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1794 // Set a new passphrase. Should set is_unsynced.
1795 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1796 EXPECT_CALL(encryption_observer_
,
1797 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1798 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1799 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1800 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1801 EXPECT_CALL(encryption_observer_
,
1802 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1803 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1807 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1808 ReadNode
node(&trans
);
1809 EXPECT_EQ(BaseNode::INIT_OK
,
1810 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1811 const syncable::Entry
* node_entry
= node
.GetEntry();
1812 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1813 EXPECT_TRUE(specifics
.has_encrypted());
1814 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1815 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1816 EXPECT_TRUE(cryptographer
->is_ready());
1817 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1818 specifics
.encrypted()));
1820 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1822 // Force a re-encrypt everything. Should not set is_unsynced.
1823 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1824 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1825 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1826 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
1828 sync_manager_
.GetEncryptionHandler()->Init();
1832 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1833 ReadNode
node(&trans
);
1834 EXPECT_EQ(BaseNode::INIT_OK
,
1835 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1836 const syncable::Entry
* node_entry
= node
.GetEntry();
1837 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1838 EXPECT_TRUE(specifics
.has_encrypted());
1839 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1840 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1841 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1842 specifics
.encrypted()));
1844 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1846 // Manually change to the same data. Should not set is_unsynced.
1848 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1849 WriteNode
node(&trans
);
1850 EXPECT_EQ(BaseNode::INIT_OK
,
1851 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1852 node
.SetEntitySpecifics(entity_specifics
);
1853 const syncable::Entry
* node_entry
= node
.GetEntry();
1854 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1855 EXPECT_TRUE(specifics
.has_encrypted());
1856 EXPECT_FALSE(node_entry
->GetIsUnsynced());
1857 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1858 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1859 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1860 specifics
.encrypted()));
1862 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1864 // Manually change to different data. Should set is_unsynced.
1866 entity_specifics
.mutable_bookmark()->set_url("url2");
1867 entity_specifics
.mutable_bookmark()->set_title("title2");
1868 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1869 WriteNode
node(&trans
);
1870 EXPECT_EQ(BaseNode::INIT_OK
,
1871 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1872 node
.SetEntitySpecifics(entity_specifics
);
1873 const syncable::Entry
* node_entry
= node
.GetEntry();
1874 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1875 EXPECT_TRUE(specifics
.has_encrypted());
1876 EXPECT_TRUE(node_entry
->GetIsUnsynced());
1877 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1878 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1879 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1880 specifics
.encrypted()));
1884 // Passwords have their own handling for encryption. Verify it does not result
1885 // in unnecessary writes via SetEntitySpecifics.
1886 TEST_F(SyncManagerTest
, UpdatePasswordSetEntitySpecificsNoChange
) {
1887 std::string client_tag
= "title";
1888 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1889 sync_pb::EntitySpecifics entity_specifics
;
1891 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1892 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1893 sync_pb::PasswordSpecificsData data
;
1894 data
.set_password_value("secret");
1895 cryptographer
->Encrypt(
1897 entity_specifics
.mutable_password()->
1898 mutable_encrypted());
1900 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
1901 syncable::GenerateSyncableHash(PASSWORDS
,
1904 // New node shouldn't start off unsynced.
1905 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1907 // Manually change to the same data via SetEntitySpecifics. Should not set
1910 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1911 WriteNode
node(&trans
);
1912 EXPECT_EQ(BaseNode::INIT_OK
,
1913 node
.InitByClientTagLookup(PASSWORDS
, client_tag
));
1914 node
.SetEntitySpecifics(entity_specifics
);
1916 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1919 // Passwords have their own handling for encryption. Verify it does not result
1920 // in unnecessary writes via SetPasswordSpecifics.
1921 TEST_F(SyncManagerTest
, UpdatePasswordSetPasswordSpecifics
) {
1922 std::string client_tag
= "title";
1923 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1924 sync_pb::EntitySpecifics entity_specifics
;
1926 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1927 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1928 sync_pb::PasswordSpecificsData data
;
1929 data
.set_password_value("secret");
1930 cryptographer
->Encrypt(
1932 entity_specifics
.mutable_password()->
1933 mutable_encrypted());
1935 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
1936 syncable::GenerateSyncableHash(PASSWORDS
,
1939 // New node shouldn't start off unsynced.
1940 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1942 // Manually change to the same data via SetPasswordSpecifics. Should not set
1945 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1946 WriteNode
node(&trans
);
1947 EXPECT_EQ(BaseNode::INIT_OK
,
1948 node
.InitByClientTagLookup(PASSWORDS
, client_tag
));
1949 node
.SetPasswordSpecifics(node
.GetPasswordSpecifics());
1951 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1953 // Manually change to different data. Should set is_unsynced.
1955 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1956 WriteNode
node(&trans
);
1957 EXPECT_EQ(BaseNode::INIT_OK
,
1958 node
.InitByClientTagLookup(PASSWORDS
, client_tag
));
1959 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1960 sync_pb::PasswordSpecificsData data
;
1961 data
.set_password_value("secret2");
1962 cryptographer
->Encrypt(
1964 entity_specifics
.mutable_password()->mutable_encrypted());
1965 node
.SetPasswordSpecifics(data
);
1966 const syncable::Entry
* node_entry
= node
.GetEntry();
1967 EXPECT_TRUE(node_entry
->GetIsUnsynced());
1971 // Passwords have their own handling for encryption. Verify setting a new
1972 // passphrase updates the data.
1973 TEST_F(SyncManagerTest
, UpdatePasswordNewPassphrase
) {
1974 std::string client_tag
= "title";
1975 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1976 sync_pb::EntitySpecifics entity_specifics
;
1978 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1979 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1980 sync_pb::PasswordSpecificsData data
;
1981 data
.set_password_value("secret");
1982 cryptographer
->Encrypt(
1984 entity_specifics
.mutable_password()->mutable_encrypted());
1986 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
1987 syncable::GenerateSyncableHash(PASSWORDS
,
1990 // New node shouldn't start off unsynced.
1991 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1993 // Set a new passphrase. Should set is_unsynced.
1994 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1995 EXPECT_CALL(encryption_observer_
,
1996 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1997 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1998 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1999 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2000 EXPECT_CALL(encryption_observer_
,
2001 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
2002 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
2005 EXPECT_EQ(CUSTOM_PASSPHRASE
,
2006 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
2007 EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2010 // Passwords have their own handling for encryption. Verify it does not result
2011 // in unnecessary writes via ReencryptEverything.
2012 TEST_F(SyncManagerTest
, UpdatePasswordReencryptEverything
) {
2013 std::string client_tag
= "title";
2014 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
2015 sync_pb::EntitySpecifics entity_specifics
;
2017 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2018 Cryptographer
* cryptographer
= trans
.GetCryptographer();
2019 sync_pb::PasswordSpecificsData data
;
2020 data
.set_password_value("secret");
2021 cryptographer
->Encrypt(
2023 entity_specifics
.mutable_password()->mutable_encrypted());
2025 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
2026 syncable::GenerateSyncableHash(PASSWORDS
,
2029 // New node shouldn't start off unsynced.
2030 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2032 // Force a re-encrypt everything. Should not set is_unsynced.
2033 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
2034 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2035 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2036 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
2037 sync_manager_
.GetEncryptionHandler()->Init();
2039 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2042 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2043 // when we write the same data, but does set it when we write new data.
2044 TEST_F(SyncManagerTest
, SetBookmarkTitle
) {
2045 std::string client_tag
= "title";
2046 sync_pb::EntitySpecifics entity_specifics
;
2047 entity_specifics
.mutable_bookmark()->set_url("url");
2048 entity_specifics
.mutable_bookmark()->set_title("title");
2049 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2050 syncable::GenerateSyncableHash(BOOKMARKS
,
2053 // New node shouldn't start off unsynced.
2054 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2056 // Manually change to the same title. Should not set is_unsynced.
2058 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2059 WriteNode
node(&trans
);
2060 EXPECT_EQ(BaseNode::INIT_OK
,
2061 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2062 node
.SetTitle(client_tag
);
2064 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2066 // Manually change to new title. Should set is_unsynced.
2068 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2069 WriteNode
node(&trans
);
2070 EXPECT_EQ(BaseNode::INIT_OK
,
2071 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2072 node
.SetTitle("title2");
2074 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2077 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2078 // bookmarks when we write the same data, but does set it when we write new
2080 TEST_F(SyncManagerTest
, SetBookmarkTitleWithEncryption
) {
2081 std::string client_tag
= "title";
2082 sync_pb::EntitySpecifics entity_specifics
;
2083 entity_specifics
.mutable_bookmark()->set_url("url");
2084 entity_specifics
.mutable_bookmark()->set_title("title");
2085 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2086 syncable::GenerateSyncableHash(BOOKMARKS
,
2089 // New node shouldn't start off unsynced.
2090 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2092 // Encrypt the datatatype, should set is_unsynced.
2093 EXPECT_CALL(encryption_observer_
,
2094 OnEncryptedTypesChanged(
2095 HasModelTypes(EncryptableUserTypes()), true));
2096 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2097 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
2098 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2099 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
2100 sync_manager_
.GetEncryptionHandler()->Init();
2102 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2104 // Manually change to the same title. Should not set is_unsynced.
2105 // NON_UNIQUE_NAME should be kEncryptedString.
2107 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2108 WriteNode
node(&trans
);
2109 EXPECT_EQ(BaseNode::INIT_OK
,
2110 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2111 node
.SetTitle(client_tag
);
2112 const syncable::Entry
* node_entry
= node
.GetEntry();
2113 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2114 EXPECT_TRUE(specifics
.has_encrypted());
2115 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2117 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2119 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2120 // should still be kEncryptedString.
2122 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2123 WriteNode
node(&trans
);
2124 EXPECT_EQ(BaseNode::INIT_OK
,
2125 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2126 node
.SetTitle("title2");
2127 const syncable::Entry
* node_entry
= node
.GetEntry();
2128 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2129 EXPECT_TRUE(specifics
.has_encrypted());
2130 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2132 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2135 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2136 // when we write the same data, but does set it when we write new data.
2137 TEST_F(SyncManagerTest
, SetNonBookmarkTitle
) {
2138 std::string client_tag
= "title";
2139 sync_pb::EntitySpecifics entity_specifics
;
2140 entity_specifics
.mutable_preference()->set_name("name");
2141 entity_specifics
.mutable_preference()->set_value("value");
2142 MakeServerNode(sync_manager_
.GetUserShare(),
2145 syncable::GenerateSyncableHash(PREFERENCES
,
2148 // New node shouldn't start off unsynced.
2149 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2151 // Manually change to the same title. Should not set is_unsynced.
2153 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2154 WriteNode
node(&trans
);
2155 EXPECT_EQ(BaseNode::INIT_OK
,
2156 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2157 node
.SetTitle(client_tag
);
2159 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2161 // Manually change to new title. Should set is_unsynced.
2163 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2164 WriteNode
node(&trans
);
2165 EXPECT_EQ(BaseNode::INIT_OK
,
2166 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2167 node
.SetTitle("title2");
2169 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2172 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2173 // non-bookmarks when we write the same data or when we write new data
2174 // data (should remained kEncryptedString).
2175 TEST_F(SyncManagerTest
, SetNonBookmarkTitleWithEncryption
) {
2176 std::string client_tag
= "title";
2177 sync_pb::EntitySpecifics entity_specifics
;
2178 entity_specifics
.mutable_preference()->set_name("name");
2179 entity_specifics
.mutable_preference()->set_value("value");
2180 MakeServerNode(sync_manager_
.GetUserShare(),
2183 syncable::GenerateSyncableHash(PREFERENCES
,
2186 // New node shouldn't start off unsynced.
2187 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2189 // Encrypt the datatatype, should set is_unsynced.
2190 EXPECT_CALL(encryption_observer_
,
2191 OnEncryptedTypesChanged(
2192 HasModelTypes(EncryptableUserTypes()), true));
2193 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2194 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
2195 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2196 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
2197 sync_manager_
.GetEncryptionHandler()->Init();
2199 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2201 // Manually change to the same title. Should not set is_unsynced.
2202 // NON_UNIQUE_NAME should be kEncryptedString.
2204 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2205 WriteNode
node(&trans
);
2206 EXPECT_EQ(BaseNode::INIT_OK
,
2207 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2208 node
.SetTitle(client_tag
);
2209 const syncable::Entry
* node_entry
= node
.GetEntry();
2210 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2211 EXPECT_TRUE(specifics
.has_encrypted());
2212 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2214 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2216 // Manually change to new title. Should not set is_unsynced because the
2217 // NON_UNIQUE_NAME should still be kEncryptedString.
2219 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2220 WriteNode
node(&trans
);
2221 EXPECT_EQ(BaseNode::INIT_OK
,
2222 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2223 node
.SetTitle("title2");
2224 const syncable::Entry
* node_entry
= node
.GetEntry();
2225 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2226 EXPECT_TRUE(specifics
.has_encrypted());
2227 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2228 EXPECT_FALSE(node_entry
->GetIsUnsynced());
2232 // Ensure that titles are truncated to 255 bytes, and attempting to reset
2233 // them to their longer version does not set IS_UNSYNCED.
2234 TEST_F(SyncManagerTest
, SetLongTitle
) {
2235 const int kNumChars
= 512;
2236 const std::string kClientTag
= "tag";
2237 std::string
title(kNumChars
, '0');
2238 sync_pb::EntitySpecifics entity_specifics
;
2239 entity_specifics
.mutable_preference()->set_name("name");
2240 entity_specifics
.mutable_preference()->set_value("value");
2241 MakeServerNode(sync_manager_
.GetUserShare(),
2244 syncable::GenerateSyncableHash(PREFERENCES
,
2247 // New node shouldn't start off unsynced.
2248 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2250 // Manually change to the long title. Should set is_unsynced.
2252 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2253 WriteNode
node(&trans
);
2254 EXPECT_EQ(BaseNode::INIT_OK
,
2255 node
.InitByClientTagLookup(PREFERENCES
, kClientTag
));
2256 node
.SetTitle(title
);
2257 EXPECT_EQ(node
.GetTitle(), title
.substr(0, 255));
2259 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2261 // Manually change to the same title. Should not set is_unsynced.
2263 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2264 WriteNode
node(&trans
);
2265 EXPECT_EQ(BaseNode::INIT_OK
,
2266 node
.InitByClientTagLookup(PREFERENCES
, kClientTag
));
2267 node
.SetTitle(title
);
2268 EXPECT_EQ(node
.GetTitle(), title
.substr(0, 255));
2270 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2272 // Manually change to new title. Should set is_unsynced.
2274 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2275 WriteNode
node(&trans
);
2276 EXPECT_EQ(BaseNode::INIT_OK
,
2277 node
.InitByClientTagLookup(PREFERENCES
, kClientTag
));
2278 node
.SetTitle("title2");
2280 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2283 // Create an encrypted entry when the cryptographer doesn't think the type is
2284 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2286 TEST_F(SyncManagerTest
, SetPreviouslyEncryptedSpecifics
) {
2287 std::string client_tag
= "tag";
2288 std::string url
= "url";
2289 std::string url2
= "new_url";
2290 std::string title
= "title";
2291 sync_pb::EntitySpecifics entity_specifics
;
2292 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
2294 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2295 Cryptographer
* crypto
= trans
.GetCryptographer();
2296 sync_pb::EntitySpecifics bm_specifics
;
2297 bm_specifics
.mutable_bookmark()->set_title("title");
2298 bm_specifics
.mutable_bookmark()->set_url("url");
2299 sync_pb::EncryptedData encrypted
;
2300 crypto
->Encrypt(bm_specifics
, &encrypted
);
2301 entity_specifics
.mutable_encrypted()->CopyFrom(encrypted
);
2302 AddDefaultFieldValue(BOOKMARKS
, &entity_specifics
);
2304 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2305 syncable::GenerateSyncableHash(BOOKMARKS
,
2311 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2312 ReadNode
node(&trans
);
2313 EXPECT_EQ(BaseNode::INIT_OK
,
2314 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2315 EXPECT_EQ(title
, node
.GetTitle());
2316 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
2320 // Overwrite the url (which overwrites the specifics).
2321 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2322 WriteNode
node(&trans
);
2323 EXPECT_EQ(BaseNode::INIT_OK
,
2324 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2326 sync_pb::BookmarkSpecifics
bookmark_specifics(node
.GetBookmarkSpecifics());
2327 bookmark_specifics
.set_url(url2
);
2328 node
.SetBookmarkSpecifics(bookmark_specifics
);
2332 // Verify it's still encrypted and it has the most recent url.
2333 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2334 ReadNode
node(&trans
);
2335 EXPECT_EQ(BaseNode::INIT_OK
,
2336 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2337 EXPECT_EQ(title
, node
.GetTitle());
2338 EXPECT_EQ(url2
, node
.GetBookmarkSpecifics().url());
2339 const syncable::Entry
* node_entry
= node
.GetEntry();
2340 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2341 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2342 EXPECT_TRUE(specifics
.has_encrypted());
2346 // Verify transaction version of a model type is incremented when node of
2347 // that type is updated.
2348 TEST_F(SyncManagerTest
, IncrementTransactionVersion
) {
2349 ModelSafeRoutingInfo routing_info
;
2350 GetModelSafeRoutingInfo(&routing_info
);
2353 ReadTransaction
read_trans(FROM_HERE
, sync_manager_
.GetUserShare());
2354 for (ModelSafeRoutingInfo::iterator i
= routing_info
.begin();
2355 i
!= routing_info
.end(); ++i
) {
2356 // Transaction version is incremented when SyncManagerTest::SetUp()
2357 // creates a node of each type.
2359 sync_manager_
.GetUserShare()->directory
->
2360 GetTransactionVersion(i
->first
));
2364 // Create bookmark node to increment transaction version of bookmark model.
2365 std::string client_tag
= "title";
2366 sync_pb::EntitySpecifics entity_specifics
;
2367 entity_specifics
.mutable_bookmark()->set_url("url");
2368 entity_specifics
.mutable_bookmark()->set_title("title");
2369 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2370 syncable::GenerateSyncableHash(BOOKMARKS
,
2375 ReadTransaction
read_trans(FROM_HERE
, sync_manager_
.GetUserShare());
2376 for (ModelSafeRoutingInfo::iterator i
= routing_info
.begin();
2377 i
!= routing_info
.end(); ++i
) {
2378 EXPECT_EQ(i
->first
== BOOKMARKS
? 2 : 1,
2379 sync_manager_
.GetUserShare()->directory
->
2380 GetTransactionVersion(i
->first
));
2385 class MockSyncScheduler
: public FakeSyncScheduler
{
2387 MockSyncScheduler() : FakeSyncScheduler() {}
2388 virtual ~MockSyncScheduler() {}
2390 MOCK_METHOD1(Start
, void(SyncScheduler::Mode
));
2391 MOCK_METHOD1(ScheduleConfiguration
, void(const ConfigurationParams
&));
2394 class ComponentsFactory
: public TestInternalComponentsFactory
{
2396 ComponentsFactory(const Switches
& switches
,
2397 SyncScheduler
* scheduler_to_use
,
2398 sessions::SyncSessionContext
** session_context
,
2399 InternalComponentsFactory::StorageOption
* storage_used
)
2400 : TestInternalComponentsFactory(
2401 switches
, InternalComponentsFactory::STORAGE_IN_MEMORY
, storage_used
),
2402 scheduler_to_use_(scheduler_to_use
),
2403 session_context_(session_context
) {}
2404 ~ComponentsFactory() override
{}
2406 scoped_ptr
<SyncScheduler
> BuildScheduler(
2407 const std::string
& name
,
2408 sessions::SyncSessionContext
* context
,
2409 CancelationSignal
* stop_handle
) override
{
2410 *session_context_
= context
;
2411 return scheduler_to_use_
.Pass();
2415 scoped_ptr
<SyncScheduler
> scheduler_to_use_
;
2416 sessions::SyncSessionContext
** session_context_
;
2419 class SyncManagerTestWithMockScheduler
: public SyncManagerTest
{
2421 SyncManagerTestWithMockScheduler() : scheduler_(NULL
) {}
2422 InternalComponentsFactory
* GetFactory() override
{
2423 scheduler_
= new MockSyncScheduler();
2424 return new ComponentsFactory(GetSwitches(), scheduler_
, &session_context_
,
2428 MockSyncScheduler
* scheduler() { return scheduler_
; }
2429 sessions::SyncSessionContext
* session_context() {
2430 return session_context_
;
2434 MockSyncScheduler
* scheduler_
;
2435 sessions::SyncSessionContext
* session_context_
;
2438 // Test that the configuration params are properly created and sent to
2439 // ScheduleConfigure. No callback should be invoked. Any disabled datatypes
2440 // should be purged.
2441 TEST_F(SyncManagerTestWithMockScheduler
, BasicConfiguration
) {
2442 ConfigureReason reason
= CONFIGURE_REASON_RECONFIGURATION
;
2443 ModelTypeSet
types_to_download(BOOKMARKS
, PREFERENCES
);
2444 ModelSafeRoutingInfo new_routing_info
;
2445 GetModelSafeRoutingInfo(&new_routing_info
);
2446 ModelTypeSet enabled_types
= GetRoutingInfoTypes(new_routing_info
);
2447 ModelTypeSet disabled_types
= Difference(ModelTypeSet::All(), enabled_types
);
2449 ConfigurationParams params
;
2450 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE
));
2451 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_
)).
2452 WillOnce(SaveArg
<0>(¶ms
));
2454 // Set data for all types.
2455 ModelTypeSet protocol_types
= ProtocolTypes();
2456 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2458 SetProgressMarkerForType(iter
.Get(), true);
2461 CallbackCounter ready_task_counter
, retry_task_counter
;
2462 sync_manager_
.ConfigureSyncer(
2469 base::Bind(&CallbackCounter::Callback
,
2470 base::Unretained(&ready_task_counter
)),
2471 base::Bind(&CallbackCounter::Callback
,
2472 base::Unretained(&retry_task_counter
)));
2473 EXPECT_EQ(0, ready_task_counter
.times_called());
2474 EXPECT_EQ(0, retry_task_counter
.times_called());
2475 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION
,
2477 EXPECT_TRUE(types_to_download
.Equals(params
.types_to_download
));
2478 EXPECT_EQ(new_routing_info
, params
.routing_info
);
2480 // Verify all the disabled types were purged.
2481 EXPECT_TRUE(sync_manager_
.InitialSyncEndedTypes().Equals(
2483 EXPECT_TRUE(sync_manager_
.GetTypesWithEmptyProgressMarkerToken(
2484 ModelTypeSet::All()).Equals(disabled_types
));
2487 // Test that on a reconfiguration (configuration where the session context
2488 // already has routing info), only those recently disabled types are purged.
2489 TEST_F(SyncManagerTestWithMockScheduler
, ReConfiguration
) {
2490 ConfigureReason reason
= CONFIGURE_REASON_RECONFIGURATION
;
2491 ModelTypeSet
types_to_download(BOOKMARKS
, PREFERENCES
);
2492 ModelTypeSet disabled_types
= ModelTypeSet(THEMES
, SESSIONS
);
2493 ModelSafeRoutingInfo old_routing_info
;
2494 ModelSafeRoutingInfo new_routing_info
;
2495 GetModelSafeRoutingInfo(&old_routing_info
);
2496 new_routing_info
= old_routing_info
;
2497 new_routing_info
.erase(THEMES
);
2498 new_routing_info
.erase(SESSIONS
);
2499 ModelTypeSet enabled_types
= GetRoutingInfoTypes(new_routing_info
);
2501 ConfigurationParams params
;
2502 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE
));
2503 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_
)).
2504 WillOnce(SaveArg
<0>(¶ms
));
2506 // Set data for all types except those recently disabled (so we can verify
2507 // only those recently disabled are purged) .
2508 ModelTypeSet protocol_types
= ProtocolTypes();
2509 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2511 if (!disabled_types
.Has(iter
.Get())) {
2512 SetProgressMarkerForType(iter
.Get(), true);
2514 SetProgressMarkerForType(iter
.Get(), false);
2518 // Set the context to have the old routing info.
2519 session_context()->SetRoutingInfo(old_routing_info
);
2521 CallbackCounter ready_task_counter
, retry_task_counter
;
2522 sync_manager_
.ConfigureSyncer(
2529 base::Bind(&CallbackCounter::Callback
,
2530 base::Unretained(&ready_task_counter
)),
2531 base::Bind(&CallbackCounter::Callback
,
2532 base::Unretained(&retry_task_counter
)));
2533 EXPECT_EQ(0, ready_task_counter
.times_called());
2534 EXPECT_EQ(0, retry_task_counter
.times_called());
2535 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION
,
2537 EXPECT_TRUE(types_to_download
.Equals(params
.types_to_download
));
2538 EXPECT_EQ(new_routing_info
, params
.routing_info
);
2540 // Verify only the recently disabled types were purged.
2541 EXPECT_TRUE(sync_manager_
.GetTypesWithEmptyProgressMarkerToken(
2542 ProtocolTypes()).Equals(disabled_types
));
2545 // Test that PurgePartiallySyncedTypes purges only those types that have not
2546 // fully completed their initial download and apply.
2547 TEST_F(SyncManagerTest
, PurgePartiallySyncedTypes
) {
2548 ModelSafeRoutingInfo routing_info
;
2549 GetModelSafeRoutingInfo(&routing_info
);
2550 ModelTypeSet enabled_types
= GetRoutingInfoTypes(routing_info
);
2552 UserShare
* share
= sync_manager_
.GetUserShare();
2554 // The test harness automatically initializes all types in the routing info.
2555 // Check that autofill is not among them.
2556 ASSERT_FALSE(enabled_types
.Has(AUTOFILL
));
2558 // Further ensure that the test harness did not create its root node.
2560 syncable::ReadTransaction
trans(FROM_HERE
, share
->directory
.get());
2561 syncable::Entry
autofill_root_node(&trans
,
2562 syncable::GET_TYPE_ROOT
,
2564 ASSERT_FALSE(autofill_root_node
.good());
2567 // One more redundant check.
2568 ASSERT_FALSE(sync_manager_
.InitialSyncEndedTypes().Has(AUTOFILL
));
2570 // Give autofill a progress marker.
2571 sync_pb::DataTypeProgressMarker autofill_marker
;
2572 autofill_marker
.set_data_type_id(
2573 GetSpecificsFieldNumberFromModelType(AUTOFILL
));
2574 autofill_marker
.set_token("token");
2575 share
->directory
->SetDownloadProgress(AUTOFILL
, autofill_marker
);
2577 // Also add a pending autofill root node update from the server.
2578 TestEntryFactory
factory_(share
->directory
.get());
2579 int autofill_meta
= factory_
.CreateUnappliedRootNode(AUTOFILL
);
2581 // Preferences is an enabled type. Check that the harness initialized it.
2582 ASSERT_TRUE(enabled_types
.Has(PREFERENCES
));
2583 ASSERT_TRUE(sync_manager_
.InitialSyncEndedTypes().Has(PREFERENCES
));
2585 // Give preferencse a progress marker.
2586 sync_pb::DataTypeProgressMarker prefs_marker
;
2587 prefs_marker
.set_data_type_id(
2588 GetSpecificsFieldNumberFromModelType(PREFERENCES
));
2589 prefs_marker
.set_token("token");
2590 share
->directory
->SetDownloadProgress(PREFERENCES
, prefs_marker
);
2592 // Add a fully synced preferences node under the root.
2593 std::string pref_client_tag
= "prefABC";
2594 std::string pref_hashed_tag
= "hashXYZ";
2595 sync_pb::EntitySpecifics pref_specifics
;
2596 AddDefaultFieldValue(PREFERENCES
, &pref_specifics
);
2597 int pref_meta
= MakeServerNode(
2598 share
, PREFERENCES
, pref_client_tag
, pref_hashed_tag
, pref_specifics
);
2600 // And now, the purge.
2601 EXPECT_TRUE(sync_manager_
.PurgePartiallySyncedTypes());
2603 // Ensure that autofill lost its progress marker, but preferences did not.
2604 ModelTypeSet empty_tokens
=
2605 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
2606 EXPECT_TRUE(empty_tokens
.Has(AUTOFILL
));
2607 EXPECT_FALSE(empty_tokens
.Has(PREFERENCES
));
2609 // Ensure that autofill lots its node, but preferences did not.
2611 syncable::ReadTransaction
trans(FROM_HERE
, share
->directory
.get());
2612 syncable::Entry
autofill_node(&trans
, GET_BY_HANDLE
, autofill_meta
);
2613 syncable::Entry
pref_node(&trans
, GET_BY_HANDLE
, pref_meta
);
2614 EXPECT_FALSE(autofill_node
.good());
2615 EXPECT_TRUE(pref_node
.good());
2619 // Test CleanupDisabledTypes properly purges all disabled types as specified
2620 // by the previous and current enabled params.
2621 TEST_F(SyncManagerTest
, PurgeDisabledTypes
) {
2622 ModelSafeRoutingInfo routing_info
;
2623 GetModelSafeRoutingInfo(&routing_info
);
2624 ModelTypeSet enabled_types
= GetRoutingInfoTypes(routing_info
);
2625 ModelTypeSet disabled_types
= Difference(ModelTypeSet::All(), enabled_types
);
2627 // The harness should have initialized the enabled_types for us.
2628 EXPECT_TRUE(enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2630 // Set progress markers for all types.
2631 ModelTypeSet protocol_types
= ProtocolTypes();
2632 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2634 SetProgressMarkerForType(iter
.Get(), true);
2637 // Verify all the enabled types remain after cleanup, and all the disabled
2638 // types were purged.
2639 sync_manager_
.PurgeDisabledTypes(disabled_types
,
2642 EXPECT_TRUE(enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2643 EXPECT_TRUE(disabled_types
.Equals(
2644 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2646 // Disable some more types.
2647 disabled_types
.Put(BOOKMARKS
);
2648 disabled_types
.Put(PREFERENCES
);
2649 ModelTypeSet new_enabled_types
=
2650 Difference(ModelTypeSet::All(), disabled_types
);
2652 // Verify only the non-disabled types remain after cleanup.
2653 sync_manager_
.PurgeDisabledTypes(disabled_types
,
2656 EXPECT_TRUE(new_enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2657 EXPECT_TRUE(disabled_types
.Equals(
2658 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2661 // Test PurgeDisabledTypes properly unapplies types by deleting their local data
2662 // and preserving their server data and progress marker.
2663 TEST_F(SyncManagerTest
, PurgeUnappliedTypes
) {
2664 ModelSafeRoutingInfo routing_info
;
2665 GetModelSafeRoutingInfo(&routing_info
);
2666 ModelTypeSet unapplied_types
= ModelTypeSet(BOOKMARKS
, PREFERENCES
);
2667 ModelTypeSet enabled_types
= GetRoutingInfoTypes(routing_info
);
2668 ModelTypeSet disabled_types
= Difference(ModelTypeSet::All(), enabled_types
);
2670 // The harness should have initialized the enabled_types for us.
2671 EXPECT_TRUE(enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2673 // Set progress markers for all types.
2674 ModelTypeSet protocol_types
= ProtocolTypes();
2675 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2677 SetProgressMarkerForType(iter
.Get(), true);
2680 // Add the following kinds of items:
2681 // 1. Fully synced preference.
2682 // 2. Locally created preference, server unknown, unsynced
2683 // 3. Locally deleted preference, server known, unsynced
2684 // 4. Server deleted preference, locally known.
2685 // 5. Server created preference, locally unknown, unapplied.
2686 // 6. A fully synced bookmark (no unique_client_tag).
2687 UserShare
* share
= sync_manager_
.GetUserShare();
2688 sync_pb::EntitySpecifics pref_specifics
;
2689 AddDefaultFieldValue(PREFERENCES
, &pref_specifics
);
2690 sync_pb::EntitySpecifics bm_specifics
;
2691 AddDefaultFieldValue(BOOKMARKS
, &bm_specifics
);
2692 int pref1_meta
= MakeServerNode(
2693 share
, PREFERENCES
, "pref1", "hash1", pref_specifics
);
2694 int64 pref2_meta
= MakeNode(share
, PREFERENCES
, "pref2");
2695 int pref3_meta
= MakeServerNode(
2696 share
, PREFERENCES
, "pref3", "hash3", pref_specifics
);
2697 int pref4_meta
= MakeServerNode(
2698 share
, PREFERENCES
, "pref4", "hash4", pref_specifics
);
2699 int pref5_meta
= MakeServerNode(
2700 share
, PREFERENCES
, "pref5", "hash5", pref_specifics
);
2701 int bookmark_meta
= MakeServerNode(
2702 share
, BOOKMARKS
, "bookmark", "", bm_specifics
);
2705 syncable::WriteTransaction
trans(FROM_HERE
,
2707 share
->directory
.get());
2708 // Pref's 1 and 2 are already set up properly.
2709 // Locally delete pref 3.
2710 syncable::MutableEntry
pref3(&trans
, GET_BY_HANDLE
, pref3_meta
);
2711 pref3
.PutIsDel(true);
2712 pref3
.PutIsUnsynced(true);
2713 // Delete pref 4 at the server.
2714 syncable::MutableEntry
pref4(&trans
, GET_BY_HANDLE
, pref4_meta
);
2715 pref4
.PutServerIsDel(true);
2716 pref4
.PutIsUnappliedUpdate(true);
2717 pref4
.PutServerVersion(2);
2718 // Pref 5 is an new unapplied update.
2719 syncable::MutableEntry
pref5(&trans
, GET_BY_HANDLE
, pref5_meta
);
2720 pref5
.PutIsUnappliedUpdate(true);
2721 pref5
.PutIsDel(true);
2722 pref5
.PutBaseVersion(-1);
2723 // Bookmark is already set up properly
2726 // Take a snapshot to clear all the dirty bits.
2727 share
->directory
.get()->SaveChanges();
2729 // Now request a purge for the unapplied types.
2730 disabled_types
.PutAll(unapplied_types
);
2731 sync_manager_
.PurgeDisabledTypes(disabled_types
,
2735 // Verify the unapplied types still have progress markers and initial sync
2736 // ended after cleanup.
2737 EXPECT_TRUE(sync_manager_
.InitialSyncEndedTypes().HasAll(unapplied_types
));
2739 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(unapplied_types
).
2742 // Ensure the items were unapplied as necessary.
2744 syncable::ReadTransaction
trans(FROM_HERE
, share
->directory
.get());
2745 syncable::Entry
pref_node(&trans
, GET_BY_HANDLE
, pref1_meta
);
2746 ASSERT_TRUE(pref_node
.good());
2747 EXPECT_TRUE(pref_node
.GetKernelCopy().is_dirty());
2748 EXPECT_FALSE(pref_node
.GetIsUnsynced());
2749 EXPECT_TRUE(pref_node
.GetIsUnappliedUpdate());
2750 EXPECT_TRUE(pref_node
.GetIsDel());
2751 EXPECT_GT(pref_node
.GetServerVersion(), 0);
2752 EXPECT_EQ(pref_node
.GetBaseVersion(), -1);
2754 // Pref 2 should just be locally deleted.
2755 syncable::Entry
pref2_node(&trans
, GET_BY_HANDLE
, pref2_meta
);
2756 ASSERT_TRUE(pref2_node
.good());
2757 EXPECT_TRUE(pref2_node
.GetKernelCopy().is_dirty());
2758 EXPECT_FALSE(pref2_node
.GetIsUnsynced());
2759 EXPECT_TRUE(pref2_node
.GetIsDel());
2760 EXPECT_FALSE(pref2_node
.GetIsUnappliedUpdate());
2761 EXPECT_TRUE(pref2_node
.GetIsDel());
2762 EXPECT_EQ(pref2_node
.GetServerVersion(), 0);
2763 EXPECT_EQ(pref2_node
.GetBaseVersion(), -1);
2765 syncable::Entry
pref3_node(&trans
, GET_BY_HANDLE
, pref3_meta
);
2766 ASSERT_TRUE(pref3_node
.good());
2767 EXPECT_TRUE(pref3_node
.GetKernelCopy().is_dirty());
2768 EXPECT_FALSE(pref3_node
.GetIsUnsynced());
2769 EXPECT_TRUE(pref3_node
.GetIsUnappliedUpdate());
2770 EXPECT_TRUE(pref3_node
.GetIsDel());
2771 EXPECT_GT(pref3_node
.GetServerVersion(), 0);
2772 EXPECT_EQ(pref3_node
.GetBaseVersion(), -1);
2774 syncable::Entry
pref4_node(&trans
, GET_BY_HANDLE
, pref4_meta
);
2775 ASSERT_TRUE(pref4_node
.good());
2776 EXPECT_TRUE(pref4_node
.GetKernelCopy().is_dirty());
2777 EXPECT_FALSE(pref4_node
.GetIsUnsynced());
2778 EXPECT_TRUE(pref4_node
.GetIsUnappliedUpdate());
2779 EXPECT_TRUE(pref4_node
.GetIsDel());
2780 EXPECT_GT(pref4_node
.GetServerVersion(), 0);
2781 EXPECT_EQ(pref4_node
.GetBaseVersion(), -1);
2783 // Pref 5 should remain untouched.
2784 syncable::Entry
pref5_node(&trans
, GET_BY_HANDLE
, pref5_meta
);
2785 ASSERT_TRUE(pref5_node
.good());
2786 EXPECT_FALSE(pref5_node
.GetKernelCopy().is_dirty());
2787 EXPECT_FALSE(pref5_node
.GetIsUnsynced());
2788 EXPECT_TRUE(pref5_node
.GetIsUnappliedUpdate());
2789 EXPECT_TRUE(pref5_node
.GetIsDel());
2790 EXPECT_GT(pref5_node
.GetServerVersion(), 0);
2791 EXPECT_EQ(pref5_node
.GetBaseVersion(), -1);
2793 syncable::Entry
bookmark_node(&trans
, GET_BY_HANDLE
, bookmark_meta
);
2794 ASSERT_TRUE(bookmark_node
.good());
2795 EXPECT_TRUE(bookmark_node
.GetKernelCopy().is_dirty());
2796 EXPECT_FALSE(bookmark_node
.GetIsUnsynced());
2797 EXPECT_TRUE(bookmark_node
.GetIsUnappliedUpdate());
2798 EXPECT_TRUE(bookmark_node
.GetIsDel());
2799 EXPECT_GT(bookmark_node
.GetServerVersion(), 0);
2800 EXPECT_EQ(bookmark_node
.GetBaseVersion(), -1);
2804 // A test harness to exercise the code that processes and passes changes from
2805 // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
2807 class SyncManagerChangeProcessingTest
: public SyncManagerTest
{
2809 void OnChangesApplied(ModelType model_type
,
2810 int64 model_version
,
2811 const BaseTransaction
* trans
,
2812 const ImmutableChangeRecordList
& changes
) override
{
2813 last_changes_
= changes
;
2816 void OnChangesComplete(ModelType model_type
) override
{}
2818 const ImmutableChangeRecordList
& GetRecentChangeList() {
2819 return last_changes_
;
2822 UserShare
* share() {
2823 return sync_manager_
.GetUserShare();
2826 // Set some flags so our nodes reasonably approximate the real world scenario
2827 // and can get past CheckTreeInvariants.
2829 // It's never going to be truly accurate, since we're squashing update
2830 // receipt, processing and application into a single transaction.
2831 void SetNodeProperties(syncable::MutableEntry
*entry
) {
2832 entry
->PutId(id_factory_
.NewServerId());
2833 entry
->PutBaseVersion(10);
2834 entry
->PutServerVersion(10);
2837 // Looks for the given change in the list. Returns the index at which it was
2838 // found. Returns -1 on lookup failure.
2839 size_t FindChangeInList(int64 id
, ChangeRecord::Action action
) {
2841 for (size_t i
= 0; i
< last_changes_
.Get().size(); ++i
) {
2842 if (last_changes_
.Get()[i
].id
== id
2843 && last_changes_
.Get()[i
].action
== action
) {
2847 ADD_FAILURE() << "Failed to find specified change";
2848 return static_cast<size_t>(-1);
2851 // Returns the current size of the change list.
2853 // Note that spurious changes do not necessarily indicate a problem.
2854 // Assertions on change list size can help detect problems, but it may be
2855 // necessary to reduce their strictness if the implementation changes.
2856 size_t GetChangeListSize() {
2857 return last_changes_
.Get().size();
2860 void ClearChangeList() { last_changes_
= ImmutableChangeRecordList(); }
2863 ImmutableChangeRecordList last_changes_
;
2864 TestIdFactory id_factory_
;
2867 // Test creation of a folder and a bookmark.
2868 TEST_F(SyncManagerChangeProcessingTest
, AddBookmarks
) {
2869 int64 type_root
= GetIdForDataType(BOOKMARKS
);
2870 int64 folder_id
= kInvalidId
;
2871 int64 child_id
= kInvalidId
;
2873 // Create a folder and a bookmark under it.
2875 syncable::WriteTransaction
trans(
2876 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
2877 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
2878 ASSERT_TRUE(root
.good());
2880 syncable::MutableEntry
folder(&trans
, syncable::CREATE
,
2881 BOOKMARKS
, root
.GetId(), "folder");
2882 ASSERT_TRUE(folder
.good());
2883 SetNodeProperties(&folder
);
2884 folder
.PutIsDir(true);
2885 folder_id
= folder
.GetMetahandle();
2887 syncable::MutableEntry
child(&trans
, syncable::CREATE
,
2888 BOOKMARKS
, folder
.GetId(), "child");
2889 ASSERT_TRUE(child
.good());
2890 SetNodeProperties(&child
);
2891 child_id
= child
.GetMetahandle();
2894 // The closing of the above scope will delete the transaction. Its processed
2895 // changes should be waiting for us in a member of the test harness.
2896 EXPECT_EQ(2UL, GetChangeListSize());
2898 // We don't need to check these return values here. The function will add a
2899 // non-fatal failure if these changes are not found.
2900 size_t folder_change_pos
=
2901 FindChangeInList(folder_id
, ChangeRecord::ACTION_ADD
);
2902 size_t child_change_pos
=
2903 FindChangeInList(child_id
, ChangeRecord::ACTION_ADD
);
2905 // Parents are delivered before children.
2906 EXPECT_LT(folder_change_pos
, child_change_pos
);
2909 // Test moving a bookmark into an empty folder.
2910 TEST_F(SyncManagerChangeProcessingTest
, MoveBookmarkIntoEmptyFolder
) {
2911 int64 type_root
= GetIdForDataType(BOOKMARKS
);
2912 int64 folder_b_id
= kInvalidId
;
2913 int64 child_id
= kInvalidId
;
2915 // Create two folders. Place a child under folder A.
2917 syncable::WriteTransaction
trans(
2918 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
2919 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
2920 ASSERT_TRUE(root
.good());
2922 syncable::MutableEntry
folder_a(&trans
, syncable::CREATE
,
2923 BOOKMARKS
, root
.GetId(), "folderA");
2924 ASSERT_TRUE(folder_a
.good());
2925 SetNodeProperties(&folder_a
);
2926 folder_a
.PutIsDir(true);
2928 syncable::MutableEntry
folder_b(&trans
, syncable::CREATE
,
2929 BOOKMARKS
, root
.GetId(), "folderB");
2930 ASSERT_TRUE(folder_b
.good());
2931 SetNodeProperties(&folder_b
);
2932 folder_b
.PutIsDir(true);
2933 folder_b_id
= folder_b
.GetMetahandle();
2935 syncable::MutableEntry
child(&trans
, syncable::CREATE
,
2936 BOOKMARKS
, folder_a
.GetId(),
2938 ASSERT_TRUE(child
.good());
2939 SetNodeProperties(&child
);
2940 child_id
= child
.GetMetahandle();
2943 // Close that transaction. The above was to setup the initial scenario. The
2944 // real test starts now.
2946 // Move the child from folder A to folder B.
2948 syncable::WriteTransaction
trans(
2949 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
2951 syncable::Entry
folder_b(&trans
, syncable::GET_BY_HANDLE
, folder_b_id
);
2952 syncable::MutableEntry
child(&trans
, syncable::GET_BY_HANDLE
, child_id
);
2954 child
.PutParentId(folder_b
.GetId());
2957 EXPECT_EQ(1UL, GetChangeListSize());
2959 // Verify that this was detected as a real change. An early version of the
2960 // UniquePosition code had a bug where moves from one folder to another were
2961 // ignored unless the moved node's UniquePosition value was also changed in
2963 FindChangeInList(child_id
, ChangeRecord::ACTION_UPDATE
);
2966 // Test moving a bookmark into a non-empty folder.
2967 TEST_F(SyncManagerChangeProcessingTest
, MoveIntoPopulatedFolder
) {
2968 int64 type_root
= GetIdForDataType(BOOKMARKS
);
2969 int64 child_a_id
= kInvalidId
;
2970 int64 child_b_id
= kInvalidId
;
2972 // Create two folders. Place one child each under folder A and folder B.
2974 syncable::WriteTransaction
trans(
2975 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
2976 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
2977 ASSERT_TRUE(root
.good());
2979 syncable::MutableEntry
folder_a(&trans
, syncable::CREATE
,
2980 BOOKMARKS
, root
.GetId(), "folderA");
2981 ASSERT_TRUE(folder_a
.good());
2982 SetNodeProperties(&folder_a
);
2983 folder_a
.PutIsDir(true);
2985 syncable::MutableEntry
folder_b(&trans
, syncable::CREATE
,
2986 BOOKMARKS
, root
.GetId(), "folderB");
2987 ASSERT_TRUE(folder_b
.good());
2988 SetNodeProperties(&folder_b
);
2989 folder_b
.PutIsDir(true);
2991 syncable::MutableEntry
child_a(&trans
, syncable::CREATE
,
2992 BOOKMARKS
, folder_a
.GetId(),
2994 ASSERT_TRUE(child_a
.good());
2995 SetNodeProperties(&child_a
);
2996 child_a_id
= child_a
.GetMetahandle();
2998 syncable::MutableEntry
child_b(&trans
, syncable::CREATE
,
2999 BOOKMARKS
, folder_b
.GetId(),
3001 SetNodeProperties(&child_b
);
3002 child_b_id
= child_b
.GetMetahandle();
3005 // Close that transaction. The above was to setup the initial scenario. The
3006 // real test starts now.
3009 syncable::WriteTransaction
trans(
3010 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3012 syncable::MutableEntry
child_a(&trans
, syncable::GET_BY_HANDLE
, child_a_id
);
3013 syncable::MutableEntry
child_b(&trans
, syncable::GET_BY_HANDLE
, child_b_id
);
3015 // Move child A from folder A to folder B and update its position.
3016 child_a
.PutParentId(child_b
.GetParentId());
3017 child_a
.PutPredecessor(child_b
.GetId());
3020 EXPECT_EQ(1UL, GetChangeListSize());
3022 // Verify that only child a is in the change list.
3023 // (This function will add a failure if the lookup fails.)
3024 FindChangeInList(child_a_id
, ChangeRecord::ACTION_UPDATE
);
3027 // Tests the ordering of deletion changes.
3028 TEST_F(SyncManagerChangeProcessingTest
, DeletionsAndChanges
) {
3029 int64 type_root
= GetIdForDataType(BOOKMARKS
);
3030 int64 folder_a_id
= kInvalidId
;
3031 int64 folder_b_id
= kInvalidId
;
3032 int64 child_id
= kInvalidId
;
3034 // Create two folders. Place a child under folder A.
3036 syncable::WriteTransaction
trans(
3037 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3038 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
3039 ASSERT_TRUE(root
.good());
3041 syncable::MutableEntry
folder_a(&trans
, syncable::CREATE
,
3042 BOOKMARKS
, root
.GetId(), "folderA");
3043 ASSERT_TRUE(folder_a
.good());
3044 SetNodeProperties(&folder_a
);
3045 folder_a
.PutIsDir(true);
3046 folder_a_id
= folder_a
.GetMetahandle();
3048 syncable::MutableEntry
folder_b(&trans
, syncable::CREATE
,
3049 BOOKMARKS
, root
.GetId(), "folderB");
3050 ASSERT_TRUE(folder_b
.good());
3051 SetNodeProperties(&folder_b
);
3052 folder_b
.PutIsDir(true);
3053 folder_b_id
= folder_b
.GetMetahandle();
3055 syncable::MutableEntry
child(&trans
, syncable::CREATE
,
3056 BOOKMARKS
, folder_a
.GetId(),
3058 ASSERT_TRUE(child
.good());
3059 SetNodeProperties(&child
);
3060 child_id
= child
.GetMetahandle();
3063 // Close that transaction. The above was to setup the initial scenario. The
3064 // real test starts now.
3067 syncable::WriteTransaction
trans(
3068 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3070 syncable::MutableEntry
folder_a(
3071 &trans
, syncable::GET_BY_HANDLE
, folder_a_id
);
3072 syncable::MutableEntry
folder_b(
3073 &trans
, syncable::GET_BY_HANDLE
, folder_b_id
);
3074 syncable::MutableEntry
child(&trans
, syncable::GET_BY_HANDLE
, child_id
);
3076 // Delete folder B and its child.
3077 child
.PutIsDel(true);
3078 folder_b
.PutIsDel(true);
3080 // Make an unrelated change to folder A.
3081 folder_a
.PutNonUniqueName("NewNameA");
3084 EXPECT_EQ(3UL, GetChangeListSize());
3086 size_t folder_a_pos
=
3087 FindChangeInList(folder_a_id
, ChangeRecord::ACTION_UPDATE
);
3088 size_t folder_b_pos
=
3089 FindChangeInList(folder_b_id
, ChangeRecord::ACTION_DELETE
);
3090 size_t child_pos
= FindChangeInList(child_id
, ChangeRecord::ACTION_DELETE
);
3092 // Deletes should appear before updates.
3093 EXPECT_LT(child_pos
, folder_a_pos
);
3094 EXPECT_LT(folder_b_pos
, folder_a_pos
);
3097 // See that attachment metadata changes are not filtered out by
3098 // SyncManagerImpl::VisiblePropertiesDiffer.
3099 TEST_F(SyncManagerChangeProcessingTest
, AttachmentMetadataOnlyChanges
) {
3100 // Create an article with no attachments. See that a change is generated.
3101 int64 article_id
= kInvalidId
;
3103 syncable::WriteTransaction
trans(
3104 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3105 int64 type_root
= GetIdForDataType(ARTICLES
);
3106 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
3107 ASSERT_TRUE(root
.good());
3108 syncable::MutableEntry
article(
3109 &trans
, syncable::CREATE
, ARTICLES
, root
.GetId(), "article");
3110 ASSERT_TRUE(article
.good());
3111 SetNodeProperties(&article
);
3112 article_id
= article
.GetMetahandle();
3114 ASSERT_EQ(1UL, GetChangeListSize());
3115 FindChangeInList(article_id
, ChangeRecord::ACTION_ADD
);
3118 // Modify the article by adding one attachment. Don't touch anything else.
3119 // See that a change is generated.
3121 syncable::WriteTransaction
trans(
3122 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3123 syncable::MutableEntry
article(&trans
, syncable::GET_BY_HANDLE
, article_id
);
3124 sync_pb::AttachmentMetadata metadata
;
3125 *metadata
.add_record()->mutable_id() = CreateAttachmentIdProto();
3126 article
.PutAttachmentMetadata(metadata
);
3128 ASSERT_EQ(1UL, GetChangeListSize());
3129 FindChangeInList(article_id
, ChangeRecord::ACTION_UPDATE
);
3132 // Modify the article by replacing its attachment with a different one. See
3133 // that a change is generated.
3135 syncable::WriteTransaction
trans(
3136 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3137 syncable::MutableEntry
article(&trans
, syncable::GET_BY_HANDLE
, article_id
);
3138 sync_pb::AttachmentMetadata metadata
= article
.GetAttachmentMetadata();
3139 *metadata
.add_record()->mutable_id() = CreateAttachmentIdProto();
3140 article
.PutAttachmentMetadata(metadata
);
3142 ASSERT_EQ(1UL, GetChangeListSize());
3143 FindChangeInList(article_id
, ChangeRecord::ACTION_UPDATE
);
3146 // Modify the article by replacing its attachment metadata with the same
3147 // attachment metadata. No change should be generated.
3149 syncable::WriteTransaction
trans(
3150 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3151 syncable::MutableEntry
article(&trans
, syncable::GET_BY_HANDLE
, article_id
);
3152 article
.PutAttachmentMetadata(article
.GetAttachmentMetadata());
3154 ASSERT_EQ(0UL, GetChangeListSize());
3157 // During initialization SyncManagerImpl loads sqlite database. If it fails to
3158 // do so it should fail initialization. This test verifies this behavior.
3159 // Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
3160 // InternalComponentsFactory to return DirectoryBackingStore that always fails
3162 class SyncManagerInitInvalidStorageTest
: public SyncManagerTest
{
3164 SyncManagerInitInvalidStorageTest() {
3167 InternalComponentsFactory
* GetFactory() override
{
3168 return new TestInternalComponentsFactory(
3169 GetSwitches(), InternalComponentsFactory::STORAGE_INVALID
,
3174 // SyncManagerInitInvalidStorageTest::GetFactory will return
3175 // DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
3176 // SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
3177 // task is to ensure that SyncManagerImpl reported initialization failure in
3178 // OnInitializationComplete callback.
3179 TEST_F(SyncManagerInitInvalidStorageTest
, FailToOpenDatabase
) {
3180 EXPECT_FALSE(initialization_succeeded_
);
3183 } // namespace syncer