File: single_client_contact_info_sync_test.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (663 lines) | stat: -rw-r--r-- 28,903 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/test/integration/contact_info_helper.h"
#include "chrome/browser/sync/test/integration/encryption_helper.h"
#include "chrome/browser/sync/test/integration/fake_server_match_status_checker.h"
#include "chrome/browser/sync/test/integration/sync_integration_test_util.h"
#include "chrome/browser/sync/test/integration/sync_service_impl_harness.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/browser/sync/test/integration/updated_progress_marker_checker.h"
#include "components/autofill/core/browser/data_manager/addresses/address_data_manager.h"
#include "components/autofill/core/browser/data_manager/personal_data_manager.h"
#include "components/autofill/core/browser/data_model/addresses/autofill_profile_test_api.h"
#include "components/autofill/core/browser/test_utils/autofill_test_utils.h"
#include "components/autofill/core/browser/webdata/addresses/contact_info_sync_util.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/account_capabilities_test_mutator.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/sync/base/data_type.h"
#include "components/sync/base/features.h"
#include "components/sync/engine/loopback_server/persistent_unique_client_entity.h"
#include "components/sync/protocol/contact_info_specifics.pb.h"
#include "components/sync/protocol/entity_specifics.pb.h"
#include "components/sync/test/fake_server.h"
#include "components/sync/test/test_matchers.h"
#include "content/public/test/browser_test.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if !BUILDFLAG(IS_ANDROID)
#include "third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.h"
#endif

namespace {

using autofill::AutofillProfile;
using contact_info_helper::AddressDataManagerProfileChecker;
using contact_info_helper::BuildTestAccountProfile;
using syncer::MatchesLocalDataDescription;
using syncer::MatchesLocalDataItemModel;
using testing::_;
using testing::ElementsAre;
using testing::IsEmpty;
using testing::UnorderedElementsAre;

#if !BUILDFLAG(IS_ANDROID)
std::string CreateSerializedProtoField(int field_number,
                                       const std::string& value) {
  std::string result;
  google::protobuf::io::StringOutputStream string_stream(&result);
  google::protobuf::io::CodedOutputStream output(&string_stream);
  google::protobuf::internal::WireFormatLite::WriteTag(
      field_number,
      google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
      &output);
  output.WriteVarint32(value.size());
  output.WriteString(value);
  return result;
}

// Matches a sync::entity_data has a contact info field with `guid` and a set of
// `unknown_fields`.
MATCHER_P2(HasContactInfoWithGuidAndUnknownFields, guid, unknown_fields, "") {
  return arg.specifics().contact_info().guid() == guid &&
         arg.specifics().contact_info().unknown_fields() == unknown_fields;
}
#endif

#if !BUILDFLAG(IS_CHROMEOS)
// Matches a sync::entity_data has a contact info field with `address`.
MATCHER_P(HasContactInfoWithAddress, address, "") {
  return base::UTF8ToUTF16(
             arg.specifics().contact_info().address_street_address().value()) ==
         address;
}

// Matches a AutofillProfile has a `autofill::FieldType::NAME_FIRST` with
// `first_name`.
MATCHER_P(HasContactInfoWithFirstName, first_name, "") {
  return arg->GetRawInfo(autofill::FieldType::NAME_FIRST) == first_name;
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

// Checker to wait until the CONTACT_INFO datatype becomes (in)active, depending
// on `expect_active`.
// This is required because ContactInfoDataTypeController has custom logic to
// wait, and stays temporarily stopped even after sync-the-transport is active,
// until account capabilities are determined for eligibility.
class ContactInfoActiveChecker : public SingleClientStatusChangeChecker {
 public:
  ContactInfoActiveChecker(syncer::SyncServiceImpl* service, bool expect_active)
      : SingleClientStatusChangeChecker(service),
        expect_active_(expect_active) {}

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override {
    return service()->GetActiveDataTypes().Has(syncer::CONTACT_INFO) ==
           expect_active_;
  }

 private:
  const bool expect_active_;
};

// Helper class to wait until the fake server's ContactInfoSpecifics match a
// given predicate.
// Unfortunately, since protos don't have an equality operator, the comparisons
// are based on the `SerializeAsString()` representation of the specifics.
class FakeServerSpecificsChecker
    : public fake_server::FakeServerMatchStatusChecker {
 public:
  using Matcher = testing::Matcher<std::vector<std::string>>;

  explicit FakeServerSpecificsChecker(const Matcher& matcher)
      : matcher_(matcher) {}

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override {
    std::vector<std::string> specifics;
    for (const sync_pb::SyncEntity& entity :
         fake_server()->GetSyncEntitiesByDataType(syncer::CONTACT_INFO)) {
      specifics.push_back(
          entity.specifics().contact_info().SerializeAsString());
    }
    testing::StringMatchResultListener listener;
    bool matches = testing::ExplainMatchResult(matcher_, specifics, &listener);
    *os << listener.str();
    return matches;
  }

 private:
  const Matcher matcher_;
};

// Since the sync server operates in terms of entity specifics, this helper
// function converts a given `profile` to the equivalent ContactInfoSpecifics.
sync_pb::ContactInfoSpecifics AsContactInfoSpecifics(
    const AutofillProfile& profile) {
  return autofill::CreateContactInfoEntityDataFromAutofillProfile(
             profile, /*base_contact_info_specifics=*/{})
      ->specifics.contact_info();
}

// Adds the given `specifics` to the `fake_server` at creation time 0.
void AddSpecificsToServer(const sync_pb::ContactInfoSpecifics& specifics,
                          fake_server::FakeServer* fake_server) {
  sync_pb::EntitySpecifics entity_specifics;
  entity_specifics.mutable_contact_info()->CopyFrom(specifics);
  fake_server->InjectEntity(
      syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
          /*non_unique_name=*/"profile", /*client_tag=*/specifics.guid(),
          /*entity_specifics=*/entity_specifics, /*creation_time=*/0,
          /*last_modified_time=*/0));
}

class SingleClientContactInfoSyncTest : public SyncTest {
 public:
  SingleClientContactInfoSyncTest() : SyncTest(SINGLE_CLIENT) {}

