File: safari_data_importer_unittest.cc

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; 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 (455 lines) | stat: -rw-r--r-- 17,144 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
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/user_data_importer/utility/safari_data_importer.h"

#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/path_service.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/run_until.h"
#include "base/test/task_environment.h"
#include "components/affiliations/core/browser/fake_affiliation_service.h"
#include "components/password_manager/core/browser/import/csv_password_sequence.h"
#include "components/password_manager/core/browser/import/import_results.h"
#include "components/password_manager/core/browser/import/password_importer.h"
#include "components/password_manager/core/browser/password_store/test_password_store.h"
#include "components/password_manager/core/browser/ui/credential_ui_entry.h"
#include "components/password_manager/core/browser/ui/saved_passwords_presenter.h"
#include "components/password_manager/core/common/password_manager_constants.h"
#include "components/password_manager/services/csv_password/fake_password_parser_service.h"
#include "components/user_data_importer/utility/safari_data_import_manager.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace user_data_importer {

class TestSafariDataImportManager : public SafariDataImportManager {
 public:
  TestSafariDataImportManager() = default;
  ~TestSafariDataImportManager() override = default;

  void ParseBookmarks(
      const base::FilePath& bookmarks_html,
      base::OnceCallback<void(BookmarkParsingResult)> callback) override {}
};

class SafariDataImporterTest : public testing::Test {
 public:
  SafariDataImporterTest()
      : receiver_{&service_},
        importer_(&presenter_,
                  std::make_unique<TestSafariDataImportManager>(),
                  "en-US") {
    mojo::PendingRemote<password_manager::mojom::CSVPasswordParser>
        pending_remote{receiver_.BindNewPipeAndPassRemote()};
    importer_.password_importer_->SetServiceForTesting(
        std::move(pending_remote));
    importer_.password_importer_->SetDeleteFileForTesting(
        mock_delete_file_.Get());

    profile_store_->Init(/*prefs=*/nullptr,
                         /*affiliated_match_helper=*/nullptr);
    account_store_->Init(/*prefs=*/nullptr,
                         /*affiliated_match_helper=*/nullptr);
    // Use of Unretained below is safe because the RunUntil loop below
    // guarantees this outlives the tasks.
    presenter_.Init(base::BindOnce(&SafariDataImporterTest::OnPresenterReady,
                                   base::Unretained(this)));
    WaitUntilPresenterIsReady();
  }

  SafariDataImporterTest(const SafariDataImporterTest&) = delete;
  SafariDataImporterTest& operator=(const SafariDataImporterTest&) = delete;

  ~SafariDataImporterTest() override {
    account_store_->ShutdownOnUIThread();
    profile_store_->ShutdownOnUIThread();
    task_environment_.RunUntilIdle();
  }

  void WaitUntilPresenterIsReady() {
    ASSERT_TRUE(base::test::RunUntil([&]() { return presenter_ready_; }));
  }

  void OnPresenterReady() { presenter_ready_ = true; }

  password_manager::ImportResults GetImportResults() const {
    return import_results_;
  }

  int GetNumberOfBookmarksImported() const {
    return number_bookmarks_imported_;
  }

  int GetNumberOfPaymentCardsImported() const {
    return number_payment_cards_imported_;
  }

  int GetNumberOfURLsImported() const { return number_urls_imported_; }

  void OnBookmarksConsumed(int number_imported) {
    bookmarks_callback_called_ = true;
    number_bookmarks_imported_ = number_imported;
  }

  void OnPasswordsConsumed(const password_manager::ImportResults& results) {
    passwords_callback_called_ = true;
    import_results_ = results;
  }

  void OnPaymentCardsConsumed(int number_imported) {
    payment_cards_callback_called_ = true;
    number_payment_cards_imported_ = number_imported;
  }

  void OnURLsConsumed(int number_imported) {
    history_callback_called_ = true;
    number_urls_imported_ = number_imported;
  }

