forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync_manager_impl_unittest.cc
3368 lines (2992 loc) · 130 KB
/
sync_manager_impl_unittest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Unit tests for the SyncApi. Note that a lot of the underlying
// functionality is provided by the Syncable layer, which has its own
// unit tests. We'll test SyncApi specific things in this harness.
#include "sync/internal_api/sync_manager_impl.h"
#include <stdint.h>
#include <cstddef>
#include <map>
#include <utility>
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/files/scoped_temp_dir.h"
#include "base/format_macros.h"
#include "base/location.h"
#include "base/memory/scoped_ptr.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/values_test_util.h"
#include "base/values.h"
#include "google_apis/gaia/gaia_constants.h"
#include "sync/engine/sync_scheduler.h"
#include "sync/internal_api/public/base/attachment_id_proto.h"
#include "sync/internal_api/public/base/cancelation_signal.h"
#include "sync/internal_api/public/base/model_type_test_util.h"
#include "sync/internal_api/public/change_record.h"
#include "sync/internal_api/public/engine/model_safe_worker.h"
#include "sync/internal_api/public/engine/polling_constants.h"
#include "sync/internal_api/public/events/protocol_event.h"
#include "sync/internal_api/public/http_post_provider_factory.h"
#include "sync/internal_api/public/http_post_provider_interface.h"
#include "sync/internal_api/public/read_node.h"
#include "sync/internal_api/public/read_transaction.h"
#include "sync/internal_api/public/test/test_entry_factory.h"
#include "sync/internal_api/public/test/test_internal_components_factory.h"
#include "sync/internal_api/public/test/test_user_share.h"
#include "sync/internal_api/public/write_node.h"
#include "sync/internal_api/public/write_transaction.h"
#include "sync/internal_api/sync_encryption_handler_impl.h"
#include "sync/internal_api/syncapi_internal.h"
#include "sync/js/js_backend.h"
#include "sync/js/js_event_handler.h"
#include "sync/js/js_test_util.h"
#include "sync/protocol/bookmark_specifics.pb.h"
#include "sync/protocol/encryption.pb.h"
#include "sync/protocol/extension_specifics.pb.h"
#include "sync/protocol/password_specifics.pb.h"
#include "sync/protocol/preference_specifics.pb.h"
#include "sync/protocol/proto_value_conversions.h"
#include "sync/protocol/sync.pb.h"
#include "sync/sessions/sync_session.h"
#include "sync/syncable/directory.h"
#include "sync/syncable/entry.h"
#include "sync/syncable/mutable_entry.h"
#include "sync/syncable/nigori_util.h"
#include "sync/syncable/syncable_id.h"
#include "sync/syncable/syncable_read_transaction.h"
#include "sync/syncable/syncable_util.h"
#include "sync/syncable/syncable_write_transaction.h"
#include "sync/test/callback_counter.h"
#include "sync/test/engine/fake_model_worker.h"
#include "sync/test/engine/fake_sync_scheduler.h"
#include "sync/test/engine/test_id_factory.h"
#include "sync/test/fake_encryptor.h"
#include "sync/util/cryptographer.h"
#include "sync/util/extensions_activity.h"
#include "sync/util/mock_unrecoverable_error_handler.h"
#include "sync/util/time.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
using base::ExpectDictStringValue;
using testing::_;
using testing::DoAll;
using testing::InSequence;
using testing::Return;
using testing::SaveArg;
using testing::StrictMock;
namespace syncer {
using sessions::SyncSessionSnapshot;
using syncable::GET_BY_HANDLE;
using syncable::IS_DEL;
using syncable::IS_UNSYNCED;
using syncable::NON_UNIQUE_NAME;
using syncable::SPECIFICS;
using syncable::kEncryptedString;
namespace {
// Makes a child node under the type root folder. Returns the id of the
// newly-created node.
int64_t MakeNode(UserShare* share,
ModelType model_type,
const std::string& client_tag) {
WriteTransaction trans(FROM_HERE, share);
WriteNode node(&trans);
WriteNode::InitUniqueByCreationResult result =
node.InitUniqueByCreation(model_type, client_tag);
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
node.SetIsFolder(false);
return node.GetId();
}
// Makes a non-folder child of the root node. Returns the id of the
// newly-created node.
int64_t MakeNodeWithRoot(UserShare* share,
ModelType model_type,
const std::string& client_tag) {
WriteTransaction trans(FROM_HERE, share);
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode node(&trans);
WriteNode::InitUniqueByCreationResult result =
node.InitUniqueByCreation(model_type, root_node, client_tag);
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
node.SetIsFolder(false);
return node.GetId();
}
// Makes a folder child of a non-root node. Returns the id of the
// newly-created node.
int64_t MakeFolderWithParent(UserShare* share,
ModelType model_type,
int64_t parent_id,
BaseNode* predecessor) {
WriteTransaction trans(FROM_HERE, share);
ReadNode parent_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
WriteNode node(&trans);
EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
node.SetIsFolder(true);
return node.GetId();
}
int64_t MakeBookmarkWithParent(UserShare* share,
int64_t parent_id,
BaseNode* predecessor) {
WriteTransaction trans(FROM_HERE, share);
ReadNode parent_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
WriteNode node(&trans);
EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
return node.GetId();
}
// Creates the "synced" root node for a particular datatype. We use the syncable
// methods here so that the syncer treats these nodes as if they were already
// received from the server.
int64_t MakeTypeRoot(UserShare* share, ModelType model_type) {
sync_pb::EntitySpecifics specifics;
AddDefaultFieldValue(model_type, &specifics);
syncable::WriteTransaction trans(
FROM_HERE, syncable::UNITTEST, share->directory.get());
// Attempt to lookup by nigori tag.
std::string type_tag = ModelTypeToRootTag(model_type);
syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag);
syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
node_id);
EXPECT_TRUE(entry.good());
entry.PutBaseVersion(1);
entry.PutServerVersion(1);
entry.PutIsUnappliedUpdate(false);
entry.PutParentId(syncable::Id::GetRoot());
entry.PutServerParentId(syncable::Id::GetRoot());
entry.PutServerIsDir(true);
entry.PutIsDir(true);
entry.PutServerSpecifics(specifics);
entry.PutSpecifics(specifics);
entry.PutUniqueServerTag(type_tag);
entry.PutNonUniqueName(type_tag);
entry.PutIsDel(false);
return entry.GetMetahandle();
}
// Simulates creating a "synced" node as a child of the root datatype node.
int64_t MakeServerNode(UserShare* share,
ModelType model_type,
const std::string& client_tag,
const std::string& hashed_tag,
const sync_pb::EntitySpecifics& specifics) {
syncable::WriteTransaction trans(
FROM_HERE, syncable::UNITTEST, share->directory.get());
syncable::Entry root_entry(&trans, syncable::GET_TYPE_ROOT, model_type);
EXPECT_TRUE(root_entry.good());
syncable::Id root_id = root_entry.GetId();
syncable::Id node_id = syncable::Id::CreateFromServerId(client_tag);
syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
node_id);
EXPECT_TRUE(entry.good());
entry.PutBaseVersion(1);
entry.PutServerVersion(1);
entry.PutIsUnappliedUpdate(false);
entry.PutServerParentId(root_id);
entry.PutParentId(root_id);
entry.PutServerIsDir(false);
entry.PutIsDir(false);
entry.PutServerSpecifics(specifics);
entry.PutSpecifics(specifics);
entry.PutNonUniqueName(client_tag);
entry.PutUniqueClientTag(hashed_tag);
entry.PutIsDel(false);
return entry.GetMetahandle();
}
int GetTotalNodeCount(UserShare* share, int64_t root) {
ReadTransaction trans(FROM_HERE, share);
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(root));
return node.GetTotalNodeCount();
}
} // namespace
class SyncApiTest : public testing::Test {
public:
void SetUp() override { test_user_share_.SetUp(); }
void TearDown() override { test_user_share_.TearDown(); }
protected:
// Create an entry with the given |model_type|, |client_tag| and
// |attachment_metadata|.
void CreateEntryWithAttachmentMetadata(
const ModelType& model_type,
const std::string& client_tag,
const sync_pb::AttachmentMetadata& attachment_metadata);
// Attempts to load the entry specified by |model_type| and |client_tag| and
// returns the lookup result code.
BaseNode::InitByLookupResult LookupEntryByClientTag(
const ModelType& model_type,
const std::string& client_tag);
// Replace the entry specified by |model_type| and |client_tag| with a
// tombstone.
void ReplaceWithTombstone(const ModelType& model_type,
const std::string& client_tag);
// Save changes to the Directory, destroy it then reload it.
bool ReloadDir();
UserShare* user_share();
syncable::Directory* dir();
SyncEncryptionHandler* encryption_handler();
private:
base::MessageLoop message_loop_;
TestUserShare test_user_share_;
};
UserShare* SyncApiTest::user_share() {
return test_user_share_.user_share();
}
syncable::Directory* SyncApiTest::dir() {
return test_user_share_.user_share()->directory.get();
}
SyncEncryptionHandler* SyncApiTest::encryption_handler() {
return test_user_share_.encryption_handler();
}
bool SyncApiTest::ReloadDir() {
return test_user_share_.Reload();
}
void SyncApiTest::CreateEntryWithAttachmentMetadata(
const ModelType& model_type,
const std::string& client_tag,
const sync_pb::AttachmentMetadata& attachment_metadata) {
syncer::WriteTransaction trans(FROM_HERE, user_share());
syncer::ReadNode root_node(&trans);
root_node.InitByRootLookup();
syncer::WriteNode node(&trans);
ASSERT_EQ(node.InitUniqueByCreation(model_type, root_node, client_tag),
syncer::WriteNode::INIT_SUCCESS);
node.SetAttachmentMetadata(attachment_metadata);
}
BaseNode::InitByLookupResult SyncApiTest::LookupEntryByClientTag(
const ModelType& model_type,
const std::string& client_tag) {
syncer::ReadTransaction trans(FROM_HERE, user_share());
syncer::ReadNode node(&trans);
return node.InitByClientTagLookup(model_type, client_tag);
}
void SyncApiTest::ReplaceWithTombstone(const ModelType& model_type,
const std::string& client_tag) {
syncer::WriteTransaction trans(FROM_HERE, user_share());
syncer::WriteNode node(&trans);
ASSERT_EQ(node.InitByClientTagLookup(model_type, client_tag),
syncer::WriteNode::INIT_OK);
node.Tombstone();
}
TEST_F(SyncApiTest, SanityCheckTest) {
{
ReadTransaction trans(FROM_HERE, user_share());
EXPECT_TRUE(trans.GetWrappedTrans());
}
{
WriteTransaction trans(FROM_HERE, user_share());
EXPECT_TRUE(trans.GetWrappedTrans());
}
{
// No entries but root should exist
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
// Metahandle 1 can be root, sanity check 2
EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByIdLookup(2));
}
}
TEST_F(SyncApiTest, BasicTagWrite) {
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
EXPECT_EQ(kInvalidId, root_node.GetFirstChildId());
}
ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag"));
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, "testtag"));
EXPECT_NE(0, node.GetId());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
EXPECT_EQ(node.GetId(), root_node.GetFirstChildId());
}
}
TEST_F(SyncApiTest, BasicTagWriteWithImplicitParent) {
int64_t type_root = MakeTypeRoot(user_share(), PREFERENCES);
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode type_root_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
EXPECT_EQ(kInvalidId, type_root_node.GetFirstChildId());
}
ignore_result(MakeNode(user_share(), PREFERENCES, "testtag"));
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PREFERENCES, "testtag"));
EXPECT_EQ(kInvalidId, node.GetParentId());
ReadNode type_root_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
EXPECT_EQ(node.GetId(), type_root_node.GetFirstChildId());
}
}
TEST_F(SyncApiTest, ModelTypesSiloed) {
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
EXPECT_EQ(root_node.GetFirstChildId(), 0);
}
ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "collideme"));
ignore_result(MakeNodeWithRoot(user_share(), PREFERENCES, "collideme"));
ignore_result(MakeNodeWithRoot(user_share(), AUTOFILL, "collideme"));
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode bookmarknode(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
bookmarknode.InitByClientTagLookup(BOOKMARKS,
"collideme"));
ReadNode prefnode(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
prefnode.InitByClientTagLookup(PREFERENCES,
"collideme"));
ReadNode autofillnode(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
autofillnode.InitByClientTagLookup(AUTOFILL,
"collideme"));
EXPECT_NE(bookmarknode.GetId(), prefnode.GetId());
EXPECT_NE(autofillnode.GetId(), prefnode.GetId());
EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId());
}
}
TEST_F(SyncApiTest, ReadMissingTagsFails) {
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
node.InitByClientTagLookup(BOOKMARKS,
"testtag"));
}
{
WriteTransaction trans(FROM_HERE, user_share());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
node.InitByClientTagLookup(BOOKMARKS,
"testtag"));
}
}
// TODO(chron): Hook this all up to the server and write full integration tests
// for update->undelete behavior.
TEST_F(SyncApiTest, TestDeleteBehavior) {
int64_t node_id;
int64_t folder_id;
std::string test_title("test1");
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
// we'll use this spare folder later
WriteNode folder_node(&trans);
EXPECT_TRUE(folder_node.InitBookmarkByCreation(root_node, NULL));
folder_id = folder_node.GetId();
WriteNode wnode(&trans);
WriteNode::InitUniqueByCreationResult result =
wnode.InitUniqueByCreation(BOOKMARKS, root_node, "testtag");
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
wnode.SetIsFolder(false);
wnode.SetTitle(test_title);
node_id = wnode.GetId();
}
// Ensure we can delete something with a tag.
{
WriteTransaction trans(FROM_HERE, user_share());
WriteNode wnode(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
wnode.InitByClientTagLookup(BOOKMARKS,
"testtag"));
EXPECT_FALSE(wnode.GetIsFolder());
EXPECT_EQ(wnode.GetTitle(), test_title);
wnode.Tombstone();
}
// Lookup of a node which was deleted should return failure,
// but have found some data about the node.
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL,
node.InitByClientTagLookup(BOOKMARKS,
"testtag"));
// Note that for proper function of this API this doesn't need to be
// filled, we're checking just to make sure the DB worked in this test.
EXPECT_EQ(node.GetTitle(), test_title);
}
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode folder_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, folder_node.InitByIdLookup(folder_id));
WriteNode wnode(&trans);
// This will undelete the tag.
WriteNode::InitUniqueByCreationResult result =
wnode.InitUniqueByCreation(BOOKMARKS, folder_node, "testtag");
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
EXPECT_EQ(wnode.GetIsFolder(), false);
EXPECT_EQ(wnode.GetParentId(), folder_node.GetId());
EXPECT_EQ(wnode.GetId(), node_id);
EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared
wnode.SetTitle(test_title);
}
// Now look up should work.
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS,
"testtag"));
EXPECT_EQ(node.GetTitle(), test_title);
EXPECT_EQ(node.GetModelType(), BOOKMARKS);
}
}
TEST_F(SyncApiTest, WriteAndReadPassword) {
KeyParams params = {"localhost", "username", "passphrase"};
{
ReadTransaction trans(FROM_HERE, user_share());
trans.GetCryptographer()->AddKey(params);
}
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode password_node(&trans);
WriteNode::InitUniqueByCreationResult result =
password_node.InitUniqueByCreation(PASSWORDS,
root_node, "foo");
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
sync_pb::PasswordSpecificsData data;
data.set_password_value("secret");
password_node.SetPasswordSpecifics(data);
}
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode password_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
password_node.InitByClientTagLookup(PASSWORDS, "foo"));
const sync_pb::PasswordSpecificsData& data =
password_node.GetPasswordSpecifics();
EXPECT_EQ("secret", data.password_value());
}
}
TEST_F(SyncApiTest, WriteEncryptedTitle) {
KeyParams params = {"localhost", "username", "passphrase"};
{
ReadTransaction trans(FROM_HERE, user_share());
trans.GetCryptographer()->AddKey(params);
}
encryption_handler()->EnableEncryptEverything();
int bookmark_id;
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode bookmark_node(&trans);
ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
bookmark_id = bookmark_node.GetId();
bookmark_node.SetTitle("foo");
WriteNode pref_node(&trans);
WriteNode::InitUniqueByCreationResult result =
pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar");
ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
pref_node.SetTitle("bar");
}
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode bookmark_node(&trans);
ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
EXPECT_EQ("foo", bookmark_node.GetTitle());
EXPECT_EQ(kEncryptedString,
bookmark_node.GetEntry()->GetNonUniqueName());
ReadNode pref_node(&trans);
ASSERT_EQ(BaseNode::INIT_OK,
pref_node.InitByClientTagLookup(PREFERENCES,
"bar"));
EXPECT_EQ(kEncryptedString, pref_node.GetTitle());
}
}
// Non-unique name should not be empty. For bookmarks non-unique name is copied
// from bookmark title. This test verifies that setting bookmark title to ""
// results in single space title and non-unique name in internal representation.
// GetTitle should still return empty string.
TEST_F(SyncApiTest, WriteEmptyBookmarkTitle) {
int bookmark_id;
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode bookmark_node(&trans);
ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
bookmark_id = bookmark_node.GetId();
bookmark_node.SetTitle("");
}
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode bookmark_node(&trans);
ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
EXPECT_EQ("", bookmark_node.GetTitle());
EXPECT_EQ(" ", bookmark_node.GetEntitySpecifics().bookmark().title());
EXPECT_EQ(" ", bookmark_node.GetEntry()->GetNonUniqueName());
}
}
TEST_F(SyncApiTest, BaseNodeSetSpecifics) {
int64_t child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
WriteTransaction trans(FROM_HERE, user_share());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
EXPECT_NE(entity_specifics.SerializeAsString(),
node.GetEntitySpecifics().SerializeAsString());
node.SetEntitySpecifics(entity_specifics);
EXPECT_EQ(entity_specifics.SerializeAsString(),
node.GetEntitySpecifics().SerializeAsString());
}
TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) {
int64_t child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
WriteTransaction trans(FROM_HERE, user_share());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty());
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100);
node.SetEntitySpecifics(entity_specifics);
EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
entity_specifics.mutable_unknown_fields()->Clear();
node.SetEntitySpecifics(entity_specifics);
EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
}
TEST_F(SyncApiTest, EmptyTags) {
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode node(&trans);
std::string empty_tag;
WriteNode::InitUniqueByCreationResult result =
node.InitUniqueByCreation(TYPED_URLS, root_node, empty_tag);
EXPECT_NE(WriteNode::INIT_SUCCESS, result);
EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION,
node.InitByClientTagLookup(TYPED_URLS, empty_tag));
}
// Test counting nodes when the type's root node has no children.
TEST_F(SyncApiTest, GetTotalNodeCountEmpty) {
int64_t type_root = MakeTypeRoot(user_share(), BOOKMARKS);
EXPECT_EQ(1, GetTotalNodeCount(user_share(), type_root));
}
// Test counting nodes when there is one child beneath the type's root.
TEST_F(SyncApiTest, GetTotalNodeCountOneChild) {
int64_t type_root = MakeTypeRoot(user_share(), BOOKMARKS);
int64_t parent =
MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL);
EXPECT_EQ(2, GetTotalNodeCount(user_share(), type_root));
EXPECT_EQ(1, GetTotalNodeCount(user_share(), parent));
}
// Test counting nodes when there are multiple children beneath the type root,
// and one of those children has children of its own.
TEST_F(SyncApiTest, GetTotalNodeCountMultipleChildren) {
int64_t type_root = MakeTypeRoot(user_share(), BOOKMARKS);
int64_t parent =
MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL);
ignore_result(MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL));
int64_t child1 = MakeFolderWithParent(user_share(), BOOKMARKS, parent, NULL);
ignore_result(MakeBookmarkWithParent(user_share(), parent, NULL));
ignore_result(MakeBookmarkWithParent(user_share(), child1, NULL));
EXPECT_EQ(6, GetTotalNodeCount(user_share(), type_root));
EXPECT_EQ(4, GetTotalNodeCount(user_share(), parent));
}
// Verify that Directory keeps track of which attachments are referenced by
// which entries.
TEST_F(SyncApiTest, AttachmentLinking) {
// Add an entry with an attachment.
std::string tag1("some tag");
syncer::AttachmentId attachment_id(syncer::AttachmentId::Create(0, 0));
sync_pb::AttachmentMetadata attachment_metadata;
sync_pb::AttachmentMetadataRecord* record = attachment_metadata.add_record();
*record->mutable_id() = attachment_id.GetProto();
ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
CreateEntryWithAttachmentMetadata(PREFERENCES, tag1, attachment_metadata);
// See that the directory knows it's linked.
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Add a second entry referencing the same attachment.
std::string tag2("some other tag");
CreateEntryWithAttachmentMetadata(PREFERENCES, tag2, attachment_metadata);
// See that the directory knows it's still linked.
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Tombstone the first entry.
ReplaceWithTombstone(syncer::PREFERENCES, tag1);
// See that the attachment is still considered linked because the entry hasn't
// been purged from the Directory.
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Save changes and see that the entry is truly gone.
ASSERT_TRUE(dir()->SaveChanges());
ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag1),
syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
// However, the attachment is still linked.
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Save, destroy, and recreate the directory. See that it's still linked.
ASSERT_TRUE(ReloadDir());
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Tombstone the second entry, save changes, see that it's truly gone.
ReplaceWithTombstone(syncer::PREFERENCES, tag2);
ASSERT_TRUE(dir()->SaveChanges());
ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag2),
syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
// Finally, the attachment is no longer linked.
ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
}
// This tests directory integrity in the case of creating a new unique node
// with client tag matching that of an existing unapplied node with server only
// data. See crbug.com/505761.
TEST_F(SyncApiTest, WriteNode_UniqueByCreation_UndeleteCase) {
int64_t preferences_root = MakeTypeRoot(user_share(), PREFERENCES);
// Create a node with server only data.
int64_t item1 = 0;
{
syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST,
user_share()->directory.get());
syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
syncable::Id::CreateFromServerId("foo1"));
DCHECK(entry.good());
entry.PutServerVersion(10);
entry.PutIsUnappliedUpdate(true);
sync_pb::EntitySpecifics specifics;
AddDefaultFieldValue(PREFERENCES, &specifics);
entry.PutServerSpecifics(specifics);
const std::string hash = syncable::GenerateSyncableHash(PREFERENCES, "foo");
entry.PutUniqueClientTag(hash);
item1 = entry.GetMetahandle();
}
// Verify that the server-only item is invisible as a child of
// of |preferences_root| because at this point it should have the
// "deleted" flag set.
EXPECT_EQ(1, GetTotalNodeCount(user_share(), preferences_root));
// Create a client node with the same tag as the node above.
int64_t item2 = MakeNode(user_share(), PREFERENCES, "foo");
// Expect this to be the same directory entry as |item1|.
EXPECT_EQ(item1, item2);
// Expect it to be visible as a child of |preferences_root|.
EXPECT_EQ(2, GetTotalNodeCount(user_share(), preferences_root));
// Tombstone the new item
{
WriteTransaction trans(FROM_HERE, user_share());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(item1));
node.Tombstone();
}
// Verify that it is gone from the index.
EXPECT_EQ(1, GetTotalNodeCount(user_share(), preferences_root));
}
namespace {
class TestHttpPostProviderInterface : public HttpPostProviderInterface {
public:
~TestHttpPostProviderInterface() override {}
void SetExtraRequestHeaders(const char* headers) override {}
void SetURL(const char* url, int port) override {}
void SetPostPayload(const char* content_type,
int content_length,
const char* content) override {}
bool MakeSynchronousPost(int* error_code, int* response_code) override {
return false;
}
int GetResponseContentLength() const override { return 0; }
const char* GetResponseContent() const override { return ""; }
const std::string GetResponseHeaderValue(
const std::string& name) const override {
return std::string();
}
void Abort() override {}
};
class TestHttpPostProviderFactory : public HttpPostProviderFactory {
public:
~TestHttpPostProviderFactory() override {}
void Init(const std::string& user_agent,
const BindToTrackerCallback& bind_to_tracker_callback) override {}
HttpPostProviderInterface* Create() override {
return new TestHttpPostProviderInterface();
}
void Destroy(HttpPostProviderInterface* http) override {
delete static_cast<TestHttpPostProviderInterface*>(http);
}
};
class SyncManagerObserverMock : public SyncManager::Observer {
public:
MOCK_METHOD1(OnSyncCycleCompleted,
void(const SyncSessionSnapshot&)); // NOLINT
MOCK_METHOD4(OnInitializationComplete,
void(const WeakHandle<JsBackend>&,
const WeakHandle<DataTypeDebugInfoListener>&,
bool,
syncer::ModelTypeSet)); // NOLINT
MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT
MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT
MOCK_METHOD1(OnActionableError, void(const SyncProtocolError&)); // NOLINT
MOCK_METHOD1(OnMigrationRequested, void(syncer::ModelTypeSet)); // NOLINT
MOCK_METHOD1(OnProtocolEvent, void(const ProtocolEvent&)); // NOLINT
};
class SyncEncryptionHandlerObserverMock
: public SyncEncryptionHandler::Observer {
public:
MOCK_METHOD2(OnPassphraseRequired,
void(PassphraseRequiredReason,
const sync_pb::EncryptedData&)); // NOLINT
MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT
MOCK_METHOD2(OnBootstrapTokenUpdated,
void(const std::string&, BootstrapTokenType type)); // NOLINT
MOCK_METHOD2(OnEncryptedTypesChanged,
void(ModelTypeSet, bool)); // NOLINT
MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT
MOCK_METHOD1(OnCryptographerStateChanged, void(Cryptographer*)); // NOLINT
MOCK_METHOD2(OnPassphraseTypeChanged, void(PassphraseType,
base::Time)); // NOLINT
MOCK_METHOD1(OnLocalSetPassphraseEncryption,
void(const SyncEncryptionHandler::NigoriState&)); // NOLINT
};
} // namespace
class SyncManagerTest : public testing::Test,
public SyncManager::ChangeDelegate {
protected:
enum NigoriStatus {
DONT_WRITE_NIGORI,
WRITE_TO_NIGORI
};
enum EncryptionStatus {
UNINITIALIZED,
DEFAULT_ENCRYPTION,
FULL_ENCRYPTION
};
SyncManagerTest()
: sync_manager_("Test sync manager") {
switches_.encryption_method =
InternalComponentsFactory::ENCRYPTION_KEYSTORE;
}
virtual ~SyncManagerTest() {
}
// Test implementation.
void SetUp() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
extensions_activity_ = new ExtensionsActivity();
SyncCredentials credentials;
credentials.account_id = "foo@bar.com";
credentials.email = "foo@bar.com";
credentials.sync_token = "sometoken";
OAuth2TokenService::ScopeSet scope_set;
scope_set.insert(GaiaConstants::kChromeSyncOAuth2Scope);
credentials.scope_set = scope_set;
sync_manager_.AddObserver(&manager_observer_);
EXPECT_CALL(manager_observer_, OnInitializationComplete(_, _, _, _)).
WillOnce(DoAll(SaveArg<0>(&js_backend_),
SaveArg<2>(&initialization_succeeded_)));
EXPECT_FALSE(js_backend_.IsInitialized());
std::vector<scoped_refptr<ModelSafeWorker> > workers;
ModelSafeRoutingInfo routing_info;
GetModelSafeRoutingInfo(&routing_info);
// This works only because all routing info types are GROUP_PASSIVE.
// If we had types in other groups, we would need additional workers
// to support them.
scoped_refptr<ModelSafeWorker> worker = new FakeModelWorker(GROUP_PASSIVE);
workers.push_back(worker);
SyncManager::InitArgs args;
args.database_location = temp_dir_.path();
args.service_url = GURL("https://example.com/");
args.post_factory =
scoped_ptr<HttpPostProviderFactory>(new TestHttpPostProviderFactory());
args.workers = workers;
args.extensions_activity = extensions_activity_.get(),
args.change_delegate = this;
args.credentials = credentials;
args.invalidator_client_id = "fake_invalidator_client_id";
args.internal_components_factory.reset(GetFactory());
args.encryptor = &encryptor_;
args.unrecoverable_error_handler =
MakeWeakHandle(mock_unrecoverable_error_handler_.GetWeakPtr());
args.cancelation_signal = &cancelation_signal_;
sync_manager_.Init(&args);
sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_);
EXPECT_TRUE(js_backend_.IsInitialized());
EXPECT_EQ(InternalComponentsFactory::STORAGE_ON_DISK,
storage_used_);
if (initialization_succeeded_) {
for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
i != routing_info.end(); ++i) {
type_roots_[i->first] =
MakeTypeRoot(sync_manager_.GetUserShare(), i->first);
}
}
PumpLoop();
}
void TearDown() {
sync_manager_.RemoveObserver(&manager_observer_);
sync_manager_.ShutdownOnSyncThread(STOP_SYNC);
PumpLoop();
}
void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) {
(*out)[NIGORI] = GROUP_PASSIVE;
(*out)[DEVICE_INFO] = GROUP_PASSIVE;
(*out)[EXPERIMENTS] = GROUP_PASSIVE;
(*out)[BOOKMARKS] = GROUP_PASSIVE;
(*out)[THEMES] = GROUP_PASSIVE;
(*out)[SESSIONS] = GROUP_PASSIVE;
(*out)[PASSWORDS] = GROUP_PASSIVE;
(*out)[PREFERENCES] = GROUP_PASSIVE;
(*out)[PRIORITY_PREFERENCES] = GROUP_PASSIVE;
(*out)[ARTICLES] = GROUP_PASSIVE;
}
ModelTypeSet GetEnabledTypes() {
ModelSafeRoutingInfo routing_info;
GetModelSafeRoutingInfo(&routing_info);
return GetRoutingInfoTypes(routing_info);
}
void OnChangesApplied(ModelType model_type,
int64_t model_version,
const BaseTransaction* trans,
const ImmutableChangeRecordList& changes) override {}
void OnChangesComplete(ModelType model_type) override {}
// Helper methods.
bool SetUpEncryption(NigoriStatus nigori_status,
EncryptionStatus encryption_status) {
UserShare* share = sync_manager_.GetUserShare();
// We need to create the nigori node as if it were an applied server update.
int64_t nigori_id = GetIdForDataType(NIGORI);
if (nigori_id == kInvalidId)
return false;
// Set the nigori cryptographer information.
if (encryption_status == FULL_ENCRYPTION)
sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
WriteTransaction trans(FROM_HERE, share);
Cryptographer* cryptographer = trans.GetCryptographer();
if (!cryptographer)
return false;
if (encryption_status != UNINITIALIZED) {
KeyParams params = {"localhost", "dummy", "foobar"};
cryptographer->AddKey(params);
} else {
DCHECK_NE(nigori_status, WRITE_TO_NIGORI);
}
if (nigori_status == WRITE_TO_NIGORI) {