Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service_autofill_unittest.cc
blobe60b0eb4b304bfe26ba12226c3e32d15d89b70dc
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 #include <set>
6 #include <string>
7 #include <utility>
8 #include <vector>
10 #include "testing/gtest/include/gtest/gtest.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/callback.h"
15 #include "base/compiler_specific.h"
16 #include "base/location.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/strings/string16.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/synchronization/waitable_event.h"
23 #include "base/time/time.h"
24 #include "chrome/browser/autofill/personal_data_manager_factory.h"
25 #include "chrome/browser/prefs/pref_service_syncable.h"
26 #include "chrome/browser/signin/account_tracker_service_factory.h"
27 #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h"
28 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
29 #include "chrome/browser/signin/signin_manager_factory.h"
30 #include "chrome/browser/sync/abstract_profile_sync_service_test.h"
31 #include "chrome/browser/sync/glue/autofill_data_type_controller.h"
32 #include "chrome/browser/sync/glue/autofill_profile_data_type_controller.h"
33 #include "chrome/browser/sync/profile_sync_components_factory.h"
34 #include "chrome/browser/sync/profile_sync_service.h"
35 #include "chrome/browser/sync/profile_sync_service_factory.h"
36 #include "chrome/browser/sync/profile_sync_test_util.h"
37 #include "chrome/browser/sync/test_profile_sync_service.h"
38 #include "chrome/browser/web_data_service_factory.h"
39 #include "chrome/test/base/testing_browser_process.h"
40 #include "chrome/test/base/testing_profile.h"
41 #include "chrome/test/base/testing_profile_manager.h"
42 #include "components/autofill/core/browser/autofill_test_utils.h"
43 #include "components/autofill/core/browser/personal_data_manager.h"
44 #include "components/autofill/core/browser/webdata/autocomplete_syncable_service.h"
45 #include "components/autofill/core/browser/webdata/autofill_change.h"
46 #include "components/autofill/core/browser/webdata/autofill_entry.h"
47 #include "components/autofill/core/browser/webdata/autofill_profile_syncable_service.h"
48 #include "components/autofill/core/browser/webdata/autofill_table.h"
49 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
50 #include "components/signin/core/browser/account_tracker_service.h"
51 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
52 #include "components/signin/core/browser/signin_manager.h"
53 #include "components/sync_driver/data_type_controller.h"
54 #include "components/webdata/common/web_database.h"
55 #include "components/webdata_services/web_data_service_test_util.h"
56 #include "content/public/test/test_browser_thread.h"
57 #include "google_apis/gaia/gaia_constants.h"
58 #include "sync/internal_api/public/base/model_type.h"
59 #include "sync/internal_api/public/data_type_debug_info_listener.h"
60 #include "sync/internal_api/public/read_node.h"
61 #include "sync/internal_api/public/read_transaction.h"
62 #include "sync/internal_api/public/write_node.h"
63 #include "sync/internal_api/public/write_transaction.h"
64 #include "sync/protocol/autofill_specifics.pb.h"
65 #include "sync/syncable/mutable_entry.h"
66 #include "sync/syncable/syncable_write_transaction.h"
67 #include "sync/test/engine/test_id_factory.h"
68 #include "testing/gmock/include/gmock/gmock.h"
70 using autofill::AutocompleteSyncableService;
71 using autofill::AutofillChange;
72 using autofill::AutofillChangeList;
73 using autofill::AutofillEntry;
74 using autofill::ServerFieldType;
75 using autofill::AutofillKey;
76 using autofill::AutofillProfile;
77 using autofill::AutofillProfileChange;
78 using autofill::AutofillProfileSyncableService;
79 using autofill::AutofillTable;
80 using autofill::AutofillWebDataService;
81 using autofill::PersonalDataManager;
82 using base::Time;
83 using base::TimeDelta;
84 using base::WaitableEvent;
85 using browser_sync::AutofillDataTypeController;
86 using browser_sync::AutofillProfileDataTypeController;
87 using content::BrowserThread;
88 using syncer::AUTOFILL;
89 using syncer::AUTOFILL_PROFILE;
90 using syncer::BaseNode;
91 using syncer::syncable::BASE_VERSION;
92 using syncer::syncable::CREATE;
93 using syncer::syncable::GET_TYPE_ROOT;
94 using syncer::syncable::MutableEntry;
95 using syncer::syncable::SERVER_SPECIFICS;
96 using syncer::syncable::SPECIFICS;
97 using syncer::syncable::UNITTEST;
98 using syncer::syncable::WriterTag;
99 using syncer::syncable::WriteTransaction;
100 using sync_driver::DataTypeController;
101 using testing::_;
102 using testing::DoAll;
103 using testing::ElementsAre;
104 using testing::Not;
105 using testing::SetArgumentPointee;
106 using testing::Return;
108 namespace syncable {
109 class Id;
112 namespace {
114 const char kTestProfileName[] = "test-profile";
116 void RunAndSignal(const base::Closure& cb, WaitableEvent* event) {
117 cb.Run();
118 event->Signal();
121 } // namespace
123 class AutofillTableMock : public AutofillTable {
124 public:
125 AutofillTableMock() : AutofillTable("en-US") {}
126 MOCK_METHOD2(RemoveFormElement,
127 bool(const base::string16& name,
128 const base::string16& value)); // NOLINT
129 MOCK_METHOD1(GetAllAutofillEntries,
130 bool(std::vector<AutofillEntry>* entries)); // NOLINT
131 MOCK_METHOD4(GetAutofillTimestamps,
132 bool(const base::string16& name, // NOLINT
133 const base::string16& value,
134 base::Time* date_created,
135 base::Time* date_last_used));
136 MOCK_METHOD1(UpdateAutofillEntries,
137 bool(const std::vector<AutofillEntry>&)); // NOLINT
138 MOCK_METHOD1(GetAutofillProfiles,
139 bool(std::vector<AutofillProfile*>*)); // NOLINT
140 MOCK_METHOD1(UpdateAutofillProfile,
141 bool(const AutofillProfile&)); // NOLINT
142 MOCK_METHOD1(AddAutofillProfile,
143 bool(const AutofillProfile&)); // NOLINT
144 MOCK_METHOD1(RemoveAutofillProfile,
145 bool(const std::string&)); // NOLINT
148 MATCHER_P(MatchProfiles, profile, "") {
149 return (profile.Compare(arg) == 0);
152 class WebDatabaseFake : public WebDatabase {
153 public:
154 explicit WebDatabaseFake(AutofillTable* autofill_table) {
155 AddTable(autofill_table);
159 class MockAutofillBackend : public autofill::AutofillWebDataBackend {
160 public:
161 MockAutofillBackend(
162 WebDatabase* web_database,
163 const base::Closure& on_changed)
164 : web_database_(web_database),
165 on_changed_(on_changed) {
168 ~MockAutofillBackend() override {}
169 WebDatabase* GetDatabase() override { return web_database_; }
170 void AddObserver(
171 autofill::AutofillWebDataServiceObserverOnDBThread* observer) override {}
172 void RemoveObserver(
173 autofill::AutofillWebDataServiceObserverOnDBThread* observer) override {}
174 void RemoveExpiredFormElements() override {}
175 void NotifyOfMultipleAutofillChanges() override {
176 DCHECK_CURRENTLY_ON(BrowserThread::DB);
177 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, on_changed_);
180 private:
181 WebDatabase* web_database_;
182 base::Closure on_changed_;
185 class ProfileSyncServiceAutofillTest;
187 template<class AutofillProfile>
188 syncer::ModelType GetModelType() {
189 return syncer::UNSPECIFIED;
192 template<>
193 syncer::ModelType GetModelType<AutofillEntry>() {
194 return syncer::AUTOFILL;
197 template<>
198 syncer::ModelType GetModelType<AutofillProfile>() {
199 return syncer::AUTOFILL_PROFILE;
202 class TokenWebDataServiceFake : public TokenWebData {
203 public:
204 TokenWebDataServiceFake()
205 : TokenWebData(
206 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
207 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)) {
210 bool IsDatabaseLoaded() override { return true; }
212 AutofillWebDataService::Handle GetAllTokens(
213 WebDataServiceConsumer* consumer) override {
214 // TODO(tim): It would be nice if WebDataService was injected on
215 // construction of ProfileOAuth2TokenService rather than fetched by
216 // Initialize so that this isn't necessary (we could pass a NULL service).
217 // We currently do return it via EXPECT_CALLs, but without depending on
218 // order-of-initialization (which seems way more fragile) we can't tell
219 // which component is asking at what time, and some components in these
220 // Autofill tests require a WebDataService.
221 return 0;
224 private:
225 ~TokenWebDataServiceFake() override {}
227 DISALLOW_COPY_AND_ASSIGN(TokenWebDataServiceFake);
230 class WebDataServiceFake : public AutofillWebDataService {
231 public:
232 WebDataServiceFake()
233 : AutofillWebDataService(
234 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
235 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)),
236 web_database_(NULL),
237 autocomplete_syncable_service_(NULL),
238 autofill_profile_syncable_service_(NULL),
239 syncable_service_created_or_destroyed_(false, false) {
242 void SetDatabase(WebDatabase* web_database) {
243 web_database_ = web_database;
246 void StartSyncableService() {
247 // The |autofill_profile_syncable_service_| must be constructed on the DB
248 // thread.
249 const base::Closure& on_changed_callback = base::Bind(
250 &WebDataServiceFake::NotifyAutofillMultipleChangedOnUIThread,
251 AsWeakPtr());
253 BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
254 base::Bind(&WebDataServiceFake::CreateSyncableService,
255 base::Unretained(this),
256 on_changed_callback));
257 syncable_service_created_or_destroyed_.Wait();
260 void ShutdownSyncableService() {
261 // The |autofill_profile_syncable_service_| must be destructed on the DB
262 // thread.
263 BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
264 base::Bind(&WebDataServiceFake::DestroySyncableService,
265 base::Unretained(this)));
266 syncable_service_created_or_destroyed_.Wait();
269 bool IsDatabaseLoaded() override { return true; }
271 WebDatabase* GetDatabase() override { return web_database_; }
273 void OnAutofillEntriesChanged(const AutofillChangeList& changes) {
274 WaitableEvent event(true, false);
276 base::Closure notify_cb =
277 base::Bind(&AutocompleteSyncableService::AutofillEntriesChanged,
278 base::Unretained(autocomplete_syncable_service_),
279 changes);
280 BrowserThread::PostTask(
281 BrowserThread::DB,
282 FROM_HERE,
283 base::Bind(&RunAndSignal, notify_cb, &event));
284 event.Wait();
287 void OnAutofillProfileChanged(const AutofillProfileChange& changes) {
288 WaitableEvent event(true, false);
290 base::Closure notify_cb =
291 base::Bind(&AutocompleteSyncableService::AutofillProfileChanged,
292 base::Unretained(autofill_profile_syncable_service_),
293 changes);
294 BrowserThread::PostTask(
295 BrowserThread::DB,
296 FROM_HERE,
297 base::Bind(&RunAndSignal, notify_cb, &event));
298 event.Wait();
301 private:
302 ~WebDataServiceFake() override {}
304 void CreateSyncableService(const base::Closure& on_changed_callback) {
305 ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
306 // These services are deleted in DestroySyncableService().
307 backend_.reset(new MockAutofillBackend(
308 GetDatabase(), on_changed_callback));
309 AutocompleteSyncableService::CreateForWebDataServiceAndBackend(
310 this, backend_.get());
311 AutofillProfileSyncableService::CreateForWebDataServiceAndBackend(
312 this, backend_.get(), "en-US");
314 autocomplete_syncable_service_ =
315 AutocompleteSyncableService::FromWebDataService(this);
316 autofill_profile_syncable_service_ =
317 AutofillProfileSyncableService::FromWebDataService(this);
319 syncable_service_created_or_destroyed_.Signal();
322 void DestroySyncableService() {
323 ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
324 autocomplete_syncable_service_ = NULL;
325 autofill_profile_syncable_service_ = NULL;
326 backend_.reset();
327 syncable_service_created_or_destroyed_.Signal();
330 WebDatabase* web_database_;
331 AutocompleteSyncableService* autocomplete_syncable_service_;
332 AutofillProfileSyncableService* autofill_profile_syncable_service_;
333 scoped_ptr<autofill::AutofillWebDataBackend> backend_;
335 WaitableEvent syncable_service_created_or_destroyed_;
337 DISALLOW_COPY_AND_ASSIGN(WebDataServiceFake);
340 scoped_ptr<KeyedService> BuildMockWebDataServiceWrapper(
341 content::BrowserContext* profile) {
342 return make_scoped_ptr(new MockWebDataServiceWrapper(
343 new WebDataServiceFake(), new TokenWebDataServiceFake()));
346 ACTION_P(MakeAutocompleteSyncComponents, wds) {
347 EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
348 if (!BrowserThread::CurrentlyOn(BrowserThread::DB))
349 return base::WeakPtr<syncer::SyncableService>();
350 return AutocompleteSyncableService::FromWebDataService(wds)->AsWeakPtr();
353 ACTION_P(ReturnNewDataTypeManagerWithDebugListener, debug_listener) {
354 return new sync_driver::DataTypeManagerImpl(
355 base::Closure(),
356 debug_listener,
357 arg1,
358 arg2,
359 arg3,
360 arg4);
363 ACTION_P(MakeAutofillProfileSyncComponents, wds) {
364 EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
365 if (!BrowserThread::CurrentlyOn(BrowserThread::DB))
366 return base::WeakPtr<syncer::SyncableService>();
367 return AutofillProfileSyncableService::FromWebDataService(wds)->AsWeakPtr();
370 class AbstractAutofillFactory {
371 public:
372 virtual DataTypeController* CreateDataTypeController(
373 ProfileSyncComponentsFactory* factory,
374 TestingProfile* profile,
375 ProfileSyncService* service) = 0;
376 virtual void SetExpectation(ProfileSyncComponentsFactoryMock* factory,
377 ProfileSyncService* service,
378 AutofillWebDataService* wds,
379 DataTypeController* dtc) = 0;
380 virtual ~AbstractAutofillFactory() {}
383 class AutofillEntryFactory : public AbstractAutofillFactory {
384 public:
385 DataTypeController* CreateDataTypeController(
386 ProfileSyncComponentsFactory* factory,
387 TestingProfile* profile,
388 ProfileSyncService* service) override {
389 return new AutofillDataTypeController(factory, profile);
392 void SetExpectation(ProfileSyncComponentsFactoryMock* factory,
393 ProfileSyncService* service,
394 AutofillWebDataService* wds,
395 DataTypeController* dtc) override {
396 EXPECT_CALL(*factory, GetSyncableServiceForType(syncer::AUTOFILL)).
397 WillOnce(MakeAutocompleteSyncComponents(wds));
401 class AutofillProfileFactory : public AbstractAutofillFactory {
402 public:
403 DataTypeController* CreateDataTypeController(
404 ProfileSyncComponentsFactory* factory,
405 TestingProfile* profile,
406 ProfileSyncService* service) override {
407 return new AutofillProfileDataTypeController(factory, profile);
410 void SetExpectation(ProfileSyncComponentsFactoryMock* factory,
411 ProfileSyncService* service,
412 AutofillWebDataService* wds,
413 DataTypeController* dtc) override {
414 EXPECT_CALL(*factory,
415 GetSyncableServiceForType(syncer::AUTOFILL_PROFILE)).
416 WillOnce(MakeAutofillProfileSyncComponents(wds));
420 class MockPersonalDataManager : public PersonalDataManager {
421 public:
422 MockPersonalDataManager() : PersonalDataManager("en-US") {}
423 MOCK_CONST_METHOD0(IsDataLoaded, bool());
424 MOCK_METHOD0(LoadProfiles, void());
425 MOCK_METHOD0(LoadCreditCards, void());
426 MOCK_METHOD0(Refresh, void());
428 static scoped_ptr<KeyedService> Build(content::BrowserContext* profile) {
429 return make_scoped_ptr(new MockPersonalDataManager());
433 template <class T> class AddAutofillHelper;
435 class ProfileSyncServiceAutofillTest
436 : public AbstractProfileSyncServiceTest,
437 public syncer::DataTypeDebugInfoListener {
438 public:
439 // DataTypeDebugInfoListener implementation.
440 void OnDataTypeConfigureComplete(const std::vector<
441 syncer::DataTypeConfigurationStats>& configuration_stats) override {
442 ASSERT_EQ(1u, configuration_stats.size());
443 association_stats_ = configuration_stats[0].association_stats;
446 protected:
447 ProfileSyncServiceAutofillTest()
448 : profile_manager_(TestingBrowserProcess::GetGlobal()),
449 debug_ptr_factory_(this) {
451 ~ProfileSyncServiceAutofillTest() override {}
453 AutofillProfileFactory profile_factory_;
454 AutofillEntryFactory entry_factory_;
456 AbstractAutofillFactory* GetFactory(syncer::ModelType type) {
457 if (type == syncer::AUTOFILL) {
458 return &entry_factory_;
459 } else if (type == syncer::AUTOFILL_PROFILE) {
460 return &profile_factory_;
461 } else {
462 NOTREACHED();
463 return NULL;
467 void SetUp() override {
468 AbstractProfileSyncServiceTest::SetUp();
469 ASSERT_TRUE(profile_manager_.SetUp());
470 TestingProfile::TestingFactories testing_factories;
471 testing_factories.push_back(std::make_pair(
472 ProfileOAuth2TokenServiceFactory::GetInstance(),
473 BuildAutoIssuingFakeProfileOAuth2TokenService));
474 profile_ = profile_manager_.CreateTestingProfile(
475 kTestProfileName,
476 scoped_ptr<PrefServiceSyncable>(),
477 base::UTF8ToUTF16(kTestProfileName),
479 std::string(),
480 testing_factories);
481 web_database_.reset(new WebDatabaseFake(&autofill_table_));
482 MockWebDataServiceWrapper* wrapper =
483 static_cast<MockWebDataServiceWrapper*>(
484 WebDataServiceFactory::GetInstance()->SetTestingFactoryAndUse(
485 profile_, BuildMockWebDataServiceWrapper));
486 web_data_service_ =
487 static_cast<WebDataServiceFake*>(wrapper->GetAutofillWebData().get());
488 web_data_service_->SetDatabase(web_database_.get());
490 personal_data_manager_ = static_cast<MockPersonalDataManager*>(
491 autofill::PersonalDataManagerFactory::GetInstance()
492 ->SetTestingFactoryAndUse(profile_,
493 MockPersonalDataManager::Build));
495 EXPECT_CALL(*personal_data_manager_, LoadProfiles()).Times(1);
496 EXPECT_CALL(*personal_data_manager_, LoadCreditCards()).Times(1);
498 personal_data_manager_->Init(
499 WebDataServiceFactory::GetAutofillWebDataForProfile(
500 profile_, ServiceAccessType::EXPLICIT_ACCESS),
501 profile_->GetPrefs(),
502 AccountTrackerServiceFactory::GetForProfile(profile_),
503 profile_->IsOffTheRecord());
505 web_data_service_->StartSyncableService();
507 // When UpdateAutofillEntries() is called with an empty list, the return
508 // value should be |true|, rather than the default of |false|.
509 std::vector<AutofillEntry> empty;
510 EXPECT_CALL(autofill_table_, UpdateAutofillEntries(empty))
511 .WillRepeatedly(Return(true));
514 void TearDown() override {
515 // Note: The tear down order is important.
516 ProfileSyncServiceFactory::GetInstance()->SetTestingFactory(profile_, NULL);
517 web_data_service_->ShutdownOnUIThread();
518 web_data_service_->ShutdownSyncableService();
519 web_data_service_ = NULL;
520 // To prevent a leak, fully release TestURLRequestContext to ensure its
521 // destruction on the IO message loop.
522 profile_ = NULL;
523 profile_manager_.DeleteTestingProfile(kTestProfileName);
524 AbstractProfileSyncServiceTest::TearDown();
527 int GetSyncCount(syncer::ModelType type) {
528 syncer::ReadTransaction trans(FROM_HERE, sync_service_->GetUserShare());
529 syncer::ReadNode node(&trans);
530 if (node.InitTypeRoot(type) != syncer::BaseNode::INIT_OK)
531 return 0;
532 return node.GetTotalNodeCount() - 1;
535 void StartSyncService(const base::Closure& callback,
536 bool will_fail_association,
537 syncer::ModelType type) {
538 AbstractAutofillFactory* factory = GetFactory(type);
539 SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile_);
540 signin->SetAuthenticatedAccountInfo("12345", "test_user@gmail.com");
541 sync_service_ = TestProfileSyncService::BuildAutoStartAsyncInit(profile_,
542 callback);
544 ProfileSyncComponentsFactoryMock* components =
545 sync_service_->components_factory_mock();
546 DataTypeController* data_type_controller =
547 factory->CreateDataTypeController(components, profile_, sync_service_);
548 factory->SetExpectation(components,
549 sync_service_,
550 web_data_service_.get(),
551 data_type_controller);
553 EXPECT_CALL(*components, CreateDataTypeManager(_, _, _, _, _)).
554 WillOnce(ReturnNewDataTypeManagerWithDebugListener(
555 syncer::MakeWeakHandle(debug_ptr_factory_.GetWeakPtr())));
557 EXPECT_CALL(*personal_data_manager_, IsDataLoaded()).
558 WillRepeatedly(Return(true));
560 // We need tokens to get the tests going
561 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
562 ->UpdateCredentials(signin->GetAuthenticatedAccountId(),
563 "oauth2_login_token");
565 sync_service_->RegisterDataTypeController(data_type_controller);
566 sync_service_->Initialize();
567 base::MessageLoop::current()->Run();
569 // It's possible this test triggered an unrecoverable error, in which case
570 // we can't get the sync count.
571 if (sync_service_->IsSyncActive()) {
572 EXPECT_EQ(GetSyncCount(type),
573 association_stats_.num_sync_items_after_association);
575 EXPECT_EQ(association_stats_.num_sync_items_after_association,
576 association_stats_.num_sync_items_before_association +
577 association_stats_.num_sync_items_added -
578 association_stats_.num_sync_items_deleted);
581 bool AddAutofillSyncNode(const AutofillEntry& entry) {
582 syncer::WriteTransaction trans(FROM_HERE, sync_service_->GetUserShare());
583 syncer::ReadNode autofill_root(&trans);
584 if (autofill_root.InitTypeRoot(syncer::AUTOFILL) != BaseNode::INIT_OK) {
585 return false;
588 syncer::WriteNode node(&trans);
589 std::string tag = AutocompleteSyncableService::KeyToTag(
590 base::UTF16ToUTF8(entry.key().name()),
591 base::UTF16ToUTF8(entry.key().value()));
592 syncer::WriteNode::InitUniqueByCreationResult result =
593 node.InitUniqueByCreation(syncer::AUTOFILL, autofill_root, tag);
594 if (result != syncer::WriteNode::INIT_SUCCESS)
595 return false;
597 sync_pb::EntitySpecifics specifics;
598 AutocompleteSyncableService::WriteAutofillEntry(entry, &specifics);
599 node.SetEntitySpecifics(specifics);
600 return true;
603 bool AddAutofillSyncNode(const AutofillProfile& profile) {
604 syncer::WriteTransaction trans(FROM_HERE, sync_service_->GetUserShare());
605 syncer::ReadNode autofill_root(&trans);
606 if (autofill_root.InitTypeRoot(AUTOFILL_PROFILE) != BaseNode::INIT_OK) {
607 return false;
609 syncer::WriteNode node(&trans);
610 std::string tag = profile.guid();
611 syncer::WriteNode::InitUniqueByCreationResult result =
612 node.InitUniqueByCreation(syncer::AUTOFILL_PROFILE,
613 autofill_root, tag);
614 if (result != syncer::WriteNode::INIT_SUCCESS)
615 return false;
617 sync_pb::EntitySpecifics specifics;
618 AutofillProfileSyncableService::WriteAutofillProfile(profile, &specifics);
619 node.SetEntitySpecifics(specifics);
620 return true;
623 bool GetAutofillEntriesFromSyncDB(std::vector<AutofillEntry>* entries,
624 std::vector<AutofillProfile>* profiles) {
625 syncer::ReadTransaction trans(FROM_HERE, sync_service_->GetUserShare());
626 syncer::ReadNode autofill_root(&trans);
627 if (autofill_root.InitTypeRoot(syncer::AUTOFILL) != BaseNode::INIT_OK) {
628 return false;
631 int64 child_id = autofill_root.GetFirstChildId();
632 while (child_id != syncer::kInvalidId) {
633 syncer::ReadNode child_node(&trans);
634 if (child_node.InitByIdLookup(child_id) != BaseNode::INIT_OK)
635 return false;
637 const sync_pb::AutofillSpecifics& autofill(
638 child_node.GetEntitySpecifics().autofill());
639 if (autofill.has_value()) {
640 AutofillKey key(base::UTF8ToUTF16(autofill.name()),
641 base::UTF8ToUTF16(autofill.value()));
642 std::vector<base::Time> timestamps;
643 int timestamps_count = autofill.usage_timestamp_size();
644 for (int i = 0; i < timestamps_count; ++i) {
645 timestamps.push_back(Time::FromInternalValue(
646 autofill.usage_timestamp(i)));
648 entries->push_back(
649 AutofillEntry(key, timestamps.front(), timestamps.back()));
650 } else if (autofill.has_profile()) {
651 AutofillProfile p;
652 p.set_guid(autofill.profile().guid());
653 AutofillProfileSyncableService::OverwriteProfileWithServerData(
654 autofill.profile(), &p, "en-US");
655 profiles->push_back(p);
657 child_id = child_node.GetSuccessorId();
659 return true;
662 bool GetAutofillProfilesFromSyncDBUnderProfileNode(
663 std::vector<AutofillProfile>* profiles) {
664 syncer::ReadTransaction trans(FROM_HERE, sync_service_->GetUserShare());
665 syncer::ReadNode autofill_root(&trans);
666 if (autofill_root.InitTypeRoot(AUTOFILL_PROFILE) != BaseNode::INIT_OK) {
667 return false;
670 int64 child_id = autofill_root.GetFirstChildId();
671 while (child_id != syncer::kInvalidId) {
672 syncer::ReadNode child_node(&trans);
673 if (child_node.InitByIdLookup(child_id) != BaseNode::INIT_OK)
674 return false;
676 const sync_pb::AutofillProfileSpecifics& autofill(
677 child_node.GetEntitySpecifics().autofill_profile());
678 AutofillProfile p;
679 p.set_guid(autofill.guid());
680 AutofillProfileSyncableService::OverwriteProfileWithServerData(
681 autofill, &p, "en-US");
682 profiles->push_back(p);
683 child_id = child_node.GetSuccessorId();
685 return true;
688 void SetIdleChangeProcessorExpectations() {
689 EXPECT_CALL(autofill_table_, RemoveFormElement(_, _)).Times(0);
690 EXPECT_CALL(autofill_table_, GetAutofillTimestamps(_, _, _, _)).Times(0);
692 // Only permit UpdateAutofillEntries() to be called with an empty list.
693 std::vector<AutofillEntry> empty;
694 EXPECT_CALL(autofill_table_, UpdateAutofillEntries(Not(empty))).Times(0);
697 static AutofillEntry MakeAutofillEntry(const char* name,
698 const char* value,
699 int time_shift0,
700 int time_shift1) {
701 // Time deep in the past would cause Autocomplete sync to discard the
702 // entries.
703 static Time base_time = Time::Now().LocalMidnight();
705 base::Time date_created = base_time + TimeDelta::FromSeconds(time_shift0);
706 base::Time date_last_used = date_created;
707 if (time_shift1 >= 0)
708 date_last_used = base_time + TimeDelta::FromSeconds(time_shift1);
709 return AutofillEntry(
710 AutofillKey(base::ASCIIToUTF16(name), base::ASCIIToUTF16(value)),
711 date_created, date_last_used);
714 static AutofillEntry MakeAutofillEntry(const char* name,
715 const char* value,
716 int time_shift) {
717 return MakeAutofillEntry(name, value, time_shift, -1);
720 friend class AddAutofillHelper<AutofillEntry>;
721 friend class AddAutofillHelper<AutofillProfile>;
722 friend class FakeServerUpdater;
724 TestingProfileManager profile_manager_;
725 TestingProfile* profile_;
726 AutofillTableMock autofill_table_;
727 scoped_ptr<WebDatabaseFake> web_database_;
728 scoped_refptr<WebDataServiceFake> web_data_service_;
729 MockPersonalDataManager* personal_data_manager_;
730 syncer::DataTypeAssociationStats association_stats_;
731 base::WeakPtrFactory<DataTypeDebugInfoListener> debug_ptr_factory_;
734 template <class T>
735 class AddAutofillHelper {
736 public:
737 AddAutofillHelper(ProfileSyncServiceAutofillTest* test,
738 const std::vector<T>& entries)
739 : callback_(base::Bind(&AddAutofillHelper::AddAutofillCallback,
740 base::Unretained(this), test, entries)),
741 success_(false) {
744 const base::Closure& callback() const { return callback_; }
745 bool success() { return success_; }
747 private:
748 void AddAutofillCallback(ProfileSyncServiceAutofillTest* test,
749 const std::vector<T>& entries) {
750 if (!test->CreateRoot(GetModelType<T>()))
751 return;
753 for (size_t i = 0; i < entries.size(); ++i) {
754 if (!test->AddAutofillSyncNode(entries[i]))
755 return;
757 success_ = true;
760 base::Closure callback_;
761 bool success_;
764 // Overload write transaction to use custom NotifyTransactionComplete
765 class WriteTransactionTest: public WriteTransaction {
766 public:
767 WriteTransactionTest(const tracked_objects::Location& from_here,
768 WriterTag writer,
769 syncer::syncable::Directory* directory,
770 scoped_ptr<WaitableEvent>* wait_for_syncapi)
771 : WriteTransaction(from_here, writer, directory),
772 wait_for_syncapi_(wait_for_syncapi) { }
774 void NotifyTransactionComplete(syncer::ModelTypeSet types) override {
775 // This is where we differ. Force a thread change here, giving another
776 // thread a chance to create a WriteTransaction
777 (*wait_for_syncapi_)->Wait();
779 WriteTransaction::NotifyTransactionComplete(types);
782 private:
783 scoped_ptr<WaitableEvent>* wait_for_syncapi_;
786 // Our fake server updater. Needs the RefCountedThreadSafe inheritance so we can
787 // post tasks with it.
788 class FakeServerUpdater : public base::RefCountedThreadSafe<FakeServerUpdater> {
789 public:
790 FakeServerUpdater(TestProfileSyncService* service,
791 scoped_ptr<WaitableEvent>* wait_for_start,
792 scoped_ptr<WaitableEvent>* wait_for_syncapi)
793 : entry_(ProfileSyncServiceAutofillTest::MakeAutofillEntry("0", "0", 0)),
794 service_(service),
795 wait_for_start_(wait_for_start),
796 wait_for_syncapi_(wait_for_syncapi),
797 is_finished_(false, false) { }
799 void Update() {
800 // This gets called in a modelsafeworker thread.
801 ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
803 syncer::UserShare* user_share = service_->GetUserShare();
804 syncer::syncable::Directory* directory = user_share->directory.get();
806 // Create autofill protobuf.
807 std::string tag = AutocompleteSyncableService::KeyToTag(
808 base::UTF16ToUTF8(entry_.key().name()),
809 base::UTF16ToUTF8(entry_.key().value()));
810 sync_pb::AutofillSpecifics new_autofill;
811 new_autofill.set_name(base::UTF16ToUTF8(entry_.key().name()));
812 new_autofill.set_value(base::UTF16ToUTF8(entry_.key().value()));
813 new_autofill.add_usage_timestamp(entry_.date_created().ToInternalValue());
814 if (entry_.date_created() != entry_.date_last_used()) {
815 new_autofill.add_usage_timestamp(
816 entry_.date_last_used().ToInternalValue());
819 sync_pb::EntitySpecifics entity_specifics;
820 entity_specifics.mutable_autofill()->CopyFrom(new_autofill);
823 // Tell main thread we've started
824 (*wait_for_start_)->Signal();
826 // Create write transaction.
827 WriteTransactionTest trans(FROM_HERE, UNITTEST, directory,
828 wait_for_syncapi_);
830 // Create actual entry based on autofill protobuf information.
831 // Simulates effects of UpdateLocalDataFromServerData
832 MutableEntry parent(&trans, GET_TYPE_ROOT, syncer::AUTOFILL);
833 MutableEntry item(&trans, CREATE, syncer::AUTOFILL, parent.GetId(), tag);
834 ASSERT_TRUE(item.good());
835 item.PutSpecifics(entity_specifics);
836 item.PutServerSpecifics(entity_specifics);
837 item.PutBaseVersion(1);
838 syncer::syncable::Id server_item_id =
839 service_->id_factory()->NewServerId();
840 item.PutId(server_item_id);
841 syncer::syncable::Id new_predecessor;
842 ASSERT_TRUE(item.PutPredecessor(new_predecessor));
844 DVLOG(1) << "FakeServerUpdater finishing.";
845 is_finished_.Signal();
848 void CreateNewEntry(const AutofillEntry& entry) {
849 entry_ = entry;
850 ASSERT_FALSE(BrowserThread::CurrentlyOn(BrowserThread::DB));
851 if (!BrowserThread::PostTask(
852 BrowserThread::DB, FROM_HERE,
853 base::Bind(&FakeServerUpdater::Update, this))) {
854 NOTREACHED() << "Failed to post task to the db thread.";
855 return;
859 void CreateNewEntryAndWait(const AutofillEntry& entry) {
860 entry_ = entry;
861 ASSERT_FALSE(BrowserThread::CurrentlyOn(BrowserThread::DB));
862 is_finished_.Reset();
863 if (!BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
864 base::Bind(&FakeServerUpdater::Update, this))) {
865 NOTREACHED() << "Failed to post task to the db thread.";
866 return;
868 is_finished_.Wait();
871 private:
872 friend class base::RefCountedThreadSafe<FakeServerUpdater>;
873 ~FakeServerUpdater() { }
875 AutofillEntry entry_;
876 TestProfileSyncService* service_;
877 scoped_ptr<WaitableEvent>* wait_for_start_;
878 scoped_ptr<WaitableEvent>* wait_for_syncapi_;
879 WaitableEvent is_finished_;
880 syncer::syncable::Id parent_id_;
883 // TODO(skrul): Test abort startup.
884 // TODO(skrul): Test processing of cloud changes.
885 // TODO(tim): Add autofill data type controller test, and a case to cover
886 // waiting for the PersonalDataManager.
887 TEST_F(ProfileSyncServiceAutofillTest, FailModelAssociation) {
888 // Don't create the root autofill node so startup fails.
889 StartSyncService(base::Closure(), true, syncer::AUTOFILL);
890 EXPECT_TRUE(sync_service_->HasUnrecoverableError());
893 TEST_F(ProfileSyncServiceAutofillTest, EmptyNativeEmptySync) {
894 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).WillOnce(Return(true));
895 SetIdleChangeProcessorExpectations();
896 CreateRootHelper create_root(this, syncer::AUTOFILL);
897 EXPECT_CALL(*personal_data_manager_, Refresh());
898 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
899 EXPECT_TRUE(create_root.success());
900 std::vector<AutofillEntry> sync_entries;
901 std::vector<AutofillProfile> sync_profiles;
902 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&sync_entries, &sync_profiles));
903 EXPECT_EQ(0U, sync_entries.size());
904 EXPECT_EQ(0U, sync_profiles.size());
907 TEST_F(ProfileSyncServiceAutofillTest, HasNativeEntriesEmptySync) {
908 std::vector<AutofillEntry> entries;
909 entries.push_back(MakeAutofillEntry("foo", "bar", 1));
910 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
911 WillOnce(DoAll(SetArgumentPointee<0>(entries), Return(true)));
912 SetIdleChangeProcessorExpectations();
913 CreateRootHelper create_root(this, syncer::AUTOFILL);
914 EXPECT_CALL(*personal_data_manager_, Refresh());
915 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
916 ASSERT_TRUE(create_root.success());
917 std::vector<AutofillEntry> sync_entries;
918 std::vector<AutofillProfile> sync_profiles;
919 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&sync_entries, &sync_profiles));
920 ASSERT_EQ(1U, entries.size());
921 EXPECT_TRUE(entries[0] == sync_entries[0]);
922 EXPECT_EQ(0U, sync_profiles.size());
925 TEST_F(ProfileSyncServiceAutofillTest, HasProfileEmptySync) {
926 std::vector<AutofillProfile*> profiles;
927 std::vector<AutofillProfile> expected_profiles;
928 // Owned by GetAutofillProfiles caller.
929 AutofillProfile* profile0 = new AutofillProfile;
930 autofill::test::SetProfileInfoWithGuid(profile0,
931 "54B3F9AA-335E-4F71-A27D-719C41564230", "Billing",
932 "Mitchell", "Morrison",
933 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
934 "91601", "US", "12345678910");
935 profiles.push_back(profile0);
936 expected_profiles.push_back(*profile0);
937 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
938 WillOnce(DoAll(SetArgumentPointee<0>(profiles), Return(true)));
939 EXPECT_CALL(*personal_data_manager_, Refresh());
940 SetIdleChangeProcessorExpectations();
941 CreateRootHelper create_root(this, syncer::AUTOFILL_PROFILE);
942 StartSyncService(create_root.callback(), false, syncer::AUTOFILL_PROFILE);
943 ASSERT_TRUE(create_root.success());
944 std::vector<AutofillProfile> sync_profiles;
945 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(&sync_profiles));
946 EXPECT_EQ(1U, sync_profiles.size());
947 EXPECT_EQ(0, expected_profiles[0].Compare(sync_profiles[0]));
950 TEST_F(ProfileSyncServiceAutofillTest, HasNativeWithDuplicatesEmptySync) {
951 // There is buggy autofill code that allows duplicate name/value
952 // pairs to exist in the database with separate pair_ids.
953 std::vector<AutofillEntry> entries;
954 entries.push_back(MakeAutofillEntry("foo", "bar", 1));
955 entries.push_back(MakeAutofillEntry("dup", "", 2));
956 entries.push_back(MakeAutofillEntry("dup", "", 3));
957 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
958 WillOnce(DoAll(SetArgumentPointee<0>(entries), Return(true)));
959 SetIdleChangeProcessorExpectations();
960 CreateRootHelper create_root(this, syncer::AUTOFILL);
961 EXPECT_CALL(*personal_data_manager_, Refresh());
962 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
963 ASSERT_TRUE(create_root.success());
964 std::vector<AutofillEntry> sync_entries;
965 std::vector<AutofillProfile> sync_profiles;
966 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&sync_entries, &sync_profiles));
967 EXPECT_EQ(2U, sync_entries.size());
970 TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSyncNoMerge) {
971 AutofillEntry native_entry(MakeAutofillEntry("native", "entry", 1));
972 AutofillEntry sync_entry(MakeAutofillEntry("sync", "entry", 2));
974 std::vector<AutofillEntry> native_entries;
975 native_entries.push_back(native_entry);
977 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
978 WillOnce(DoAll(SetArgumentPointee<0>(native_entries), Return(true)));
980 std::vector<AutofillEntry> sync_entries;
981 sync_entries.push_back(sync_entry);
983 AddAutofillHelper<AutofillEntry> add_autofill(this, sync_entries);
985 EXPECT_CALL(autofill_table_, UpdateAutofillEntries(ElementsAre(sync_entry))).
986 WillOnce(Return(true));
988 EXPECT_CALL(*personal_data_manager_, Refresh());
989 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL);
990 ASSERT_TRUE(add_autofill.success());
992 std::set<AutofillEntry> expected_entries;
993 expected_entries.insert(native_entry);
994 expected_entries.insert(sync_entry);
996 std::vector<AutofillEntry> new_sync_entries;
997 std::vector<AutofillProfile> new_sync_profiles;
998 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
999 &new_sync_profiles));
1000 std::set<AutofillEntry> new_sync_entries_set(new_sync_entries.begin(),
1001 new_sync_entries.end());
1003 EXPECT_TRUE(expected_entries == new_sync_entries_set);
1006 TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSyncMergeEntry) {
1007 AutofillEntry native_entry(MakeAutofillEntry("merge", "entry", 1));
1008 AutofillEntry sync_entry(MakeAutofillEntry("merge", "entry", 2));
1009 AutofillEntry merged_entry(MakeAutofillEntry("merge", "entry", 1, 2));
1011 std::vector<AutofillEntry> native_entries;
1012 native_entries.push_back(native_entry);
1013 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
1014 WillOnce(DoAll(SetArgumentPointee<0>(native_entries), Return(true)));
1016 std::vector<AutofillEntry> sync_entries;
1017 sync_entries.push_back(sync_entry);
1018 AddAutofillHelper<AutofillEntry> add_autofill(this, sync_entries);
1020 EXPECT_CALL(autofill_table_,
1021 UpdateAutofillEntries(ElementsAre(merged_entry))).WillOnce(Return(true));
1022 EXPECT_CALL(*personal_data_manager_, Refresh());
1023 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL);
1024 ASSERT_TRUE(add_autofill.success());
1026 std::vector<AutofillEntry> new_sync_entries;
1027 std::vector<AutofillProfile> new_sync_profiles;
1028 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
1029 &new_sync_profiles));
1030 ASSERT_EQ(1U, new_sync_entries.size());
1031 EXPECT_TRUE(merged_entry == new_sync_entries[0]);
1034 TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSyncMergeProfile) {
1035 AutofillProfile sync_profile;
1036 autofill::test::SetProfileInfoWithGuid(&sync_profile,
1037 "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
1038 "Mitchell", "Morrison",
1039 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1040 "91601", "US", "12345678910");
1042 AutofillProfile* native_profile = new AutofillProfile;
1043 autofill::test::SetProfileInfoWithGuid(native_profile,
1044 "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing", "Alicia", "Saenz",
1045 "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL",
1046 "32801", "US", "19482937549");
1048 std::vector<AutofillProfile*> native_profiles;
1049 native_profiles.push_back(native_profile);
1050 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
1051 WillOnce(DoAll(SetArgumentPointee<0>(native_profiles), Return(true)));
1053 std::vector<AutofillProfile> sync_profiles;
1054 sync_profiles.push_back(sync_profile);
1055 AddAutofillHelper<AutofillProfile> add_autofill(this, sync_profiles);
1057 EXPECT_CALL(autofill_table_,
1058 UpdateAutofillProfile(MatchProfiles(sync_profile))).
1059 WillOnce(Return(true));
1060 EXPECT_CALL(*personal_data_manager_, Refresh());
1061 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL_PROFILE);
1062 ASSERT_TRUE(add_autofill.success());
1064 std::vector<AutofillProfile> new_sync_profiles;
1065 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1066 &new_sync_profiles));
1067 ASSERT_EQ(1U, new_sync_profiles.size());
1068 EXPECT_EQ(0, sync_profile.Compare(new_sync_profiles[0]));
1071 TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSyncMergeProfileCombine) {
1072 AutofillProfile sync_profile;
1073 autofill::test::SetProfileInfoWithGuid(&sync_profile,
1074 "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
1075 "Mitchell", "Morrison",
1076 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1077 "91601", "US", "12345678910");
1079 AutofillProfile* native_profile = new AutofillProfile;
1080 // Same address, but different names, phones and e-mails.
1081 autofill::test::SetProfileInfoWithGuid(native_profile,
1082 "23355099-1170-4B71-8ED4-144470CC9EBF", "Billing", "Alicia", "Saenz",
1083 "joewayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1084 "91601", "US", "19482937549");
1086 AutofillProfile expected_profile(sync_profile);
1087 expected_profile.OverwriteWith(*native_profile, "en-US");
1089 std::vector<AutofillProfile*> native_profiles;
1090 native_profiles.push_back(native_profile);
1091 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
1092 WillOnce(DoAll(SetArgumentPointee<0>(native_profiles), Return(true)));
1093 EXPECT_CALL(autofill_table_,
1094 AddAutofillProfile(MatchProfiles(expected_profile))).
1095 WillOnce(Return(true));
1096 EXPECT_CALL(autofill_table_,
1097 RemoveAutofillProfile("23355099-1170-4B71-8ED4-144470CC9EBF")).
1098 WillOnce(Return(true));
1099 std::vector<AutofillProfile> sync_profiles;
1100 sync_profiles.push_back(sync_profile);
1101 AddAutofillHelper<AutofillProfile> add_autofill(this, sync_profiles);
1103 EXPECT_CALL(*personal_data_manager_, Refresh());
1104 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL_PROFILE);
1105 ASSERT_TRUE(add_autofill.success());
1107 std::vector<AutofillProfile> new_sync_profiles;
1108 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1109 &new_sync_profiles));
1110 ASSERT_EQ(1U, new_sync_profiles.size());
1111 // Check that key fields are the same.
1112 EXPECT_TRUE(new_sync_profiles[0].IsSubsetOf(sync_profile, "en-US"));
1115 TEST_F(ProfileSyncServiceAutofillTest, MergeProfileWithDifferentGuid) {
1116 AutofillProfile sync_profile;
1118 autofill::test::SetProfileInfoWithGuid(&sync_profile,
1119 "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
1120 "Mitchell", "Morrison",
1121 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1122 "91601", "US", "12345678910");
1124 std::string native_guid = "EDC609ED-7EEE-4F27-B00C-423242A9C44B";
1125 AutofillProfile* native_profile = new AutofillProfile;
1126 autofill::test::SetProfileInfoWithGuid(native_profile,
1127 native_guid.c_str(), "Billing",
1128 "Mitchell", "Morrison",
1129 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1130 "91601", "US", "12345678910");
1132 std::vector<AutofillProfile*> native_profiles;
1133 native_profiles.push_back(native_profile);
1134 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
1135 WillOnce(DoAll(SetArgumentPointee<0>(native_profiles), Return(true)));
1137 std::vector<AutofillProfile> sync_profiles;
1138 sync_profiles.push_back(sync_profile);
1139 AddAutofillHelper<AutofillProfile> add_autofill(this, sync_profiles);
1141 EXPECT_CALL(autofill_table_, AddAutofillProfile(_)).
1142 WillOnce(Return(true));
1143 EXPECT_CALL(autofill_table_, RemoveAutofillProfile(native_guid)).
1144 WillOnce(Return(true));
1145 EXPECT_CALL(*personal_data_manager_, Refresh());
1146 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL_PROFILE);
1147 ASSERT_TRUE(add_autofill.success());
1149 std::vector<AutofillProfile> new_sync_profiles;
1150 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1151 &new_sync_profiles));
1152 ASSERT_EQ(1U, new_sync_profiles.size());
1153 EXPECT_EQ(0, sync_profile.Compare(new_sync_profiles[0]));
1154 EXPECT_EQ(sync_profile.guid(), new_sync_profiles[0].guid());
1157 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeAddEntry) {
1158 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).WillOnce(Return(true));
1159 EXPECT_CALL(*personal_data_manager_, Refresh());
1160 SetIdleChangeProcessorExpectations();
1161 CreateRootHelper create_root(this, syncer::AUTOFILL);
1162 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
1163 ASSERT_TRUE(create_root.success());
1165 AutofillEntry added_entry(MakeAutofillEntry("added", "entry", 1));
1167 EXPECT_CALL(autofill_table_, GetAutofillTimestamps(_, _, _, _)).
1168 WillOnce(DoAll(SetArgumentPointee<2>(added_entry.date_created()),
1169 SetArgumentPointee<3>(added_entry.date_last_used()),
1170 Return(true)));
1172 AutofillChangeList changes;
1173 changes.push_back(AutofillChange(AutofillChange::ADD, added_entry.key()));
1175 web_data_service_->OnAutofillEntriesChanged(changes);
1177 std::vector<AutofillEntry> new_sync_entries;
1178 std::vector<AutofillProfile> new_sync_profiles;
1179 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
1180 &new_sync_profiles));
1181 ASSERT_EQ(1U, new_sync_entries.size());
1182 EXPECT_TRUE(added_entry == new_sync_entries[0]);
1185 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeAddProfile) {
1186 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).WillOnce(Return(true));
1187 EXPECT_CALL(*personal_data_manager_, Refresh());
1188 SetIdleChangeProcessorExpectations();
1189 CreateRootHelper create_root(this, syncer::AUTOFILL_PROFILE);
1190 StartSyncService(create_root.callback(), false, syncer::AUTOFILL_PROFILE);
1191 ASSERT_TRUE(create_root.success());
1193 AutofillProfile added_profile;
1194 autofill::test::SetProfileInfoWithGuid(&added_profile,
1195 "D6ADA912-D374-4C0A-917D-F5C8EBE43011", "Josephine", "Alicia", "Saenz",
1196 "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL",
1197 "32801", "US", "19482937549");
1199 AutofillProfileChange change(
1200 AutofillProfileChange::ADD, added_profile.guid(), &added_profile);
1201 web_data_service_->OnAutofillProfileChanged(change);
1203 std::vector<AutofillProfile> new_sync_profiles;
1204 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1205 &new_sync_profiles));
1206 ASSERT_EQ(1U, new_sync_profiles.size());
1207 EXPECT_EQ(0, added_profile.Compare(new_sync_profiles[0]));
1210 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeUpdateEntry) {
1211 AutofillEntry original_entry(MakeAutofillEntry("my", "entry", 1));
1212 std::vector<AutofillEntry> original_entries;
1213 original_entries.push_back(original_entry);
1215 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
1216 WillOnce(DoAll(SetArgumentPointee<0>(original_entries), Return(true)));
1217 EXPECT_CALL(*personal_data_manager_, Refresh());
1218 CreateRootHelper create_root(this, syncer::AUTOFILL);
1219 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
1220 ASSERT_TRUE(create_root.success());
1222 AutofillEntry updated_entry(MakeAutofillEntry("my", "entry", 1, 2));
1224 EXPECT_CALL(autofill_table_, GetAutofillTimestamps(_, _, _, _)).
1225 WillOnce(DoAll(SetArgumentPointee<2>(updated_entry.date_created()),
1226 SetArgumentPointee<3>(updated_entry.date_last_used()),
1227 Return(true)));
1229 AutofillChangeList changes;
1230 changes.push_back(AutofillChange(AutofillChange::UPDATE,
1231 updated_entry.key()));
1232 web_data_service_->OnAutofillEntriesChanged(changes);
1234 std::vector<AutofillEntry> new_sync_entries;
1235 std::vector<AutofillProfile> new_sync_profiles;
1236 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
1237 &new_sync_profiles));
1238 ASSERT_EQ(1U, new_sync_entries.size());
1239 EXPECT_TRUE(updated_entry == new_sync_entries[0]);
1243 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeRemoveEntry) {
1244 AutofillEntry original_entry(MakeAutofillEntry("my", "entry", 1));
1245 std::vector<AutofillEntry> original_entries;
1246 original_entries.push_back(original_entry);
1248 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
1249 WillOnce(DoAll(SetArgumentPointee<0>(original_entries), Return(true)));
1250 EXPECT_CALL(*personal_data_manager_, Refresh());
1251 CreateRootHelper create_root(this, syncer::AUTOFILL);
1252 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
1253 ASSERT_TRUE(create_root.success());
1255 AutofillChangeList changes;
1256 changes.push_back(AutofillChange(AutofillChange::REMOVE,
1257 original_entry.key()));
1258 web_data_service_->OnAutofillEntriesChanged(changes);
1260 std::vector<AutofillEntry> new_sync_entries;
1261 std::vector<AutofillProfile> new_sync_profiles;
1262 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
1263 &new_sync_profiles));
1264 ASSERT_EQ(0U, new_sync_entries.size());
1267 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeRemoveProfile) {
1268 AutofillProfile sync_profile;
1269 autofill::test::SetProfileInfoWithGuid(&sync_profile,
1270 "3BA5FA1B-1EC4-4BB3-9B57-EC92BE3C1A09", "Josephine", "Alicia", "Saenz",
1271 "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL",
1272 "32801", "US", "19482937549");
1273 AutofillProfile* native_profile = new AutofillProfile;
1274 autofill::test::SetProfileInfoWithGuid(native_profile,
1275 "3BA5FA1B-1EC4-4BB3-9B57-EC92BE3C1A09", "Josephine", "Alicia", "Saenz",
1276 "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL",
1277 "32801", "US", "19482937549");
1279 std::vector<AutofillProfile*> native_profiles;
1280 native_profiles.push_back(native_profile);
1281 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
1282 WillOnce(DoAll(SetArgumentPointee<0>(native_profiles), Return(true)));
1284 std::vector<AutofillProfile> sync_profiles;
1285 sync_profiles.push_back(sync_profile);
1286 AddAutofillHelper<AutofillProfile> add_autofill(this, sync_profiles);
1287 EXPECT_CALL(*personal_data_manager_, Refresh());
1288 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL_PROFILE);
1289 ASSERT_TRUE(add_autofill.success());
1291 AutofillProfileChange change(
1292 AutofillProfileChange::REMOVE, sync_profile.guid(), NULL);
1293 web_data_service_->OnAutofillProfileChanged(change);
1295 std::vector<AutofillProfile> new_sync_profiles;
1296 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1297 &new_sync_profiles));
1298 ASSERT_EQ(0U, new_sync_profiles.size());
1301 // http://crbug.com/57884
1302 TEST_F(ProfileSyncServiceAutofillTest, DISABLED_ServerChangeRace) {
1303 // Once for MergeDataAndStartSyncing() and twice for ProcessSyncChanges(), via
1304 // LoadAutofillData().
1305 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
1306 Times(3).WillRepeatedly(Return(true));
1307 // On the other hand Autofill and Autocomplete are separated now, so
1308 // GetAutofillProfiles() should not be called.
1309 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).Times(0);
1310 EXPECT_CALL(autofill_table_, UpdateAutofillEntries(_)).
1311 WillRepeatedly(Return(true));
1312 EXPECT_CALL(*personal_data_manager_, Refresh()).Times(3);
1313 CreateRootHelper create_root(this, syncer::AUTOFILL);
1314 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
1315 ASSERT_TRUE(create_root.success());
1317 // (true, false) means we have to reset after |Signal|, init to unsignaled.
1318 scoped_ptr<WaitableEvent> wait_for_start(new WaitableEvent(true, false));
1319 scoped_ptr<WaitableEvent> wait_for_syncapi(new WaitableEvent(true, false));
1320 scoped_refptr<FakeServerUpdater> updater(new FakeServerUpdater(
1321 sync_service_, &wait_for_start, &wait_for_syncapi));
1323 // This server side update will stall waiting for CommitWaiter.
1324 updater->CreateNewEntry(MakeAutofillEntry("server", "entry", 1));
1325 wait_for_start->Wait();
1327 AutofillEntry syncapi_entry(MakeAutofillEntry("syncapi", "entry", 2));
1328 ASSERT_TRUE(AddAutofillSyncNode(syncapi_entry));
1329 DVLOG(1) << "Syncapi update finished.";
1331 // If we reach here, it means syncapi succeeded and we didn't deadlock. Yay!
1332 // Signal FakeServerUpdater that it can complete.
1333 wait_for_syncapi->Signal();
1335 // Make another entry to ensure nothing broke afterwards and wait for finish
1336 // to clean up.
1337 updater->CreateNewEntryAndWait(MakeAutofillEntry("server2", "entry2", 3));
1339 std::vector<AutofillEntry> sync_entries;
1340 std::vector<AutofillProfile> sync_profiles;
1341 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&sync_entries, &sync_profiles));
1342 EXPECT_EQ(3U, sync_entries.size());
1343 EXPECT_EQ(0U, sync_profiles.size());
1344 for (size_t i = 0; i < sync_entries.size(); i++) {
1345 DVLOG(1) << "Entry " << i << ": " << sync_entries[i].key().name()
1346 << ", " << sync_entries[i].key().value();