  void ImportBookmarks(std::string html_data) {
    bookmarks_callback_called_ = false;
    importer_.ImportBookmarks(
        std::move(html_data),
        // Use of Unretained below is safe because the RunUntil loop below
        // guarantees this outlives the tasks.
        base::BindOnce(&SafariDataImporterTest::OnBookmarksConsumed,
                       base::Unretained(this)));
    ASSERT_TRUE(
        base::test::RunUntil([&]() { return bookmarks_callback_called_; }));
  }

  void ImportHistory() {
    history_callback_called_ = false;
    importer_.ImportHistory(
        // Use of Unretained below is safe because the RunUntil loop below
        // guarantees this outlives the tasks.
        base::BindOnce(&SafariDataImporterTest::OnURLsConsumed,
                       base::Unretained(this)));
    ASSERT_TRUE(
        base::test::RunUntil([&]() { return history_callback_called_; }));
  }

  void ImportPasswords(std::string csv_data) {
    passwords_callback_called_ = false;
    importer_.ImportPasswords(
        std::move(csv_data),
        // Use of Unretained below is safe because the RunUntil loop below
        // guarantees this outlives the tasks.
        base::BindOnce(&SafariDataImporterTest::OnPasswordsConsumed,
                       base::Unretained(this)));
    ASSERT_TRUE(
        base::test::RunUntil([&]() { return passwords_callback_called_; }));
  }

  void ExecuteImport() {
    passwords_callback_called_ = false;
    importer_.ContinueImport(
        std::vector<int>(),
        // Use of Unretained below is safe because the RunUntil loop below
        // guarantees this outlives the tasks.
        base::BindOnce(&SafariDataImporterTest::OnPasswordsConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnBookmarksConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnURLsConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnPaymentCardsConsumed,
                       base::Unretained(this)));
    ASSERT_TRUE(
        base::test::RunUntil([&]() { return passwords_callback_called_; }));
  }

  void ResolvePasswordConflicts(const std::vector<int>& selected_ids) {
    passwords_callback_called_ = false;
    importer_.ContinueImport(
        selected_ids,
        // Use of Unretained below is safe because the RunUntil loop below
        // guarantees this outlives the tasks.
        base::BindOnce(&SafariDataImporterTest::OnPasswordsConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnBookmarksConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnURLsConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnPaymentCardsConsumed,
                       base::Unretained(this)));
    ASSERT_TRUE(
        base::test::RunUntil([&]() { return passwords_callback_called_; }));
  }

  void ImportPaymentCards(std::vector<PaymentCardEntry> payment_cards) {
    payment_cards_callback_called_ = false;
    importer_.ImportPaymentCards(
        std::move(payment_cards),
        // Use of Unretained below is safe because the RunUntil loop below
        // guarantees this outlives the tasks.
        base::BindOnce(&SafariDataImporterTest::OnPaymentCardsConsumed,
                       base::Unretained(this)));
    ASSERT_TRUE(
        base::test::RunUntil([&]() { return payment_cards_callback_called_; }));
  }

  void ImportInvalidFile() {
    passwords_callback_called_ = false;
    bookmarks_callback_called_ = false;
    history_callback_called_ = false;
    payment_cards_callback_called_ = false;

    importer_.StartImport(
        base::FilePath(FILE_PATH_LITERAL("/invalid/path/to/zip/file")),
        // Use of Unretained below is safe because the RunUntil loop below
        // guarantees this outlives the tasks.
        base::BindOnce(&SafariDataImporterTest::OnPasswordsConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnBookmarksConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnURLsConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnPaymentCardsConsumed,
                       base::Unretained(this)));

    ASSERT_TRUE(base::test::RunUntil([&]() {
      return passwords_callback_called_ && payment_cards_callback_called_ &&
             bookmarks_callback_called_ && history_callback_called_;
    })) << CallbackTimeoutMessage();
  }