  // In SINGLE_CLIENT tests, there's only a single PersonalDataManager.
  autofill::PersonalDataManager* GetPersonalDataManager() const {
    return contact_info_helper::GetPersonalDataManager(GetProfile(0));
  }
};

IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest, DownloadInitialData) {
  const AutofillProfile kProfile = BuildTestAccountProfile();
  AddSpecificsToServer(AsContactInfoSpecifics(kProfile), GetFakeServer());
  ASSERT_TRUE(SetupSync());
  EXPECT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(kProfile))
                  .Wait());
}

IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest, UploadProfile) {
  const AutofillProfile kProfile = BuildTestAccountProfile();
  ASSERT_TRUE(SetupSync());
  GetPersonalDataManager()->address_data_manager().AddProfile(kProfile);
  EXPECT_TRUE(FakeServerSpecificsChecker(
                  UnorderedElementsAre(
                      AsContactInfoSpecifics(kProfile).SerializeAsString()))
                  .Wait());
}

// Tests that profile changes due to `AutofillProfile::FinalizeAfterImport()`
// don't cause a reupload and hence can't cause ping-pong loops.
// This is not expected to happen because only the PersonalDataManager can
// trigger reuploads - and it only operates on finalized profiles.
IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest, FinalizeAfterImport) {
  AutofillProfile unfinalized_profile(
      AutofillProfile::RecordType::kAccount,
      autofill::i18n_model_definition::kLegacyHierarchyCountryCode);
  unfinalized_profile.SetRawInfo(autofill::NAME_FULL, u"Full Name");
  AutofillProfile finalized_profile = unfinalized_profile;
  finalized_profile.FinalizeAfterImport();
  ASSERT_NE(unfinalized_profile, finalized_profile);

  // Add the `unfinalized_profile` to the server. An unfinalized profile is
  // never uploaded through Autofill, but non-Autofill clients might do so.
  AddSpecificsToServer(AsContactInfoSpecifics(unfinalized_profile),
                       GetFakeServer());
  ASSERT_TRUE(SetupSync());
  // Expect that the PersonalDataManager receives the `finalized_profile`. The
  // finalization step happen when reading the profile from AutofillTable.
  EXPECT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(finalized_profile))
                  .Wait());

  // Expect that the finalized profile is not propagated back to the server.
  // Since the PersonalDatamanager is operating on a single thread, this is
  // verified by adding a dummy profile. It will only reach the server after any
  // already pending changes.
  const AutofillProfile kDummyProfile = BuildTestAccountProfile();
  GetPersonalDataManager()->address_data_manager().AddProfile(kDummyProfile);
  EXPECT_TRUE(
      FakeServerSpecificsChecker(
          UnorderedElementsAre(
              AsContactInfoSpecifics(unfinalized_profile).SerializeAsString(),
              AsContactInfoSpecifics(kDummyProfile).SerializeAsString()))
          .Wait());
}

