summaryrefslogtreecommitdiffstats
path: root/browser/components/urlbar/tests/quicksuggest/browser/browser_quicksuggest_block.js
blob: 081818c02b9d4802afd3ded1a2fc523ba9f10bd2 (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
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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

// Tests blocking quick suggest results, including best matches. See also:
//
// browser_bestMatch.js
//   Includes tests for blocking best match rows independent of quick suggest,
//   especially the superficial UI part that should be common to all types of
//   best matches

"use strict";

ChromeUtils.defineESModuleGetters(this, {
  CONTEXTUAL_SERVICES_PING_TYPES:
    "resource:///modules/PartnerLinkAttribution.sys.mjs",
});

const { TELEMETRY_SCALARS } = UrlbarProviderQuickSuggest;
const { TIMESTAMP_TEMPLATE } = QuickSuggest;

// Include the timestamp template in the suggestion URLs so we can make sure
// their original URLs with the unreplaced templates are blocked and not their
// URLs with timestamps.
const REMOTE_SETTINGS_RESULTS = [
  {
    id: 1,
    url: `https://example.com/sponsored?t=${TIMESTAMP_TEMPLATE}`,
    title: "Sponsored suggestion",
    keywords: ["sponsored"],
    click_url: "https://example.com/click",
    impression_url: "https://example.com/impression",
    advertiser: "TestAdvertiser",
    iab_category: "22 - Shopping",
  },
  {
    id: 2,
    url: `https://example.com/nonsponsored?t=${TIMESTAMP_TEMPLATE}`,
    title: "Non-sponsored suggestion",
    keywords: ["nonsponsored"],
    click_url: "https://example.com/click",
    impression_url: "https://example.com/impression",
    advertiser: "TestAdvertiser",
    iab_category: "5 - Education",
  },
];

// Spy for the custom impression/click sender
let spy;

add_setup(async function () {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.bestMatch.blockingEnabled", true],
      ["browser.urlbar.quicksuggest.blockingEnabled", true],
    ],
  });

  ({ spy } = QuickSuggestTestUtils.createTelemetryPingSpy());

  await PlacesUtils.history.clear();
  await PlacesUtils.bookmarks.eraseEverything();
  await UrlbarTestUtils.formHistory.clear();

  await QuickSuggest.blockedSuggestions._test_readyPromise;
  await QuickSuggest.blockedSuggestions.clear();

  Services.telemetry.clearScalars();
  Services.telemetry.clearEvents();

  await QuickSuggestTestUtils.ensureQuickSuggestInit({
    remoteSettingsResults: [
      {
        type: "data",
        attachment: REMOTE_SETTINGS_RESULTS,
      },
    ],
    config: QuickSuggestTestUtils.BEST_MATCH_CONFIG,
  });
});

/**
 * Adds a test task that runs the given callback with combinations of the
 * following:
 *
 * - Best match disabled and enabled
 * - Each result in `REMOTE_SETTINGS_RESULTS`
 *
 * @param {Function} fn
 *   The callback function. It's passed: `{ isBestMatch, suggestion }`
 */
function add_combo_task(fn) {
  let taskFn = async () => {
    for (let isBestMatch of [false, true]) {
      UrlbarPrefs.set("bestMatch.enabled", isBestMatch);
      for (let result of REMOTE_SETTINGS_RESULTS) {
        info(`Running ${fn.name}: ${JSON.stringify({ isBestMatch, result })}`);
        await fn({ isBestMatch, result });
      }
      UrlbarPrefs.clear("bestMatch.enabled");
    }
  };
  Object.defineProperty(taskFn, "name", { value: fn.name });
  add_task(taskFn);
}

// Picks the block button with the keyboard.
add_combo_task(async function basic_keyboard({ result, isBestMatch }) {
  await doBasicBlockTest({
    result,
    isBestMatch,
    block: async () => {
      if (UrlbarPrefs.get("resultMenu")) {
        await UrlbarTestUtils.openResultMenuAndPressAccesskey(window, "D", {
          resultIndex: 1,
        });
      } else {
        // TAB twice to select the block button: once to select the main
        // part of the row, once to select the block button.
        EventUtils.synthesizeKey("KEY_Tab", { repeat: 2 });
        EventUtils.synthesizeKey("KEY_Enter");
      }
    },
  });
});

// Picks the block button with the mouse.
add_combo_task(async function basic_mouse({ result, isBestMatch }) {
  await doBasicBlockTest({
    result,
    isBestMatch,
    block: async () => {
      if (UrlbarPrefs.get("resultMenu")) {
        await UrlbarTestUtils.openResultMenuAndPressAccesskey(window, "D", {
          resultIndex: 1,
          openByMouse: true,
        });
      } else {
        EventUtils.synthesizeMouseAtCenter(
          UrlbarTestUtils.getButtonForResultIndex(window, "block", 1),
          {}
        );
      }
    },
  });
});

