summaryrefslogtreecommitdiffstats
path: root/browser/components/aboutlogins/tests/browser/browser_openImportCSV.js
blob: c4994215d8cbd0f07cc732f9ca5fb99466ac81d5 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const { FileTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/FileTestUtils.sys.mjs"
);

let { TelemetryTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/TelemetryTestUtils.sys.mjs"
);

let { MockFilePicker } = SpecialPowers;

/**
 * A helper class to deal with Login CSV import UI.
 */
class CsvImportHelper {
  /**
   * Waits until the mock file picker is opened and sets the destFilePath as it's selected file.
   *
   * @param {nsIFile} destFile
   *        The file being passed to the picker.
   * @returns {string} A promise that is resolved when the picker selects the file.
   */
  static waitForOpenFilePicker(destFile) {
    return new Promise(resolve => {
      MockFilePicker.showCallback = fp => {
        info("showCallback");
        info("fileName: " + destFile.path);
        MockFilePicker.setFiles([destFile]);
        MockFilePicker.filterIndex = 1;
        info("done showCallback");
        resolve();
      };
    });
  }

  /**
   * Clicks the 3 dot menu and then "Import from a file..." and then it serves a CSV file.
   * It also does the needed assertions and telemetry validations.
   * If you await for it to return, it will have processed the CSV file already.
   *
   * @param {browser} browser
   *        The browser object.
   * @param {string[]} linesInFile
   *        An array of strings to be used to generate the CSV file. Each string is a line.
   * @returns {Promise} A promise that is resolved when the picker selects the file.
   */
  static async clickImportFromCsvMenu(browser, linesInFile) {
    MockFilePicker.init(window);
    MockFilePicker.returnValue = MockFilePicker.returnOK;
    let csvFile = await LoginTestUtils.file.setupCsvFileWithLines(linesInFile);

    await BrowserTestUtils.synthesizeMouseAtCenter("menu-button", {}, browser);

    await SpecialPowers.spawn(browser, [], async () => {
      let menuButton = content.document.querySelector("menu-button");
      return ContentTaskUtils.waitForCondition(function waitForMenu() {
        return !menuButton.shadowRoot.querySelector(".menu").hidden;
      }, "waiting for menu to open");
    });

    Services.telemetry.clearEvents();

    function getImportMenuItem() {
      let menuButton = window.document.querySelector("menu-button");
      let importButton = menuButton.shadowRoot.querySelector(
        ".menuitem-import-file"
      );
      // Force the menu item to be visible for the test.
      importButton.hidden = false;
      return importButton;
    }

    BrowserTestUtils.synthesizeMouseAtCenter(getImportMenuItem, {}, browser);

    async function waitForFilePicker() {
      let filePickerPromise = CsvImportHelper.waitForOpenFilePicker(csvFile);
      // First event is for opening about:logins
      await LoginTestUtils.telemetry.waitForEventCount(
        1,
        "content",
        "pwmgr",
        "mgmt_menu_item_used"
      );
      TelemetryTestUtils.assertEvents(
        [["pwmgr", "mgmt_menu_item_used", "import_from_csv"]],
        { category: "pwmgr", method: "mgmt_menu_item_used" },
        { process: "content", clear: false }
      );

      info("waiting for Import file picker to get opened");
      await filePickerPromise;
      Assert.ok(true, "Import file picker opened");
    }

    await waitForFilePicker();
  }

  /**
   * An utility method to fetch the data from the CSV import success dialog.
   *
   * @param {browser} browser
   *        The browser object.
   * @returns {Promise<Object>} A promise that contains added, modified, noChange and errors count.
   */
  static async getCsvImportSuccessDialogData(browser) {
    return SpecialPowers.spawn(browser, [], async () => {
      let dialog = Cu.waiveXrays(
        content.document.querySelector("import-summary-dialog")
      );
      await ContentTaskUtils.waitForCondition(
        () => !dialog.hidden,
        "Waiting for the dialog to be visible"
      );

      let added = dialog.shadowRoot.querySelector(
        ".import-items-added .result-count"
      ).textContent;
      let modified = dialog.shadowRoot.querySelector(
        ".import-items-modified .result-count"
      ).textContent;
      let noChange = dialog.shadowRoot.querySelector(
        ".import-items-no-change .result-count"
      ).textContent;
      let errors = dialog.shadowRoot.querySelector(
        ".import-items-errors .result-count"
      ).textContent;
      const dialogData = {
        added,
        modified,
        noChange,
        errors,
      };
      if (dialog.shadowRoot.activeElement) {
        dialogData.l10nFocused =
          dialog.shadowRoot.activeElement.getAttribute("data-l10n-id");
      }
      return dialogData;
    });
  }