// ChromeOS does not support signing out of a primary account.
#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest, ClearOnSignout) {
  const AutofillProfile kProfile = BuildTestAccountProfile();
  AddSpecificsToServer(AsContactInfoSpecifics(kProfile), GetFakeServer());
  ASSERT_TRUE(SetupSync());
  ASSERT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(kProfile))
                  .Wait());
  GetClient(0)->SignOutPrimaryAccount();
  EXPECT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(), IsEmpty())
                  .Wait());
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

// Specialized fixture to test the behavior for custom passphrase users with and
// without kSyncEnableContactInfoDataTypeForCustomPassphraseUsers enabled.
class SingleClientContactInfoPassphraseSyncTest
    : public SingleClientContactInfoSyncTest,
      public testing::WithParamInterface<bool> {
 public:
  SingleClientContactInfoPassphraseSyncTest() {
    passphrase_feature_.InitWithFeatureState(
        syncer::kSyncEnableContactInfoDataTypeForCustomPassphraseUsers,
        EnabledForPassphraseUsersTestParam());
  }

  bool EnabledForPassphraseUsersTestParam() const { return GetParam(); }

 private:
  base::test::ScopedFeatureList passphrase_feature_;
};

INSTANTIATE_TEST_SUITE_P(,
                         SingleClientContactInfoPassphraseSyncTest,
                         testing::Bool());

// TODO(336993637): Flaky on Android.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_Passphrase DISABLED_Passphrase
#else
#define MAYBE_Passphrase Passphrase
#endif
IN_PROC_BROWSER_TEST_P(SingleClientContactInfoPassphraseSyncTest,
                       MAYBE_Passphrase) {
  ASSERT_TRUE(SetupSync());
  ASSERT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));
  GetSyncService(0)->GetUserSettings()->SetEncryptionPassphrase("123456");
  ASSERT_TRUE(
      ServerPassphraseTypeChecker(syncer::PassphraseType::kCustomPassphrase)
          .Wait());
  EXPECT_TRUE(ContactInfoActiveChecker(
                  GetSyncService(0),
                  /*expect_active=*/EnabledForPassphraseUsersTestParam())
                  .Wait());
}

// Transport Mode is only supported on these platforms.
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
// CONTACT_INFO should be able to run in transport mode and the availability of
// account profiles should depend on the signed-in state.
IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest,
                       TransportMode) {
  AutofillProfile profile = BuildTestAccountProfile();
  AddSpecificsToServer(AsContactInfoSpecifics(profile), GetFakeServer());
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  EXPECT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));
  EXPECT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(profile))
                  .Wait());
  // ChromeOS doesn't have the concept of sign-out.
  GetClient(0)->SignOutPrimaryAccount();
  EXPECT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(), IsEmpty())
                  .Wait());
}

IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest,
                       DeleteAccountDataInErrorState) {
  // Add a profile to account storage.
  AutofillProfile profile = BuildTestAccountProfile();
  AddSpecificsToServer(AsContactInfoSpecifics(profile), GetFakeServer());
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  EXPECT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));
  EXPECT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(profile))
                  .Wait());

  // Trigger auth error, sync stops.
  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(GetProfile(0));
  signin::UpdatePersistentErrorOfRefreshTokenForAccount(
      identity_manager,
      identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSignin),
      GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
  ASSERT_TRUE(
      identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSignin));
  EXPECT_TRUE(ContactInfoActiveChecker(GetSyncService(0),
                                       /*expect_active=*/false)
                  .Wait());

  // The data has been deleted.
  EXPECT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(), IsEmpty())
                  .Wait());

  // Fix the error, data is re-downloaded.
  signin::UpdatePersistentErrorOfRefreshTokenForAccount(
      identity_manager,
      identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSignin),
      GoogleServiceAuthError::AuthErrorNone());

  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  EXPECT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));
  EXPECT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(profile))
                  .Wait());
}