// Uses the key shortcut to block a suggestion.
add_combo_task(async function basic_keyShortcut({ result, isBestMatch }) {
  await doBasicBlockTest({
    result,
    isBestMatch,
    block: () => {
      // Arrow down once to select the row.
      EventUtils.synthesizeKey("KEY_ArrowDown");
      EventUtils.synthesizeKey("KEY_Delete", { shiftKey: true });
    },
  });
});

async function doBasicBlockTest({ result, isBestMatch, block }) {
  spy.resetHistory();

  // Do a search that triggers the suggestion.
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: result.keywords[0],
  });
  Assert.equal(
    UrlbarTestUtils.getResultCount(window),
    2,
    "Two rows are present after searching (heuristic + suggestion)"
  );

  let isSponsored = result.keywords[0] == "sponsored";
  await QuickSuggestTestUtils.assertIsQuickSuggest({
    window,
    isBestMatch,
    isSponsored,
    originalUrl: result.url,
  });

  // Block the suggestion.
  await block();

  // The row should have been removed.
  Assert.ok(
    UrlbarTestUtils.isPopupOpen(window),
    "View remains open after blocking result"
  );
  Assert.equal(
    UrlbarTestUtils.getResultCount(window),
    1,
    "Only one row after blocking suggestion"
  );
  await QuickSuggestTestUtils.assertNoQuickSuggestResults(window);

  // The URL should be blocked.
  Assert.ok(
    await QuickSuggest.blockedSuggestions.has(result.url),
    "Suggestion is blocked"
  );

  // Check telemetry scalars.
  let index = 2;
  let scalars = {};
  if (isSponsored) {
    scalars[TELEMETRY_SCALARS.IMPRESSION_SPONSORED] = index;
    scalars[TELEMETRY_SCALARS.BLOCK_SPONSORED] = index;
  } else {
    scalars[TELEMETRY_SCALARS.IMPRESSION_NONSPONSORED] = index;
    scalars[TELEMETRY_SCALARS.BLOCK_NONSPONSORED] = index;
  }
  if (isBestMatch) {
    if (isSponsored) {
      scalars = {
        ...scalars,
        [TELEMETRY_SCALARS.IMPRESSION_SPONSORED_BEST_MATCH]: index,
        [TELEMETRY_SCALARS.BLOCK_SPONSORED_BEST_MATCH]: index,
      };
    } else {
      scalars = {
        ...scalars,
        [TELEMETRY_SCALARS.IMPRESSION_NONSPONSORED_BEST_MATCH]: index,
        [TELEMETRY_SCALARS.BLOCK_NONSPONSORED_BEST_MATCH]: index,
      };
    }
  }
  QuickSuggestTestUtils.assertScalars(scalars);

  // Check the engagement event.
  let match_type = isBestMatch ? "best-match" : "firefox-suggest";
  QuickSuggestTestUtils.assertEvents([
    {
      category: QuickSuggest.TELEMETRY_EVENT_CATEGORY,
      method: "engagement",
      object: "block",
      extra: {
        match_type,
        position: String(index),
        suggestion_type: isSponsored ? "sponsored" : "nonsponsored",
      },
    },
  ]);

  // Check the custom telemetry pings.
  QuickSuggestTestUtils.assertPings(spy, [
    {
      type: CONTEXTUAL_SERVICES_PING_TYPES.QS_IMPRESSION,
      payload: {
        match_type,
        block_id: result.id,
        is_clicked: false,
        position: index,
      },
    },
    {
      type: CONTEXTUAL_SERVICES_PING_TYPES.QS_BLOCK,
      payload: {
        match_type,
        block_id: result.id,
        iab_category: result.iab_category,
        position: index,
      },
    },
  ]);

  await UrlbarTestUtils.promisePopupClose(window);
  await QuickSuggest.blockedSuggestions.clear();
}

