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/cancelation_signal.h"
28 #include "sync/internal_api/public/base/model_type_test_util.h"
29 #include "sync/internal_api/public/change_record.h"
30 #include "sync/internal_api/public/engine/model_safe_worker.h"
31 #include "sync/internal_api/public/engine/polling_constants.h"
32 #include "sync/internal_api/public/events/protocol_event.h"
33 #include "sync/internal_api/public/http_post_provider_factory.h"
34 #include "sync/internal_api/public/http_post_provider_interface.h"
35 #include "sync/internal_api/public/read_node.h"
36 #include "sync/internal_api/public/read_transaction.h"
37 #include "sync/internal_api/public/test/test_entry_factory.h"
38 #include "sync/internal_api/public/test/test_internal_components_factory.h"
39 #include "sync/internal_api/public/test/test_user_share.h"
40 #include "sync/internal_api/public/write_node.h"
41 #include "sync/internal_api/public/write_transaction.h"
42 #include "sync/internal_api/sync_encryption_handler_impl.h"
43 #include "sync/internal_api/sync_manager_impl.h"
44 #include "sync/internal_api/syncapi_internal.h"
45 #include "sync/js/js_backend.h"
46 #include "sync/js/js_event_handler.h"
47 #include "sync/js/js_test_util.h"
48 #include "sync/protocol/bookmark_specifics.pb.h"
49 #include "sync/protocol/encryption.pb.h"
50 #include "sync/protocol/extension_specifics.pb.h"
51 #include "sync/protocol/password_specifics.pb.h"
52 #include "sync/protocol/preference_specifics.pb.h"
53 #include "sync/protocol/proto_value_conversions.h"
54 #include "sync/protocol/sync.pb.h"
55 #include "sync/sessions/sync_session.h"
56 #include "sync/syncable/directory.h"
57 #include "sync/syncable/entry.h"
58 #include "sync/syncable/mutable_entry.h"
59 #include "sync/syncable/nigori_util.h"
60 #include "sync/syncable/syncable_id.h"
61 #include "sync/syncable/syncable_read_transaction.h"
62 #include "sync/syncable/syncable_util.h"
63 #include "sync/syncable/syncable_write_transaction.h"
64 #include "sync/test/callback_counter.h"
65 #include "sync/test/engine/fake_model_worker.h"
66 #include "sync/test/engine/fake_sync_scheduler.h"
67 #include "sync/test/engine/test_id_factory.h"
68 #include "sync/test/fake_encryptor.h"
69 #include "sync/util/cryptographer.h"
70 #include "sync/util/extensions_activity.h"
71 #include "sync/util/test_unrecoverable_error_handler.h"
72 #include "sync/util/time.h"
73 #include "testing/gmock/include/gmock/gmock.h"
74 #include "testing/gtest/include/gtest/gtest.h"
76 using base::ExpectDictStringValue
;
79 using testing::InSequence
;
80 using testing::Return
;
81 using testing::SaveArg
;
82 using testing::StrictMock
;
86 using sessions::SyncSessionSnapshot
;
87 using syncable::GET_BY_HANDLE
;
88 using syncable::IS_DEL
;
89 using syncable::IS_UNSYNCED
;
90 using syncable::NON_UNIQUE_NAME
;
91 using syncable::SPECIFICS
;
92 using syncable::kEncryptedString
;
96 // Makes a non-folder child of the root node. Returns the id of the
97 // newly-created node.
98 int64
MakeNode(UserShare
* share
,
100 const std::string
& client_tag
) {
101 WriteTransaction
trans(FROM_HERE
, share
);
102 ReadNode
root_node(&trans
);
103 root_node
.InitByRootLookup();
104 WriteNode
node(&trans
);
105 WriteNode::InitUniqueByCreationResult result
=
106 node
.InitUniqueByCreation(model_type
, root_node
, client_tag
);
107 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
108 node
.SetIsFolder(false);
112 // Makes a folder child of a non-root node. Returns the id of the
113 // newly-created node.
114 int64
MakeFolderWithParent(UserShare
* share
,
115 ModelType model_type
,
117 BaseNode
* predecessor
) {
118 WriteTransaction
trans(FROM_HERE
, share
);
119 ReadNode
parent_node(&trans
);
120 EXPECT_EQ(BaseNode::INIT_OK
, parent_node
.InitByIdLookup(parent_id
));
121 WriteNode
node(&trans
);
122 EXPECT_TRUE(node
.InitBookmarkByCreation(parent_node
, predecessor
));
123 node
.SetIsFolder(true);
127 int64
MakeBookmarkWithParent(UserShare
* share
,
129 BaseNode
* predecessor
) {
130 WriteTransaction
trans(FROM_HERE
, share
);
131 ReadNode
parent_node(&trans
);
132 EXPECT_EQ(BaseNode::INIT_OK
, parent_node
.InitByIdLookup(parent_id
));
133 WriteNode
node(&trans
);
134 EXPECT_TRUE(node
.InitBookmarkByCreation(parent_node
, predecessor
));
138 // Creates the "synced" root node for a particular datatype. We use the syncable
139 // methods here so that the syncer treats these nodes as if they were already
140 // received from the server.
141 int64
MakeServerNodeForType(UserShare
* share
,
142 ModelType model_type
) {
143 sync_pb::EntitySpecifics specifics
;
144 AddDefaultFieldValue(model_type
, &specifics
);
145 syncable::WriteTransaction
trans(
146 FROM_HERE
, syncable::UNITTEST
, share
->directory
.get());
147 // Attempt to lookup by nigori tag.
148 std::string type_tag
= ModelTypeToRootTag(model_type
);
149 syncable::Id node_id
= syncable::Id::CreateFromServerId(type_tag
);
150 syncable::MutableEntry
entry(&trans
, syncable::CREATE_NEW_UPDATE_ITEM
,
152 EXPECT_TRUE(entry
.good());
153 entry
.PutBaseVersion(1);
154 entry
.PutServerVersion(1);
155 entry
.PutIsUnappliedUpdate(false);
156 entry
.PutServerParentId(syncable::GetNullId());
157 entry
.PutServerIsDir(true);
158 entry
.PutIsDir(true);
159 entry
.PutServerSpecifics(specifics
);
160 entry
.PutUniqueServerTag(type_tag
);
161 entry
.PutNonUniqueName(type_tag
);
162 entry
.PutIsDel(false);
163 entry
.PutSpecifics(specifics
);
164 return entry
.GetMetahandle();
167 // Simulates creating a "synced" node as a child of the root datatype node.
168 int64
MakeServerNode(UserShare
* share
, ModelType model_type
,
169 const std::string
& client_tag
,
170 const std::string
& hashed_tag
,
171 const sync_pb::EntitySpecifics
& specifics
) {
172 syncable::WriteTransaction
trans(
173 FROM_HERE
, syncable::UNITTEST
, share
->directory
.get());
174 syncable::Entry
root_entry(&trans
, syncable::GET_TYPE_ROOT
, model_type
);
175 EXPECT_TRUE(root_entry
.good());
176 syncable::Id root_id
= root_entry
.GetId();
177 syncable::Id node_id
= syncable::Id::CreateFromServerId(client_tag
);
178 syncable::MutableEntry
entry(&trans
, syncable::CREATE_NEW_UPDATE_ITEM
,
180 EXPECT_TRUE(entry
.good());
181 entry
.PutBaseVersion(1);
182 entry
.PutServerVersion(1);
183 entry
.PutIsUnappliedUpdate(false);
184 entry
.PutServerParentId(root_id
);
185 entry
.PutParentId(root_id
);
186 entry
.PutServerIsDir(false);
187 entry
.PutIsDir(false);
188 entry
.PutServerSpecifics(specifics
);
189 entry
.PutNonUniqueName(client_tag
);
190 entry
.PutUniqueClientTag(hashed_tag
);
191 entry
.PutIsDel(false);
192 entry
.PutSpecifics(specifics
);
193 return entry
.GetMetahandle();
198 class SyncApiTest
: public testing::Test
{
200 virtual void SetUp() {
201 test_user_share_
.SetUp();
204 virtual void TearDown() {
205 test_user_share_
.TearDown();
209 // Create an entry with the given |model_type|, |client_tag| and
210 // |attachment_metadata|.
211 void CreateEntryWithAttachmentMetadata(
212 const ModelType
& model_type
,
213 const std::string
& client_tag
,
214 const sync_pb::AttachmentMetadata
& attachment_metadata
);
216 // Attempts to load the entry specified by |model_type| and |client_tag| and
217 // returns the lookup result code.
218 BaseNode::InitByLookupResult
LookupEntryByClientTag(
219 const ModelType
& model_type
,
220 const std::string
& client_tag
);
222 // Replace the entry specified by |model_type| and |client_tag| with a
224 void ReplaceWithTombstone(const ModelType
& model_type
,
225 const std::string
& client_tag
);
227 // Save changes to the Directory, destroy it then reload it.
230 UserShare
* user_share();
231 syncable::Directory
* dir();
232 SyncEncryptionHandler
* encryption_handler();
235 base::MessageLoop message_loop_
;
236 TestUserShare test_user_share_
;
239 UserShare
* SyncApiTest::user_share() {
240 return test_user_share_
.user_share();
243 syncable::Directory
* SyncApiTest::dir() {
244 return test_user_share_
.user_share()->directory
.get();
247 SyncEncryptionHandler
* SyncApiTest::encryption_handler() {
248 return test_user_share_
.encryption_handler();
251 bool SyncApiTest::ReloadDir() {
252 return test_user_share_
.Reload();
255 void SyncApiTest::CreateEntryWithAttachmentMetadata(
256 const ModelType
& model_type
,
257 const std::string
& client_tag
,
258 const sync_pb::AttachmentMetadata
& attachment_metadata
) {
259 syncer::WriteTransaction
trans(FROM_HERE
, user_share());
260 syncer::ReadNode
root_node(&trans
);
261 root_node
.InitByRootLookup();
262 syncer::WriteNode
node(&trans
);
263 ASSERT_EQ(node
.InitUniqueByCreation(model_type
, root_node
, client_tag
),
264 syncer::WriteNode::INIT_SUCCESS
);
265 node
.SetAttachmentMetadata(attachment_metadata
);
268 BaseNode::InitByLookupResult
SyncApiTest::LookupEntryByClientTag(
269 const ModelType
& model_type
,
270 const std::string
& client_tag
) {
271 syncer::ReadTransaction
trans(FROM_HERE
, user_share());
272 syncer::ReadNode
node(&trans
);
273 return node
.InitByClientTagLookup(model_type
, client_tag
);
276 void SyncApiTest::ReplaceWithTombstone(const ModelType
& model_type
,
277 const std::string
& client_tag
) {
278 syncer::WriteTransaction
trans(FROM_HERE
, user_share());
279 syncer::WriteNode
node(&trans
);
280 ASSERT_EQ(node
.InitByClientTagLookup(model_type
, client_tag
),
281 syncer::WriteNode::INIT_OK
);
285 TEST_F(SyncApiTest
, SanityCheckTest
) {
287 ReadTransaction
trans(FROM_HERE
, user_share());
288 EXPECT_TRUE(trans
.GetWrappedTrans());
291 WriteTransaction
trans(FROM_HERE
, user_share());
292 EXPECT_TRUE(trans
.GetWrappedTrans());
295 // No entries but root should exist
296 ReadTransaction
trans(FROM_HERE
, user_share());
297 ReadNode
node(&trans
);
298 // Metahandle 1 can be root, sanity check 2
299 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD
, node
.InitByIdLookup(2));
303 TEST_F(SyncApiTest
, BasicTagWrite
) {
305 ReadTransaction
trans(FROM_HERE
, user_share());
306 ReadNode
root_node(&trans
);
307 root_node
.InitByRootLookup();
308 EXPECT_EQ(root_node
.GetFirstChildId(), 0);
311 ignore_result(MakeNode(user_share(), BOOKMARKS
, "testtag"));
314 ReadTransaction
trans(FROM_HERE
, user_share());
315 ReadNode
node(&trans
);
316 EXPECT_EQ(BaseNode::INIT_OK
,
317 node
.InitByClientTagLookup(BOOKMARKS
, "testtag"));
319 ReadNode
root_node(&trans
);
320 root_node
.InitByRootLookup();
321 EXPECT_NE(node
.GetId(), 0);
322 EXPECT_EQ(node
.GetId(), root_node
.GetFirstChildId());
326 TEST_F(SyncApiTest
, ModelTypesSiloed
) {
328 WriteTransaction
trans(FROM_HERE
, user_share());
329 ReadNode
root_node(&trans
);
330 root_node
.InitByRootLookup();
331 EXPECT_EQ(root_node
.GetFirstChildId(), 0);
334 ignore_result(MakeNode(user_share(), BOOKMARKS
, "collideme"));
335 ignore_result(MakeNode(user_share(), PREFERENCES
, "collideme"));
336 ignore_result(MakeNode(user_share(), AUTOFILL
, "collideme"));
339 ReadTransaction
trans(FROM_HERE
, user_share());
341 ReadNode
bookmarknode(&trans
);
342 EXPECT_EQ(BaseNode::INIT_OK
,
343 bookmarknode
.InitByClientTagLookup(BOOKMARKS
,
346 ReadNode
prefnode(&trans
);
347 EXPECT_EQ(BaseNode::INIT_OK
,
348 prefnode
.InitByClientTagLookup(PREFERENCES
,
351 ReadNode
autofillnode(&trans
);
352 EXPECT_EQ(BaseNode::INIT_OK
,
353 autofillnode
.InitByClientTagLookup(AUTOFILL
,
356 EXPECT_NE(bookmarknode
.GetId(), prefnode
.GetId());
357 EXPECT_NE(autofillnode
.GetId(), prefnode
.GetId());
358 EXPECT_NE(bookmarknode
.GetId(), autofillnode
.GetId());
362 TEST_F(SyncApiTest
, ReadMissingTagsFails
) {
364 ReadTransaction
trans(FROM_HERE
, user_share());
365 ReadNode
node(&trans
);
366 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD
,
367 node
.InitByClientTagLookup(BOOKMARKS
,
371 WriteTransaction
trans(FROM_HERE
, user_share());
372 WriteNode
node(&trans
);
373 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD
,
374 node
.InitByClientTagLookup(BOOKMARKS
,
379 // TODO(chron): Hook this all up to the server and write full integration tests
380 // for update->undelete behavior.
381 TEST_F(SyncApiTest
, TestDeleteBehavior
) {
384 std::string
test_title("test1");
387 WriteTransaction
trans(FROM_HERE
, user_share());
388 ReadNode
root_node(&trans
);
389 root_node
.InitByRootLookup();
391 // we'll use this spare folder later
392 WriteNode
folder_node(&trans
);
393 EXPECT_TRUE(folder_node
.InitBookmarkByCreation(root_node
, NULL
));
394 folder_id
= folder_node
.GetId();
396 WriteNode
wnode(&trans
);
397 WriteNode::InitUniqueByCreationResult result
=
398 wnode
.InitUniqueByCreation(BOOKMARKS
, root_node
, "testtag");
399 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
400 wnode
.SetIsFolder(false);
401 wnode
.SetTitle(test_title
);
403 node_id
= wnode
.GetId();
406 // Ensure we can delete something with a tag.
408 WriteTransaction
trans(FROM_HERE
, user_share());
409 WriteNode
wnode(&trans
);
410 EXPECT_EQ(BaseNode::INIT_OK
,
411 wnode
.InitByClientTagLookup(BOOKMARKS
,
413 EXPECT_FALSE(wnode
.GetIsFolder());
414 EXPECT_EQ(wnode
.GetTitle(), test_title
);
419 // Lookup of a node which was deleted should return failure,
420 // but have found some data about the node.
422 ReadTransaction
trans(FROM_HERE
, user_share());
423 ReadNode
node(&trans
);
424 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL
,
425 node
.InitByClientTagLookup(BOOKMARKS
,
427 // Note that for proper function of this API this doesn't need to be
428 // filled, we're checking just to make sure the DB worked in this test.
429 EXPECT_EQ(node
.GetTitle(), test_title
);
433 WriteTransaction
trans(FROM_HERE
, user_share());
434 ReadNode
folder_node(&trans
);
435 EXPECT_EQ(BaseNode::INIT_OK
, folder_node
.InitByIdLookup(folder_id
));
437 WriteNode
wnode(&trans
);
438 // This will undelete the tag.
439 WriteNode::InitUniqueByCreationResult result
=
440 wnode
.InitUniqueByCreation(BOOKMARKS
, folder_node
, "testtag");
441 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
442 EXPECT_EQ(wnode
.GetIsFolder(), false);
443 EXPECT_EQ(wnode
.GetParentId(), folder_node
.GetId());
444 EXPECT_EQ(wnode
.GetId(), node_id
);
445 EXPECT_NE(wnode
.GetTitle(), test_title
); // Title should be cleared
446 wnode
.SetTitle(test_title
);
449 // Now look up should work.
451 ReadTransaction
trans(FROM_HERE
, user_share());
452 ReadNode
node(&trans
);
453 EXPECT_EQ(BaseNode::INIT_OK
,
454 node
.InitByClientTagLookup(BOOKMARKS
,
456 EXPECT_EQ(node
.GetTitle(), test_title
);
457 EXPECT_EQ(node
.GetModelType(), BOOKMARKS
);
461 TEST_F(SyncApiTest
, WriteAndReadPassword
) {
462 KeyParams params
= {"localhost", "username", "passphrase"};
464 ReadTransaction
trans(FROM_HERE
, user_share());
465 trans
.GetCryptographer()->AddKey(params
);
468 WriteTransaction
trans(FROM_HERE
, user_share());
469 ReadNode
root_node(&trans
);
470 root_node
.InitByRootLookup();
472 WriteNode
password_node(&trans
);
473 WriteNode::InitUniqueByCreationResult result
=
474 password_node
.InitUniqueByCreation(PASSWORDS
,
476 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
477 sync_pb::PasswordSpecificsData data
;
478 data
.set_password_value("secret");
479 password_node
.SetPasswordSpecifics(data
);
482 ReadTransaction
trans(FROM_HERE
, user_share());
483 ReadNode
root_node(&trans
);
484 root_node
.InitByRootLookup();
486 ReadNode
password_node(&trans
);
487 EXPECT_EQ(BaseNode::INIT_OK
,
488 password_node
.InitByClientTagLookup(PASSWORDS
, "foo"));
489 const sync_pb::PasswordSpecificsData
& data
=
490 password_node
.GetPasswordSpecifics();
491 EXPECT_EQ("secret", data
.password_value());
495 TEST_F(SyncApiTest
, WriteEncryptedTitle
) {
496 KeyParams params
= {"localhost", "username", "passphrase"};
498 ReadTransaction
trans(FROM_HERE
, user_share());
499 trans
.GetCryptographer()->AddKey(params
);
501 encryption_handler()->EnableEncryptEverything();
504 WriteTransaction
trans(FROM_HERE
, user_share());
505 ReadNode
root_node(&trans
);
506 root_node
.InitByRootLookup();
508 WriteNode
bookmark_node(&trans
);
509 ASSERT_TRUE(bookmark_node
.InitBookmarkByCreation(root_node
, NULL
));
510 bookmark_id
= bookmark_node
.GetId();
511 bookmark_node
.SetTitle("foo");
513 WriteNode
pref_node(&trans
);
514 WriteNode::InitUniqueByCreationResult result
=
515 pref_node
.InitUniqueByCreation(PREFERENCES
, root_node
, "bar");
516 ASSERT_EQ(WriteNode::INIT_SUCCESS
, result
);
517 pref_node
.SetTitle("bar");
520 ReadTransaction
trans(FROM_HERE
, user_share());
521 ReadNode
root_node(&trans
);
522 root_node
.InitByRootLookup();
524 ReadNode
bookmark_node(&trans
);
525 ASSERT_EQ(BaseNode::INIT_OK
, bookmark_node
.InitByIdLookup(bookmark_id
));
526 EXPECT_EQ("foo", bookmark_node
.GetTitle());
527 EXPECT_EQ(kEncryptedString
,
528 bookmark_node
.GetEntry()->GetNonUniqueName());
530 ReadNode
pref_node(&trans
);
531 ASSERT_EQ(BaseNode::INIT_OK
,
532 pref_node
.InitByClientTagLookup(PREFERENCES
,
534 EXPECT_EQ(kEncryptedString
, pref_node
.GetTitle());
538 TEST_F(SyncApiTest
, BaseNodeSetSpecifics
) {
539 int64 child_id
= MakeNode(user_share(), BOOKMARKS
, "testtag");
540 WriteTransaction
trans(FROM_HERE
, user_share());
541 WriteNode
node(&trans
);
542 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(child_id
));
544 sync_pb::EntitySpecifics entity_specifics
;
545 entity_specifics
.mutable_bookmark()->set_url("http://www.google.com");
547 EXPECT_NE(entity_specifics
.SerializeAsString(),
548 node
.GetEntitySpecifics().SerializeAsString());
549 node
.SetEntitySpecifics(entity_specifics
);
550 EXPECT_EQ(entity_specifics
.SerializeAsString(),
551 node
.GetEntitySpecifics().SerializeAsString());
554 TEST_F(SyncApiTest
, BaseNodeSetSpecificsPreservesUnknownFields
) {
555 int64 child_id
= MakeNode(user_share(), BOOKMARKS
, "testtag");
556 WriteTransaction
trans(FROM_HERE
, user_share());
557 WriteNode
node(&trans
);
558 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(child_id
));
559 EXPECT_TRUE(node
.GetEntitySpecifics().unknown_fields().empty());
561 sync_pb::EntitySpecifics entity_specifics
;
562 entity_specifics
.mutable_bookmark()->set_url("http://www.google.com");
563 entity_specifics
.mutable_unknown_fields()->AddFixed32(5, 100);
564 node
.SetEntitySpecifics(entity_specifics
);
565 EXPECT_FALSE(node
.GetEntitySpecifics().unknown_fields().empty());
567 entity_specifics
.mutable_unknown_fields()->Clear();
568 node
.SetEntitySpecifics(entity_specifics
);
569 EXPECT_FALSE(node
.GetEntitySpecifics().unknown_fields().empty());
572 TEST_F(SyncApiTest
, EmptyTags
) {
573 WriteTransaction
trans(FROM_HERE
, user_share());
574 ReadNode
root_node(&trans
);
575 root_node
.InitByRootLookup();
576 WriteNode
node(&trans
);
577 std::string empty_tag
;
578 WriteNode::InitUniqueByCreationResult result
=
579 node
.InitUniqueByCreation(TYPED_URLS
, root_node
, empty_tag
);
580 EXPECT_NE(WriteNode::INIT_SUCCESS
, result
);
581 EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION
,
582 node
.InitByClientTagLookup(TYPED_URLS
, empty_tag
));
585 // Test counting nodes when the type's root node has no children.
586 TEST_F(SyncApiTest
, GetTotalNodeCountEmpty
) {
587 int64 type_root
= MakeServerNodeForType(user_share(), BOOKMARKS
);
589 ReadTransaction
trans(FROM_HERE
, user_share());
590 ReadNode
type_root_node(&trans
);
591 EXPECT_EQ(BaseNode::INIT_OK
,
592 type_root_node
.InitByIdLookup(type_root
));
593 EXPECT_EQ(1, type_root_node
.GetTotalNodeCount());
597 // Test counting nodes when there is one child beneath the type's root.
598 TEST_F(SyncApiTest
, GetTotalNodeCountOneChild
) {
599 int64 type_root
= MakeServerNodeForType(user_share(), BOOKMARKS
);
600 int64 parent
= MakeFolderWithParent(user_share(), BOOKMARKS
, type_root
, NULL
);
602 ReadTransaction
trans(FROM_HERE
, user_share());
603 ReadNode
type_root_node(&trans
);
604 EXPECT_EQ(BaseNode::INIT_OK
,
605 type_root_node
.InitByIdLookup(type_root
));
606 EXPECT_EQ(2, type_root_node
.GetTotalNodeCount());
607 ReadNode
parent_node(&trans
);
608 EXPECT_EQ(BaseNode::INIT_OK
,
609 parent_node
.InitByIdLookup(parent
));
610 EXPECT_EQ(1, parent_node
.GetTotalNodeCount());
614 // Test counting nodes when there are multiple children beneath the type root,
615 // and one of those children has children of its own.
616 TEST_F(SyncApiTest
, GetTotalNodeCountMultipleChildren
) {
617 int64 type_root
= MakeServerNodeForType(user_share(), BOOKMARKS
);
618 int64 parent
= MakeFolderWithParent(user_share(), BOOKMARKS
, type_root
, NULL
);
619 ignore_result(MakeFolderWithParent(user_share(), BOOKMARKS
, type_root
, NULL
));
620 int64 child1
= MakeFolderWithParent(user_share(), BOOKMARKS
, parent
, NULL
);
621 ignore_result(MakeBookmarkWithParent(user_share(), parent
, NULL
));
622 ignore_result(MakeBookmarkWithParent(user_share(), child1
, NULL
));
625 ReadTransaction
trans(FROM_HERE
, user_share());
626 ReadNode
type_root_node(&trans
);
627 EXPECT_EQ(BaseNode::INIT_OK
,
628 type_root_node
.InitByIdLookup(type_root
));
629 EXPECT_EQ(6, type_root_node
.GetTotalNodeCount());
630 ReadNode
node(&trans
);
631 EXPECT_EQ(BaseNode::INIT_OK
,
632 node
.InitByIdLookup(parent
));
633 EXPECT_EQ(4, node
.GetTotalNodeCount());
637 // Verify that Directory keeps track of which attachments are referenced by
639 TEST_F(SyncApiTest
, AttachmentLinking
) {
640 // Add an entry with an attachment.
641 std::string
tag1("some tag");
642 syncer::AttachmentId
attachment_id(syncer::AttachmentId::Create());
643 sync_pb::AttachmentMetadata attachment_metadata
;
644 sync_pb::AttachmentMetadataRecord
* record
= attachment_metadata
.add_record();
645 *record
->mutable_id() = attachment_id
.GetProto();
646 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
647 CreateEntryWithAttachmentMetadata(PREFERENCES
, tag1
, attachment_metadata
);
649 // See that the directory knows it's linked.
650 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
652 // Add a second entry referencing the same attachment.
653 std::string
tag2("some other tag");
654 CreateEntryWithAttachmentMetadata(PREFERENCES
, tag2
, attachment_metadata
);
656 // See that the directory knows it's still linked.
657 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
659 // Tombstone the first entry.
660 ReplaceWithTombstone(syncer::PREFERENCES
, tag1
);
662 // See that the attachment is still considered linked because the entry hasn't
663 // been purged from the Directory.
664 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
666 // Save changes and see that the entry is truly gone.
667 ASSERT_TRUE(dir()->SaveChanges());
668 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES
, tag1
),
669 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD
);
671 // However, the attachment is still linked.
672 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
674 // Save, destroy, and recreate the directory. See that it's still linked.
675 ASSERT_TRUE(ReloadDir());
676 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
678 // Tombstone the second entry, save changes, see that it's truly gone.
679 ReplaceWithTombstone(syncer::PREFERENCES
, tag2
);
680 ASSERT_TRUE(dir()->SaveChanges());
681 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES
, tag2
),
682 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD
);
684 // Finally, the attachment is no longer linked.
685 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id
.GetProto()));
690 class TestHttpPostProviderInterface
: public HttpPostProviderInterface
{
692 virtual ~TestHttpPostProviderInterface() {}
694 virtual void SetExtraRequestHeaders(const char* headers
) OVERRIDE
{}
695 virtual void SetURL(const char* url
, int port
) OVERRIDE
{}
696 virtual void SetPostPayload(const char* content_type
,
698 const char* content
) OVERRIDE
{}
699 virtual bool MakeSynchronousPost(int* error_code
, int* response_code
)
703 virtual int GetResponseContentLength() const OVERRIDE
{
706 virtual const char* GetResponseContent() const OVERRIDE
{
709 virtual const std::string
GetResponseHeaderValue(
710 const std::string
& name
) const OVERRIDE
{
711 return std::string();
713 virtual void Abort() OVERRIDE
{}
716 class TestHttpPostProviderFactory
: public HttpPostProviderFactory
{
718 virtual ~TestHttpPostProviderFactory() {}
719 virtual void Init(const std::string
& user_agent
) OVERRIDE
{ }
720 virtual HttpPostProviderInterface
* Create() OVERRIDE
{
721 return new TestHttpPostProviderInterface();
723 virtual void Destroy(HttpPostProviderInterface
* http
) OVERRIDE
{
724 delete static_cast<TestHttpPostProviderInterface
*>(http
);
728 class SyncManagerObserverMock
: public SyncManager::Observer
{
730 MOCK_METHOD1(OnSyncCycleCompleted
,
731 void(const SyncSessionSnapshot
&)); // NOLINT
732 MOCK_METHOD4(OnInitializationComplete
,
733 void(const WeakHandle
<JsBackend
>&,
734 const WeakHandle
<DataTypeDebugInfoListener
>&,
736 syncer::ModelTypeSet
)); // NOLINT
737 MOCK_METHOD1(OnConnectionStatusChange
, void(ConnectionStatus
)); // NOLINT
738 MOCK_METHOD1(OnUpdatedToken
, void(const std::string
&)); // NOLINT
739 MOCK_METHOD1(OnActionableError
, void(const SyncProtocolError
&)); // NOLINT
740 MOCK_METHOD1(OnMigrationRequested
, void(syncer::ModelTypeSet
)); // NOLINT
741 MOCK_METHOD1(OnProtocolEvent
, void(const ProtocolEvent
&)); // NOLINT
744 class SyncEncryptionHandlerObserverMock
745 : public SyncEncryptionHandler::Observer
{
747 MOCK_METHOD2(OnPassphraseRequired
,
748 void(PassphraseRequiredReason
,
749 const sync_pb::EncryptedData
&)); // NOLINT
750 MOCK_METHOD0(OnPassphraseAccepted
, void()); // NOLINT
751 MOCK_METHOD2(OnBootstrapTokenUpdated
,
752 void(const std::string
&, BootstrapTokenType type
)); // NOLINT
753 MOCK_METHOD2(OnEncryptedTypesChanged
,
754 void(ModelTypeSet
, bool)); // NOLINT
755 MOCK_METHOD0(OnEncryptionComplete
, void()); // NOLINT
756 MOCK_METHOD1(OnCryptographerStateChanged
, void(Cryptographer
*)); // NOLINT
757 MOCK_METHOD2(OnPassphraseTypeChanged
, void(PassphraseType
,
758 base::Time
)); // NOLINT
763 class SyncManagerTest
: public testing::Test
,
764 public SyncManager::ChangeDelegate
{
771 enum EncryptionStatus
{
778 : sync_manager_("Test sync manager") {
779 switches_
.encryption_method
=
780 InternalComponentsFactory::ENCRYPTION_KEYSTORE
;
783 virtual ~SyncManagerTest() {
786 // Test implementation.
788 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
790 extensions_activity_
= new ExtensionsActivity();
792 SyncCredentials credentials
;
793 credentials
.email
= "foo@bar.com";
794 credentials
.sync_token
= "sometoken";
795 OAuth2TokenService::ScopeSet scope_set
;
796 scope_set
.insert(GaiaConstants::kChromeSyncOAuth2Scope
);
797 credentials
.scope_set
= scope_set
;
799 sync_manager_
.AddObserver(&manager_observer_
);
800 EXPECT_CALL(manager_observer_
, OnInitializationComplete(_
, _
, _
, _
)).
801 WillOnce(DoAll(SaveArg
<0>(&js_backend_
),
802 SaveArg
<2>(&initialization_succeeded_
)));
804 EXPECT_FALSE(js_backend_
.IsInitialized());
806 std::vector
<scoped_refptr
<ModelSafeWorker
> > workers
;
807 ModelSafeRoutingInfo routing_info
;
808 GetModelSafeRoutingInfo(&routing_info
);
810 // This works only because all routing info types are GROUP_PASSIVE.
811 // If we had types in other groups, we would need additional workers
813 scoped_refptr
<ModelSafeWorker
> worker
= new FakeModelWorker(GROUP_PASSIVE
);
814 workers
.push_back(worker
);
816 // Takes ownership of |fake_invalidator_|.
819 WeakHandle
<JsEventHandler
>(),
823 scoped_ptr
<HttpPostProviderFactory
>(new TestHttpPostProviderFactory()),
825 extensions_activity_
.get(),
828 "fake_invalidator_client_id",
830 std::string(), // bootstrap tokens
831 scoped_ptr
<InternalComponentsFactory
>(GetFactory()).get(),
833 scoped_ptr
<UnrecoverableErrorHandler
>(
834 new TestUnrecoverableErrorHandler
).Pass(),
836 &cancelation_signal_
);
838 sync_manager_
.GetEncryptionHandler()->AddObserver(&encryption_observer_
);
840 EXPECT_TRUE(js_backend_
.IsInitialized());
842 if (initialization_succeeded_
) {
843 for (ModelSafeRoutingInfo::iterator i
= routing_info
.begin();
844 i
!= routing_info
.end(); ++i
) {
845 type_roots_
[i
->first
] = MakeServerNodeForType(
846 sync_manager_
.GetUserShare(), i
->first
);
854 sync_manager_
.RemoveObserver(&manager_observer_
);
855 sync_manager_
.ShutdownOnSyncThread();
859 void GetModelSafeRoutingInfo(ModelSafeRoutingInfo
* out
) {
860 (*out
)[NIGORI
] = GROUP_PASSIVE
;
861 (*out
)[DEVICE_INFO
] = GROUP_PASSIVE
;
862 (*out
)[EXPERIMENTS
] = GROUP_PASSIVE
;
863 (*out
)[BOOKMARKS
] = GROUP_PASSIVE
;
864 (*out
)[THEMES
] = GROUP_PASSIVE
;
865 (*out
)[SESSIONS
] = GROUP_PASSIVE
;
866 (*out
)[PASSWORDS
] = GROUP_PASSIVE
;
867 (*out
)[PREFERENCES
] = GROUP_PASSIVE
;
868 (*out
)[PRIORITY_PREFERENCES
] = GROUP_PASSIVE
;
871 ModelTypeSet
GetEnabledTypes() {
872 ModelSafeRoutingInfo routing_info
;
873 GetModelSafeRoutingInfo(&routing_info
);
874 return GetRoutingInfoTypes(routing_info
);
877 virtual void OnChangesApplied(
878 ModelType model_type
,
880 const BaseTransaction
* trans
,
881 const ImmutableChangeRecordList
& changes
) OVERRIDE
{}
883 virtual void OnChangesComplete(ModelType model_type
) OVERRIDE
{}
886 bool SetUpEncryption(NigoriStatus nigori_status
,
887 EncryptionStatus encryption_status
) {
888 UserShare
* share
= sync_manager_
.GetUserShare();
890 // We need to create the nigori node as if it were an applied server update.
891 int64 nigori_id
= GetIdForDataType(NIGORI
);
892 if (nigori_id
== kInvalidId
)
895 // Set the nigori cryptographer information.
896 if (encryption_status
== FULL_ENCRYPTION
)
897 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
899 WriteTransaction
trans(FROM_HERE
, share
);
900 Cryptographer
* cryptographer
= trans
.GetCryptographer();
903 if (encryption_status
!= UNINITIALIZED
) {
904 KeyParams params
= {"localhost", "dummy", "foobar"};
905 cryptographer
->AddKey(params
);
907 DCHECK_NE(nigori_status
, WRITE_TO_NIGORI
);
909 if (nigori_status
== WRITE_TO_NIGORI
) {
910 sync_pb::NigoriSpecifics nigori
;
911 cryptographer
->GetKeys(nigori
.mutable_encryption_keybag());
912 share
->directory
->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
914 trans
.GetWrappedTrans());
915 WriteNode
node(&trans
);
916 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(nigori_id
));
917 node
.SetNigoriSpecifics(nigori
);
919 return cryptographer
->is_ready();
922 int64
GetIdForDataType(ModelType type
) {
923 if (type_roots_
.count(type
) == 0)
925 return type_roots_
[type
];
929 message_loop_
.RunUntilIdle();
932 void SetJsEventHandler(const WeakHandle
<JsEventHandler
>& event_handler
) {
933 js_backend_
.Call(FROM_HERE
, &JsBackend::SetJsEventHandler
,
938 // Looks up an entry by client tag and resets IS_UNSYNCED value to false.
939 // Returns true if entry was previously unsynced, false if IS_UNSYNCED was
941 bool ResetUnsyncedEntry(ModelType type
,
942 const std::string
& client_tag
) {
943 UserShare
* share
= sync_manager_
.GetUserShare();
944 syncable::WriteTransaction
trans(
945 FROM_HERE
, syncable::UNITTEST
, share
->directory
.get());
946 const std::string hash
= syncable::GenerateSyncableHash(type
, client_tag
);
947 syncable::MutableEntry
entry(&trans
, syncable::GET_BY_CLIENT_TAG
,
949 EXPECT_TRUE(entry
.good());
950 if (!entry
.GetIsUnsynced())
952 entry
.PutIsUnsynced(false);
956 virtual InternalComponentsFactory
* GetFactory() {
957 return new TestInternalComponentsFactory(GetSwitches(), STORAGE_IN_MEMORY
);
960 // Returns true if we are currently encrypting all sync data. May
961 // be called on any thread.
962 bool EncryptEverythingEnabledForTest() {
963 return sync_manager_
.GetEncryptionHandler()->EncryptEverythingEnabled();
966 // Gets the set of encrypted types from the cryptographer
967 // Note: opens a transaction. May be called from any thread.
968 ModelTypeSet
GetEncryptedTypes() {
969 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
970 return GetEncryptedTypesWithTrans(&trans
);
973 ModelTypeSet
GetEncryptedTypesWithTrans(BaseTransaction
* trans
) {
974 return trans
->GetDirectory()->GetNigoriHandler()->
975 GetEncryptedTypes(trans
->GetWrappedTrans());
978 void SimulateInvalidatorStateChangeForTest(InvalidatorState state
) {
979 DCHECK(sync_manager_
.thread_checker_
.CalledOnValidThread());
980 sync_manager_
.SetInvalidatorEnabled(state
== INVALIDATIONS_ENABLED
);
983 void SetProgressMarkerForType(ModelType type
, bool set
) {
985 sync_pb::DataTypeProgressMarker marker
;
986 marker
.set_token("token");
987 marker
.set_data_type_id(GetSpecificsFieldNumberFromModelType(type
));
988 sync_manager_
.directory()->SetDownloadProgress(type
, marker
);
990 sync_pb::DataTypeProgressMarker marker
;
991 sync_manager_
.directory()->SetDownloadProgress(type
, marker
);
995 InternalComponentsFactory::Switches
GetSwitches() const {
1000 // Needed by |sync_manager_|.
1001 base::MessageLoop message_loop_
;
1002 // Needed by |sync_manager_|.
1003 base::ScopedTempDir temp_dir_
;
1004 // Sync Id's for the roots of the enabled datatypes.
1005 std::map
<ModelType
, int64
> type_roots_
;
1006 scoped_refptr
<ExtensionsActivity
> extensions_activity_
;
1009 FakeEncryptor encryptor_
;
1010 SyncManagerImpl sync_manager_
;
1011 CancelationSignal cancelation_signal_
;
1012 WeakHandle
<JsBackend
> js_backend_
;
1013 bool initialization_succeeded_
;
1014 StrictMock
<SyncManagerObserverMock
> manager_observer_
;
1015 StrictMock
<SyncEncryptionHandlerObserverMock
> encryption_observer_
;
1016 InternalComponentsFactory::Switches switches_
;
1019 TEST_F(SyncManagerTest
, GetAllNodesForTypeTest
) {
1020 ModelSafeRoutingInfo routing_info
;
1021 GetModelSafeRoutingInfo(&routing_info
);
1022 sync_manager_
.StartSyncingNormally(routing_info
);
1024 scoped_ptr
<base::ListValue
> node_list(
1025 sync_manager_
.GetAllNodesForType(syncer::PREFERENCES
));
1027 // Should have one node: the type root node.
1028 ASSERT_EQ(1U, node_list
->GetSize());
1030 const base::DictionaryValue
* first_result
;
1031 ASSERT_TRUE(node_list
->GetDictionary(0, &first_result
));
1032 EXPECT_TRUE(first_result
->HasKey("ID"));
1033 EXPECT_TRUE(first_result
->HasKey("NON_UNIQUE_NAME"));
1036 TEST_F(SyncManagerTest
, RefreshEncryptionReady
) {
1037 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1038 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1039 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1040 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1042 sync_manager_
.GetEncryptionHandler()->Init();
1045 const ModelTypeSet encrypted_types
= GetEncryptedTypes();
1046 EXPECT_TRUE(encrypted_types
.Has(PASSWORDS
));
1047 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1050 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1051 ReadNode
node(&trans
);
1052 EXPECT_EQ(BaseNode::INIT_OK
,
1053 node
.InitByIdLookup(GetIdForDataType(NIGORI
)));
1054 sync_pb::NigoriSpecifics nigori
= node
.GetNigoriSpecifics();
1055 EXPECT_TRUE(nigori
.has_encryption_keybag());
1056 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1057 EXPECT_TRUE(cryptographer
->is_ready());
1058 EXPECT_TRUE(cryptographer
->CanDecrypt(nigori
.encryption_keybag()));
1062 // Attempt to refresh encryption when nigori not downloaded.
1063 TEST_F(SyncManagerTest
, RefreshEncryptionNotReady
) {
1064 // Don't set up encryption (no nigori node created).
1066 // Should fail. Triggers an OnPassphraseRequired because the cryptographer
1068 EXPECT_CALL(encryption_observer_
, OnPassphraseRequired(_
, _
)).Times(1);
1069 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1070 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1071 sync_manager_
.GetEncryptionHandler()->Init();
1074 const ModelTypeSet encrypted_types
= GetEncryptedTypes();
1075 EXPECT_TRUE(encrypted_types
.Has(PASSWORDS
)); // Hardcoded.
1076 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1079 // Attempt to refresh encryption when nigori is empty.
1080 TEST_F(SyncManagerTest
, RefreshEncryptionEmptyNigori
) {
1081 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI
, DEFAULT_ENCRYPTION
));
1082 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete()).Times(1);
1083 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1084 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1086 // Should write to nigori.
1087 sync_manager_
.GetEncryptionHandler()->Init();
1090 const ModelTypeSet encrypted_types
= GetEncryptedTypes();
1091 EXPECT_TRUE(encrypted_types
.Has(PASSWORDS
)); // Hardcoded.
1092 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1095 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1096 ReadNode
node(&trans
);
1097 EXPECT_EQ(BaseNode::INIT_OK
,
1098 node
.InitByIdLookup(GetIdForDataType(NIGORI
)));
1099 sync_pb::NigoriSpecifics nigori
= node
.GetNigoriSpecifics();
1100 EXPECT_TRUE(nigori
.has_encryption_keybag());
1101 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1102 EXPECT_TRUE(cryptographer
->is_ready());
1103 EXPECT_TRUE(cryptographer
->CanDecrypt(nigori
.encryption_keybag()));
1107 TEST_F(SyncManagerTest
, EncryptDataTypesWithNoData
) {
1108 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1109 EXPECT_CALL(encryption_observer_
,
1110 OnEncryptedTypesChanged(
1111 HasModelTypes(EncryptableUserTypes()), true));
1112 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1113 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1114 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1117 TEST_F(SyncManagerTest
, EncryptDataTypesWithData
) {
1118 size_t batch_size
= 5;
1119 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1121 // Create some unencrypted unsynced data.
1122 int64 folder
= MakeFolderWithParent(sync_manager_
.GetUserShare(),
1124 GetIdForDataType(BOOKMARKS
),
1126 // First batch_size nodes are children of folder.
1128 for (i
= 0; i
< batch_size
; ++i
) {
1129 MakeBookmarkWithParent(sync_manager_
.GetUserShare(), folder
, NULL
);
1131 // Next batch_size nodes are a different type and on their own.
1132 for (; i
< 2*batch_size
; ++i
) {
1133 MakeNode(sync_manager_
.GetUserShare(), SESSIONS
,
1134 base::StringPrintf("%" PRIuS
"", i
));
1136 // Last batch_size nodes are a third type that will not need encryption.
1137 for (; i
< 3*batch_size
; ++i
) {
1138 MakeNode(sync_manager_
.GetUserShare(), THEMES
,
1139 base::StringPrintf("%" PRIuS
"", i
));
1143 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1144 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1145 SyncEncryptionHandler::SensitiveTypes()));
1146 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1147 trans
.GetWrappedTrans(),
1149 false /* not encrypted */));
1150 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1151 trans
.GetWrappedTrans(),
1153 false /* not encrypted */));
1154 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1155 trans
.GetWrappedTrans(),
1157 false /* not encrypted */));
1160 EXPECT_CALL(encryption_observer_
,
1161 OnEncryptedTypesChanged(
1162 HasModelTypes(EncryptableUserTypes()), true));
1163 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1164 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1165 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1167 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1168 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1169 EncryptableUserTypes()));
1170 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1171 trans
.GetWrappedTrans(),
1173 true /* is encrypted */));
1174 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1175 trans
.GetWrappedTrans(),
1177 true /* is encrypted */));
1178 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1179 trans
.GetWrappedTrans(),
1181 true /* is encrypted */));
1184 // Trigger's a ReEncryptEverything with new passphrase.
1185 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1186 EXPECT_CALL(encryption_observer_
,
1187 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1188 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1189 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1190 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1191 EXPECT_CALL(encryption_observer_
,
1192 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1193 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1194 "new_passphrase", true);
1195 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1197 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1198 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1199 EncryptableUserTypes()));
1200 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1201 trans
.GetWrappedTrans(),
1203 true /* is encrypted */));
1204 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1205 trans
.GetWrappedTrans(),
1207 true /* is encrypted */));
1208 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1209 trans
.GetWrappedTrans(),
1211 true /* is encrypted */));
1213 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1214 // a reencryption and should just notify immediately.
1215 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1216 EXPECT_CALL(encryption_observer_
,
1217 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
)).Times(0);
1218 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted()).Times(0);
1219 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete()).Times(0);
1220 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1223 // Test that when there are no pending keys and the cryptographer is not
1224 // initialized, we add a key based on the current GAIA password.
1225 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1226 TEST_F(SyncManagerTest
, SetInitialGaiaPass
) {
1227 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI
, UNINITIALIZED
));
1228 EXPECT_CALL(encryption_observer_
,
1229 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1230 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1231 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1232 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1233 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1236 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1237 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1238 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1240 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1241 ReadNode
node(&trans
);
1242 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1243 sync_pb::NigoriSpecifics nigori
= node
.GetNigoriSpecifics();
1244 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1245 EXPECT_TRUE(cryptographer
->is_ready());
1246 EXPECT_TRUE(cryptographer
->CanDecrypt(nigori
.encryption_keybag()));
1250 // Test that when there are no pending keys and we have on the old GAIA
1251 // password, we update and re-encrypt everything with the new GAIA password.
1252 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1253 TEST_F(SyncManagerTest
, UpdateGaiaPass
) {
1254 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1255 Cryptographer
verifier(&encryptor_
);
1257 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1258 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1259 std::string bootstrap_token
;
1260 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1261 verifier
.Bootstrap(bootstrap_token
);
1263 EXPECT_CALL(encryption_observer_
,
1264 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1265 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1266 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1267 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1268 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1271 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1272 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1273 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1275 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1276 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1277 EXPECT_TRUE(cryptographer
->is_ready());
1278 // Verify the default key has changed.
1279 sync_pb::EncryptedData encrypted
;
1280 cryptographer
->GetKeys(&encrypted
);
1281 EXPECT_FALSE(verifier
.CanDecrypt(encrypted
));
1285 // Sets a new explicit passphrase. This should update the bootstrap token
1286 // and re-encrypt everything.
1287 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1288 TEST_F(SyncManagerTest
, SetPassphraseWithPassword
) {
1289 Cryptographer
verifier(&encryptor_
);
1290 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1292 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1293 // Store the default (soon to be old) key.
1294 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1295 std::string bootstrap_token
;
1296 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1297 verifier
.Bootstrap(bootstrap_token
);
1299 ReadNode
root_node(&trans
);
1300 root_node
.InitByRootLookup();
1302 WriteNode
password_node(&trans
);
1303 WriteNode::InitUniqueByCreationResult result
=
1304 password_node
.InitUniqueByCreation(PASSWORDS
,
1306 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
1307 sync_pb::PasswordSpecificsData data
;
1308 data
.set_password_value("secret");
1309 password_node
.SetPasswordSpecifics(data
);
1311 EXPECT_CALL(encryption_observer_
,
1312 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1313 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1314 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1315 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1316 EXPECT_CALL(encryption_observer_
,
1317 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1318 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1321 EXPECT_EQ(CUSTOM_PASSPHRASE
,
1322 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1323 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1325 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1326 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1327 EXPECT_TRUE(cryptographer
->is_ready());
1328 // Verify the default key has changed.
1329 sync_pb::EncryptedData encrypted
;
1330 cryptographer
->GetKeys(&encrypted
);
1331 EXPECT_FALSE(verifier
.CanDecrypt(encrypted
));
1333 ReadNode
password_node(&trans
);
1334 EXPECT_EQ(BaseNode::INIT_OK
,
1335 password_node
.InitByClientTagLookup(PASSWORDS
,
1337 const sync_pb::PasswordSpecificsData
& data
=
1338 password_node
.GetPasswordSpecifics();
1339 EXPECT_EQ("secret", data
.password_value());
1343 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1344 // being encrypted with a new (unprovided) GAIA password, then supply the
1346 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1347 TEST_F(SyncManagerTest
, SupplyPendingGAIAPass
) {
1348 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1349 Cryptographer
other_cryptographer(&encryptor_
);
1351 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1352 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1353 std::string bootstrap_token
;
1354 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1355 other_cryptographer
.Bootstrap(bootstrap_token
);
1357 // Now update the nigori to reflect the new keys, and update the
1358 // cryptographer to have pending keys.
1359 KeyParams params
= {"localhost", "dummy", "passphrase2"};
1360 other_cryptographer
.AddKey(params
);
1361 WriteNode
node(&trans
);
1362 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1363 sync_pb::NigoriSpecifics nigori
;
1364 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1365 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1366 EXPECT_TRUE(cryptographer
->has_pending_keys());
1367 node
.SetNigoriSpecifics(nigori
);
1369 EXPECT_CALL(encryption_observer_
,
1370 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1371 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1372 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1373 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1374 sync_manager_
.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
1375 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1376 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1377 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1379 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1380 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1381 EXPECT_TRUE(cryptographer
->is_ready());
1382 // Verify we're encrypting with the new key.
1383 sync_pb::EncryptedData encrypted
;
1384 cryptographer
->GetKeys(&encrypted
);
1385 EXPECT_TRUE(other_cryptographer
.CanDecrypt(encrypted
));
1389 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1390 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1391 // the current GAIA password and verify the bootstrap token is updated. Then
1392 // supply the old GAIA password, and verify we re-encrypt all data with the
1393 // new GAIA password.
1394 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1395 TEST_F(SyncManagerTest
, SupplyPendingOldGAIAPass
) {
1396 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1397 Cryptographer
other_cryptographer(&encryptor_
);
1399 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1400 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1401 std::string bootstrap_token
;
1402 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1403 other_cryptographer
.Bootstrap(bootstrap_token
);
1405 // Now update the nigori to reflect the new keys, and update the
1406 // cryptographer to have pending keys.
1407 KeyParams params
= {"localhost", "dummy", "old_gaia"};
1408 other_cryptographer
.AddKey(params
);
1409 WriteNode
node(&trans
);
1410 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1411 sync_pb::NigoriSpecifics nigori
;
1412 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1413 node
.SetNigoriSpecifics(nigori
);
1414 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1416 // other_cryptographer now contains all encryption keys, and is encrypting
1417 // with the newest gaia.
1418 KeyParams new_params
= {"localhost", "dummy", "new_gaia"};
1419 other_cryptographer
.AddKey(new_params
);
1421 // The bootstrap token should have been updated. Save it to ensure it's based
1422 // on the new GAIA password.
1423 std::string bootstrap_token
;
1424 EXPECT_CALL(encryption_observer_
,
1425 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
))
1426 .WillOnce(SaveArg
<0>(&bootstrap_token
));
1427 EXPECT_CALL(encryption_observer_
, OnPassphraseRequired(_
,_
));
1428 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1429 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1432 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1433 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1434 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1435 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1437 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1438 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1439 EXPECT_TRUE(cryptographer
->is_initialized());
1440 EXPECT_FALSE(cryptographer
->is_ready());
1441 // Verify we're encrypting with the new key, even though we have pending
1443 sync_pb::EncryptedData encrypted
;
1444 other_cryptographer
.GetKeys(&encrypted
);
1445 EXPECT_TRUE(cryptographer
->CanDecrypt(encrypted
));
1447 EXPECT_CALL(encryption_observer_
,
1448 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1449 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1450 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1451 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1452 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1455 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1456 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1458 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1459 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1460 EXPECT_TRUE(cryptographer
->is_ready());
1462 // Verify we're encrypting with the new key.
1463 sync_pb::EncryptedData encrypted
;
1464 other_cryptographer
.GetKeys(&encrypted
);
1465 EXPECT_TRUE(cryptographer
->CanDecrypt(encrypted
));
1467 // Verify the saved bootstrap token is based on the new gaia password.
1468 Cryptographer
temp_cryptographer(&encryptor_
);
1469 temp_cryptographer
.Bootstrap(bootstrap_token
);
1470 EXPECT_TRUE(temp_cryptographer
.CanDecrypt(encrypted
));
1474 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1475 // being encrypted with an explicit (unprovided) passphrase, then supply the
1477 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1478 TEST_F(SyncManagerTest
, SupplyPendingExplicitPass
) {
1479 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1480 Cryptographer
other_cryptographer(&encryptor_
);
1482 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1483 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1484 std::string bootstrap_token
;
1485 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1486 other_cryptographer
.Bootstrap(bootstrap_token
);
1488 // Now update the nigori to reflect the new keys, and update the
1489 // cryptographer to have pending keys.
1490 KeyParams params
= {"localhost", "dummy", "explicit"};
1491 other_cryptographer
.AddKey(params
);
1492 WriteNode
node(&trans
);
1493 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1494 sync_pb::NigoriSpecifics nigori
;
1495 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1496 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1497 EXPECT_TRUE(cryptographer
->has_pending_keys());
1498 nigori
.set_keybag_is_frozen(true);
1499 node
.SetNigoriSpecifics(nigori
);
1501 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1502 EXPECT_CALL(encryption_observer_
,
1503 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1504 EXPECT_CALL(encryption_observer_
, OnPassphraseRequired(_
, _
));
1505 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
1506 sync_manager_
.GetEncryptionHandler()->Init();
1507 EXPECT_CALL(encryption_observer_
,
1508 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1509 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1510 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1511 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1512 sync_manager_
.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
1513 EXPECT_EQ(CUSTOM_PASSPHRASE
,
1514 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1515 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1517 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1518 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1519 EXPECT_TRUE(cryptographer
->is_ready());
1520 // Verify we're encrypting with the new key.
1521 sync_pb::EncryptedData encrypted
;
1522 cryptographer
->GetKeys(&encrypted
);
1523 EXPECT_TRUE(other_cryptographer
.CanDecrypt(encrypted
));
1527 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1528 // being encrypted with a new (unprovided) GAIA password, then supply the
1529 // password as a user-provided password.
1530 // This is the android case 7/8.
1531 TEST_F(SyncManagerTest
, SupplyPendingGAIAPassUserProvided
) {
1532 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI
, UNINITIALIZED
));
1533 Cryptographer
other_cryptographer(&encryptor_
);
1535 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1536 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1537 // Now update the nigori to reflect the new keys, and update the
1538 // cryptographer to have pending keys.
1539 KeyParams params
= {"localhost", "dummy", "passphrase"};
1540 other_cryptographer
.AddKey(params
);
1541 WriteNode
node(&trans
);
1542 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitTypeRoot(NIGORI
));
1543 sync_pb::NigoriSpecifics nigori
;
1544 other_cryptographer
.GetKeys(nigori
.mutable_encryption_keybag());
1545 node
.SetNigoriSpecifics(nigori
);
1546 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
1547 EXPECT_FALSE(cryptographer
->is_ready());
1549 EXPECT_CALL(encryption_observer_
,
1550 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1551 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1552 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1553 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1554 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1557 EXPECT_EQ(IMPLICIT_PASSPHRASE
,
1558 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1559 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1561 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1562 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1563 EXPECT_TRUE(cryptographer
->is_ready());
1567 TEST_F(SyncManagerTest
, SetPassphraseWithEmptyPasswordNode
) {
1568 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1570 std::string tag
= "foo";
1572 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1573 ReadNode
root_node(&trans
);
1574 root_node
.InitByRootLookup();
1576 WriteNode
password_node(&trans
);
1577 WriteNode::InitUniqueByCreationResult result
=
1578 password_node
.InitUniqueByCreation(PASSWORDS
, root_node
, tag
);
1579 EXPECT_EQ(WriteNode::INIT_SUCCESS
, result
);
1580 node_id
= password_node
.GetId();
1582 EXPECT_CALL(encryption_observer_
,
1583 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1584 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1585 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1586 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1587 EXPECT_CALL(encryption_observer_
,
1588 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1589 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1592 EXPECT_EQ(CUSTOM_PASSPHRASE
,
1593 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
1594 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1596 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1597 ReadNode
password_node(&trans
);
1598 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY
,
1599 password_node
.InitByClientTagLookup(PASSWORDS
,
1603 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1604 ReadNode
password_node(&trans
);
1605 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY
,
1606 password_node
.InitByIdLookup(node_id
));
1610 TEST_F(SyncManagerTest
, NudgeDelayTest
) {
1611 EXPECT_EQ(sync_manager_
.GetNudgeDelayTimeDelta(BOOKMARKS
),
1612 base::TimeDelta::FromMilliseconds(
1613 SyncManagerImpl::GetDefaultNudgeDelay()));
1615 EXPECT_EQ(sync_manager_
.GetNudgeDelayTimeDelta(AUTOFILL
),
1616 base::TimeDelta::FromSeconds(
1617 kDefaultShortPollIntervalSeconds
));
1619 EXPECT_EQ(sync_manager_
.GetNudgeDelayTimeDelta(PREFERENCES
),
1620 base::TimeDelta::FromMilliseconds(
1621 SyncManagerImpl::GetPreferencesNudgeDelay()));
1624 // Friended by WriteNode, so can't be in an anonymouse namespace.
1625 TEST_F(SyncManagerTest
, EncryptBookmarksWithLegacyData
) {
1626 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1628 SyncAPINameToServerName("Google", &title
);
1629 std::string url
= "http://www.google.com";
1630 std::string raw_title2
= ".."; // An invalid cosmo title.
1632 SyncAPINameToServerName(raw_title2
, &title2
);
1633 std::string url2
= "http://www.bla.com";
1635 // Create a bookmark using the legacy format.
1636 int64 node_id1
= MakeNode(sync_manager_
.GetUserShare(),
1639 int64 node_id2
= MakeNode(sync_manager_
.GetUserShare(),
1643 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1644 WriteNode
node(&trans
);
1645 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(node_id1
));
1647 sync_pb::EntitySpecifics entity_specifics
;
1648 entity_specifics
.mutable_bookmark()->set_url(url
);
1649 node
.SetEntitySpecifics(entity_specifics
);
1651 // Set the old style title.
1652 syncable::MutableEntry
* node_entry
= node
.entry_
;
1653 node_entry
->PutNonUniqueName(title
);
1655 WriteNode
node2(&trans
);
1656 EXPECT_EQ(BaseNode::INIT_OK
, node2
.InitByIdLookup(node_id2
));
1658 sync_pb::EntitySpecifics entity_specifics2
;
1659 entity_specifics2
.mutable_bookmark()->set_url(url2
);
1660 node2
.SetEntitySpecifics(entity_specifics2
);
1662 // Set the old style title.
1663 syncable::MutableEntry
* node_entry2
= node2
.entry_
;
1664 node_entry2
->PutNonUniqueName(title2
);
1668 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1669 ReadNode
node(&trans
);
1670 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(node_id1
));
1671 EXPECT_EQ(BOOKMARKS
, node
.GetModelType());
1672 EXPECT_EQ(title
, node
.GetTitle());
1673 EXPECT_EQ(title
, node
.GetBookmarkSpecifics().title());
1674 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
1676 ReadNode
node2(&trans
);
1677 EXPECT_EQ(BaseNode::INIT_OK
, node2
.InitByIdLookup(node_id2
));
1678 EXPECT_EQ(BOOKMARKS
, node2
.GetModelType());
1679 // We should de-canonicalize the title in GetTitle(), but the title in the
1680 // specifics should be stored in the server legal form.
1681 EXPECT_EQ(raw_title2
, node2
.GetTitle());
1682 EXPECT_EQ(title2
, node2
.GetBookmarkSpecifics().title());
1683 EXPECT_EQ(url2
, node2
.GetBookmarkSpecifics().url());
1687 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1688 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1689 trans
.GetWrappedTrans(),
1691 false /* not encrypted */));
1694 EXPECT_CALL(encryption_observer_
,
1695 OnEncryptedTypesChanged(
1696 HasModelTypes(EncryptableUserTypes()), true));
1697 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1698 sync_manager_
.GetEncryptionHandler()->EnableEncryptEverything();
1699 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1702 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1703 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans
).Equals(
1704 EncryptableUserTypes()));
1705 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1706 trans
.GetWrappedTrans(),
1708 true /* is encrypted */));
1710 ReadNode
node(&trans
);
1711 EXPECT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(node_id1
));
1712 EXPECT_EQ(BOOKMARKS
, node
.GetModelType());
1713 EXPECT_EQ(title
, node
.GetTitle());
1714 EXPECT_EQ(title
, node
.GetBookmarkSpecifics().title());
1715 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
1717 ReadNode
node2(&trans
);
1718 EXPECT_EQ(BaseNode::INIT_OK
, node2
.InitByIdLookup(node_id2
));
1719 EXPECT_EQ(BOOKMARKS
, node2
.GetModelType());
1720 // We should de-canonicalize the title in GetTitle(), but the title in the
1721 // specifics should be stored in the server legal form.
1722 EXPECT_EQ(raw_title2
, node2
.GetTitle());
1723 EXPECT_EQ(title2
, node2
.GetBookmarkSpecifics().title());
1724 EXPECT_EQ(url2
, node2
.GetBookmarkSpecifics().url());
1728 // Create a bookmark and set the title/url, then verify the data was properly
1729 // set. This replicates the unique way bookmarks have of creating sync nodes.
1730 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1731 TEST_F(SyncManagerTest
, CreateLocalBookmark
) {
1732 std::string title
= "title";
1733 std::string url
= "url";
1735 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1736 ReadNode
bookmark_root(&trans
);
1737 ASSERT_EQ(BaseNode::INIT_OK
, bookmark_root
.InitTypeRoot(BOOKMARKS
));
1738 WriteNode
node(&trans
);
1739 ASSERT_TRUE(node
.InitBookmarkByCreation(bookmark_root
, NULL
));
1740 node
.SetIsFolder(false);
1741 node
.SetTitle(title
);
1743 sync_pb::BookmarkSpecifics
bookmark_specifics(node
.GetBookmarkSpecifics());
1744 bookmark_specifics
.set_url(url
);
1745 node
.SetBookmarkSpecifics(bookmark_specifics
);
1748 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1749 ReadNode
bookmark_root(&trans
);
1750 ASSERT_EQ(BaseNode::INIT_OK
, bookmark_root
.InitTypeRoot(BOOKMARKS
));
1751 int64 child_id
= bookmark_root
.GetFirstChildId();
1753 ReadNode
node(&trans
);
1754 ASSERT_EQ(BaseNode::INIT_OK
, node
.InitByIdLookup(child_id
));
1755 EXPECT_FALSE(node
.GetIsFolder());
1756 EXPECT_EQ(title
, node
.GetTitle());
1757 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
1761 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1763 TEST_F(SyncManagerTest
, UpdateEntryWithEncryption
) {
1764 std::string client_tag
= "title";
1765 sync_pb::EntitySpecifics entity_specifics
;
1766 entity_specifics
.mutable_bookmark()->set_url("url");
1767 entity_specifics
.mutable_bookmark()->set_title("title");
1768 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
1769 syncable::GenerateSyncableHash(BOOKMARKS
,
1772 // New node shouldn't start off unsynced.
1773 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1774 // Manually change to the same data. Should not set is_unsynced.
1776 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1777 WriteNode
node(&trans
);
1778 EXPECT_EQ(BaseNode::INIT_OK
,
1779 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1780 node
.SetEntitySpecifics(entity_specifics
);
1782 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1784 // Encrypt the datatatype, should set is_unsynced.
1785 EXPECT_CALL(encryption_observer_
,
1786 OnEncryptedTypesChanged(
1787 HasModelTypes(EncryptableUserTypes()), true));
1788 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1789 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
1791 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1792 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
1793 sync_manager_
.GetEncryptionHandler()->Init();
1796 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1797 ReadNode
node(&trans
);
1798 EXPECT_EQ(BaseNode::INIT_OK
,
1799 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1800 const syncable::Entry
* node_entry
= node
.GetEntry();
1801 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1802 EXPECT_TRUE(specifics
.has_encrypted());
1803 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1804 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1805 EXPECT_TRUE(cryptographer
->is_ready());
1806 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1807 specifics
.encrypted()));
1809 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1811 // Set a new passphrase. Should set is_unsynced.
1812 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1813 EXPECT_CALL(encryption_observer_
,
1814 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
1815 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
1816 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1817 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1818 EXPECT_CALL(encryption_observer_
,
1819 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
1820 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
1824 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1825 ReadNode
node(&trans
);
1826 EXPECT_EQ(BaseNode::INIT_OK
,
1827 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1828 const syncable::Entry
* node_entry
= node
.GetEntry();
1829 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1830 EXPECT_TRUE(specifics
.has_encrypted());
1831 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1832 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1833 EXPECT_TRUE(cryptographer
->is_ready());
1834 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1835 specifics
.encrypted()));
1837 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1839 // Force a re-encrypt everything. Should not set is_unsynced.
1840 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
1841 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
1842 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
1843 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
1845 sync_manager_
.GetEncryptionHandler()->Init();
1849 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1850 ReadNode
node(&trans
);
1851 EXPECT_EQ(BaseNode::INIT_OK
,
1852 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
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_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1857 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1858 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1859 specifics
.encrypted()));
1861 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1863 // Manually change to the same data. Should not set is_unsynced.
1865 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1866 WriteNode
node(&trans
);
1867 EXPECT_EQ(BaseNode::INIT_OK
,
1868 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1869 node
.SetEntitySpecifics(entity_specifics
);
1870 const syncable::Entry
* node_entry
= node
.GetEntry();
1871 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1872 EXPECT_TRUE(specifics
.has_encrypted());
1873 EXPECT_FALSE(node_entry
->GetIsUnsynced());
1874 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1875 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1876 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1877 specifics
.encrypted()));
1879 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
1881 // Manually change to different data. Should set is_unsynced.
1883 entity_specifics
.mutable_bookmark()->set_url("url2");
1884 entity_specifics
.mutable_bookmark()->set_title("title2");
1885 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1886 WriteNode
node(&trans
);
1887 EXPECT_EQ(BaseNode::INIT_OK
,
1888 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
1889 node
.SetEntitySpecifics(entity_specifics
);
1890 const syncable::Entry
* node_entry
= node
.GetEntry();
1891 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
1892 EXPECT_TRUE(specifics
.has_encrypted());
1893 EXPECT_TRUE(node_entry
->GetIsUnsynced());
1894 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
1895 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1896 EXPECT_TRUE(cryptographer
->CanDecryptUsingDefaultKey(
1897 specifics
.encrypted()));
1901 // Passwords have their own handling for encryption. Verify it does not result
1902 // in unnecessary writes via SetEntitySpecifics.
1903 TEST_F(SyncManagerTest
, UpdatePasswordSetEntitySpecificsNoChange
) {
1904 std::string client_tag
= "title";
1905 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1906 sync_pb::EntitySpecifics entity_specifics
;
1908 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1909 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1910 sync_pb::PasswordSpecificsData data
;
1911 data
.set_password_value("secret");
1912 cryptographer
->Encrypt(
1914 entity_specifics
.mutable_password()->
1915 mutable_encrypted());
1917 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
1918 syncable::GenerateSyncableHash(PASSWORDS
,
1921 // New node shouldn't start off unsynced.
1922 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1924 // Manually change to the same data via SetEntitySpecifics. Should not set
1927 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1928 WriteNode
node(&trans
);
1929 EXPECT_EQ(BaseNode::INIT_OK
,
1930 node
.InitByClientTagLookup(PASSWORDS
, client_tag
));
1931 node
.SetEntitySpecifics(entity_specifics
);
1933 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1936 // Passwords have their own handling for encryption. Verify it does not result
1937 // in unnecessary writes via SetPasswordSpecifics.
1938 TEST_F(SyncManagerTest
, UpdatePasswordSetPasswordSpecifics
) {
1939 std::string client_tag
= "title";
1940 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1941 sync_pb::EntitySpecifics entity_specifics
;
1943 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1944 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1945 sync_pb::PasswordSpecificsData data
;
1946 data
.set_password_value("secret");
1947 cryptographer
->Encrypt(
1949 entity_specifics
.mutable_password()->
1950 mutable_encrypted());
1952 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
1953 syncable::GenerateSyncableHash(PASSWORDS
,
1956 // New node shouldn't start off unsynced.
1957 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1959 // Manually change to the same data via SetPasswordSpecifics. Should not set
1962 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1963 WriteNode
node(&trans
);
1964 EXPECT_EQ(BaseNode::INIT_OK
,
1965 node
.InitByClientTagLookup(PASSWORDS
, client_tag
));
1966 node
.SetPasswordSpecifics(node
.GetPasswordSpecifics());
1968 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
1970 // Manually change to different data. Should set is_unsynced.
1972 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1973 WriteNode
node(&trans
);
1974 EXPECT_EQ(BaseNode::INIT_OK
,
1975 node
.InitByClientTagLookup(PASSWORDS
, client_tag
));
1976 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1977 sync_pb::PasswordSpecificsData data
;
1978 data
.set_password_value("secret2");
1979 cryptographer
->Encrypt(
1981 entity_specifics
.mutable_password()->mutable_encrypted());
1982 node
.SetPasswordSpecifics(data
);
1983 const syncable::Entry
* node_entry
= node
.GetEntry();
1984 EXPECT_TRUE(node_entry
->GetIsUnsynced());
1988 // Passwords have their own handling for encryption. Verify setting a new
1989 // passphrase updates the data.
1990 TEST_F(SyncManagerTest
, UpdatePasswordNewPassphrase
) {
1991 std::string client_tag
= "title";
1992 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
1993 sync_pb::EntitySpecifics entity_specifics
;
1995 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
1996 Cryptographer
* cryptographer
= trans
.GetCryptographer();
1997 sync_pb::PasswordSpecificsData data
;
1998 data
.set_password_value("secret");
1999 cryptographer
->Encrypt(
2001 entity_specifics
.mutable_password()->mutable_encrypted());
2003 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
2004 syncable::GenerateSyncableHash(PASSWORDS
,
2007 // New node shouldn't start off unsynced.
2008 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2010 // Set a new passphrase. Should set is_unsynced.
2011 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
2012 EXPECT_CALL(encryption_observer_
,
2013 OnBootstrapTokenUpdated(_
, PASSPHRASE_BOOTSTRAP_TOKEN
));
2014 EXPECT_CALL(encryption_observer_
, OnPassphraseAccepted());
2015 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2016 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2017 EXPECT_CALL(encryption_observer_
,
2018 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE
, _
));
2019 sync_manager_
.GetEncryptionHandler()->SetEncryptionPassphrase(
2022 EXPECT_EQ(CUSTOM_PASSPHRASE
,
2023 sync_manager_
.GetEncryptionHandler()->GetPassphraseType());
2024 EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2027 // Passwords have their own handling for encryption. Verify it does not result
2028 // in unnecessary writes via ReencryptEverything.
2029 TEST_F(SyncManagerTest
, UpdatePasswordReencryptEverything
) {
2030 std::string client_tag
= "title";
2031 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
2032 sync_pb::EntitySpecifics entity_specifics
;
2034 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2035 Cryptographer
* cryptographer
= trans
.GetCryptographer();
2036 sync_pb::PasswordSpecificsData data
;
2037 data
.set_password_value("secret");
2038 cryptographer
->Encrypt(
2040 entity_specifics
.mutable_password()->mutable_encrypted());
2042 MakeServerNode(sync_manager_
.GetUserShare(), PASSWORDS
, client_tag
,
2043 syncable::GenerateSyncableHash(PASSWORDS
,
2046 // New node shouldn't start off unsynced.
2047 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2049 // Force a re-encrypt everything. Should not set is_unsynced.
2050 testing::Mock::VerifyAndClearExpectations(&encryption_observer_
);
2051 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2052 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2053 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, false));
2054 sync_manager_
.GetEncryptionHandler()->Init();
2056 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS
, client_tag
));
2059 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2060 // when we write the same data, but does set it when we write new data.
2061 TEST_F(SyncManagerTest
, SetBookmarkTitle
) {
2062 std::string client_tag
= "title";
2063 sync_pb::EntitySpecifics entity_specifics
;
2064 entity_specifics
.mutable_bookmark()->set_url("url");
2065 entity_specifics
.mutable_bookmark()->set_title("title");
2066 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2067 syncable::GenerateSyncableHash(BOOKMARKS
,
2070 // New node shouldn't start off unsynced.
2071 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2073 // Manually change to the same title. Should not set is_unsynced.
2075 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2076 WriteNode
node(&trans
);
2077 EXPECT_EQ(BaseNode::INIT_OK
,
2078 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2079 node
.SetTitle(client_tag
);
2081 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2083 // Manually change to new title. Should set is_unsynced.
2085 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2086 WriteNode
node(&trans
);
2087 EXPECT_EQ(BaseNode::INIT_OK
,
2088 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2089 node
.SetTitle("title2");
2091 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2094 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2095 // bookmarks when we write the same data, but does set it when we write new
2097 TEST_F(SyncManagerTest
, SetBookmarkTitleWithEncryption
) {
2098 std::string client_tag
= "title";
2099 sync_pb::EntitySpecifics entity_specifics
;
2100 entity_specifics
.mutable_bookmark()->set_url("url");
2101 entity_specifics
.mutable_bookmark()->set_title("title");
2102 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2103 syncable::GenerateSyncableHash(BOOKMARKS
,
2106 // New node shouldn't start off unsynced.
2107 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2109 // Encrypt the datatatype, should set is_unsynced.
2110 EXPECT_CALL(encryption_observer_
,
2111 OnEncryptedTypesChanged(
2112 HasModelTypes(EncryptableUserTypes()), true));
2113 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2114 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
2115 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2116 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
2117 sync_manager_
.GetEncryptionHandler()->Init();
2119 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2121 // Manually change to the same title. Should not set is_unsynced.
2122 // NON_UNIQUE_NAME should be kEncryptedString.
2124 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2125 WriteNode
node(&trans
);
2126 EXPECT_EQ(BaseNode::INIT_OK
,
2127 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2128 node
.SetTitle(client_tag
);
2129 const syncable::Entry
* node_entry
= node
.GetEntry();
2130 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2131 EXPECT_TRUE(specifics
.has_encrypted());
2132 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2134 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2136 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2137 // should still be kEncryptedString.
2139 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2140 WriteNode
node(&trans
);
2141 EXPECT_EQ(BaseNode::INIT_OK
,
2142 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2143 node
.SetTitle("title2");
2144 const syncable::Entry
* node_entry
= node
.GetEntry();
2145 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2146 EXPECT_TRUE(specifics
.has_encrypted());
2147 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2149 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS
, client_tag
));
2152 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2153 // when we write the same data, but does set it when we write new data.
2154 TEST_F(SyncManagerTest
, SetNonBookmarkTitle
) {
2155 std::string client_tag
= "title";
2156 sync_pb::EntitySpecifics entity_specifics
;
2157 entity_specifics
.mutable_preference()->set_name("name");
2158 entity_specifics
.mutable_preference()->set_value("value");
2159 MakeServerNode(sync_manager_
.GetUserShare(),
2162 syncable::GenerateSyncableHash(PREFERENCES
,
2165 // New node shouldn't start off unsynced.
2166 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2168 // Manually change to the same title. Should not set is_unsynced.
2170 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2171 WriteNode
node(&trans
);
2172 EXPECT_EQ(BaseNode::INIT_OK
,
2173 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2174 node
.SetTitle(client_tag
);
2176 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2178 // Manually change to new title. Should set is_unsynced.
2180 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2181 WriteNode
node(&trans
);
2182 EXPECT_EQ(BaseNode::INIT_OK
,
2183 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2184 node
.SetTitle("title2");
2186 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2189 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2190 // non-bookmarks when we write the same data or when we write new data
2191 // data (should remained kEncryptedString).
2192 TEST_F(SyncManagerTest
, SetNonBookmarkTitleWithEncryption
) {
2193 std::string client_tag
= "title";
2194 sync_pb::EntitySpecifics entity_specifics
;
2195 entity_specifics
.mutable_preference()->set_name("name");
2196 entity_specifics
.mutable_preference()->set_value("value");
2197 MakeServerNode(sync_manager_
.GetUserShare(),
2200 syncable::GenerateSyncableHash(PREFERENCES
,
2203 // New node shouldn't start off unsynced.
2204 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2206 // Encrypt the datatatype, should set is_unsynced.
2207 EXPECT_CALL(encryption_observer_
,
2208 OnEncryptedTypesChanged(
2209 HasModelTypes(EncryptableUserTypes()), true));
2210 EXPECT_CALL(encryption_observer_
, OnEncryptionComplete());
2211 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, FULL_ENCRYPTION
));
2212 EXPECT_CALL(encryption_observer_
, OnCryptographerStateChanged(_
));
2213 EXPECT_CALL(encryption_observer_
, OnEncryptedTypesChanged(_
, true));
2214 sync_manager_
.GetEncryptionHandler()->Init();
2216 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2218 // Manually change to the same title. Should not set is_unsynced.
2219 // NON_UNIQUE_NAME should be kEncryptedString.
2221 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2222 WriteNode
node(&trans
);
2223 EXPECT_EQ(BaseNode::INIT_OK
,
2224 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2225 node
.SetTitle(client_tag
);
2226 const syncable::Entry
* node_entry
= node
.GetEntry();
2227 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2228 EXPECT_TRUE(specifics
.has_encrypted());
2229 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2231 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, client_tag
));
2233 // Manually change to new title. Should not set is_unsynced because the
2234 // NON_UNIQUE_NAME should still be kEncryptedString.
2236 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2237 WriteNode
node(&trans
);
2238 EXPECT_EQ(BaseNode::INIT_OK
,
2239 node
.InitByClientTagLookup(PREFERENCES
, client_tag
));
2240 node
.SetTitle("title2");
2241 const syncable::Entry
* node_entry
= node
.GetEntry();
2242 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2243 EXPECT_TRUE(specifics
.has_encrypted());
2244 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2245 EXPECT_FALSE(node_entry
->GetIsUnsynced());
2249 // Ensure that titles are truncated to 255 bytes, and attempting to reset
2250 // them to their longer version does not set IS_UNSYNCED.
2251 TEST_F(SyncManagerTest
, SetLongTitle
) {
2252 const int kNumChars
= 512;
2253 const std::string kClientTag
= "tag";
2254 std::string
title(kNumChars
, '0');
2255 sync_pb::EntitySpecifics entity_specifics
;
2256 entity_specifics
.mutable_preference()->set_name("name");
2257 entity_specifics
.mutable_preference()->set_value("value");
2258 MakeServerNode(sync_manager_
.GetUserShare(),
2261 syncable::GenerateSyncableHash(PREFERENCES
,
2264 // New node shouldn't start off unsynced.
2265 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2267 // Manually change to the long title. Should set is_unsynced.
2269 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2270 WriteNode
node(&trans
);
2271 EXPECT_EQ(BaseNode::INIT_OK
,
2272 node
.InitByClientTagLookup(PREFERENCES
, kClientTag
));
2273 node
.SetTitle(title
);
2274 EXPECT_EQ(node
.GetTitle(), title
.substr(0, 255));
2276 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2278 // Manually change to the same title. Should not set is_unsynced.
2280 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2281 WriteNode
node(&trans
);
2282 EXPECT_EQ(BaseNode::INIT_OK
,
2283 node
.InitByClientTagLookup(PREFERENCES
, kClientTag
));
2284 node
.SetTitle(title
);
2285 EXPECT_EQ(node
.GetTitle(), title
.substr(0, 255));
2287 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2289 // Manually change to new title. Should set is_unsynced.
2291 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2292 WriteNode
node(&trans
);
2293 EXPECT_EQ(BaseNode::INIT_OK
,
2294 node
.InitByClientTagLookup(PREFERENCES
, kClientTag
));
2295 node
.SetTitle("title2");
2297 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES
, kClientTag
));
2300 // Create an encrypted entry when the cryptographer doesn't think the type is
2301 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2303 TEST_F(SyncManagerTest
, SetPreviouslyEncryptedSpecifics
) {
2304 std::string client_tag
= "tag";
2305 std::string url
= "url";
2306 std::string url2
= "new_url";
2307 std::string title
= "title";
2308 sync_pb::EntitySpecifics entity_specifics
;
2309 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI
, DEFAULT_ENCRYPTION
));
2311 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2312 Cryptographer
* crypto
= trans
.GetCryptographer();
2313 sync_pb::EntitySpecifics bm_specifics
;
2314 bm_specifics
.mutable_bookmark()->set_title("title");
2315 bm_specifics
.mutable_bookmark()->set_url("url");
2316 sync_pb::EncryptedData encrypted
;
2317 crypto
->Encrypt(bm_specifics
, &encrypted
);
2318 entity_specifics
.mutable_encrypted()->CopyFrom(encrypted
);
2319 AddDefaultFieldValue(BOOKMARKS
, &entity_specifics
);
2321 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2322 syncable::GenerateSyncableHash(BOOKMARKS
,
2328 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2329 ReadNode
node(&trans
);
2330 EXPECT_EQ(BaseNode::INIT_OK
,
2331 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2332 EXPECT_EQ(title
, node
.GetTitle());
2333 EXPECT_EQ(url
, node
.GetBookmarkSpecifics().url());
2337 // Overwrite the url (which overwrites the specifics).
2338 WriteTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2339 WriteNode
node(&trans
);
2340 EXPECT_EQ(BaseNode::INIT_OK
,
2341 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2343 sync_pb::BookmarkSpecifics
bookmark_specifics(node
.GetBookmarkSpecifics());
2344 bookmark_specifics
.set_url(url2
);
2345 node
.SetBookmarkSpecifics(bookmark_specifics
);
2349 // Verify it's still encrypted and it has the most recent url.
2350 ReadTransaction
trans(FROM_HERE
, sync_manager_
.GetUserShare());
2351 ReadNode
node(&trans
);
2352 EXPECT_EQ(BaseNode::INIT_OK
,
2353 node
.InitByClientTagLookup(BOOKMARKS
, client_tag
));
2354 EXPECT_EQ(title
, node
.GetTitle());
2355 EXPECT_EQ(url2
, node
.GetBookmarkSpecifics().url());
2356 const syncable::Entry
* node_entry
= node
.GetEntry();
2357 EXPECT_EQ(kEncryptedString
, node_entry
->GetNonUniqueName());
2358 const sync_pb::EntitySpecifics
& specifics
= node_entry
->GetSpecifics();
2359 EXPECT_TRUE(specifics
.has_encrypted());
2363 // Verify transaction version of a model type is incremented when node of
2364 // that type is updated.
2365 TEST_F(SyncManagerTest
, IncrementTransactionVersion
) {
2366 ModelSafeRoutingInfo routing_info
;
2367 GetModelSafeRoutingInfo(&routing_info
);
2370 ReadTransaction
read_trans(FROM_HERE
, sync_manager_
.GetUserShare());
2371 for (ModelSafeRoutingInfo::iterator i
= routing_info
.begin();
2372 i
!= routing_info
.end(); ++i
) {
2373 // Transaction version is incremented when SyncManagerTest::SetUp()
2374 // creates a node of each type.
2376 sync_manager_
.GetUserShare()->directory
->
2377 GetTransactionVersion(i
->first
));
2381 // Create bookmark node to increment transaction version of bookmark model.
2382 std::string client_tag
= "title";
2383 sync_pb::EntitySpecifics entity_specifics
;
2384 entity_specifics
.mutable_bookmark()->set_url("url");
2385 entity_specifics
.mutable_bookmark()->set_title("title");
2386 MakeServerNode(sync_manager_
.GetUserShare(), BOOKMARKS
, client_tag
,
2387 syncable::GenerateSyncableHash(BOOKMARKS
,
2392 ReadTransaction
read_trans(FROM_HERE
, sync_manager_
.GetUserShare());
2393 for (ModelSafeRoutingInfo::iterator i
= routing_info
.begin();
2394 i
!= routing_info
.end(); ++i
) {
2395 EXPECT_EQ(i
->first
== BOOKMARKS
? 2 : 1,
2396 sync_manager_
.GetUserShare()->directory
->
2397 GetTransactionVersion(i
->first
));
2402 class MockSyncScheduler
: public FakeSyncScheduler
{
2404 MockSyncScheduler() : FakeSyncScheduler() {}
2405 virtual ~MockSyncScheduler() {}
2407 MOCK_METHOD1(Start
, void(SyncScheduler::Mode
));
2408 MOCK_METHOD1(ScheduleConfiguration
, void(const ConfigurationParams
&));
2411 class ComponentsFactory
: public TestInternalComponentsFactory
{
2413 ComponentsFactory(const Switches
& switches
,
2414 SyncScheduler
* scheduler_to_use
,
2415 sessions::SyncSessionContext
** session_context
)
2416 : TestInternalComponentsFactory(switches
, syncer::STORAGE_IN_MEMORY
),
2417 scheduler_to_use_(scheduler_to_use
),
2418 session_context_(session_context
) {}
2419 virtual ~ComponentsFactory() {}
2421 virtual scoped_ptr
<SyncScheduler
> BuildScheduler(
2422 const std::string
& name
,
2423 sessions::SyncSessionContext
* context
,
2424 CancelationSignal
* stop_handle
) OVERRIDE
{
2425 *session_context_
= context
;
2426 return scheduler_to_use_
.Pass();
2430 scoped_ptr
<SyncScheduler
> scheduler_to_use_
;
2431 sessions::SyncSessionContext
** session_context_
;
2434 class SyncManagerTestWithMockScheduler
: public SyncManagerTest
{
2436 SyncManagerTestWithMockScheduler() : scheduler_(NULL
) {}
2437 virtual InternalComponentsFactory
* GetFactory() OVERRIDE
{
2438 scheduler_
= new MockSyncScheduler();
2439 return new ComponentsFactory(GetSwitches(), scheduler_
, &session_context_
);
2442 MockSyncScheduler
* scheduler() { return scheduler_
; }
2443 sessions::SyncSessionContext
* session_context() {
2444 return session_context_
;
2448 MockSyncScheduler
* scheduler_
;
2449 sessions::SyncSessionContext
* session_context_
;
2452 // Test that the configuration params are properly created and sent to
2453 // ScheduleConfigure. No callback should be invoked. Any disabled datatypes
2454 // should be purged.
2455 TEST_F(SyncManagerTestWithMockScheduler
, BasicConfiguration
) {
2456 ConfigureReason reason
= CONFIGURE_REASON_RECONFIGURATION
;
2457 ModelTypeSet
types_to_download(BOOKMARKS
, PREFERENCES
);
2458 ModelSafeRoutingInfo new_routing_info
;
2459 GetModelSafeRoutingInfo(&new_routing_info
);
2460 ModelTypeSet enabled_types
= GetRoutingInfoTypes(new_routing_info
);
2461 ModelTypeSet disabled_types
= Difference(ModelTypeSet::All(), enabled_types
);
2463 ConfigurationParams params
;
2464 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE
));
2465 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_
)).
2466 WillOnce(SaveArg
<0>(¶ms
));
2468 // Set data for all types.
2469 ModelTypeSet protocol_types
= ProtocolTypes();
2470 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2472 SetProgressMarkerForType(iter
.Get(), true);
2475 CallbackCounter ready_task_counter
, retry_task_counter
;
2476 sync_manager_
.ConfigureSyncer(
2483 base::Bind(&CallbackCounter::Callback
,
2484 base::Unretained(&ready_task_counter
)),
2485 base::Bind(&CallbackCounter::Callback
,
2486 base::Unretained(&retry_task_counter
)));
2487 EXPECT_EQ(0, ready_task_counter
.times_called());
2488 EXPECT_EQ(0, retry_task_counter
.times_called());
2489 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION
,
2491 EXPECT_TRUE(types_to_download
.Equals(params
.types_to_download
));
2492 EXPECT_EQ(new_routing_info
, params
.routing_info
);
2494 // Verify all the disabled types were purged.
2495 EXPECT_TRUE(sync_manager_
.InitialSyncEndedTypes().Equals(
2497 EXPECT_TRUE(sync_manager_
.GetTypesWithEmptyProgressMarkerToken(
2498 ModelTypeSet::All()).Equals(disabled_types
));
2501 // Test that on a reconfiguration (configuration where the session context
2502 // already has routing info), only those recently disabled types are purged.
2503 TEST_F(SyncManagerTestWithMockScheduler
, ReConfiguration
) {
2504 ConfigureReason reason
= CONFIGURE_REASON_RECONFIGURATION
;
2505 ModelTypeSet
types_to_download(BOOKMARKS
, PREFERENCES
);
2506 ModelTypeSet disabled_types
= ModelTypeSet(THEMES
, SESSIONS
);
2507 ModelSafeRoutingInfo old_routing_info
;
2508 ModelSafeRoutingInfo new_routing_info
;
2509 GetModelSafeRoutingInfo(&old_routing_info
);
2510 new_routing_info
= old_routing_info
;
2511 new_routing_info
.erase(THEMES
);
2512 new_routing_info
.erase(SESSIONS
);
2513 ModelTypeSet enabled_types
= GetRoutingInfoTypes(new_routing_info
);
2515 ConfigurationParams params
;
2516 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE
));
2517 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_
)).
2518 WillOnce(SaveArg
<0>(¶ms
));
2520 // Set data for all types except those recently disabled (so we can verify
2521 // only those recently disabled are purged) .
2522 ModelTypeSet protocol_types
= ProtocolTypes();
2523 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2525 if (!disabled_types
.Has(iter
.Get())) {
2526 SetProgressMarkerForType(iter
.Get(), true);
2528 SetProgressMarkerForType(iter
.Get(), false);
2532 // Set the context to have the old routing info.
2533 session_context()->SetRoutingInfo(old_routing_info
);
2535 CallbackCounter ready_task_counter
, retry_task_counter
;
2536 sync_manager_
.ConfigureSyncer(
2543 base::Bind(&CallbackCounter::Callback
,
2544 base::Unretained(&ready_task_counter
)),
2545 base::Bind(&CallbackCounter::Callback
,
2546 base::Unretained(&retry_task_counter
)));
2547 EXPECT_EQ(0, ready_task_counter
.times_called());
2548 EXPECT_EQ(0, retry_task_counter
.times_called());
2549 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION
,
2551 EXPECT_TRUE(types_to_download
.Equals(params
.types_to_download
));
2552 EXPECT_EQ(new_routing_info
, params
.routing_info
);
2554 // Verify only the recently disabled types were purged.
2555 EXPECT_TRUE(sync_manager_
.GetTypesWithEmptyProgressMarkerToken(
2556 ProtocolTypes()).Equals(disabled_types
));
2559 // Test that PurgePartiallySyncedTypes purges only those types that have not
2560 // fully completed their initial download and apply.
2561 TEST_F(SyncManagerTest
, PurgePartiallySyncedTypes
) {
2562 ModelSafeRoutingInfo routing_info
;
2563 GetModelSafeRoutingInfo(&routing_info
);
2564 ModelTypeSet enabled_types
= GetRoutingInfoTypes(routing_info
);
2566 UserShare
* share
= sync_manager_
.GetUserShare();
2568 // The test harness automatically initializes all types in the routing info.
2569 // Check that autofill is not among them.
2570 ASSERT_FALSE(enabled_types
.Has(AUTOFILL
));
2572 // Further ensure that the test harness did not create its root node.
2574 syncable::ReadTransaction
trans(FROM_HERE
, share
->directory
.get());
2575 syncable::Entry
autofill_root_node(&trans
,
2576 syncable::GET_TYPE_ROOT
,
2578 ASSERT_FALSE(autofill_root_node
.good());
2581 // One more redundant check.
2582 ASSERT_FALSE(sync_manager_
.InitialSyncEndedTypes().Has(AUTOFILL
));
2584 // Give autofill a progress marker.
2585 sync_pb::DataTypeProgressMarker autofill_marker
;
2586 autofill_marker
.set_data_type_id(
2587 GetSpecificsFieldNumberFromModelType(AUTOFILL
));
2588 autofill_marker
.set_token("token");
2589 share
->directory
->SetDownloadProgress(AUTOFILL
, autofill_marker
);
2591 // Also add a pending autofill root node update from the server.
2592 TestEntryFactory
factory_(share
->directory
.get());
2593 int autofill_meta
= factory_
.CreateUnappliedRootNode(AUTOFILL
);
2595 // Preferences is an enabled type. Check that the harness initialized it.
2596 ASSERT_TRUE(enabled_types
.Has(PREFERENCES
));
2597 ASSERT_TRUE(sync_manager_
.InitialSyncEndedTypes().Has(PREFERENCES
));
2599 // Give preferencse a progress marker.
2600 sync_pb::DataTypeProgressMarker prefs_marker
;
2601 prefs_marker
.set_data_type_id(
2602 GetSpecificsFieldNumberFromModelType(PREFERENCES
));
2603 prefs_marker
.set_token("token");
2604 share
->directory
->SetDownloadProgress(PREFERENCES
, prefs_marker
);
2606 // Add a fully synced preferences node under the root.
2607 std::string pref_client_tag
= "prefABC";
2608 std::string pref_hashed_tag
= "hashXYZ";
2609 sync_pb::EntitySpecifics pref_specifics
;
2610 AddDefaultFieldValue(PREFERENCES
, &pref_specifics
);
2611 int pref_meta
= MakeServerNode(
2612 share
, PREFERENCES
, pref_client_tag
, pref_hashed_tag
, pref_specifics
);
2614 // And now, the purge.
2615 EXPECT_TRUE(sync_manager_
.PurgePartiallySyncedTypes());
2617 // Ensure that autofill lost its progress marker, but preferences did not.
2618 ModelTypeSet empty_tokens
=
2619 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
2620 EXPECT_TRUE(empty_tokens
.Has(AUTOFILL
));
2621 EXPECT_FALSE(empty_tokens
.Has(PREFERENCES
));
2623 // Ensure that autofill lots its node, but preferences did not.
2625 syncable::ReadTransaction
trans(FROM_HERE
, share
->directory
.get());
2626 syncable::Entry
autofill_node(&trans
, GET_BY_HANDLE
, autofill_meta
);
2627 syncable::Entry
pref_node(&trans
, GET_BY_HANDLE
, pref_meta
);
2628 EXPECT_FALSE(autofill_node
.good());
2629 EXPECT_TRUE(pref_node
.good());
2633 // Test CleanupDisabledTypes properly purges all disabled types as specified
2634 // by the previous and current enabled params.
2635 TEST_F(SyncManagerTest
, PurgeDisabledTypes
) {
2636 ModelSafeRoutingInfo routing_info
;
2637 GetModelSafeRoutingInfo(&routing_info
);
2638 ModelTypeSet enabled_types
= GetRoutingInfoTypes(routing_info
);
2639 ModelTypeSet disabled_types
= Difference(ModelTypeSet::All(), enabled_types
);
2641 // The harness should have initialized the enabled_types for us.
2642 EXPECT_TRUE(enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2644 // Set progress markers for all types.
2645 ModelTypeSet protocol_types
= ProtocolTypes();
2646 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2648 SetProgressMarkerForType(iter
.Get(), true);
2651 // Verify all the enabled types remain after cleanup, and all the disabled
2652 // types were purged.
2653 sync_manager_
.PurgeDisabledTypes(disabled_types
,
2656 EXPECT_TRUE(enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2657 EXPECT_TRUE(disabled_types
.Equals(
2658 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2660 // Disable some more types.
2661 disabled_types
.Put(BOOKMARKS
);
2662 disabled_types
.Put(PREFERENCES
);
2663 ModelTypeSet new_enabled_types
=
2664 Difference(ModelTypeSet::All(), disabled_types
);
2666 // Verify only the non-disabled types remain after cleanup.
2667 sync_manager_
.PurgeDisabledTypes(disabled_types
,
2670 EXPECT_TRUE(new_enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2671 EXPECT_TRUE(disabled_types
.Equals(
2672 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2675 // Test PurgeDisabledTypes properly unapplies types by deleting their local data
2676 // and preserving their server data and progress marker.
2677 TEST_F(SyncManagerTest
, PurgeUnappliedTypes
) {
2678 ModelSafeRoutingInfo routing_info
;
2679 GetModelSafeRoutingInfo(&routing_info
);
2680 ModelTypeSet unapplied_types
= ModelTypeSet(BOOKMARKS
, PREFERENCES
);
2681 ModelTypeSet enabled_types
= GetRoutingInfoTypes(routing_info
);
2682 ModelTypeSet disabled_types
= Difference(ModelTypeSet::All(), enabled_types
);
2684 // The harness should have initialized the enabled_types for us.
2685 EXPECT_TRUE(enabled_types
.Equals(sync_manager_
.InitialSyncEndedTypes()));
2687 // Set progress markers for all types.
2688 ModelTypeSet protocol_types
= ProtocolTypes();
2689 for (ModelTypeSet::Iterator iter
= protocol_types
.First(); iter
.Good();
2691 SetProgressMarkerForType(iter
.Get(), true);
2694 // Add the following kinds of items:
2695 // 1. Fully synced preference.
2696 // 2. Locally created preference, server unknown, unsynced
2697 // 3. Locally deleted preference, server known, unsynced
2698 // 4. Server deleted preference, locally known.
2699 // 5. Server created preference, locally unknown, unapplied.
2700 // 6. A fully synced bookmark (no unique_client_tag).
2701 UserShare
* share
= sync_manager_
.GetUserShare();
2702 sync_pb::EntitySpecifics pref_specifics
;
2703 AddDefaultFieldValue(PREFERENCES
, &pref_specifics
);
2704 sync_pb::EntitySpecifics bm_specifics
;
2705 AddDefaultFieldValue(BOOKMARKS
, &bm_specifics
);
2706 int pref1_meta
= MakeServerNode(
2707 share
, PREFERENCES
, "pref1", "hash1", pref_specifics
);
2708 int64 pref2_meta
= MakeNode(share
, PREFERENCES
, "pref2");
2709 int pref3_meta
= MakeServerNode(
2710 share
, PREFERENCES
, "pref3", "hash3", pref_specifics
);
2711 int pref4_meta
= MakeServerNode(
2712 share
, PREFERENCES
, "pref4", "hash4", pref_specifics
);
2713 int pref5_meta
= MakeServerNode(
2714 share
, PREFERENCES
, "pref5", "hash5", pref_specifics
);
2715 int bookmark_meta
= MakeServerNode(
2716 share
, BOOKMARKS
, "bookmark", "", bm_specifics
);
2719 syncable::WriteTransaction
trans(FROM_HERE
,
2721 share
->directory
.get());
2722 // Pref's 1 and 2 are already set up properly.
2723 // Locally delete pref 3.
2724 syncable::MutableEntry
pref3(&trans
, GET_BY_HANDLE
, pref3_meta
);
2725 pref3
.PutIsDel(true);
2726 pref3
.PutIsUnsynced(true);
2727 // Delete pref 4 at the server.
2728 syncable::MutableEntry
pref4(&trans
, GET_BY_HANDLE
, pref4_meta
);
2729 pref4
.PutServerIsDel(true);
2730 pref4
.PutIsUnappliedUpdate(true);
2731 pref4
.PutServerVersion(2);
2732 // Pref 5 is an new unapplied update.
2733 syncable::MutableEntry
pref5(&trans
, GET_BY_HANDLE
, pref5_meta
);
2734 pref5
.PutIsUnappliedUpdate(true);
2735 pref5
.PutIsDel(true);
2736 pref5
.PutBaseVersion(-1);
2737 // Bookmark is already set up properly
2740 // Take a snapshot to clear all the dirty bits.
2741 share
->directory
.get()->SaveChanges();
2743 // Now request a purge for the unapplied types.
2744 disabled_types
.PutAll(unapplied_types
);
2745 sync_manager_
.PurgeDisabledTypes(disabled_types
,
2749 // Verify the unapplied types still have progress markers and initial sync
2750 // ended after cleanup.
2751 EXPECT_TRUE(sync_manager_
.InitialSyncEndedTypes().HasAll(unapplied_types
));
2753 sync_manager_
.GetTypesWithEmptyProgressMarkerToken(unapplied_types
).
2756 // Ensure the items were unapplied as necessary.
2758 syncable::ReadTransaction
trans(FROM_HERE
, share
->directory
.get());
2759 syncable::Entry
pref_node(&trans
, GET_BY_HANDLE
, pref1_meta
);
2760 ASSERT_TRUE(pref_node
.good());
2761 EXPECT_TRUE(pref_node
.GetKernelCopy().is_dirty());
2762 EXPECT_FALSE(pref_node
.GetIsUnsynced());
2763 EXPECT_TRUE(pref_node
.GetIsUnappliedUpdate());
2764 EXPECT_TRUE(pref_node
.GetIsDel());
2765 EXPECT_GT(pref_node
.GetServerVersion(), 0);
2766 EXPECT_EQ(pref_node
.GetBaseVersion(), -1);
2768 // Pref 2 should just be locally deleted.
2769 syncable::Entry
pref2_node(&trans
, GET_BY_HANDLE
, pref2_meta
);
2770 ASSERT_TRUE(pref2_node
.good());
2771 EXPECT_TRUE(pref2_node
.GetKernelCopy().is_dirty());
2772 EXPECT_FALSE(pref2_node
.GetIsUnsynced());
2773 EXPECT_TRUE(pref2_node
.GetIsDel());
2774 EXPECT_FALSE(pref2_node
.GetIsUnappliedUpdate());
2775 EXPECT_TRUE(pref2_node
.GetIsDel());
2776 EXPECT_EQ(pref2_node
.GetServerVersion(), 0);
2777 EXPECT_EQ(pref2_node
.GetBaseVersion(), -1);
2779 syncable::Entry
pref3_node(&trans
, GET_BY_HANDLE
, pref3_meta
);
2780 ASSERT_TRUE(pref3_node
.good());
2781 EXPECT_TRUE(pref3_node
.GetKernelCopy().is_dirty());
2782 EXPECT_FALSE(pref3_node
.GetIsUnsynced());
2783 EXPECT_TRUE(pref3_node
.GetIsUnappliedUpdate());
2784 EXPECT_TRUE(pref3_node
.GetIsDel());
2785 EXPECT_GT(pref3_node
.GetServerVersion(), 0);
2786 EXPECT_EQ(pref3_node
.GetBaseVersion(), -1);
2788 syncable::Entry
pref4_node(&trans
, GET_BY_HANDLE
, pref4_meta
);
2789 ASSERT_TRUE(pref4_node
.good());
2790 EXPECT_TRUE(pref4_node
.GetKernelCopy().is_dirty());
2791 EXPECT_FALSE(pref4_node
.GetIsUnsynced());
2792 EXPECT_TRUE(pref4_node
.GetIsUnappliedUpdate());
2793 EXPECT_TRUE(pref4_node
.GetIsDel());
2794 EXPECT_GT(pref4_node
.GetServerVersion(), 0);
2795 EXPECT_EQ(pref4_node
.GetBaseVersion(), -1);
2797 // Pref 5 should remain untouched.
2798 syncable::Entry
pref5_node(&trans
, GET_BY_HANDLE
, pref5_meta
);
2799 ASSERT_TRUE(pref5_node
.good());
2800 EXPECT_FALSE(pref5_node
.GetKernelCopy().is_dirty());
2801 EXPECT_FALSE(pref5_node
.GetIsUnsynced());
2802 EXPECT_TRUE(pref5_node
.GetIsUnappliedUpdate());
2803 EXPECT_TRUE(pref5_node
.GetIsDel());
2804 EXPECT_GT(pref5_node
.GetServerVersion(), 0);
2805 EXPECT_EQ(pref5_node
.GetBaseVersion(), -1);
2807 syncable::Entry
bookmark_node(&trans
, GET_BY_HANDLE
, bookmark_meta
);
2808 ASSERT_TRUE(bookmark_node
.good());
2809 EXPECT_TRUE(bookmark_node
.GetKernelCopy().is_dirty());
2810 EXPECT_FALSE(bookmark_node
.GetIsUnsynced());
2811 EXPECT_TRUE(bookmark_node
.GetIsUnappliedUpdate());
2812 EXPECT_TRUE(bookmark_node
.GetIsDel());
2813 EXPECT_GT(bookmark_node
.GetServerVersion(), 0);
2814 EXPECT_EQ(bookmark_node
.GetBaseVersion(), -1);
2818 // A test harness to exercise the code that processes and passes changes from
2819 // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
2821 class SyncManagerChangeProcessingTest
: public SyncManagerTest
{
2823 virtual void OnChangesApplied(
2824 ModelType model_type
,
2825 int64 model_version
,
2826 const BaseTransaction
* trans
,
2827 const ImmutableChangeRecordList
& changes
) OVERRIDE
{
2828 last_changes_
= changes
;
2831 virtual void OnChangesComplete(ModelType model_type
) OVERRIDE
{}
2833 const ImmutableChangeRecordList
& GetRecentChangeList() {
2834 return last_changes_
;
2837 UserShare
* share() {
2838 return sync_manager_
.GetUserShare();
2841 // Set some flags so our nodes reasonably approximate the real world scenario
2842 // and can get past CheckTreeInvariants.
2844 // It's never going to be truly accurate, since we're squashing update
2845 // receipt, processing and application into a single transaction.
2846 void SetNodeProperties(syncable::MutableEntry
*entry
) {
2847 entry
->PutId(id_factory_
.NewServerId());
2848 entry
->PutBaseVersion(10);
2849 entry
->PutServerVersion(10);
2852 // Looks for the given change in the list. Returns the index at which it was
2853 // found. Returns -1 on lookup failure.
2854 size_t FindChangeInList(int64 id
, ChangeRecord::Action action
) {
2856 for (size_t i
= 0; i
< last_changes_
.Get().size(); ++i
) {
2857 if (last_changes_
.Get()[i
].id
== id
2858 && last_changes_
.Get()[i
].action
== action
) {
2862 ADD_FAILURE() << "Failed to find specified change";
2866 // Returns the current size of the change list.
2868 // Note that spurious changes do not necessarily indicate a problem.
2869 // Assertions on change list size can help detect problems, but it may be
2870 // necessary to reduce their strictness if the implementation changes.
2871 size_t GetChangeListSize() {
2872 return last_changes_
.Get().size();
2876 ImmutableChangeRecordList last_changes_
;
2877 TestIdFactory id_factory_
;
2880 // Test creation of a folder and a bookmark.
2881 TEST_F(SyncManagerChangeProcessingTest
, AddBookmarks
) {
2882 int64 type_root
= GetIdForDataType(BOOKMARKS
);
2883 int64 folder_id
= kInvalidId
;
2884 int64 child_id
= kInvalidId
;
2886 // Create a folder and a bookmark under it.
2888 syncable::WriteTransaction
trans(
2889 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
2890 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
2891 ASSERT_TRUE(root
.good());
2893 syncable::MutableEntry
folder(&trans
, syncable::CREATE
,
2894 BOOKMARKS
, root
.GetId(), "folder");
2895 ASSERT_TRUE(folder
.good());
2896 SetNodeProperties(&folder
);
2897 folder
.PutIsDir(true);
2898 folder_id
= folder
.GetMetahandle();
2900 syncable::MutableEntry
child(&trans
, syncable::CREATE
,
2901 BOOKMARKS
, folder
.GetId(), "child");
2902 ASSERT_TRUE(child
.good());
2903 SetNodeProperties(&child
);
2904 child_id
= child
.GetMetahandle();
2907 // The closing of the above scope will delete the transaction. Its processed
2908 // changes should be waiting for us in a member of the test harness.
2909 EXPECT_EQ(2UL, GetChangeListSize());
2911 // We don't need to check these return values here. The function will add a
2912 // non-fatal failure if these changes are not found.
2913 size_t folder_change_pos
=
2914 FindChangeInList(folder_id
, ChangeRecord::ACTION_ADD
);
2915 size_t child_change_pos
=
2916 FindChangeInList(child_id
, ChangeRecord::ACTION_ADD
);
2918 // Parents are delivered before children.
2919 EXPECT_LT(folder_change_pos
, child_change_pos
);
2922 // Test moving a bookmark into an empty folder.
2923 TEST_F(SyncManagerChangeProcessingTest
, MoveBookmarkIntoEmptyFolder
) {
2924 int64 type_root
= GetIdForDataType(BOOKMARKS
);
2925 int64 folder_b_id
= kInvalidId
;
2926 int64 child_id
= kInvalidId
;
2928 // Create two folders. Place a child under folder A.
2930 syncable::WriteTransaction
trans(
2931 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
2932 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
2933 ASSERT_TRUE(root
.good());
2935 syncable::MutableEntry
folder_a(&trans
, syncable::CREATE
,
2936 BOOKMARKS
, root
.GetId(), "folderA");
2937 ASSERT_TRUE(folder_a
.good());
2938 SetNodeProperties(&folder_a
);
2939 folder_a
.PutIsDir(true);
2941 syncable::MutableEntry
folder_b(&trans
, syncable::CREATE
,
2942 BOOKMARKS
, root
.GetId(), "folderB");
2943 ASSERT_TRUE(folder_b
.good());
2944 SetNodeProperties(&folder_b
);
2945 folder_b
.PutIsDir(true);
2946 folder_b_id
= folder_b
.GetMetahandle();
2948 syncable::MutableEntry
child(&trans
, syncable::CREATE
,
2949 BOOKMARKS
, folder_a
.GetId(),
2951 ASSERT_TRUE(child
.good());
2952 SetNodeProperties(&child
);
2953 child_id
= child
.GetMetahandle();
2956 // Close that transaction. The above was to setup the initial scenario. The
2957 // real test starts now.
2959 // Move the child from folder A to folder B.
2961 syncable::WriteTransaction
trans(
2962 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
2964 syncable::Entry
folder_b(&trans
, syncable::GET_BY_HANDLE
, folder_b_id
);
2965 syncable::MutableEntry
child(&trans
, syncable::GET_BY_HANDLE
, child_id
);
2967 child
.PutParentId(folder_b
.GetId());
2970 EXPECT_EQ(1UL, GetChangeListSize());
2972 // Verify that this was detected as a real change. An early version of the
2973 // UniquePosition code had a bug where moves from one folder to another were
2974 // ignored unless the moved node's UniquePosition value was also changed in
2976 FindChangeInList(child_id
, ChangeRecord::ACTION_UPDATE
);
2979 // Test moving a bookmark into a non-empty folder.
2980 TEST_F(SyncManagerChangeProcessingTest
, MoveIntoPopulatedFolder
) {
2981 int64 type_root
= GetIdForDataType(BOOKMARKS
);
2982 int64 child_a_id
= kInvalidId
;
2983 int64 child_b_id
= kInvalidId
;
2985 // Create two folders. Place one child each under folder A and folder B.
2987 syncable::WriteTransaction
trans(
2988 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
2989 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
2990 ASSERT_TRUE(root
.good());
2992 syncable::MutableEntry
folder_a(&trans
, syncable::CREATE
,
2993 BOOKMARKS
, root
.GetId(), "folderA");
2994 ASSERT_TRUE(folder_a
.good());
2995 SetNodeProperties(&folder_a
);
2996 folder_a
.PutIsDir(true);
2998 syncable::MutableEntry
folder_b(&trans
, syncable::CREATE
,
2999 BOOKMARKS
, root
.GetId(), "folderB");
3000 ASSERT_TRUE(folder_b
.good());
3001 SetNodeProperties(&folder_b
);
3002 folder_b
.PutIsDir(true);
3004 syncable::MutableEntry
child_a(&trans
, syncable::CREATE
,
3005 BOOKMARKS
, folder_a
.GetId(),
3007 ASSERT_TRUE(child_a
.good());
3008 SetNodeProperties(&child_a
);
3009 child_a_id
= child_a
.GetMetahandle();
3011 syncable::MutableEntry
child_b(&trans
, syncable::CREATE
,
3012 BOOKMARKS
, folder_b
.GetId(),
3014 SetNodeProperties(&child_b
);
3015 child_b_id
= child_b
.GetMetahandle();
3018 // Close that transaction. The above was to setup the initial scenario. The
3019 // real test starts now.
3022 syncable::WriteTransaction
trans(
3023 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3025 syncable::MutableEntry
child_a(&trans
, syncable::GET_BY_HANDLE
, child_a_id
);
3026 syncable::MutableEntry
child_b(&trans
, syncable::GET_BY_HANDLE
, child_b_id
);
3028 // Move child A from folder A to folder B and update its position.
3029 child_a
.PutParentId(child_b
.GetParentId());
3030 child_a
.PutPredecessor(child_b
.GetId());
3033 EXPECT_EQ(1UL, GetChangeListSize());
3035 // Verify that only child a is in the change list.
3036 // (This function will add a failure if the lookup fails.)
3037 FindChangeInList(child_a_id
, ChangeRecord::ACTION_UPDATE
);
3040 // Tests the ordering of deletion changes.
3041 TEST_F(SyncManagerChangeProcessingTest
, DeletionsAndChanges
) {
3042 int64 type_root
= GetIdForDataType(BOOKMARKS
);
3043 int64 folder_a_id
= kInvalidId
;
3044 int64 folder_b_id
= kInvalidId
;
3045 int64 child_id
= kInvalidId
;
3047 // Create two folders. Place a child under folder A.
3049 syncable::WriteTransaction
trans(
3050 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3051 syncable::Entry
root(&trans
, syncable::GET_BY_HANDLE
, type_root
);
3052 ASSERT_TRUE(root
.good());
3054 syncable::MutableEntry
folder_a(&trans
, syncable::CREATE
,
3055 BOOKMARKS
, root
.GetId(), "folderA");
3056 ASSERT_TRUE(folder_a
.good());
3057 SetNodeProperties(&folder_a
);
3058 folder_a
.PutIsDir(true);
3059 folder_a_id
= folder_a
.GetMetahandle();
3061 syncable::MutableEntry
folder_b(&trans
, syncable::CREATE
,
3062 BOOKMARKS
, root
.GetId(), "folderB");
3063 ASSERT_TRUE(folder_b
.good());
3064 SetNodeProperties(&folder_b
);
3065 folder_b
.PutIsDir(true);
3066 folder_b_id
= folder_b
.GetMetahandle();
3068 syncable::MutableEntry
child(&trans
, syncable::CREATE
,
3069 BOOKMARKS
, folder_a
.GetId(),
3071 ASSERT_TRUE(child
.good());
3072 SetNodeProperties(&child
);
3073 child_id
= child
.GetMetahandle();
3076 // Close that transaction. The above was to setup the initial scenario. The
3077 // real test starts now.
3080 syncable::WriteTransaction
trans(
3081 FROM_HERE
, syncable::SYNCER
, share()->directory
.get());
3083 syncable::MutableEntry
folder_a(
3084 &trans
, syncable::GET_BY_HANDLE
, folder_a_id
);
3085 syncable::MutableEntry
folder_b(
3086 &trans
, syncable::GET_BY_HANDLE
, folder_b_id
);
3087 syncable::MutableEntry
child(&trans
, syncable::GET_BY_HANDLE
, child_id
);
3089 // Delete folder B and its child.
3090 child
.PutIsDel(true);
3091 folder_b
.PutIsDel(true);
3093 // Make an unrelated change to folder A.
3094 folder_a
.PutNonUniqueName("NewNameA");
3097 EXPECT_EQ(3UL, GetChangeListSize());
3099 size_t folder_a_pos
=
3100 FindChangeInList(folder_a_id
, ChangeRecord::ACTION_UPDATE
);
3101 size_t folder_b_pos
=
3102 FindChangeInList(folder_b_id
, ChangeRecord::ACTION_DELETE
);
3103 size_t child_pos
= FindChangeInList(child_id
, ChangeRecord::ACTION_DELETE
);
3105 // Deletes should appear before updates.
3106 EXPECT_LT(child_pos
, folder_a_pos
);
3107 EXPECT_LT(folder_b_pos
, folder_a_pos
);
3110 // During initialization SyncManagerImpl loads sqlite database. If it fails to
3111 // do so it should fail initialization. This test verifies this behavior.
3112 // Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
3113 // InternalComponentsFactory to return DirectoryBackingStore that always fails
3115 class SyncManagerInitInvalidStorageTest
: public SyncManagerTest
{
3117 SyncManagerInitInvalidStorageTest() {
3120 virtual InternalComponentsFactory
* GetFactory() OVERRIDE
{
3121 return new TestInternalComponentsFactory(GetSwitches(), STORAGE_INVALID
);
3125 // SyncManagerInitInvalidStorageTest::GetFactory will return
3126 // DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
3127 // SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
3128 // task is to ensure that SyncManagerImpl reported initialization failure in
3129 // OnInitializationComplete callback.
3130 TEST_F(SyncManagerInitInvalidStorageTest
, FailToOpenDatabase
) {
3131 EXPECT_FALSE(initialization_succeeded_
);
3134 } // namespace syncer