  void ImportFile() {
    base::FilePath zip_archive_path;
    ASSERT_TRUE(base::PathService::Get(base::DIR_ASSETS, &zip_archive_path));
    zip_archive_path =
        zip_archive_path.Append(FILE_PATH_LITERAL("test_archive.zip"));

    passwords_callback_called_ = false;
    bookmarks_callback_called_ = false;
    history_callback_called_ = false;
    payment_cards_callback_called_ = false;

    importer_.StartImport(
        zip_archive_path,
        // Use of Unretained below is safe because the RunUntil loop below
        // guarantees this outlives the tasks.
        base::BindOnce(&SafariDataImporterTest::OnPasswordsConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnBookmarksConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnURLsConsumed,
                       base::Unretained(this)),
        base::BindOnce(&SafariDataImporterTest::OnPaymentCardsConsumed,
                       base::Unretained(this)));

    ASSERT_TRUE(base::test::RunUntil([&]() {
      return passwords_callback_called_ && payment_cards_callback_called_ &&
             bookmarks_callback_called_ && history_callback_called_;
    })) << CallbackTimeoutMessage();
  }

  void CancelImport() { importer_.CancelImport(); }

 private:
  // Formats an error message when timing out while waiting for callbacks.
  std::string CallbackTimeoutMessage() {
    std::string message = "Timed out waiting for: ";
    bool found_uncalled_callback = false;
    if (!passwords_callback_called_) {
      message += "passwords";
      found_uncalled_callback = true;
    }

    if (!payment_cards_callback_called_) {
      if (found_uncalled_callback) {
        message += ", ";
      }
      message += "payment cards";
      found_uncalled_callback = true;
    }

    if (!bookmarks_callback_called_) {
      if (found_uncalled_callback) {
        message += ", ";
      }
      message += "bookmarks";
      found_uncalled_callback = true;
    }

    if (!history_callback_called_) {
      if (found_uncalled_callback) {
        message += ", ";
      }
      message += "history";
      found_uncalled_callback = true;
    }

    if (!found_uncalled_callback) {
      message += "unknown reason";
    }

    return message;
  }

  base::test::TaskEnvironment task_environment_;
  bool presenter_ready_ = false;
  password_manager::ImportResults import_results_;
  bool passwords_callback_called_ = false;
  bool bookmarks_callback_called_ = false;
  bool history_callback_called_ = false;
  bool payment_cards_callback_called_ = false;
  int number_bookmarks_imported_ = -1;
  int number_urls_imported_ = -1;
  int number_payment_cards_imported_ = -1;
  password_manager::FakePasswordParserService service_;
  mojo::Receiver<password_manager::mojom::CSVPasswordParser> receiver_;
  scoped_refptr<password_manager::TestPasswordStore> profile_store_ =
      base::MakeRefCounted<password_manager::TestPasswordStore>(
          password_manager::IsAccountStore(false));
  scoped_refptr<password_manager::TestPasswordStore> account_store_ =
      base::MakeRefCounted<password_manager::TestPasswordStore>(
          password_manager::IsAccountStore(true));
  affiliations::FakeAffiliationService affiliation_service_;
  password_manager::SavedPasswordsPresenter presenter_{
      &affiliation_service_, profile_store_, account_store_};
  SafariDataImporter importer_;
  testing::StrictMock<base::MockCallback<
      password_manager::PasswordImporter::DeleteFileCallback>>
      mock_delete_file_;
};

TEST_F(SafariDataImporterTest, NoBookmark) {
  ImportBookmarks("");

  ASSERT_EQ(GetNumberOfBookmarksImported(), 0);
}

TEST_F(SafariDataImporterTest, NoHistory) {
  ImportHistory();

  ASSERT_EQ(GetNumberOfURLsImported(), 0);
}

TEST_F(SafariDataImporterTest, NoPassword) {
  ImportPasswords("");

  password_manager::ImportResults import_results = GetImportResults();
  ASSERT_EQ(import_results.number_imported, 0u);
}

TEST_F(SafariDataImporterTest, NoPaymentCard) {
  ImportPaymentCards(std::vector<PaymentCardEntry>());

  ASSERT_EQ(GetNumberOfPaymentCardsImported(), 0);
}