  /**
   * An utility method to fetch the data from the CSV import error dialog.
   *
   * @param {browser} browser
   *        The browser object.
   * @returns {Promise<Object>} A promise that contains the hidden state and l10n id for title, description and focused element.
   */
  static async getCsvImportErrorDialogData(browser) {
    return SpecialPowers.spawn(browser, [], async () => {
      const dialog = Cu.waiveXrays(
        content.document.querySelector("import-error-dialog")
      );
      const l10nTitle = dialog._genericDialog
        .querySelector(".error-title")
        .getAttribute("data-l10n-id");
      const l10nDescription = dialog._genericDialog
        .querySelector(".error-description")
        .getAttribute("data-l10n-id");
      return {
        hidden: dialog.hidden,
        l10nFocused:
          dialog.shadowRoot.activeElement.getAttribute("data-l10n-id"),
        l10nTitle,
        l10nDescription,
      };
    });
  }

  /**
   * An utility method to wait until CSV import is complete.
   *
   * @returns {Promise} A promise that gets resolved when the import is complete.
   */
  static async waitForImportToComplete() {
    info("Waiting for the import to complete");
    await LoginTestUtils.telemetry.waitForEventCount(1, "parent");
    TelemetryTestUtils.assertEvents(
      [["pwmgr", "mgmt_menu_item_used", "import_csv_complete"]],
      { category: "pwmgr", method: "mgmt_menu_item_used" },
      { process: "parent" }
    );
  }

  /**
   * An utility method open the about:loginsimportreport page.
   *
   * @param {browser} browser
   *        The browser object.
   * @returns {Promise<Object>} A promise that contains the about:loginsimportreport tab.
   */
  static async clickDetailedReport(browser) {
    let loadedReportTab = BrowserTestUtils.waitForNewTab(
      gBrowser,
      "about:loginsimportreport",
      true
    );
    await SpecialPowers.spawn(browser, [], async () => {
      let dialog = Cu.waiveXrays(
        content.document.querySelector("import-summary-dialog")
      );
      await ContentTaskUtils.waitForCondition(
        () => !dialog.hidden,
        "Waiting for the dialog to be visible"
      );
      let detailedReportLink = dialog.shadowRoot.querySelector(
        ".open-detailed-report"
      );

      detailedReportLink.click();
    });
    return loadedReportTab;
  }

  /**
   * An utility method to fetch data from the about:loginsimportreport page.
   *
   * @param {browser} browser
   *        The browser object.
   * @returns {Promise<Object>} A promise that contains the detailed report data like added, modified, noChange, errors and rows.
   */
  static async getDetailedReportData(browser) {
    const data = await SpecialPowers.spawn(
      gBrowser.selectedBrowser,
      [],
      async () => {
        function getCount(selector) {
          const attribute = content.document
            .querySelector(selector)
            .getAttribute("data-l10n-args");
          return JSON.parse(attribute).count;
        }
        const rows = [];
        for (let element of content.document.querySelectorAll(".row-details")) {
          rows.push(element.getAttribute("data-l10n-id"));
        }
        const added = getCount(".new-logins");
        const modified = getCount(".exiting-logins");
        const noChange = getCount(".duplicate-logins");
        const errors = getCount(".errors-logins");
        return {
          rows,
          added,
          modified,
          noChange,
          errors,
        };
      }
    );
    return data;
  }
}

const random = Math.round(Math.random() * 100000001);

add_setup(async function () {
  registerCleanupFunction(() => {
    Services.logins.removeAllUserFacingLogins();
  });
});

add_task(async function test_open_import_one_item_from_csv() {
  await BrowserTestUtils.withNewTab(
    { gBrowser, url: "about:logins" },
    async browser => {
      await CsvImportHelper.clickImportFromCsvMenu(browser, [
        "url,username,password,httpRealm,formActionOrigin,guid,timeCreated,timeLastUsed,timePasswordChanged",
        `https://example.com,joe${random}@example.com,qwerty,My realm,,{${random}-e194-4279-ae1b-d7d281bb46f0},1589617814635,1589710449871,1589617846802`,
      ]);
      await CsvImportHelper.waitForImportToComplete();

      let summary = await CsvImportHelper.getCsvImportSuccessDialogData(
        browser
      );
      Assert.equal(summary.added, "1", "It should have one item as added");
      Assert.equal(
        summary.l10nFocused,
        "about-logins-import-dialog-done",
        "dismiss button should be focused"
      );
    }
  );
});