// Account storage is not enabled when the user is in auth error.
IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest,
                       AuthErrorState) {
  // Setup transport mode.
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  EXPECT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));

  // Trigger auth error, sync stops.
  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(GetProfile(0));
  signin::UpdatePersistentErrorOfRefreshTokenForAccount(
      identity_manager,
      identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSignin),
      GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
  ASSERT_TRUE(
      identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSignin));
  EXPECT_TRUE(ContactInfoActiveChecker(GetSyncService(0),
                                       /*expect_active=*/false)
                  .Wait());

  EXPECT_FALSE(GetPersonalDataManager()
                   ->address_data_manager()
                   .IsEligibleForAddressAccountStorage());
  EXPECT_FALSE(GetPersonalDataManager()
                   ->address_data_manager()
                   .IsAutofillSyncToggleAvailable());

  // Fix the authentication error, sync is available again.
  signin::UpdatePersistentErrorOfRefreshTokenForAccount(
      identity_manager,
      identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSignin),
      GoogleServiceAuthError::AuthErrorNone());
  EXPECT_TRUE(ContactInfoActiveChecker(GetSyncService(0),
                                       /*expect_active=*/true)
                  .Wait());
  EXPECT_TRUE(GetPersonalDataManager()
                  ->address_data_manager()
                  .IsEligibleForAddressAccountStorage());
  EXPECT_TRUE(GetPersonalDataManager()
                  ->address_data_manager()
                  .IsAutofillSyncToggleAvailable());
}

// Regression test for https://crbug.com/340194452
IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest,
                       IsAutofillSyncToggleAvailable) {
  // Setup transport mode.
  ASSERT_TRUE(SetupClients());
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  EXPECT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));
  // The toggle is available.
  EXPECT_TRUE(GetPersonalDataManager()
                  ->address_data_manager()
                  .IsAutofillSyncToggleAvailable());

  // Turn account storage OFF.
  GetPersonalDataManager()
      ->address_data_manager()
      .SetAutofillSelectableTypeEnabled(
          /*enabled=*/false);
  EXPECT_TRUE(ContactInfoActiveChecker(GetSyncService(0),
                                       /*expect_active=*/false)
                  .Wait());

  // The toggle is still available.
  EXPECT_TRUE(GetPersonalDataManager()
                  ->address_data_manager()
                  .IsAutofillSyncToggleAvailable());

  // Turn on Sync.
  ASSERT_TRUE(GetClient(0)->SetupSync());

  // The toggle is no longer available.
  EXPECT_FALSE(GetPersonalDataManager()
                   ->address_data_manager()
                   .IsAutofillSyncToggleAvailable());

  // Sign out.
  GetClient(0)->SignOutPrimaryAccount();

  // The toggle is not available.
  EXPECT_FALSE(GetPersonalDataManager()
                   ->address_data_manager()
                   .IsAutofillSyncToggleAvailable());
}
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)

