File: autofill_merge_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (285 lines) | stat: -rw-r--r-- 11,111 bytes parent folder | download | duplicates (5)
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
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>

#include <algorithm>
#include <map>
#include <memory>
#include <vector>

#include "base/feature_list.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "components/autofill/core/browser/autofill_type.h"
#include "components/autofill/core/browser/data_manager/addresses/address_data_manager.h"
#include "components/autofill/core/browser/data_manager/addresses/address_data_manager_test_api.h"
#include "components/autofill/core/browser/data_manager/test_personal_data_manager.h"
#include "components/autofill/core/browser/form_import/form_data_importer.h"
#include "components/autofill/core/browser/form_import/form_data_importer_test_api.h"
#include "components/autofill/core/browser/form_structure.h"
#include "components/autofill/core/browser/foundations/test_autofill_client.h"
#include "components/autofill/core/browser/test_utils/autofill_test_utils.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/form_data_test_api.h"
#include "testing/data_driven_testing/data_driven_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_APPLE)
#include "base/apple/foundation_util.h"
#endif

namespace autofill {
namespace {

const base::FilePath::CharType kFeatureName[] = FILE_PATH_LITERAL("autofill");
const base::FilePath::CharType kTestName[] = FILE_PATH_LITERAL("merge");
const base::FilePath::CharType kFileNamePattern[] = FILE_PATH_LITERAL("*.in");

const char kFieldSeparator[] = ":";
const char kProfileSeparator[] = "---";

const FieldType kProfileFieldTypes[] = {NAME_FIRST,
                                        NAME_MIDDLE,
                                        NAME_LAST,
                                        NAME_FULL,
                                        EMAIL_ADDRESS,
                                        COMPANY_NAME,
                                        ADDRESS_HOME_STREET_ADDRESS,
                                        ADDRESS_HOME_CITY,
                                        ADDRESS_HOME_STATE,
                                        ADDRESS_HOME_ZIP,
                                        ADDRESS_HOME_COUNTRY,
                                        PHONE_HOME_WHOLE_NUMBER};

const base::FilePath& GetTestDataDir() {
  static base::NoDestructor<base::FilePath> dir([] {
    base::FilePath dir;
    base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &dir);
    return dir.AppendASCII("components")
        .AppendASCII("test")
        .AppendASCII("data");
  }());
  return *dir;
}

const std::vector<base::FilePath> GetTestFiles() {
  base::FilePath dir = GetTestDataDir();

  dir = dir.AppendASCII("autofill").Append(kTestName).AppendASCII("input");
  base::FileEnumerator input_files(dir, false, base::FileEnumerator::FILES,
                                   kFileNamePattern);
  std::vector<base::FilePath> files;
  for (base::FilePath input_file = input_files.Next(); !input_file.empty();
       input_file = input_files.Next()) {
    files.push_back(input_file);
  }
  std::sort(files.begin(), files.end());

#if BUILDFLAG(IS_APPLE)
  base::apple::ClearAmIBundledCache();
#endif  // BUILDFLAG(IS_APPLE)

  return files;
}

// Fakes that a `form` has been seen (without its field value) and parsed and
// then values have been entered. Returns the resulting FormStructure.
std::unique_ptr<FormStructure> ConstructFormStructureFromFormData(
    const FormData& form) {
  auto cached_form_structure =
      std::make_unique<FormStructure>(test::WithoutValues(form));
  cached_form_structure->DetermineHeuristicTypes(GeoIpCountryCode(""), nullptr);

  auto form_structure = std::make_unique<FormStructure>(form);
  form_structure->RetrieveFromCache(
      *cached_form_structure,
      FormStructure::RetrieveFromCacheReason::kFormImport);
  return form_structure;
}

// Serializes the |profiles| into a string.
std::string SerializeProfiles(
    const std::vector<const AutofillProfile*>& profiles) {
  std::string result;
  for (const AutofillProfile* profile : profiles) {
    result += kProfileSeparator;
    result += "\n";
    for (const FieldType& type : kProfileFieldTypes) {
      std::u16string value = profile->GetRawInfo(type);
      result += FieldTypeToStringView(type);
      result += kFieldSeparator;
      if (!value.empty()) {
        base::ReplaceFirstSubstringAfterOffset(&value, 0, u"\\n", u"\n");
        result += " ";
        result += base::UTF16ToUTF8(value);
      }
      result += "\n";
    }
  }

  return result;
}

// A data-driven test for verifying merging of Autofill profiles. Each input is
// a structured dump of a set of implicitly detected autofill profiles. The
// corresponding output file is a dump of the saved profiles that result from
// importing the input profiles. The output file format is identical to the
// input format.
class AutofillMergeTest : public testing::DataDrivenTest,
                          public testing::TestWithParam<base::FilePath> {
 public:
  AutofillMergeTest(const AutofillMergeTest&) = delete;
  AutofillMergeTest& operator=(const AutofillMergeTest&) = delete;

 protected:
  AutofillMergeTest();
  ~AutofillMergeTest() override;

  // testing::Test:
  void SetUp() override;

  // DataDrivenTest:
  void GenerateResults(const std::string& input, std::string* output) override;

  // Deserializes a set of Autofill profiles from |profiles|, imports each
  // sequentially, and fills |merged_profiles| with the serialized result.
  void MergeProfiles(const std::string& profiles, std::string* merged_profiles);

  TestAddressDataManager& test_address_data_manager() {
    return autofill_client_.GetPersonalDataManager()
        .test_address_data_manager();
  }

  ukm::SourceId ukm_source_id() const { return 123; }

  base::test::TaskEnvironment task_environment_;
  base::test::ScopedFeatureList scoped_feature_list_;
  TestAutofillClient autofill_client_;
  std::unique_ptr<FormDataImporter> form_data_importer_;
};

AutofillMergeTest::AutofillMergeTest()
    : testing::DataDrivenTest(GetTestDataDir(), kFeatureName, kTestName) {}

AutofillMergeTest::~AutofillMergeTest() = default;

void AutofillMergeTest::SetUp() {
  test_api(test_address_data_manager()).set_auto_accept_address_imports(true);
  form_data_importer_ = std::make_unique<FormDataImporter>(
      &autofill_client_, /*history_service=*/nullptr);
  scoped_feature_list_.InitWithFeatures(
      /*enabled_features=*/{},
      /*disabled_features=*/{});
}

void AutofillMergeTest::GenerateResults(const std::string& input,
                                        std::string* output) {
  MergeProfiles(input, output);
}

void AutofillMergeTest::MergeProfiles(const std::string& profiles,
                                      std::string* merged_profiles) {
  // Start with no saved profiles.
  test_address_data_manager().ClearProfiles();

  // Create a test form.
  FormData form;
  form.set_name(u"MyTestForm");
  form.set_url(GURL("https://www.example.com/origin.html"));
  form.set_action(GURL("https://www.example.com/action.html"));

  // Parse the input line by line.
  std::vector<std::string> lines = base::SplitString(
      profiles, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  for (size_t i = 0; i < lines.size(); ++i) {
    std::string line = lines[i];
    if (line != kProfileSeparator) {
      // Add a field to the current profile.
      size_t separator_pos = line.find(kFieldSeparator);
      ASSERT_NE(std::string::npos, separator_pos)
          << "Wrong format for separator on line " << i;
      std::u16string field_type =
          base::UTF8ToUTF16(line.substr(0, separator_pos));
      do {
        ++separator_pos;
      } while (separator_pos < line.size() && line[separator_pos] == ' ');
      std::u16string value = base::UTF8ToUTF16(line.substr(separator_pos));
      base::ReplaceFirstSubstringAfterOffset(&value, 0, u"\\n", u"\n");

      FormFieldData field;
      field.set_label(field_type);
      field.set_name(field_type);
      field.set_value(value);
      field.set_form_control_type(FormControlType::kInputText);
      field.set_is_focusable(true);
      test_api(form).Append(field);
    }

    // The first line is always a profile separator, and the last profile is not
    // followed by an explicit separator.
    if ((i > 0 && line == kProfileSeparator) || i == lines.size() - 1) {
      // Reached the end of a profile.  Try to import it.
      std::unique_ptr<FormStructure> form_structure =
          ConstructFormStructureFromFormData(form);
      for (size_t j = 0; j < form_structure->field_count(); ++j) {
        // Set the heuristic type for each field, which is currently serialized
        // into the field's name.
        AutofillField* field =
            const_cast<AutofillField*>(form_structure->field(j));
        FieldType type = TypeNameToFieldType(base::UTF16ToUTF8(field->name()));
        field->set_heuristic_type(GetActiveHeuristicSource(), type);
      }

      // Extract the profile.
      auto extracted_data =
          test_api(*form_data_importer_)
              .ExtractFormData(*form_structure,
                               /*profile_autofill_enabled=*/true,
                               /*payment_methods_autofill_enabled=*/true);
      test_api(*form_data_importer_)
          .ProcessExtractedAddressProfiles(
              extracted_data.extracted_address_profiles,
              /*allow_prompt=*/true, ukm_source_id());
      EXPECT_FALSE(extracted_data.extracted_credit_card);

      // Clear the |form| to start a new profile.
      form.set_fields({});
    }
  }

  std::vector<const AutofillProfile*> imported_profiles =
      test_address_data_manager().GetProfiles();
  // To ensure a consistent order with the output files, sort the profiles by
  // modification date. This corresponds to the order in which the profiles
  // were imported (or updated).
  std::ranges::sort(imported_profiles,
                    [](const AutofillProfile* a, const AutofillProfile* b) {
                      return a->usage_history().modification_date() <
                             b->usage_history().modification_date();
                    });
  *merged_profiles = SerializeProfiles(imported_profiles);
}

TEST_P(AutofillMergeTest, DataDrivenMergeProfiles) {
  const bool kIsExpectedToPass = true;
  RunOneDataDrivenTest(GetParam(), GetOutputDirectory(), kIsExpectedToPass);
}

INSTANTIATE_TEST_SUITE_P(All,
                         AutofillMergeTest,
                         testing::ValuesIn(GetTestFiles()));

}  // namespace
}  // namespace autofill