// Blocks multiple suggestions one after the other.
add_task(async function blockMultiple() {
  for (let isBestMatch of [false, true]) {
    UrlbarPrefs.set("bestMatch.enabled", isBestMatch);
    info(`Testing with best match enabled: ${isBestMatch}`);

    for (let i = 0; i < REMOTE_SETTINGS_RESULTS.length; i++) {
      // Do a search that triggers the i'th suggestion.
      let { keywords, url } = REMOTE_SETTINGS_RESULTS[i];
      await UrlbarTestUtils.promiseAutocompleteResultPopup({
        window,
        value: keywords[0],
      });
      await QuickSuggestTestUtils.assertIsQuickSuggest({
        window,
        isBestMatch,
        originalUrl: url,
        isSponsored: keywords[0] == "sponsored",
      });

      // Block it.
      if (UrlbarPrefs.get("resultMenu")) {
        await UrlbarTestUtils.openResultMenuAndPressAccesskey(window, "D", {
          resultIndex: 1,
        });
      } else {
        EventUtils.synthesizeKey("KEY_Tab", { repeat: 2 });
        EventUtils.synthesizeKey("KEY_Enter");
      }
      Assert.ok(
        await QuickSuggest.blockedSuggestions.has(url),
        "Suggestion is blocked after picking block button"
      );

      // Make sure all previous suggestions remain blocked and no other
      // suggestions are blocked yet.
      for (let j = 0; j < REMOTE_SETTINGS_RESULTS.length; j++) {
        Assert.equal(
          await QuickSuggest.blockedSuggestions.has(
            REMOTE_SETTINGS_RESULTS[j].url
          ),
          j <= i,
          `Suggestion at index ${j} is blocked or not as expected`
        );
      }
    }

    await UrlbarTestUtils.promisePopupClose(window);
    await QuickSuggest.blockedSuggestions.clear();
    UrlbarPrefs.clear("bestMatch.enabled");
  }
});

// Tests with blocking disabled for both best matches and non-best-matches.
add_combo_task(async function disabled_both({ result, isBestMatch }) {
  await doDisabledTest({
    result,
    isBestMatch,
    quickSuggestBlockingEnabled: false,
    bestMatchBlockingEnabled: false,
  });
});

// Tests with blocking disabled only for non-best-matches.
add_combo_task(async function disabled_quickSuggest({ result, isBestMatch }) {
  await doDisabledTest({
    result,
    isBestMatch,
    quickSuggestBlockingEnabled: false,
    bestMatchBlockingEnabled: true,
  });
});

// Tests with blocking disabled only for best matches.
add_combo_task(async function disabled_bestMatch({ result, isBestMatch }) {
  await doDisabledTest({
    result,
    isBestMatch,
    quickSuggestBlockingEnabled: true,
    bestMatchBlockingEnabled: false,
  });
});

async function doDisabledTest({
  result,
  isBestMatch,
  bestMatchBlockingEnabled,
  quickSuggestBlockingEnabled,
}) {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.bestMatch.blockingEnabled", bestMatchBlockingEnabled],
      [
        "browser.urlbar.quicksuggest.blockingEnabled",
        quickSuggestBlockingEnabled,
      ],
    ],
  });

  // Do a search to show a suggestion.
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: result.keywords[0],
  });
  let expectedResultCount = 2;
  Assert.equal(
    UrlbarTestUtils.getResultCount(window),
    expectedResultCount,
    "Two rows are present after searching (heuristic + suggestion)"
  );
  let details = await QuickSuggestTestUtils.assertIsQuickSuggest({
    window,
    isBestMatch,
    originalUrl: result.url,
    isSponsored: result.keywords[0] == "sponsored",
  });

  // Arrow down to select the suggestion and press the key shortcut to block.
  EventUtils.synthesizeKey("KEY_ArrowDown");
  EventUtils.synthesizeKey("KEY_Delete", { shiftKey: true });
  Assert.ok(
    UrlbarTestUtils.isPopupOpen(window),
    "View remains open after trying to block result"
  );

  if (
    (isBestMatch && !bestMatchBlockingEnabled) ||
    (!isBestMatch && !quickSuggestBlockingEnabled)
  ) {
    // Blocking is disabled. The key shortcut shouldn't have done anything.
    if (!UrlbarPrefs.get("resultMenu")) {
      Assert.ok(
        !details.element.row._buttons.get("block"),
        "Block button is not present"
      );
    }
    Assert.equal(
      UrlbarTestUtils.getResultCount(window),
      expectedResultCount,
      "Same number of results after key shortcut"
    );
    await QuickSuggestTestUtils.assertIsQuickSuggest({
      window,
      isBestMatch,
      originalUrl: result.url,
      isSponsored: result.keywords[0] == "sponsored",
    });
    Assert.ok(
      !(await QuickSuggest.blockedSuggestions.has(result.url)),
      "Suggestion is not blocked"
    );
  } else {
    // Blocking is enabled. The suggestion should have been blocked.
    if (!UrlbarPrefs.get("resultMenu")) {
      Assert.ok(
        details.element.row._buttons.get("block"),
        "Block button is present"
      );
    }
    Assert.equal(
      UrlbarTestUtils.getResultCount(window),
      1,
      "Only one row after blocking suggestion"
    );
    await QuickSuggestTestUtils.assertNoQuickSuggestResults(window);
    Assert.ok(
      await QuickSuggest.blockedSuggestions.has(result.url),
      "Suggestion is blocked"
    );
    await QuickSuggest.blockedSuggestions.clear();
  }

  await UrlbarTestUtils.promisePopupClose(window);
  await SpecialPowers.popPrefEnv();
}