TEST_F(SafariDataImporterTest, PasswordImport) {
  constexpr char kTestCSVInput[] =
      "Url,Username,Password,Note\n"
      "http://example1.com,username1,password1,note1\n"
      "http://example1.com,username2,password2,note2\n"
      "http://example2.com,username1,password3,note3\n";

  ImportPasswords(kTestCSVInput);
  password_manager::ImportResults import_results = GetImportResults();
  ASSERT_EQ(import_results.number_imported, 0u);
  ASSERT_EQ(import_results.number_to_import, 3u);

  // Confirm password import.
  ExecuteImport();
  import_results = GetImportResults();
  ASSERT_EQ(import_results.number_imported, 3u);
  ASSERT_EQ(import_results.number_to_import, 0u);
}

TEST_F(SafariDataImporterTest, PasswordImportConflicts) {
  constexpr char kTestCSVInput[] =
      "Url,Username,Password,Note\n"
      "http://example1.com,username1,password1,note1\n"
      "http://example1.com,username2,password2,note2\n"
      "http://example2.com,username1,password3,note3\n";

  constexpr char kTestCSVConflicts[] =
      "Url,Username,Password,Note\n"
      "http://example1.com,username2,password4,note2\n"
      "http://example2.com,username1,password5,note3\n";

  // Import 3 passwords.
  ImportPasswords(kTestCSVInput);
  password_manager::ImportResults import_results = GetImportResults();
  ASSERT_EQ(import_results.number_imported, 0u);
  ASSERT_EQ(import_results.number_to_import, 3u);

  // Confirm password import.
  ExecuteImport();
  import_results = GetImportResults();
  ASSERT_EQ(import_results.number_imported, 3u);
  ASSERT_EQ(import_results.number_to_import, 0u);

  // Attempt to import 2 conflicting passwords, which should fail.
  ImportPasswords(kTestCSVConflicts);
  import_results = GetImportResults();
  ASSERT_EQ(import_results.number_imported, 0u);
  ASSERT_EQ(import_results.number_to_import, 0u);
  // 2 conflicting entries need to be displayed to the user.
  ASSERT_EQ(import_results.displayed_entries.size(), 2u);

  // Resolve the 2 conflicts.
  std::vector<int> selected_ids;
  selected_ids.push_back(0);
  selected_ids.push_back(1);
  ResolvePasswordConflicts(selected_ids);
  import_results = GetImportResults();
  ASSERT_EQ(import_results.number_imported, 2u);
  ASSERT_EQ(import_results.number_to_import, 0u);
}

TEST_F(SafariDataImporterTest, CallbacksAreCalled) {
  ImportInvalidFile();
}

TEST_F(SafariDataImporterTest, CancelImport) {
  ImportFile();

  password_manager::ImportResults import_results = GetImportResults();
  ASSERT_EQ(import_results.number_to_import, 3u);
  // TODO(crbug.com/407587751): Update test when bookmarks parsing is
  // implemented.
  ASSERT_EQ(GetNumberOfBookmarksImported(), 0);
  ASSERT_EQ(GetNumberOfPaymentCardsImported(), 3);
  ASSERT_EQ(GetNumberOfURLsImported(), 5);  // Note: Approximation.

  CancelImport();
}

TEST_F(SafariDataImporterTest, ExecuteImport) {
  ImportFile();

  password_manager::ImportResults import_results = GetImportResults();
  ASSERT_EQ(import_results.number_to_import, 3u);
  ASSERT_EQ(import_results.number_imported, 0u);
  // TODO(crbug.com/407587751): Update test when bookmarks parsing is
  // implemented.
  ASSERT_EQ(GetNumberOfBookmarksImported(), 0);
  ASSERT_EQ(GetNumberOfPaymentCardsImported(), 3);
  ASSERT_EQ(GetNumberOfURLsImported(), 5);  // Note: Approximation.

  ExecuteImport();
  import_results = GetImportResults();
  ASSERT_EQ(import_results.number_imported, 3u);
  ASSERT_EQ(import_results.number_to_import, 0u);
  // TODO(crbug.com/407587751): Update test when bookmarks parsing is
  // implemented.
  ASSERT_EQ(GetNumberOfBookmarksImported(), 0);
  // TODO(crbug.com/407587751): Update test when payment cards import is
  // implemented.
  ASSERT_EQ(GetNumberOfPaymentCardsImported(), 0);
  ASSERT_EQ(GetNumberOfURLsImported(), 5);
}

}  // namespace user_data_importer