#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest,
                       PreservesUnsupportedFieldsDataOnCommits) {
  // Create an unsupported field with an unused tag.
  const std::string kUnsupportedField =
      CreateSerializedProtoField(/*field_number=*/999999, "unknown_field");

  autofill::AutofillProfile profile = BuildTestAccountProfile();
  profile.SetRawInfo(autofill::NAME_FULL, u"Full Name");
  profile.FinalizeAfterImport();

  sync_pb::EntitySpecifics entity_data;
  sync_pb::ContactInfoSpecifics* specifics = entity_data.mutable_contact_info();
  *specifics = autofill::ContactInfoSpecificsFromAutofillProfile(profile, {});
  *specifics->mutable_unknown_fields() = kUnsupportedField;
  GetFakeServer()->InjectEntity(
      syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
          /*non_unique_name=*/"",
          /*client_tag=*/
          profile.guid(), entity_data,
          /*creation_time=*/0,
          /*last_modified_time=*/0));

  ASSERT_TRUE(SetupSync());
  ASSERT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));
  ASSERT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(profile))
                  .Wait());

  // Apply a change to the profile.
  profile.SetRawInfo(autofill::NAME_FULL, u"New Name");
  GetPersonalDataManager()->address_data_manager().UpdateProfile(profile);

  // Add a second profile to make sure that the server receives the update.
  autofill::AutofillProfile profile2 = BuildTestAccountProfile();
  GetPersonalDataManager()->address_data_manager().AddProfile(profile2);

  ASSERT_TRUE(ServerCountMatchStatusChecker(syncer::CONTACT_INFO, 2).Wait());
  // Verifies that `profile` has preserved unknown_fields.
  EXPECT_THAT(fake_server_->GetSyncEntitiesByDataType(syncer::CONTACT_INFO),
              UnorderedElementsAre(
                  HasContactInfoWithGuidAndUnknownFields(profile.guid(),
                                                         kUnsupportedField),
                  HasContactInfoWithGuidAndUnknownFields(profile2.guid(), "")));
}

#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest,
                       ShouldReturnLocalDataDescriptions) {
  ASSERT_TRUE(SetupClients());

  autofill::AutofillProfile profile1 = autofill::test::GetFullProfile();
  GetPersonalDataManager()->address_data_manager().AddProfile(profile1);

  autofill::AutofillProfile profile2 = autofill::test::GetFullProfile2();
  GetPersonalDataManager()->address_data_manager().AddProfile(profile2);

  ASSERT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(profile1, profile2))
                  .Wait());
  ASSERT_THAT(
      GetPersonalDataManager()->address_data_manager().GetProfilesByRecordType(
          autofill::AutofillProfile::RecordType::kLocalOrSyncable),
      UnorderedElementsAre(HasContactInfoWithFirstName(profile1.GetRawInfo(
                               autofill::FieldType::NAME_FIRST)),
                           HasContactInfoWithFirstName(profile2.GetRawInfo(
                               autofill::FieldType::NAME_FIRST))));

  // Setup transport mode.
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  ASSERT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));

  EXPECT_THAT(
      GetClient(0)->GetLocalDataDescriptionAndWait(syncer::CONTACT_INFO),
      MatchesLocalDataDescription(
          syncer::DataType::CONTACT_INFO,
          UnorderedElementsAre(
              MatchesLocalDataItemModel(profile1.guid(),
                                        syncer::LocalDataItemModel::NoIcon(),
                                        /*title=*/_, /*subtitle=*/_),
              MatchesLocalDataItemModel(profile2.guid(),
                                        syncer::LocalDataItemModel::NoIcon(),
                                        /*title=*/_, /*subtitle=*/_)),
          // TODO(crbug.com/373568992): Merge Desktop and Mobile data
          // under common struct.
          /*item_count=*/0u, /*domains=*/IsEmpty(),
          /*domain_count=*/0u));
}

IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest,
                       ShouldBatchUploadAllEntries) {
  ASSERT_TRUE(SetupClients());

  autofill::AutofillProfile profile1 = autofill::test::GetFullProfile();
  GetPersonalDataManager()->address_data_manager().AddProfile(profile1);

  autofill::AutofillProfile profile2 = autofill::test::GetFullProfile2();
  GetPersonalDataManager()->address_data_manager().AddProfile(profile2);

  ASSERT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(profile1, profile2))
                  .Wait());
  ASSERT_THAT(
      GetPersonalDataManager()->address_data_manager().GetProfilesByRecordType(
          autofill::AutofillProfile::RecordType::kLocalOrSyncable),
      UnorderedElementsAre(HasContactInfoWithFirstName(profile1.GetRawInfo(
                               autofill::FieldType::NAME_FIRST)),
                           HasContactInfoWithFirstName(profile2.GetRawInfo(
                               autofill::FieldType::NAME_FIRST))));

  // Setup transport mode.
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  ASSERT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));

  GetSyncService(0)->TriggerLocalDataMigration({syncer::CONTACT_INFO});

  EXPECT_TRUE(ServerCountMatchStatusChecker(syncer::CONTACT_INFO, 2).Wait());
  EXPECT_THAT(fake_server_->GetSyncEntitiesByDataType(syncer::CONTACT_INFO),
              UnorderedElementsAre(
                  HasContactInfoWithAddress(profile1.GetRawInfo(
                      autofill::FieldType::ADDRESS_HOME_STREET_ADDRESS)),
                  HasContactInfoWithAddress(profile2.GetRawInfo(
                      autofill::FieldType::ADDRESS_HOME_STREET_ADDRESS))));

  EXPECT_THAT(
      GetPersonalDataManager()->address_data_manager().GetProfilesByRecordType(
          autofill::AutofillProfile::RecordType::kLocalOrSyncable),
      IsEmpty());

  EXPECT_THAT(
      GetPersonalDataManager()->address_data_manager().GetProfilesByRecordType(
          autofill::AutofillProfile::RecordType::kAccount),
      UnorderedElementsAre(HasContactInfoWithFirstName(profile1.GetRawInfo(
                               autofill::FieldType::NAME_FIRST)),
                           HasContactInfoWithFirstName(profile2.GetRawInfo(
                               autofill::FieldType::NAME_FIRST))));
}

IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest,
                       ShouldBatchUploadSomeEntries) {
  ASSERT_TRUE(SetupClients());

  autofill::AutofillProfile profile1 = autofill::test::GetFullProfile();
  GetPersonalDataManager()->address_data_manager().AddProfile(profile1);

  autofill::AutofillProfile profile2 = autofill::test::GetFullProfile2();
  GetPersonalDataManager()->address_data_manager().AddProfile(profile2);

  ASSERT_TRUE(AddressDataManagerProfileChecker(
                  &GetPersonalDataManager()->address_data_manager(),
                  UnorderedElementsAre(profile1, profile2))
                  .Wait());
  ASSERT_THAT(
      GetPersonalDataManager()->address_data_manager().GetProfilesByRecordType(
          autofill::AutofillProfile::RecordType::kLocalOrSyncable),
      UnorderedElementsAre(HasContactInfoWithFirstName(profile1.GetRawInfo(
                               autofill::FieldType::NAME_FIRST)),
                           HasContactInfoWithFirstName(profile2.GetRawInfo(
                               autofill::FieldType::NAME_FIRST))));

  // Setup transport mode.
  ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount());
  ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive());
  ASSERT_TRUE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));

  GetSyncService(0)->TriggerLocalDataMigrationForItems(
      {{syncer::CONTACT_INFO, {profile1.guid()}}});

  EXPECT_TRUE(ServerCountMatchStatusChecker(syncer::CONTACT_INFO, 1).Wait());
  EXPECT_THAT(fake_server_->GetSyncEntitiesByDataType(syncer::CONTACT_INFO),
              ElementsAre(HasContactInfoWithAddress(profile1.GetRawInfo(
                  autofill::FieldType::ADDRESS_HOME_STREET_ADDRESS))));

  EXPECT_THAT(
      GetPersonalDataManager()->address_data_manager().GetProfilesByRecordType(
          autofill::AutofillProfile::RecordType::kLocalOrSyncable),
      ElementsAre(HasContactInfoWithFirstName(
          profile2.GetRawInfo(autofill::FieldType::NAME_FIRST))));

  EXPECT_THAT(
      GetPersonalDataManager()->address_data_manager().GetProfilesByRecordType(
          autofill::AutofillProfile::RecordType::kAccount),
      ElementsAre(HasContactInfoWithFirstName(
          profile1.GetRawInfo(autofill::FieldType::NAME_FIRST))));
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

IN_PROC_BROWSER_TEST_F(SingleClientContactInfoSyncTest,
                       DisabledForManagedAccounts) {
  // Sign in with a managed account.
  ASSERT_TRUE(SetupSync(SyncTestAccount::kEnterpriseAccount1));

  EXPECT_FALSE(
      GetSyncService(0)->GetActiveDataTypes().Has(syncer::CONTACT_INFO));
}
#endif

}  // namespace