add_task(async function test_open_import_all_four_categories() {
  await BrowserTestUtils.withNewTab(
    { gBrowser, url: "about:logins" },
    async browser => {
      const initialCsvData = [
        "url,username,password,httpRealm,formActionOrigin,guid,timeCreated,timeLastUsed,timePasswordChanged",
        `https://example1.com,existing${random},existing,,,{${random}-07a1-4bcf-86f0-7d56b9c1f48f},1582229924361,1582495972623,1582229924000`,
        `https://example1.com,duplicate,duplicate,,,{dddd0080-07a1-4bcf-86f0-7d56b9c1f48f},1582229924361,1582495972623,1582229924363`,
      ];
      const updatedCsvData = [
        "url,username,password,httpRealm,formActionOrigin,guid,timeCreated,timeLastUsed,timePasswordChanged",
        `https://example1.com,added${random},added,,,,,,`,
        `https://example1.com,existing${random},modified,,,{${random}-07a1-4bcf-86f0-7d56b9c1f48f},1582229924361,1582495972623,1582229924363`,
        `https://example1.com,duplicate,duplicate,,,{dddd0080-07a1-4bcf-86f0-7d56b9c1f48f},1582229924361,1582495972623,1582229924363`,
        `https://example1.com,error,,,,,,,`,
      ];

      await CsvImportHelper.clickImportFromCsvMenu(browser, initialCsvData);
      await CsvImportHelper.waitForImportToComplete();
      await BrowserTestUtils.synthesizeMouseAtCenter(
        "dismiss-button",
        {},
        browser
      );
      await CsvImportHelper.clickImportFromCsvMenu(browser, updatedCsvData);
      await CsvImportHelper.waitForImportToComplete();

      let summary = await CsvImportHelper.getCsvImportSuccessDialogData(
        browser
      );
      Assert.equal(summary.added, "1", "It should have one item as added");
      Assert.equal(
        summary.modified,
        "1",
        "It should have one item as modified"
      );
      Assert.equal(
        summary.noChange,
        "1",
        "It should have one item as unchanged"
      );
      Assert.equal(summary.errors, "1", "It should have one item as error");
    }
  );
});

add_task(async function test_open_import_all_four_detailed_report() {
  await BrowserTestUtils.withNewTab(
    { gBrowser, url: "about:logins" },
    async browser => {
      const initialCsvData = [
        "url,username,password,httpRealm,formActionOrigin,guid,timeCreated,timeLastUsed,timePasswordChanged",
        `https://example2.com,existing${random},existing,,,{${random}-07a1-4bcf-86f0-7d56b9c1f48f},1582229924361,1582495972623,1582229924000`,
        "https://example2.com,duplicate,duplicate,,,{dddd0080-07a1-4bcf-86f0-7d56b9c1f48f},1582229924361,1582495972623,1582229924363",
      ];
      const updatedCsvData = [
        "url,username,password,httpRealm,formActionOrigin,guid,timeCreated,timeLastUsed,timePasswordChanged",
        `https://example2.com,added${random},added,,,,,,`,
        `https://example2.com,existing${random},modified,,,{${random}-07a1-4bcf-86f0-7d56b9c1f48f},1582229924361,1582495972623,1582229924363`,
        "https://example2.com,duplicate,duplicate,,,{dddd0080-07a1-4bcf-86f0-7d56b9c1f48f},1582229924361,1582495972623,1582229924363",
        "https://example2.com,error,,,,,,,",
      ];

      await CsvImportHelper.clickImportFromCsvMenu(browser, initialCsvData);
      await CsvImportHelper.waitForImportToComplete();
      await BrowserTestUtils.synthesizeMouseAtCenter(
        "dismiss-button",
        {},
        browser
      );
      await CsvImportHelper.clickImportFromCsvMenu(browser, updatedCsvData);
      await CsvImportHelper.waitForImportToComplete();
      const reportTab = await CsvImportHelper.clickDetailedReport(browser);
      const report = await CsvImportHelper.getDetailedReportData(browser);
      BrowserTestUtils.removeTab(reportTab);
      const { added, modified, noChange, errors, rows } = report;
      Assert.equal(added, 1, "It should have one item as added");
      Assert.equal(modified, 1, "It should have one item as modified");
      Assert.equal(noChange, 1, "It should have one item as unchanged");
      Assert.equal(errors, 1, "It should have one item as error");
      Assert.deepEqual(
        [
          "about-logins-import-report-row-description-added",
          "about-logins-import-report-row-description-modified",
          "about-logins-import-report-row-description-no-change",
          "about-logins-import-report-row-description-error-missing-field",
        ],
        rows,
        "It should have expected rows in order"
      );
    }
  );
});

add_task(async function test_open_import_from_csv_with_invalid_file() {
  await BrowserTestUtils.withNewTab(
    { gBrowser, url: "about:logins" },
    async browser => {
      await CsvImportHelper.clickImportFromCsvMenu(browser, [
        "invalid csv file",
      ]);

      info("Waiting for the import error dialog");
      const errorDialog = await CsvImportHelper.getCsvImportErrorDialogData(
        browser
      );
      Assert.equal(errorDialog.hidden, false, "Dialog should not be hidden");
      Assert.equal(
        errorDialog.l10nTitle,
        "about-logins-import-dialog-error-file-format-title",
        "Dialog error title should be correct"
      );
      Assert.equal(
        errorDialog.l10nDescription,
        "about-logins-import-dialog-error-file-format-description",
        "Dialog error description should be correct"
      );
      Assert.equal(
        errorDialog.l10nFocused,
        "about-logins-import-dialog-error-learn-more",
        "Learn more link should be focused."
      );
    }
  );
});