summaryrefslogtreecommitdiffstats
path: root/browser/modules/test/browser/browser_PartnerLinkAttribution.js
blob: 08e393694d00329e02d282e224139bdb5ff11e46 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

/**
 * This file tests urlbar telemetry with search related actions.
 */

"use strict";

const SCALAR_URLBAR = "browser.engagement.navigation.urlbar";

// The preference to enable suggestions in the urlbar.
const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
// The name of the search engine used to generate suggestions.
const SUGGESTION_ENGINE_NAME =
  "browser_UsageTelemetry usageTelemetrySearchSuggestions.xml";

ChromeUtils.defineESModuleGetters(this, {
  CustomizableUITestUtils:
    "resource://testing-common/CustomizableUITestUtils.sys.mjs",

  Region: "resource://gre/modules/Region.sys.mjs",
  SearchTestUtils: "resource://testing-common/SearchTestUtils.sys.mjs",
  UrlbarTestUtils: "resource://testing-common/UrlbarTestUtils.sys.mjs",
});

XPCOMUtils.defineLazyModuleGetters(this, {
  HttpServer: "resource://testing-common/httpd.js",
});

let gCUITestUtils = new CustomizableUITestUtils(window);
SearchTestUtils.init(this);

var gHttpServer = null;
var gRequests = [];

function submitHandler(request, response) {
  gRequests.push(request);
  response.setStatusLine(request.httpVersion, 200, "Ok");
}

add_setup(async function () {
  // Ensure the initial init is complete.
  await Services.search.init();

  // Clear history so that history added by previous tests doesn't mess up this
  // test when it selects results in the urlbar.
  await PlacesUtils.history.clear();

  let searchExtensions = getChromeDir(getResolvedURI(gTestPath));
  searchExtensions.append("search-engines");

  await SearchTestUtils.useMochitestEngines(searchExtensions);

  SearchTestUtils.useMockIdleService();
  let response = await fetch(`resource://search-extensions/engines.json`);
  let json = await response.json();
  await SearchTestUtils.updateRemoteSettingsConfig(json.data);

  let topsitesAttribution = Services.prefs.getStringPref(
    "browser.partnerlink.campaign.topsites"
  );
  gHttpServer = new HttpServer();
  gHttpServer.registerPathHandler(`/cid/${topsitesAttribution}`, submitHandler);
  gHttpServer.start(-1);

  await SpecialPowers.pushPrefEnv({
    set: [
      // Enable search suggestions in the urlbar.
      [SUGGEST_URLBAR_PREF, true],
      // Clear historical search suggestions to avoid interference from previous
      // tests.
      ["browser.urlbar.maxHistoricalSearchSuggestions", 0],
      [
        "browser.partnerlink.attributionURL",
        `http://localhost:${gHttpServer.identity.primaryPort}/cid/`,
      ],
    ],
  });

  await gCUITestUtils.addSearchBar();

  // Make sure to restore the engine once we're done.
  registerCleanupFunction(async function () {
    let settingsWritten = SearchTestUtils.promiseSearchNotification(
      "write-settings-to-disk-complete"
    );
    await SearchTestUtils.updateRemoteSettingsConfig();
    await gHttpServer.stop();
    gHttpServer = null;
    await PlacesUtils.history.clear();
    gCUITestUtils.removeSearchBar();
    await settingsWritten;
  });
});

function searchInAwesomebar(value, win = window) {
  return UrlbarTestUtils.promiseAutocompleteResultPopup({
    window: win,
    waitForFocus,
    value,
    fireInputEvent: true,
  });
}

async function searchInSearchbar(inputText) {
  let win = window;
  await new Promise(r => waitForFocus(r, win));
  let sb = BrowserSearch.searchBar;
  // Write the search query in the searchbar.
  sb.focus();
  sb.value = inputText;
  sb.textbox.controller.startSearch(inputText);
  // Wait for the popup to be shown and built.
  let popup = sb.textbox.popup;
  await Promise.all([
    BrowserTestUtils.waitForEvent(popup, "popupshown"),
    BrowserTestUtils.waitForEvent(popup.oneOffButtons, "rebuild"),
  ]);
  // And then for the search to complete.
  await BrowserTestUtils.waitForCondition(
    () =>
      sb.textbox.controller.searchStatus >=
      Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH,
    "The search in the searchbar must complete."
  );
}

