Update CrOS OOBE throbber to MD throbber; delete old asset
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service_autofill_unittest.cc
blobb0f59359bc8080ccd380d524ac4819d75b9ce407
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_service.h"
34 #include "chrome/browser/sync/profile_sync_service_factory.h"
35 #include "chrome/browser/sync/profile_sync_test_util.h"
36 #include "chrome/browser/sync/test_profile_sync_service.h"
37 #include "chrome/browser/web_data_service_factory.h"
38 #include "chrome/test/base/testing_browser_process.h"
39 #include "chrome/test/base/testing_profile.h"
40 #include "chrome/test/base/testing_profile_manager.h"
41 #include "components/autofill/core/browser/autofill_test_utils.h"
42 #include "components/autofill/core/browser/personal_data_manager.h"
43 #include "components/autofill/core/browser/webdata/autocomplete_syncable_service.h"
44 #include "components/autofill/core/browser/webdata/autofill_change.h"
45 #include "components/autofill/core/browser/webdata/autofill_entry.h"
46 #include "components/autofill/core/browser/webdata/autofill_profile_syncable_service.h"
47 #include "components/autofill/core/browser/webdata/autofill_table.h"
48 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
49 #include "components/signin/core/browser/account_tracker_service.h"
50 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
51 #include "components/signin/core/browser/signin_manager.h"
52 #include "components/sync_driver/data_type_controller.h"
53 #include "components/sync_driver/profile_sync_components_factory.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 {
110 const char kTestProfileName[] = "test-profile";
112 void RunAndSignal(const base::Closure& cb, WaitableEvent* event) {
113 cb.Run();
114 event->Signal();
117 } // namespace
119 class AutofillTableMock : public AutofillTable {
120 public:
121 AutofillTableMock() {}
122 MOCK_METHOD2(RemoveFormElement,
123 bool(const base::string16& name,
124 const base::string16& value)); // NOLINT
125 MOCK_METHOD1(GetAllAutofillEntries,
126 bool(std::vector<AutofillEntry>* entries)); // NOLINT
127 MOCK_METHOD4(GetAutofillTimestamps,
128 bool(const base::string16& name, // NOLINT
129 const base::string16& value,
130 base::Time* date_created,
131 base::Time* date_last_used));
132 MOCK_METHOD1(UpdateAutofillEntries,
133 bool(const std::vector<AutofillEntry>&)); // NOLINT
134 MOCK_METHOD1(GetAutofillProfiles,
135 bool(std::vector<AutofillProfile*>*)); // NOLINT
136 MOCK_METHOD1(UpdateAutofillProfile,
137 bool(const AutofillProfile&)); // NOLINT
138 MOCK_METHOD1(AddAutofillProfile,
139 bool(const AutofillProfile&)); // NOLINT
140 MOCK_METHOD1(RemoveAutofillProfile,
141 bool(const std::string&)); // NOLINT
144 MATCHER_P(MatchProfiles, profile, "") {
145 return (profile.Compare(arg) == 0);
148 class WebDatabaseFake : public WebDatabase {
149 public:
150 explicit WebDatabaseFake(AutofillTable* autofill_table) {
151 AddTable(autofill_table);
155 class MockAutofillBackend : public autofill::AutofillWebDataBackend {
156 public:
157 MockAutofillBackend(
158 WebDatabase* web_database,
159 const base::Closure& on_changed)
160 : web_database_(web_database),
161 on_changed_(on_changed) {
164 ~MockAutofillBackend() override {}
165 WebDatabase* GetDatabase() override { return web_database_; }
166 void AddObserver(
167 autofill::AutofillWebDataServiceObserverOnDBThread* observer) override {}
168 void RemoveObserver(
169 autofill::AutofillWebDataServiceObserverOnDBThread* observer) override {}
170 void RemoveExpiredFormElements() override {}
171 void NotifyOfMultipleAutofillChanges() override {
172 DCHECK_CURRENTLY_ON(BrowserThread::DB);
173 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, on_changed_);
176 private:
177 WebDatabase* web_database_;
178 base::Closure on_changed_;
181 class ProfileSyncServiceAutofillTest;
183 template<class AutofillProfile>
184 syncer::ModelType GetModelType() {
185 return syncer::UNSPECIFIED;
188 template<>
189 syncer::ModelType GetModelType<AutofillEntry>() {
190 return syncer::AUTOFILL;
193 template<>
194 syncer::ModelType GetModelType<AutofillProfile>() {
195 return syncer::AUTOFILL_PROFILE;
198 class TokenWebDataServiceFake : public TokenWebData {
199 public:
200 TokenWebDataServiceFake()
201 : TokenWebData(
202 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
203 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)) {
206 bool IsDatabaseLoaded() override { return true; }
208 AutofillWebDataService::Handle GetAllTokens(
209 WebDataServiceConsumer* consumer) override {
210 // TODO(tim): It would be nice if WebDataService was injected on
211 // construction of ProfileOAuth2TokenService rather than fetched by
212 // Initialize so that this isn't necessary (we could pass a NULL service).
213 // We currently do return it via EXPECT_CALLs, but without depending on
214 // order-of-initialization (which seems way more fragile) we can't tell
215 // which component is asking at what time, and some components in these
216 // Autofill tests require a WebDataService.
217 return 0;
220 private:
221 ~TokenWebDataServiceFake() override {}
223 DISALLOW_COPY_AND_ASSIGN(TokenWebDataServiceFake);
226 class WebDataServiceFake : public AutofillWebDataService {
227 public:
228 WebDataServiceFake()
229 : AutofillWebDataService(
230 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
231 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)),
232 web_database_(NULL),
233 autocomplete_syncable_service_(NULL),
234 autofill_profile_syncable_service_(NULL),
235 syncable_service_created_or_destroyed_(false, false) {
238 void SetDatabase(WebDatabase* web_database) {
239 web_database_ = web_database;
242 void StartSyncableService() {
243 // The |autofill_profile_syncable_service_| must be constructed on the DB
244 // thread.
245 const base::Closure& on_changed_callback = base::Bind(
246 &WebDataServiceFake::NotifyAutofillMultipleChangedOnUIThread,
247 AsWeakPtr());
249 BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
250 base::Bind(&WebDataServiceFake::CreateSyncableService,
251 base::Unretained(this),
252 on_changed_callback));
253 syncable_service_created_or_destroyed_.Wait();
256 void ShutdownSyncableService() {
257 // The |autofill_profile_syncable_service_| must be destructed on the DB
258 // thread.
259 BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
260 base::Bind(&WebDataServiceFake::DestroySyncableService,
261 base::Unretained(this)));
262 syncable_service_created_or_destroyed_.Wait();
265 bool IsDatabaseLoaded() override { return true; }
267 WebDatabase* GetDatabase() override { return web_database_; }
269 void OnAutofillEntriesChanged(const AutofillChangeList& changes) {
270 WaitableEvent event(true, false);
272 base::Closure notify_cb =
273 base::Bind(&AutocompleteSyncableService::AutofillEntriesChanged,
274 base::Unretained(autocomplete_syncable_service_),
275 changes);
276 BrowserThread::PostTask(
277 BrowserThread::DB,
278 FROM_HERE,
279 base::Bind(&RunAndSignal, notify_cb, &event));
280 event.Wait();
283 void OnAutofillProfileChanged(const AutofillProfileChange& changes) {
284 WaitableEvent event(true, false);
286 base::Closure notify_cb =
287 base::Bind(&AutocompleteSyncableService::AutofillProfileChanged,
288 base::Unretained(autofill_profile_syncable_service_),
289 changes);
290 BrowserThread::PostTask(
291 BrowserThread::DB,
292 FROM_HERE,
293 base::Bind(&RunAndSignal, notify_cb, &event));
294 event.Wait();
297 private:
298 ~WebDataServiceFake() override {}
300 void CreateSyncableService(const base::Closure& on_changed_callback) {
301 ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
302 // These services are deleted in DestroySyncableService().
303 backend_.reset(new MockAutofillBackend(
304 GetDatabase(), on_changed_callback));
305 AutocompleteSyncableService::CreateForWebDataServiceAndBackend(
306 this, backend_.get());
307 AutofillProfileSyncableService::CreateForWebDataServiceAndBackend(
308 this, backend_.get(), "en-US");
310 autocomplete_syncable_service_ =
311 AutocompleteSyncableService::FromWebDataService(this);
312 autofill_profile_syncable_service_ =
313 AutofillProfileSyncableService::FromWebDataService(this);
315 syncable_service_created_or_destroyed_.Signal();
318 void DestroySyncableService() {
319 ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
320 autocomplete_syncable_service_ = NULL;
321 autofill_profile_syncable_service_ = NULL;
322 backend_.reset();
323 syncable_service_created_or_destroyed_.Signal();
326 WebDatabase* web_database_;
327 AutocompleteSyncableService* autocomplete_syncable_service_;
328 AutofillProfileSyncableService* autofill_profile_syncable_service_;
329 scoped_ptr<autofill::AutofillWebDataBackend> backend_;
331 WaitableEvent syncable_service_created_or_destroyed_;
333 DISALLOW_COPY_AND_ASSIGN(WebDataServiceFake);
336 scoped_ptr<KeyedService> BuildMockWebDataServiceWrapper(
337 content::BrowserContext* profile) {
338 return make_scoped_ptr(new MockWebDataServiceWrapper(
339 new WebDataServiceFake(), new TokenWebDataServiceFake()));
342 ACTION_P(MakeAutocompleteSyncComponents, wds) {
343 EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
344 if (!BrowserThread::CurrentlyOn(BrowserThread::DB))
345 return base::WeakPtr<syncer::SyncableService>();
346 return AutocompleteSyncableService::FromWebDataService(wds)->AsWeakPtr();
349 ACTION_P(ReturnNewDataTypeManagerWithDebugListener, debug_listener) {
350 return new sync_driver::DataTypeManagerImpl(
351 base::Closure(),
352 debug_listener,
353 arg1,
354 arg2,
355 arg3,
356 arg4);
359 ACTION_P(MakeAutofillProfileSyncComponents, wds) {
360 EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
361 if (!BrowserThread::CurrentlyOn(BrowserThread::DB))
362 return base::WeakPtr<syncer::SyncableService>();
363 return AutofillProfileSyncableService::FromWebDataService(wds)->AsWeakPtr();
366 class AbstractAutofillFactory {
367 public:
368 virtual DataTypeController* CreateDataTypeController(
369 ProfileSyncComponentsFactory* factory,
370 TestingProfile* profile,
371 ProfileSyncService* service) = 0;
372 virtual void SetExpectation(ProfileSyncComponentsFactoryMock* factory,
373 ProfileSyncService* service,
374 AutofillWebDataService* wds,
375 DataTypeController* dtc) = 0;
376 virtual ~AbstractAutofillFactory() {}
379 class AutofillEntryFactory : public AbstractAutofillFactory {
380 public:
381 DataTypeController* CreateDataTypeController(
382 ProfileSyncComponentsFactory* factory,
383 TestingProfile* profile,
384 ProfileSyncService* service) override {
385 return new AutofillDataTypeController(factory, profile);
388 void SetExpectation(ProfileSyncComponentsFactoryMock* factory,
389 ProfileSyncService* service,
390 AutofillWebDataService* wds,
391 DataTypeController* dtc) override {
392 EXPECT_CALL(*factory, GetSyncableServiceForType(syncer::AUTOFILL)).
393 WillOnce(MakeAutocompleteSyncComponents(wds));
397 class AutofillProfileFactory : public AbstractAutofillFactory {
398 public:
399 DataTypeController* CreateDataTypeController(
400 ProfileSyncComponentsFactory* factory,
401 TestingProfile* profile,
402 ProfileSyncService* service) override {
403 return new AutofillProfileDataTypeController(factory, profile);
406 void SetExpectation(ProfileSyncComponentsFactoryMock* factory,
407 ProfileSyncService* service,
408 AutofillWebDataService* wds,
409 DataTypeController* dtc) override {
410 EXPECT_CALL(*factory,
411 GetSyncableServiceForType(syncer::AUTOFILL_PROFILE)).
412 WillOnce(MakeAutofillProfileSyncComponents(wds));
416 class MockPersonalDataManager : public PersonalDataManager {
417 public:
418 MockPersonalDataManager() : PersonalDataManager("en-US") {}
419 MOCK_CONST_METHOD0(IsDataLoaded, bool());
420 MOCK_METHOD0(LoadProfiles, void());
421 MOCK_METHOD0(LoadCreditCards, void());
422 MOCK_METHOD0(Refresh, void());
424 static scoped_ptr<KeyedService> Build(content::BrowserContext* profile) {
425 return make_scoped_ptr(new MockPersonalDataManager());
429 template <class T> class AddAutofillHelper;
431 class ProfileSyncServiceAutofillTest
432 : public AbstractProfileSyncServiceTest,
433 public syncer::DataTypeDebugInfoListener {
434 public:
435 // DataTypeDebugInfoListener implementation.
436 void OnDataTypeConfigureComplete(const std::vector<
437 syncer::DataTypeConfigurationStats>& configuration_stats) override {
438 ASSERT_EQ(1u, configuration_stats.size());
439 association_stats_ = configuration_stats[0].association_stats;
442 protected:
443 ProfileSyncServiceAutofillTest()
444 : profile_manager_(TestingBrowserProcess::GetGlobal()),
445 debug_ptr_factory_(this) {
447 ~ProfileSyncServiceAutofillTest() override {}
449 AutofillProfileFactory profile_factory_;
450 AutofillEntryFactory entry_factory_;
452 AbstractAutofillFactory* GetFactory(syncer::ModelType type) {
453 if (type == syncer::AUTOFILL) {
454 return &entry_factory_;
455 } else if (type == syncer::AUTOFILL_PROFILE) {
456 return &profile_factory_;
457 } else {
458 NOTREACHED();
459 return NULL;
463 void SetUp() override {
464 AbstractProfileSyncServiceTest::SetUp();
465 ASSERT_TRUE(profile_manager_.SetUp());
466 TestingProfile::TestingFactories testing_factories;
467 testing_factories.push_back(std::make_pair(
468 ProfileOAuth2TokenServiceFactory::GetInstance(),
469 BuildAutoIssuingFakeProfileOAuth2TokenService));
470 profile_ = profile_manager_.CreateTestingProfile(
471 kTestProfileName,
472 scoped_ptr<PrefServiceSyncable>(),
473 base::UTF8ToUTF16(kTestProfileName),
475 std::string(),
476 testing_factories);
477 web_database_.reset(new WebDatabaseFake(&autofill_table_));
478 MockWebDataServiceWrapper* wrapper =
479 static_cast<MockWebDataServiceWrapper*>(
480 WebDataServiceFactory::GetInstance()->SetTestingFactoryAndUse(
481 profile_, BuildMockWebDataServiceWrapper));
482 web_data_service_ =
483 static_cast<WebDataServiceFake*>(wrapper->GetAutofillWebData().get());
484 web_data_service_->SetDatabase(web_database_.get());
486 personal_data_manager_ = static_cast<MockPersonalDataManager*>(
487 autofill::PersonalDataManagerFactory::GetInstance()
488 ->SetTestingFactoryAndUse(profile_,
489 MockPersonalDataManager::Build));
491 EXPECT_CALL(*personal_data_manager_, LoadProfiles()).Times(1);
492 EXPECT_CALL(*personal_data_manager_, LoadCreditCards()).Times(1);
494 personal_data_manager_->Init(
495 WebDataServiceFactory::GetAutofillWebDataForProfile(
496 profile_, ServiceAccessType::EXPLICIT_ACCESS),
497 profile_->GetPrefs(),
498 AccountTrackerServiceFactory::GetForProfile(profile_),
499 profile_->IsOffTheRecord());
501 web_data_service_->StartSyncableService();
503 // When UpdateAutofillEntries() is called with an empty list, the return
504 // value should be |true|, rather than the default of |false|.
505 std::vector<AutofillEntry> empty;
506 EXPECT_CALL(autofill_table_, UpdateAutofillEntries(empty))
507 .WillRepeatedly(Return(true));
510 void TearDown() override {
511 // Note: The tear down order is important.
512 ProfileSyncServiceFactory::GetInstance()->SetTestingFactory(profile_, NULL);
513 web_data_service_->ShutdownOnUIThread();
514 web_data_service_->ShutdownSyncableService();
515 web_data_service_ = NULL;
516 // To prevent a leak, fully release TestURLRequestContext to ensure its
517 // destruction on the IO message loop.
518 profile_ = NULL;
519 profile_manager_.DeleteTestingProfile(kTestProfileName);
520 AbstractProfileSyncServiceTest::TearDown();
523 int GetSyncCount(syncer::ModelType type) {
524 syncer::ReadTransaction trans(FROM_HERE, sync_service_->GetUserShare());
525 syncer::ReadNode node(&trans);
526 if (node.InitTypeRoot(type) != syncer::BaseNode::INIT_OK)
527 return 0;
528 return node.GetTotalNodeCount() - 1;
531 void StartSyncService(const base::Closure& callback,
532 bool will_fail_association,
533 syncer::ModelType type) {
534 AbstractAutofillFactory* factory = GetFactory(type);
535 SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile_);
536 signin->SetAuthenticatedAccountInfo("12345", "test_user@gmail.com");
537 sync_service_ = TestProfileSyncService::BuildAutoStartAsyncInit(profile_,
538 callback);
540 ProfileSyncComponentsFactoryMock* components =
541 sync_service_->components_factory_mock();
542 DataTypeController* data_type_controller =
543 factory->CreateDataTypeController(components, profile_, sync_service_);
544 factory->SetExpectation(components,
545 sync_service_,
546 web_data_service_.get(),
547 data_type_controller);
549 EXPECT_CALL(*components, CreateDataTypeManager(_, _, _, _, _)).
550 WillOnce(ReturnNewDataTypeManagerWithDebugListener(
551 syncer::MakeWeakHandle(debug_ptr_factory_.GetWeakPtr())));
553 EXPECT_CALL(*personal_data_manager_, IsDataLoaded()).
554 WillRepeatedly(Return(true));
556 // We need tokens to get the tests going
557 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
558 ->UpdateCredentials(signin->GetAuthenticatedAccountId(),
559 "oauth2_login_token");
561 sync_service_->RegisterDataTypeController(data_type_controller);
562 sync_service_->Initialize();
563 base::MessageLoop::current()->Run();
565 // It's possible this test triggered an unrecoverable error, in which case
566 // we can't get the sync count.
567 if (sync_service_->IsSyncActive()) {
568 EXPECT_EQ(GetSyncCount(type),
569 association_stats_.num_sync_items_after_association);
571 EXPECT_EQ(association_stats_.num_sync_items_after_association,
572 association_stats_.num_sync_items_before_association +
573 association_stats_.num_sync_items_added -
574 association_stats_.num_sync_items_deleted);
577 bool AddAutofillSyncNode(const AutofillEntry& entry) {
578 syncer::WriteTransaction trans(FROM_HERE, sync_service_->GetUserShare());
579 syncer::WriteNode node(&trans);
580 std::string tag = AutocompleteSyncableService::KeyToTag(
581 base::UTF16ToUTF8(entry.key().name()),
582 base::UTF16ToUTF8(entry.key().value()));
583 syncer::WriteNode::InitUniqueByCreationResult result =
584 node.InitUniqueByCreation(syncer::AUTOFILL, tag);
585 if (result != syncer::WriteNode::INIT_SUCCESS)
586 return false;
588 sync_pb::EntitySpecifics specifics;
589 AutocompleteSyncableService::WriteAutofillEntry(entry, &specifics);
590 node.SetEntitySpecifics(specifics);
591 return true;
594 bool AddAutofillSyncNode(const AutofillProfile& profile) {
595 syncer::WriteTransaction trans(FROM_HERE, sync_service_->GetUserShare());
596 syncer::WriteNode node(&trans);
597 std::string tag = profile.guid();
598 syncer::WriteNode::InitUniqueByCreationResult result =
599 node.InitUniqueByCreation(syncer::AUTOFILL_PROFILE, tag);
600 if (result != syncer::WriteNode::INIT_SUCCESS)
601 return false;
603 sync_pb::EntitySpecifics specifics;
604 AutofillProfileSyncableService::WriteAutofillProfile(profile, &specifics);
605 node.SetEntitySpecifics(specifics);
606 return true;
609 bool GetAutofillEntriesFromSyncDB(std::vector<AutofillEntry>* entries,
610 std::vector<AutofillProfile>* profiles) {
611 syncer::ReadTransaction trans(FROM_HERE, sync_service_->GetUserShare());
612 syncer::ReadNode autofill_root(&trans);
613 if (autofill_root.InitTypeRoot(syncer::AUTOFILL) != BaseNode::INIT_OK) {
614 return false;
617 int64 child_id = autofill_root.GetFirstChildId();
618 while (child_id != syncer::kInvalidId) {
619 syncer::ReadNode child_node(&trans);
620 if (child_node.InitByIdLookup(child_id) != BaseNode::INIT_OK)
621 return false;
623 const sync_pb::AutofillSpecifics& autofill(
624 child_node.GetEntitySpecifics().autofill());
625 if (autofill.has_value()) {
626 AutofillKey key(base::UTF8ToUTF16(autofill.name()),
627 base::UTF8ToUTF16(autofill.value()));
628 std::vector<base::Time> timestamps;
629 int timestamps_count = autofill.usage_timestamp_size();
630 for (int i = 0; i < timestamps_count; ++i) {
631 timestamps.push_back(Time::FromInternalValue(
632 autofill.usage_timestamp(i)));
634 entries->push_back(
635 AutofillEntry(key, timestamps.front(), timestamps.back()));
636 } else if (autofill.has_profile()) {
637 AutofillProfile p;
638 p.set_guid(autofill.profile().guid());
639 AutofillProfileSyncableService::OverwriteProfileWithServerData(
640 autofill.profile(), &p, "en-US");
641 profiles->push_back(p);
643 child_id = child_node.GetSuccessorId();
645 return true;
648 bool GetAutofillProfilesFromSyncDBUnderProfileNode(
649 std::vector<AutofillProfile>* profiles) {
650 syncer::ReadTransaction trans(FROM_HERE, sync_service_->GetUserShare());
651 syncer::ReadNode autofill_root(&trans);
652 if (autofill_root.InitTypeRoot(AUTOFILL_PROFILE) != BaseNode::INIT_OK) {
653 return false;
656 int64 child_id = autofill_root.GetFirstChildId();
657 while (child_id != syncer::kInvalidId) {
658 syncer::ReadNode child_node(&trans);
659 if (child_node.InitByIdLookup(child_id) != BaseNode::INIT_OK)
660 return false;
662 const sync_pb::AutofillProfileSpecifics& autofill(
663 child_node.GetEntitySpecifics().autofill_profile());
664 AutofillProfile p;
665 p.set_guid(autofill.guid());
666 AutofillProfileSyncableService::OverwriteProfileWithServerData(
667 autofill, &p, "en-US");
668 profiles->push_back(p);
669 child_id = child_node.GetSuccessorId();
671 return true;
674 void SetIdleChangeProcessorExpectations() {
675 EXPECT_CALL(autofill_table_, RemoveFormElement(_, _)).Times(0);
676 EXPECT_CALL(autofill_table_, GetAutofillTimestamps(_, _, _, _)).Times(0);
678 // Only permit UpdateAutofillEntries() to be called with an empty list.
679 std::vector<AutofillEntry> empty;
680 EXPECT_CALL(autofill_table_, UpdateAutofillEntries(Not(empty))).Times(0);
683 static AutofillEntry MakeAutofillEntry(const char* name,
684 const char* value,
685 int time_shift0,
686 int time_shift1) {
687 // Time deep in the past would cause Autocomplete sync to discard the
688 // entries.
689 static Time base_time = Time::Now().LocalMidnight();
691 base::Time date_created = base_time + TimeDelta::FromSeconds(time_shift0);
692 base::Time date_last_used = date_created;
693 if (time_shift1 >= 0)
694 date_last_used = base_time + TimeDelta::FromSeconds(time_shift1);
695 return AutofillEntry(
696 AutofillKey(base::ASCIIToUTF16(name), base::ASCIIToUTF16(value)),
697 date_created, date_last_used);
700 static AutofillEntry MakeAutofillEntry(const char* name,
701 const char* value,
702 int time_shift) {
703 return MakeAutofillEntry(name, value, time_shift, -1);
706 friend class AddAutofillHelper<AutofillEntry>;
707 friend class AddAutofillHelper<AutofillProfile>;
708 friend class FakeServerUpdater;
710 TestingProfileManager profile_manager_;
711 TestingProfile* profile_;
712 AutofillTableMock autofill_table_;
713 scoped_ptr<WebDatabaseFake> web_database_;
714 scoped_refptr<WebDataServiceFake> web_data_service_;
715 MockPersonalDataManager* personal_data_manager_;
716 syncer::DataTypeAssociationStats association_stats_;
717 base::WeakPtrFactory<DataTypeDebugInfoListener> debug_ptr_factory_;
720 template <class T>
721 class AddAutofillHelper {
722 public:
723 AddAutofillHelper(ProfileSyncServiceAutofillTest* test,
724 const std::vector<T>& entries)
725 : callback_(base::Bind(&AddAutofillHelper::AddAutofillCallback,
726 base::Unretained(this), test, entries)),
727 success_(false) {
730 const base::Closure& callback() const { return callback_; }
731 bool success() { return success_; }
733 private:
734 void AddAutofillCallback(ProfileSyncServiceAutofillTest* test,
735 const std::vector<T>& entries) {
736 if (!test->CreateRoot(GetModelType<T>()))
737 return;
739 for (size_t i = 0; i < entries.size(); ++i) {
740 if (!test->AddAutofillSyncNode(entries[i]))
741 return;
743 success_ = true;
746 base::Closure callback_;
747 bool success_;
750 // Overload write transaction to use custom NotifyTransactionComplete
751 class WriteTransactionTest: public WriteTransaction {
752 public:
753 WriteTransactionTest(const tracked_objects::Location& from_here,
754 WriterTag writer,
755 syncer::syncable::Directory* directory,
756 scoped_ptr<WaitableEvent>* wait_for_syncapi)
757 : WriteTransaction(from_here, writer, directory),
758 wait_for_syncapi_(wait_for_syncapi) { }
760 void NotifyTransactionComplete(syncer::ModelTypeSet types) override {
761 // This is where we differ. Force a thread change here, giving another
762 // thread a chance to create a WriteTransaction
763 (*wait_for_syncapi_)->Wait();
765 WriteTransaction::NotifyTransactionComplete(types);
768 private:
769 scoped_ptr<WaitableEvent>* wait_for_syncapi_;
772 // Our fake server updater. Needs the RefCountedThreadSafe inheritance so we can
773 // post tasks with it.
774 class FakeServerUpdater : public base::RefCountedThreadSafe<FakeServerUpdater> {
775 public:
776 FakeServerUpdater(TestProfileSyncService* service,
777 scoped_ptr<WaitableEvent>* wait_for_start,
778 scoped_ptr<WaitableEvent>* wait_for_syncapi)
779 : entry_(ProfileSyncServiceAutofillTest::MakeAutofillEntry("0", "0", 0)),
780 service_(service),
781 wait_for_start_(wait_for_start),
782 wait_for_syncapi_(wait_for_syncapi),
783 is_finished_(false, false) { }
785 void Update() {
786 // This gets called in a modelsafeworker thread.
787 ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::DB));
789 syncer::UserShare* user_share = service_->GetUserShare();
790 syncer::syncable::Directory* directory = user_share->directory.get();
792 // Create autofill protobuf.
793 std::string tag = AutocompleteSyncableService::KeyToTag(
794 base::UTF16ToUTF8(entry_.key().name()),
795 base::UTF16ToUTF8(entry_.key().value()));
796 sync_pb::AutofillSpecifics new_autofill;
797 new_autofill.set_name(base::UTF16ToUTF8(entry_.key().name()));
798 new_autofill.set_value(base::UTF16ToUTF8(entry_.key().value()));
799 new_autofill.add_usage_timestamp(entry_.date_created().ToInternalValue());
800 if (entry_.date_created() != entry_.date_last_used()) {
801 new_autofill.add_usage_timestamp(
802 entry_.date_last_used().ToInternalValue());
805 sync_pb::EntitySpecifics entity_specifics;
806 entity_specifics.mutable_autofill()->CopyFrom(new_autofill);
809 // Tell main thread we've started
810 (*wait_for_start_)->Signal();
812 // Create write transaction.
813 WriteTransactionTest trans(FROM_HERE, UNITTEST, directory,
814 wait_for_syncapi_);
816 // Create actual entry based on autofill protobuf information.
817 // Simulates effects of UpdateLocalDataFromServerData
818 MutableEntry parent(&trans, GET_TYPE_ROOT, syncer::AUTOFILL);
819 MutableEntry item(&trans, CREATE, syncer::AUTOFILL, parent.GetId(), tag);
820 ASSERT_TRUE(item.good());
821 item.PutSpecifics(entity_specifics);
822 item.PutServerSpecifics(entity_specifics);
823 item.PutBaseVersion(1);
824 syncer::syncable::Id server_item_id =
825 service_->id_factory()->NewServerId();
826 item.PutId(server_item_id);
827 syncer::syncable::Id new_predecessor;
828 ASSERT_TRUE(item.PutPredecessor(new_predecessor));
830 DVLOG(1) << "FakeServerUpdater finishing.";
831 is_finished_.Signal();
834 void CreateNewEntry(const AutofillEntry& entry) {
835 entry_ = entry;
836 ASSERT_FALSE(BrowserThread::CurrentlyOn(BrowserThread::DB));
837 if (!BrowserThread::PostTask(
838 BrowserThread::DB, FROM_HERE,
839 base::Bind(&FakeServerUpdater::Update, this))) {
840 NOTREACHED() << "Failed to post task to the db thread.";
841 return;
845 void CreateNewEntryAndWait(const AutofillEntry& entry) {
846 entry_ = entry;
847 ASSERT_FALSE(BrowserThread::CurrentlyOn(BrowserThread::DB));
848 is_finished_.Reset();
849 if (!BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
850 base::Bind(&FakeServerUpdater::Update, this))) {
851 NOTREACHED() << "Failed to post task to the db thread.";
852 return;
854 is_finished_.Wait();
857 private:
858 friend class base::RefCountedThreadSafe<FakeServerUpdater>;
859 ~FakeServerUpdater() { }
861 AutofillEntry entry_;
862 TestProfileSyncService* service_;
863 scoped_ptr<WaitableEvent>* wait_for_start_;
864 scoped_ptr<WaitableEvent>* wait_for_syncapi_;
865 WaitableEvent is_finished_;
866 syncer::syncable::Id parent_id_;
869 // TODO(skrul): Test abort startup.
870 // TODO(skrul): Test processing of cloud changes.
871 // TODO(tim): Add autofill data type controller test, and a case to cover
872 // waiting for the PersonalDataManager.
873 TEST_F(ProfileSyncServiceAutofillTest, FailModelAssociation) {
874 // Don't create the root autofill node so startup fails.
875 StartSyncService(base::Closure(), true, syncer::AUTOFILL);
876 EXPECT_TRUE(sync_service_->HasUnrecoverableError());
879 TEST_F(ProfileSyncServiceAutofillTest, EmptyNativeEmptySync) {
880 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).WillOnce(Return(true));
881 SetIdleChangeProcessorExpectations();
882 CreateRootHelper create_root(this, syncer::AUTOFILL);
883 EXPECT_CALL(*personal_data_manager_, Refresh());
884 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
885 EXPECT_TRUE(create_root.success());
886 std::vector<AutofillEntry> sync_entries;
887 std::vector<AutofillProfile> sync_profiles;
888 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&sync_entries, &sync_profiles));
889 EXPECT_EQ(0U, sync_entries.size());
890 EXPECT_EQ(0U, sync_profiles.size());
893 TEST_F(ProfileSyncServiceAutofillTest, HasNativeEntriesEmptySync) {
894 std::vector<AutofillEntry> entries;
895 entries.push_back(MakeAutofillEntry("foo", "bar", 1));
896 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
897 WillOnce(DoAll(SetArgumentPointee<0>(entries), Return(true)));
898 SetIdleChangeProcessorExpectations();
899 CreateRootHelper create_root(this, syncer::AUTOFILL);
900 EXPECT_CALL(*personal_data_manager_, Refresh());
901 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
902 ASSERT_TRUE(create_root.success());
903 std::vector<AutofillEntry> sync_entries;
904 std::vector<AutofillProfile> sync_profiles;
905 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&sync_entries, &sync_profiles));
906 ASSERT_EQ(1U, entries.size());
907 EXPECT_TRUE(entries[0] == sync_entries[0]);
908 EXPECT_EQ(0U, sync_profiles.size());
911 TEST_F(ProfileSyncServiceAutofillTest, HasProfileEmptySync) {
912 std::vector<AutofillProfile*> profiles;
913 std::vector<AutofillProfile> expected_profiles;
914 // Owned by GetAutofillProfiles caller.
915 AutofillProfile* profile0 = new AutofillProfile;
916 autofill::test::SetProfileInfoWithGuid(profile0,
917 "54B3F9AA-335E-4F71-A27D-719C41564230", "Billing",
918 "Mitchell", "Morrison",
919 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
920 "91601", "US", "12345678910");
921 profiles.push_back(profile0);
922 expected_profiles.push_back(*profile0);
923 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
924 WillOnce(DoAll(SetArgumentPointee<0>(profiles), Return(true)));
925 EXPECT_CALL(*personal_data_manager_, Refresh());
926 SetIdleChangeProcessorExpectations();
927 CreateRootHelper create_root(this, syncer::AUTOFILL_PROFILE);
928 StartSyncService(create_root.callback(), false, syncer::AUTOFILL_PROFILE);
929 ASSERT_TRUE(create_root.success());
930 std::vector<AutofillProfile> sync_profiles;
931 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(&sync_profiles));
932 EXPECT_EQ(1U, sync_profiles.size());
933 EXPECT_EQ(0, expected_profiles[0].Compare(sync_profiles[0]));
936 TEST_F(ProfileSyncServiceAutofillTest, HasNativeWithDuplicatesEmptySync) {
937 // There is buggy autofill code that allows duplicate name/value
938 // pairs to exist in the database with separate pair_ids.
939 std::vector<AutofillEntry> entries;
940 entries.push_back(MakeAutofillEntry("foo", "bar", 1));
941 entries.push_back(MakeAutofillEntry("dup", "", 2));
942 entries.push_back(MakeAutofillEntry("dup", "", 3));
943 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
944 WillOnce(DoAll(SetArgumentPointee<0>(entries), Return(true)));
945 SetIdleChangeProcessorExpectations();
946 CreateRootHelper create_root(this, syncer::AUTOFILL);
947 EXPECT_CALL(*personal_data_manager_, Refresh());
948 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
949 ASSERT_TRUE(create_root.success());
950 std::vector<AutofillEntry> sync_entries;
951 std::vector<AutofillProfile> sync_profiles;
952 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&sync_entries, &sync_profiles));
953 EXPECT_EQ(2U, sync_entries.size());
956 TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSyncNoMerge) {
957 AutofillEntry native_entry(MakeAutofillEntry("native", "entry", 1));
958 AutofillEntry sync_entry(MakeAutofillEntry("sync", "entry", 2));
960 std::vector<AutofillEntry> native_entries;
961 native_entries.push_back(native_entry);
963 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
964 WillOnce(DoAll(SetArgumentPointee<0>(native_entries), Return(true)));
966 std::vector<AutofillEntry> sync_entries;
967 sync_entries.push_back(sync_entry);
969 AddAutofillHelper<AutofillEntry> add_autofill(this, sync_entries);
971 EXPECT_CALL(autofill_table_, UpdateAutofillEntries(ElementsAre(sync_entry))).
972 WillOnce(Return(true));
974 EXPECT_CALL(*personal_data_manager_, Refresh());
975 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL);
976 ASSERT_TRUE(add_autofill.success());
978 std::set<AutofillEntry> expected_entries;
979 expected_entries.insert(native_entry);
980 expected_entries.insert(sync_entry);
982 std::vector<AutofillEntry> new_sync_entries;
983 std::vector<AutofillProfile> new_sync_profiles;
984 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
985 &new_sync_profiles));
986 std::set<AutofillEntry> new_sync_entries_set(new_sync_entries.begin(),
987 new_sync_entries.end());
989 EXPECT_TRUE(expected_entries == new_sync_entries_set);
992 TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSyncMergeEntry) {
993 AutofillEntry native_entry(MakeAutofillEntry("merge", "entry", 1));
994 AutofillEntry sync_entry(MakeAutofillEntry("merge", "entry", 2));
995 AutofillEntry merged_entry(MakeAutofillEntry("merge", "entry", 1, 2));
997 std::vector<AutofillEntry> native_entries;
998 native_entries.push_back(native_entry);
999 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
1000 WillOnce(DoAll(SetArgumentPointee<0>(native_entries), Return(true)));
1002 std::vector<AutofillEntry> sync_entries;
1003 sync_entries.push_back(sync_entry);
1004 AddAutofillHelper<AutofillEntry> add_autofill(this, sync_entries);
1006 EXPECT_CALL(autofill_table_,
1007 UpdateAutofillEntries(ElementsAre(merged_entry))).WillOnce(Return(true));
1008 EXPECT_CALL(*personal_data_manager_, Refresh());
1009 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL);
1010 ASSERT_TRUE(add_autofill.success());
1012 std::vector<AutofillEntry> new_sync_entries;
1013 std::vector<AutofillProfile> new_sync_profiles;
1014 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
1015 &new_sync_profiles));
1016 ASSERT_EQ(1U, new_sync_entries.size());
1017 EXPECT_TRUE(merged_entry == new_sync_entries[0]);
1020 TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSyncMergeProfile) {
1021 AutofillProfile sync_profile;
1022 autofill::test::SetProfileInfoWithGuid(&sync_profile,
1023 "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
1024 "Mitchell", "Morrison",
1025 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1026 "91601", "US", "12345678910");
1028 AutofillProfile* native_profile = new AutofillProfile;
1029 autofill::test::SetProfileInfoWithGuid(native_profile,
1030 "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing", "Alicia", "Saenz",
1031 "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL",
1032 "32801", "US", "19482937549");
1034 std::vector<AutofillProfile*> native_profiles;
1035 native_profiles.push_back(native_profile);
1036 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
1037 WillOnce(DoAll(SetArgumentPointee<0>(native_profiles), Return(true)));
1039 std::vector<AutofillProfile> sync_profiles;
1040 sync_profiles.push_back(sync_profile);
1041 AddAutofillHelper<AutofillProfile> add_autofill(this, sync_profiles);
1043 EXPECT_CALL(autofill_table_,
1044 UpdateAutofillProfile(MatchProfiles(sync_profile))).
1045 WillOnce(Return(true));
1046 EXPECT_CALL(*personal_data_manager_, Refresh());
1047 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL_PROFILE);
1048 ASSERT_TRUE(add_autofill.success());
1050 std::vector<AutofillProfile> new_sync_profiles;
1051 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1052 &new_sync_profiles));
1053 ASSERT_EQ(1U, new_sync_profiles.size());
1054 EXPECT_EQ(0, sync_profile.Compare(new_sync_profiles[0]));
1057 TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSyncMergeProfileCombine) {
1058 AutofillProfile sync_profile;
1059 autofill::test::SetProfileInfoWithGuid(&sync_profile,
1060 "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
1061 "Mitchell", "Morrison",
1062 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1063 "91601", "US", "12345678910");
1065 AutofillProfile* native_profile = new AutofillProfile;
1066 // Same address, but different names, phones and e-mails.
1067 autofill::test::SetProfileInfoWithGuid(native_profile,
1068 "23355099-1170-4B71-8ED4-144470CC9EBF", "Billing", "Alicia", "Saenz",
1069 "joewayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1070 "91601", "US", "19482937549");
1072 AutofillProfile expected_profile(sync_profile);
1073 expected_profile.OverwriteWith(*native_profile, "en-US");
1075 std::vector<AutofillProfile*> native_profiles;
1076 native_profiles.push_back(native_profile);
1077 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
1078 WillOnce(DoAll(SetArgumentPointee<0>(native_profiles), Return(true)));
1079 EXPECT_CALL(autofill_table_,
1080 AddAutofillProfile(MatchProfiles(expected_profile))).
1081 WillOnce(Return(true));
1082 EXPECT_CALL(autofill_table_,
1083 RemoveAutofillProfile("23355099-1170-4B71-8ED4-144470CC9EBF")).
1084 WillOnce(Return(true));
1085 std::vector<AutofillProfile> sync_profiles;
1086 sync_profiles.push_back(sync_profile);
1087 AddAutofillHelper<AutofillProfile> add_autofill(this, sync_profiles);
1089 EXPECT_CALL(*personal_data_manager_, Refresh());
1090 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL_PROFILE);
1091 ASSERT_TRUE(add_autofill.success());
1093 std::vector<AutofillProfile> new_sync_profiles;
1094 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1095 &new_sync_profiles));
1096 ASSERT_EQ(1U, new_sync_profiles.size());
1097 // Check that key fields are the same.
1098 EXPECT_TRUE(new_sync_profiles[0].IsSubsetOf(sync_profile, "en-US"));
1101 TEST_F(ProfileSyncServiceAutofillTest, MergeProfileWithDifferentGuid) {
1102 AutofillProfile sync_profile;
1104 autofill::test::SetProfileInfoWithGuid(&sync_profile,
1105 "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
1106 "Mitchell", "Morrison",
1107 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1108 "91601", "US", "12345678910");
1110 std::string native_guid = "EDC609ED-7EEE-4F27-B00C-423242A9C44B";
1111 AutofillProfile* native_profile = new AutofillProfile;
1112 autofill::test::SetProfileInfoWithGuid(native_profile,
1113 native_guid.c_str(), "Billing",
1114 "Mitchell", "Morrison",
1115 "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA",
1116 "91601", "US", "12345678910");
1118 std::vector<AutofillProfile*> native_profiles;
1119 native_profiles.push_back(native_profile);
1120 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
1121 WillOnce(DoAll(SetArgumentPointee<0>(native_profiles), Return(true)));
1123 std::vector<AutofillProfile> sync_profiles;
1124 sync_profiles.push_back(sync_profile);
1125 AddAutofillHelper<AutofillProfile> add_autofill(this, sync_profiles);
1127 EXPECT_CALL(autofill_table_, AddAutofillProfile(_)).
1128 WillOnce(Return(true));
1129 EXPECT_CALL(autofill_table_, RemoveAutofillProfile(native_guid)).
1130 WillOnce(Return(true));
1131 EXPECT_CALL(*personal_data_manager_, Refresh());
1132 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL_PROFILE);
1133 ASSERT_TRUE(add_autofill.success());
1135 std::vector<AutofillProfile> new_sync_profiles;
1136 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1137 &new_sync_profiles));
1138 ASSERT_EQ(1U, new_sync_profiles.size());
1139 EXPECT_EQ(0, sync_profile.Compare(new_sync_profiles[0]));
1140 EXPECT_EQ(sync_profile.guid(), new_sync_profiles[0].guid());
1143 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeAddEntry) {
1144 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).WillOnce(Return(true));
1145 EXPECT_CALL(*personal_data_manager_, Refresh());
1146 SetIdleChangeProcessorExpectations();
1147 CreateRootHelper create_root(this, syncer::AUTOFILL);
1148 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
1149 ASSERT_TRUE(create_root.success());
1151 AutofillEntry added_entry(MakeAutofillEntry("added", "entry", 1));
1153 EXPECT_CALL(autofill_table_, GetAutofillTimestamps(_, _, _, _)).
1154 WillOnce(DoAll(SetArgumentPointee<2>(added_entry.date_created()),
1155 SetArgumentPointee<3>(added_entry.date_last_used()),
1156 Return(true)));
1158 AutofillChangeList changes;
1159 changes.push_back(AutofillChange(AutofillChange::ADD, added_entry.key()));
1161 web_data_service_->OnAutofillEntriesChanged(changes);
1163 std::vector<AutofillEntry> new_sync_entries;
1164 std::vector<AutofillProfile> new_sync_profiles;
1165 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
1166 &new_sync_profiles));
1167 ASSERT_EQ(1U, new_sync_entries.size());
1168 EXPECT_TRUE(added_entry == new_sync_entries[0]);
1171 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeAddProfile) {
1172 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).WillOnce(Return(true));
1173 EXPECT_CALL(*personal_data_manager_, Refresh());
1174 SetIdleChangeProcessorExpectations();
1175 CreateRootHelper create_root(this, syncer::AUTOFILL_PROFILE);
1176 StartSyncService(create_root.callback(), false, syncer::AUTOFILL_PROFILE);
1177 ASSERT_TRUE(create_root.success());
1179 AutofillProfile added_profile;
1180 autofill::test::SetProfileInfoWithGuid(&added_profile,
1181 "D6ADA912-D374-4C0A-917D-F5C8EBE43011", "Josephine", "Alicia", "Saenz",
1182 "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL",
1183 "32801", "US", "19482937549");
1185 AutofillProfileChange change(
1186 AutofillProfileChange::ADD, added_profile.guid(), &added_profile);
1187 web_data_service_->OnAutofillProfileChanged(change);
1189 std::vector<AutofillProfile> new_sync_profiles;
1190 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1191 &new_sync_profiles));
1192 ASSERT_EQ(1U, new_sync_profiles.size());
1193 EXPECT_EQ(0, added_profile.Compare(new_sync_profiles[0]));
1196 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeUpdateEntry) {
1197 AutofillEntry original_entry(MakeAutofillEntry("my", "entry", 1));
1198 std::vector<AutofillEntry> original_entries;
1199 original_entries.push_back(original_entry);
1201 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
1202 WillOnce(DoAll(SetArgumentPointee<0>(original_entries), Return(true)));
1203 EXPECT_CALL(*personal_data_manager_, Refresh());
1204 CreateRootHelper create_root(this, syncer::AUTOFILL);
1205 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
1206 ASSERT_TRUE(create_root.success());
1208 AutofillEntry updated_entry(MakeAutofillEntry("my", "entry", 1, 2));
1210 EXPECT_CALL(autofill_table_, GetAutofillTimestamps(_, _, _, _)).
1211 WillOnce(DoAll(SetArgumentPointee<2>(updated_entry.date_created()),
1212 SetArgumentPointee<3>(updated_entry.date_last_used()),
1213 Return(true)));
1215 AutofillChangeList changes;
1216 changes.push_back(AutofillChange(AutofillChange::UPDATE,
1217 updated_entry.key()));
1218 web_data_service_->OnAutofillEntriesChanged(changes);
1220 std::vector<AutofillEntry> new_sync_entries;
1221 std::vector<AutofillProfile> new_sync_profiles;
1222 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
1223 &new_sync_profiles));
1224 ASSERT_EQ(1U, new_sync_entries.size());
1225 EXPECT_TRUE(updated_entry == new_sync_entries[0]);
1229 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeRemoveEntry) {
1230 AutofillEntry original_entry(MakeAutofillEntry("my", "entry", 1));
1231 std::vector<AutofillEntry> original_entries;
1232 original_entries.push_back(original_entry);
1234 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
1235 WillOnce(DoAll(SetArgumentPointee<0>(original_entries), Return(true)));
1236 EXPECT_CALL(*personal_data_manager_, Refresh());
1237 CreateRootHelper create_root(this, syncer::AUTOFILL);
1238 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
1239 ASSERT_TRUE(create_root.success());
1241 AutofillChangeList changes;
1242 changes.push_back(AutofillChange(AutofillChange::REMOVE,
1243 original_entry.key()));
1244 web_data_service_->OnAutofillEntriesChanged(changes);
1246 std::vector<AutofillEntry> new_sync_entries;
1247 std::vector<AutofillProfile> new_sync_profiles;
1248 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&new_sync_entries,
1249 &new_sync_profiles));
1250 ASSERT_EQ(0U, new_sync_entries.size());
1253 TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeRemoveProfile) {
1254 AutofillProfile sync_profile;
1255 autofill::test::SetProfileInfoWithGuid(&sync_profile,
1256 "3BA5FA1B-1EC4-4BB3-9B57-EC92BE3C1A09", "Josephine", "Alicia", "Saenz",
1257 "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL",
1258 "32801", "US", "19482937549");
1259 AutofillProfile* native_profile = new AutofillProfile;
1260 autofill::test::SetProfileInfoWithGuid(native_profile,
1261 "3BA5FA1B-1EC4-4BB3-9B57-EC92BE3C1A09", "Josephine", "Alicia", "Saenz",
1262 "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL",
1263 "32801", "US", "19482937549");
1265 std::vector<AutofillProfile*> native_profiles;
1266 native_profiles.push_back(native_profile);
1267 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).
1268 WillOnce(DoAll(SetArgumentPointee<0>(native_profiles), Return(true)));
1270 std::vector<AutofillProfile> sync_profiles;
1271 sync_profiles.push_back(sync_profile);
1272 AddAutofillHelper<AutofillProfile> add_autofill(this, sync_profiles);
1273 EXPECT_CALL(*personal_data_manager_, Refresh());
1274 StartSyncService(add_autofill.callback(), false, syncer::AUTOFILL_PROFILE);
1275 ASSERT_TRUE(add_autofill.success());
1277 AutofillProfileChange change(
1278 AutofillProfileChange::REMOVE, sync_profile.guid(), NULL);
1279 web_data_service_->OnAutofillProfileChanged(change);
1281 std::vector<AutofillProfile> new_sync_profiles;
1282 ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(
1283 &new_sync_profiles));
1284 ASSERT_EQ(0U, new_sync_profiles.size());
1287 // http://crbug.com/57884
1288 TEST_F(ProfileSyncServiceAutofillTest, DISABLED_ServerChangeRace) {
1289 // Once for MergeDataAndStartSyncing() and twice for ProcessSyncChanges(), via
1290 // LoadAutofillData().
1291 EXPECT_CALL(autofill_table_, GetAllAutofillEntries(_)).
1292 Times(3).WillRepeatedly(Return(true));
1293 // On the other hand Autofill and Autocomplete are separated now, so
1294 // GetAutofillProfiles() should not be called.
1295 EXPECT_CALL(autofill_table_, GetAutofillProfiles(_)).Times(0);
1296 EXPECT_CALL(autofill_table_, UpdateAutofillEntries(_)).
1297 WillRepeatedly(Return(true));
1298 EXPECT_CALL(*personal_data_manager_, Refresh()).Times(3);
1299 CreateRootHelper create_root(this, syncer::AUTOFILL);
1300 StartSyncService(create_root.callback(), false, syncer::AUTOFILL);
1301 ASSERT_TRUE(create_root.success());
1303 // (true, false) means we have to reset after |Signal|, init to unsignaled.
1304 scoped_ptr<WaitableEvent> wait_for_start(new WaitableEvent(true, false));
1305 scoped_ptr<WaitableEvent> wait_for_syncapi(new WaitableEvent(true, false));
1306 scoped_refptr<FakeServerUpdater> updater(new FakeServerUpdater(
1307 sync_service_, &wait_for_start, &wait_for_syncapi));
1309 // This server side update will stall waiting for CommitWaiter.
1310 updater->CreateNewEntry(MakeAutofillEntry("server", "entry", 1));
1311 wait_for_start->Wait();
1313 AutofillEntry syncapi_entry(MakeAutofillEntry("syncapi", "entry", 2));
1314 ASSERT_TRUE(AddAutofillSyncNode(syncapi_entry));
1315 DVLOG(1) << "Syncapi update finished.";
1317 // If we reach here, it means syncapi succeeded and we didn't deadlock. Yay!
1318 // Signal FakeServerUpdater that it can complete.
1319 wait_for_syncapi->Signal();
1321 // Make another entry to ensure nothing broke afterwards and wait for finish
1322 // to clean up.
1323 updater->CreateNewEntryAndWait(MakeAutofillEntry("server2", "entry2", 3));
1325 std::vector<AutofillEntry> sync_entries;
1326 std::vector<AutofillProfile> sync_profiles;
1327 ASSERT_TRUE(GetAutofillEntriesFromSyncDB(&sync_entries, &sync_profiles));
1328 EXPECT_EQ(3U, sync_entries.size());
1329 EXPECT_EQ(0U, sync_profiles.size());
1330 for (size_t i = 0; i < sync_entries.size(); i++) {
1331 DVLOG(1) << "Entry " << i << ": " << sync_entries[i].key().name()
1332 << ", " << sync_entries[i].key().value();