add_task(async function test_simpleQuery_no_attribution() {
  await Services.search.setDefault(
    Services.search.getEngineByName("Simple Engine"),
    Ci.nsISearchService.CHANGE_REASON_UNKNOWN
  );

  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    "about:blank"
  );

  info("Simulate entering a simple search.");
  let promiseLoad = BrowserTestUtils.waitForDocLoadAndStopIt(
    "https://example.com/?sourceId=Mozilla-search&search=simple+query",
    tab
  );
  await searchInAwesomebar("simple query");
  EventUtils.synthesizeKey("KEY_Enter");
  await promiseLoad;

  await new Promise(resolve => Services.tm.dispatchToMainThread(resolve));

  Assert.equal(gRequests.length, 0, "Should not have submitted an attribution");

  BrowserTestUtils.removeTab(tab);

  await Services.search.setDefault(
    Services.search.getEngineByName("basic"),
    Ci.nsISearchService.CHANGE_REASON_UNKNOWN
  );
});

async function checkAttributionRecorded(actionFn, cleanupFn) {
  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    "data:text/plain;charset=utf8,simple%20query"
  );

  let promiseLoad = BrowserTestUtils.waitForDocLoadAndStopIt(
    "https://mochi.test:8888/browser/browser/components/search/test/browser/?search=simple+query&foo=1",
    tab
  );
  await actionFn(tab);
  await promiseLoad;

  await BrowserTestUtils.waitForCondition(
    () => gRequests.length == 1,
    "Should have received an attribution submission"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Region"),
    Region.home,
    "Should have set the region correctly"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Source"),
    "searchurl",
    "Should have set the source correctly"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Target-url"),
    "https://mochi.test:8888/browser/browser/components/search/test/browser/?foo=1",
    "Should have set the target url correctly and stripped the search terms"
  );
  if (cleanupFn) {
    await cleanupFn();
  }
  BrowserTestUtils.removeTab(tab);
  gRequests = [];
}

add_task(async function test_urlbar() {
  await checkAttributionRecorded(async tab => {
    await searchInAwesomebar("simple query");
    EventUtils.synthesizeKey("KEY_Enter");
  });
});

add_task(async function test_searchbar() {
  await checkAttributionRecorded(async tab => {
    let sb = BrowserSearch.searchBar;
    // Write the search query in the searchbar.
    sb.focus();
    sb.value = "simple query";
    sb.textbox.controller.startSearch("simple query");
    // Wait for the popup to show.
    await BrowserTestUtils.waitForEvent(sb.textbox.popup, "popupshown");
    // And then for the search to complete.
    await BrowserTestUtils.waitForCondition(
      () =>
        sb.textbox.controller.searchStatus >=
        Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH,
      "The search in the searchbar must complete."
    );
    EventUtils.synthesizeKey("KEY_Enter");
  });
});

add_task(async function test_context_menu() {
  let contextMenu;
  await checkAttributionRecorded(
    async tab => {
      info("Select all the text in the page.");
      await SpecialPowers.spawn(tab.linkedBrowser, [""], async function () {
        return new Promise(resolve => {
          content.document.addEventListener(
            "selectionchange",
            () => resolve(),
            {
              once: true,
            }
          );
          content.document
            .getSelection()
            .selectAllChildren(content.document.body);
        });
      });

      info("Open the context menu.");
      contextMenu = document.getElementById("contentAreaContextMenu");
      let shownPromise = BrowserTestUtils.waitForEvent(
        contextMenu,
        "popupshown"
      );
      BrowserTestUtils.synthesizeMouseAtCenter(
        "body",
        { type: "contextmenu", button: 2 },
        gBrowser.selectedBrowser
      );
      await shownPromise;

      let hiddenPromise = BrowserTestUtils.waitForEvent(
        contextMenu,
        "popuphidden"
      );

      info("Click on search.");
      let searchItem = contextMenu.querySelector("#context-searchselect");
      contextMenu.activateItem(searchItem);
      await hiddenPromise;
    },
    () => {
      BrowserTestUtils.removeTab(gBrowser.selectedTab);
    }
  );
});

add_task(async function test_about_newtab() {
  await SpecialPowers.pushPrefEnv({
    set: [
      [
        "browser.newtabpage.activity-stream.improvesearch.handoffToAwesomebar",
        false,
      ],
    ],
  });
  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    "about:newtab",
    false
  );
  await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
    await ContentTaskUtils.waitForCondition(() => !content.document.hidden);
  });

  info("Trigger a simple search, just text + enter.");
  let promiseLoad = BrowserTestUtils.waitForDocLoadAndStopIt(
    "https://mochi.test:8888/browser/browser/components/search/test/browser/?search=simple+query&foo=1",
    tab
  );
  await typeInSearchField(
    tab.linkedBrowser,
    "simple query",
    "newtab-search-text"
  );
  await BrowserTestUtils.synthesizeKey("VK_RETURN", {}, tab.linkedBrowser);
  await promiseLoad;

  await BrowserTestUtils.waitForCondition(
    () => gRequests.length == 1,
    "Should have received an attribution submission"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Region"),
    Region.home,
    "Should have set the region correctly"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Source"),
    "searchurl",
    "Should have set the source correctly"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Target-url"),
    "https://mochi.test:8888/browser/browser/components/search/test/browser/?foo=1",
    "Should have set the target url correctly and stripped the search terms"
  );

  BrowserTestUtils.removeTab(tab);
  await SpecialPowers.popPrefEnv();
  gRequests = [];
});

add_task(async function test_urlbar_oneOff_click() {
  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    "about:blank"
  );

  info("Type a query.");
  let promiseLoad = BrowserTestUtils.waitForDocLoadAndStopIt(
    "https://mochi.test:8888/browser/browser/components/search/test/browser/?search=query&foo=1",
    tab
  );
  await searchInAwesomebar("query");
  info("Click the first one-off button.");
  UrlbarTestUtils.getOneOffSearchButtons(window)
    .getSelectableButtons(false)[0]
    .click();
  EventUtils.synthesizeKey("KEY_Enter");
  await promiseLoad;

  await BrowserTestUtils.waitForCondition(
    () => gRequests.length == 1,
    "Should have received an attribution submission"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Region"),
    Region.home,
    "Should have set the region correctly"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Source"),
    "searchurl",
    "Should have set the source correctly"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Target-url"),
    "https://mochi.test:8888/browser/browser/components/search/test/browser/?foo=1",
    "Should have set the target url correctly and stripped the search terms"
  );

  BrowserTestUtils.removeTab(tab);
  gRequests = [];
});

add_task(async function test_searchbar_oneOff_click() {
  // For this test, set the other engine as default, so that we can select
  // the attribution engine as the first one in the one-offs.
  await Services.search.setDefault(
    Services.search.getEngineByName("Simple Engine"),
    Ci.nsISearchService.CHANGE_REASON_UNKNOWN
  );

  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    "about:blank"
  );

  info("Type a query.");
  let promiseLoad = BrowserTestUtils.waitForDocLoadAndStopIt(
    "https://mochi.test:8888/browser/browser/components/search/test/browser/?search=searchbar&foo=1",
    tab
  );
  await searchInSearchbar("searchbar");
  info("Click the first one-off button.");
  BrowserSearch.searchBar.textbox.popup.oneOffButtons
    .getSelectableButtons(false)[0]
    .click();
  await promiseLoad;

  await BrowserTestUtils.waitForCondition(
    () => gRequests.length == 1,
    "Should have received an attribution submission"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Region"),
    Region.home,
    "Should have set the region correctly"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Source"),
    "searchurl",
    "Should have set the source correctly"
  );
  Assert.equal(
    gRequests[0].getHeader("X-Target-url"),
    "https://mochi.test:8888/browser/browser/components/search/test/browser/?foo=1",
    "Should have set the target url correctly and stripped the search terms"
  );

  BrowserTestUtils.removeTab(tab);
  // Set back the engine in case of other tests in this file.
  await Services.search.setDefault(
    Services.search.getEngineByName("basic"),
    Ci.nsISearchService.CHANGE_REASON_UNKNOWN
  );
  gRequests = [];
});