summaryrefslogtreecommitdiffstats
path: root/browser/components/urlbar/tests/browser/browser_tokenAlias.js
blob: d215c2536ffc7698cda6f61187962851152a0268 (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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

// This test checks "@" search engine aliases ("token aliases") in the urlbar.

"use strict";

const TEST_ALIAS_ENGINE_NAME = "Test";
const ALIAS = "@test";
const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml";

// We make sure that aliases and search terms are correctly recognized when they
// are separated by each of these different types of spaces and combinations of
// spaces.  U+3000 is the ideographic space in CJK and is commonly used by CJK
// speakers.
const TEST_SPACES = [" ", "\u3000", " \u3000", "\u3000 "];

// Allow more time for Mac machines so they don't time out in verify mode.  See
// bug 1673062.
if (AppConstants.platform == "macosx") {
  requestLongerTimeout(5);
}

add_setup(async function () {
  // Add a default engine with suggestions, to avoid hitting the network when
  // fetching them.
  let defaultEngine = await SearchTestUtils.promiseNewSearchEngine({
    url: getRootDirectory(gTestPath) + TEST_ENGINE_BASENAME,
    setAsDefault: true,
  });
  defaultEngine.alias = "@default";
  await SearchTestUtils.installSearchExtension({
    name: TEST_ALIAS_ENGINE_NAME,
    keyword: ALIAS,
  });

  // Search results aren't shown in quantumbar unless search suggestions are
  // enabled.
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.suggest.searches", true]],
  });
});

// Simple test that tries different variations of an alias, without reverting
// the urlbar value in between.
add_task(async function testNoRevert() {
  await doSimpleTest(false);
});

// Simple test that tries different variations of an alias, reverting the urlbar
// value in between.
add_task(async function testRevert() {
  await doSimpleTest(true);
});

async function doSimpleTest(revertBetweenSteps) {
  // When autofill is enabled, searching for "@tes" will autofill to "@test",
  // which gets in the way of this test task, so temporarily disable it.
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.autoFill", false]],
  });

  // "@tes" -- not an alias, no search mode
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: ALIAS.substr(0, ALIAS.length - 1),
  });
  await UrlbarTestUtils.assertSearchMode(window, null);
  Assert.equal(
    gURLBar.value,
    ALIAS.substr(0, ALIAS.length - 1),
    "value should be alias substring"
  );

  if (revertBetweenSteps) {
    gURLBar.handleRevert();
    gURLBar.blur();
  }

  // "@test" -- alias but no trailing space, no search mode
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: ALIAS,
  });
  await UrlbarTestUtils.assertSearchMode(window, null);
  Assert.equal(gURLBar.value, ALIAS, "value should be alias");

  if (revertBetweenSteps) {
    gURLBar.handleRevert();
    gURLBar.blur();
  }

  // "@test " -- alias with trailing space, search mode
  for (let spaces of TEST_SPACES) {
    info("Testing: " + JSON.stringify({ spaces: codePoints(spaces) }));

    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      value: ALIAS + spaces,
    });
    // Wait for the second new search that starts when search mode is entered.
    await UrlbarTestUtils.promiseSearchComplete(window);
    await UrlbarTestUtils.assertSearchMode(window, {
      engineName: TEST_ALIAS_ENGINE_NAME,
      entry: "typed",
    });
    Assert.equal(gURLBar.value, "", "value should be empty");
    await UrlbarTestUtils.exitSearchMode(window);

    if (revertBetweenSteps) {
      gURLBar.handleRevert();
      gURLBar.blur();
    }
  }

  // "@test foo" -- alias, search mode
  for (let spaces of TEST_SPACES) {
    info("Testing: " + JSON.stringify({ spaces: codePoints(spaces) }));

    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      value: ALIAS + spaces + "foo",
    });
    // Wait for the second new search that starts when search mode is entered.
    await UrlbarTestUtils.promiseSearchComplete(window);
    await UrlbarTestUtils.assertSearchMode(window, {
      engineName: TEST_ALIAS_ENGINE_NAME,
      entry: "typed",
    });
    Assert.equal(gURLBar.value, "foo", "value should be query");
    await UrlbarTestUtils.exitSearchMode(window);

    if (revertBetweenSteps) {
      gURLBar.handleRevert();
      gURLBar.blur();
    }
  }

  // "@test " -- alias with trailing space, search mode
  for (let spaces of TEST_SPACES) {
    info("Testing: " + JSON.stringify({ spaces: codePoints(spaces) }));

    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      value: ALIAS + spaces,
    });
    // Wait for the second new search that starts when search mode is entered.
    await UrlbarTestUtils.promiseSearchComplete(window);
    await UrlbarTestUtils.assertSearchMode(window, {
      engineName: TEST_ALIAS_ENGINE_NAME,
      entry: "typed",
    });
    Assert.equal(gURLBar.value, "", "value should be empty");
    await UrlbarTestUtils.exitSearchMode(window);

    if (revertBetweenSteps) {
      gURLBar.handleRevert();
      gURLBar.blur();
    }
  }

  // "@test" -- alias but no trailing space, no highlight
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: ALIAS,
  });
  await UrlbarTestUtils.assertSearchMode(window, null);
  Assert.equal(gURLBar.value, ALIAS, "value should be alias");

  if (revertBetweenSteps) {
    gURLBar.handleRevert();
    gURLBar.blur();
  }

  // "@tes" -- not an alias, no highlight
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: ALIAS.substr(0, ALIAS.length - 1),
  });
  await UrlbarTestUtils.assertSearchMode(window, null);
  Assert.equal(
    gURLBar.value,
    ALIAS.substr(0, ALIAS.length - 1),
    "value should be alias substring"
  );

  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );

  await SpecialPowers.popPrefEnv();
}

// An alias should be recognized even when there are spaces before it, and
// search mode should be entered.
add_task(async function spacesBeforeAlias() {
  for (let spaces of TEST_SPACES) {
    info("Testing: " + JSON.stringify({ spaces: codePoints(spaces) }));

    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      value: spaces + ALIAS + spaces,
    });
    // Wait for the second new search that starts when search mode is entered.
    await UrlbarTestUtils.promiseSearchComplete(window);
    await UrlbarTestUtils.assertSearchMode(window, {
      engineName: TEST_ALIAS_ENGINE_NAME,
      entry: "typed",
    });
    Assert.equal(gURLBar.value, "", "value should be empty");
    await UrlbarTestUtils.exitSearchMode(window);
    await UrlbarTestUtils.promisePopupClose(window, () =>
      EventUtils.synthesizeKey("KEY_Escape")
    );
  }
});

// An alias in the middle of a string should not be recognized and search mode
// should not be entered.
add_task(async function charsBeforeAlias() {
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "not an alias " + ALIAS + " ",
  });
  await UrlbarTestUtils.assertSearchMode(window, null);
  Assert.equal(
    gURLBar.value,
    "not an alias " + ALIAS + " ",
    "value should be unchanged"
  );

  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

// While already in search mode, an alias should not be recognized.
add_task(async function alreadyInSearchMode() {
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "",
  });
  await UrlbarTestUtils.enterSearchMode(window, {
    source: UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
  });

  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: ALIAS + " ",
  });

  // Search mode source should still be bookmarks.
  await UrlbarTestUtils.assertSearchMode(window, {
    source: UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
    entry: "oneoff",
  });
  Assert.equal(gURLBar.value, ALIAS + " ", "value should be unchanged");

  // Exit search mode, but first remove the value in the input.  Since the value
  // is "alias ", we'd actually immediately re-enter search mode otherwise.
  gURLBar.value = "";

  await UrlbarTestUtils.exitSearchMode(window);
  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

// Types a space while typing an alias to ensure we stop autofilling.
add_task(async function spaceWhileTypingAlias() {
  for (let spaces of TEST_SPACES) {
    if (spaces.length != 1) {
      continue;
    }
    info("Testing: " + JSON.stringify({ spaces: codePoints(spaces) }));

    let value = ALIAS.substring(0, ALIAS.length - 1);
    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      value,
      selectionStart: value.length,
      selectionEnd: value.length,
    });
    Assert.equal(gURLBar.value, ALIAS + " ", "Alias should be autofilled");

    let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
    EventUtils.synthesizeKey(spaces);
    await searchPromise;

    Assert.equal(
      gURLBar.value,
      value + spaces,
      "Alias should not be autofilled"
    );
    await UrlbarTestUtils.assertSearchMode(window, null);

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

// Aliases are case insensitive.  Make sure that searching with an alias using a
// weird case still causes the alias to be recognized and search mode entered.
add_task(async function aliasCase() {
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@TeSt ",
  });
  // Wait for the second new search that starts when search mode is entered.
  await UrlbarTestUtils.promiseSearchComplete(window);
  await UrlbarTestUtils.assertSearchMode(window, {
    engineName: TEST_ALIAS_ENGINE_NAME,
    entry: "typed",
  });
  Assert.equal(gURLBar.value, "", "value should be empty");
  await UrlbarTestUtils.exitSearchMode(window);
  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

// Same as previous but with a query.
add_task(async function aliasCase_query() {
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@tEsT query",
  });
  // Wait for the second new search that starts when search mode is entered.
  await UrlbarTestUtils.promiseSearchComplete(window);
  await UrlbarTestUtils.assertSearchMode(window, {
    engineName: TEST_ALIAS_ENGINE_NAME,
    entry: "typed",
  });
  Assert.equal(gURLBar.value, "query", "value should be query");
  await UrlbarTestUtils.exitSearchMode(window);
  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

// Selecting a non-heuristic (non-first) search engine result with an alias and
// empty query should put the alias in the urlbar and highlight it.
// Also checks that internal aliases appear with the "@" keyword.
add_task(async function nonHeuristicAliases() {
  // Get the list of token alias engines (those with aliases that start with
  // "@").
  let tokenEngines = [];
  for (let engine of await Services.search.getEngines()) {
    let aliases = [];
    if (engine.alias) {
      aliases.push(engine.alias);
    }
    aliases.push(...engine.aliases);
    let tokenAliases = aliases.filter(a => a.startsWith("@"));
    if (tokenAliases.length) {
      tokenEngines.push({ engine, tokenAliases });
    }
  }
  if (!tokenEngines.length) {
    Assert.ok(true, "No token alias engines, skipping task.");
    return;
  }
  info(
    "Got token alias engines: " + tokenEngines.map(({ engine }) => engine.name)
  );

  // Populate the results with the list of token alias engines by searching for
  // "@".
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@",
  });
  await UrlbarTestUtils.waitForAutocompleteResultAt(
    window,
    tokenEngines.length - 1
  );
  // Key down to select each result in turn.  The urlbar should preview search
  // mode for each engine.
  for (let { tokenAliases } of tokenEngines) {
    let alias = tokenAliases[0];
    let engineName = (await UrlbarSearchUtils.engineForAlias(alias)).name;
    EventUtils.synthesizeKey("KEY_ArrowDown");
    let expectedSearchMode = {
      engineName,
      entry: "keywordoffer",
      isPreview: true,
    };
    if (Services.search.getEngineByName(engineName).isGeneralPurposeEngine) {
      expectedSearchMode.source = UrlbarUtils.RESULT_SOURCE.SEARCH;
    }
    await UrlbarTestUtils.assertSearchMode(window, expectedSearchMode);
    Assert.ok(!gURLBar.value, "The Urlbar should be empty.");
  }

  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

// Clicking on an @ alias offer (an @ alias with an empty search string) in the
// view should enter search mode.
add_task(async function clickAndFillAlias() {
  // Do a search for "@" to show all the @ aliases.
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@",
  });

  // Find our test engine in the results.  It's probably last, but for
  // robustness don't assume it is.
  let testEngineItem;
  for (let i = 0; !testEngineItem; i++) {
    let details = await UrlbarTestUtils.getDetailsOfResultAt(window, i);
    Assert.equal(
      details.displayed.title,
      `Search with ${details.searchParams.engine}`,
      "The result's title is set correctly."
    );
    Assert.ok(!details.action, "The result should have no action text.");
    if (details.searchParams && details.searchParams.keyword == ALIAS) {
      testEngineItem = await UrlbarTestUtils.waitForAutocompleteResultAt(
        window,
        i
      );
    }
  }

  // Click it.
  let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
  EventUtils.synthesizeMouseAtCenter(testEngineItem, {});
  await searchPromise;

  await UrlbarTestUtils.assertSearchMode(window, {
    engineName: testEngineItem.result.payload.engine,
    entry: "keywordoffer",
  });

  await UrlbarTestUtils.exitSearchMode(window);
  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

// Pressing enter on an @ alias offer (an @ alias with an empty search string)
// in the view should enter search mode.
add_task(async function enterAndFillAlias() {
  // Do a search for "@" to show all the @ aliases.
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@",
  });

  // Find our test engine in the results.  It's probably last, but for
  // robustness don't assume it is.
  let details;
  let index = 0;
  for (; ; index++) {
    details = await UrlbarTestUtils.getDetailsOfResultAt(window, index);
    if (details.searchParams && details.searchParams.keyword == ALIAS) {
      index++;
      break;
    }
  }

  // Key down to it and press enter.
  EventUtils.synthesizeKey("KEY_ArrowDown", { repeat: index });
  let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
  EventUtils.synthesizeKey("KEY_Enter");
  await searchPromise;

  await UrlbarTestUtils.assertSearchMode(window, {
    engineName: details.searchParams.engine,
    entry: "keywordoffer",
  });

  await UrlbarTestUtils.exitSearchMode(window);
  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

// Pressing Enter on an @ alias autofill should enter search mode.
add_task(async function enterAutofillsAlias() {
  for (let value of [ALIAS.substring(0, ALIAS.length - 1), ALIAS]) {
    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      value,
      selectionStart: value.length,
      selectionEnd: value.length,
    });

    // Press Enter.
    let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
    EventUtils.synthesizeKey("KEY_Enter");
    await searchPromise;

    await UrlbarTestUtils.assertSearchMode(window, {
      engineName: TEST_ALIAS_ENGINE_NAME,
      entry: "keywordoffer",
    });

    await UrlbarTestUtils.exitSearchMode(window);
  }
  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

// Pressing Right on an @ alias autofill should enter search mode.
add_task(async function rightEntersSearchMode() {
  for (let value of [ALIAS.substring(0, ALIAS.length - 1), ALIAS]) {
    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      value,
      selectionStart: value.length,
      selectionEnd: value.length,
    });

    let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
    EventUtils.synthesizeKey("KEY_ArrowRight");
    await searchPromise;

    await UrlbarTestUtils.assertSearchMode(window, {
      engineName: TEST_ALIAS_ENGINE_NAME,
      entry: "typed",
    });
    Assert.equal(gURLBar.value, "", "value should be empty");
    await UrlbarTestUtils.exitSearchMode(window);
  }

  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

// Pressing Tab when an @ alias is autofilled should enter search mode preview.
add_task(async function rightEntersSearchMode() {
  for (let value of [ALIAS.substring(0, ALIAS.length - 1), ALIAS]) {
    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      value,
      selectionStart: value.length,
      selectionEnd: value.length,
    });

    Assert.equal(
      UrlbarTestUtils.getSelectedRowIndex(window),
      -1,
      "There is no selected result."
    );

    EventUtils.synthesizeKey("KEY_Tab");
    Assert.equal(
      UrlbarTestUtils.getSelectedRowIndex(window),
      0,
      "The first result is selected."
    );

    await UrlbarTestUtils.assertSearchMode(window, {
      engineName: TEST_ALIAS_ENGINE_NAME,
      entry: "keywordoffer",
      isPreview: true,
    });
    Assert.equal(gURLBar.value, "", "value should be empty");

    let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
    EventUtils.synthesizeKey("KEY_Enter");
    await searchPromise;

    await UrlbarTestUtils.assertSearchMode(window, {
      engineName: TEST_ALIAS_ENGINE_NAME,
      entry: "keywordoffer",
      isPreview: false,
    });
    await UrlbarTestUtils.exitSearchMode(window);
  }

  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );
});

/**
 * This test checks that if an engine is marked as hidden then
 * it should not appear in the popup when using the "@" token alias in the search bar.
 */
add_task(async function hiddenEngine() {
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@",
    fireInputEvent: true,
  });

  const defaultEngine = await Services.search.getDefault();

  let foundDefaultEngineInPopup = false;

  // Checks that the default engine appears in the urlbar's popup.
  for (let i = 0; i < UrlbarTestUtils.getResultCount(window); i++) {
    let details = await UrlbarTestUtils.getDetailsOfResultAt(window, i);
    if (defaultEngine.name == details.searchParams.engine) {
      foundDefaultEngineInPopup = true;
      break;
    }
  }
  Assert.ok(foundDefaultEngineInPopup, "Default engine appears in the popup.");

  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );

  // Checks that a hidden default engine (i.e. an engine removed from
  // a user's search settings) does not appear in the urlbar's popup.
  defaultEngine.hidden = true;
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@",
    fireInputEvent: true,
  });
  foundDefaultEngineInPopup = false;
  for (let i = 0; i < UrlbarTestUtils.getResultCount(window); i++) {
    let details = await UrlbarTestUtils.getDetailsOfResultAt(window, i);
    if (defaultEngine.name == details.searchParams.engine) {
      foundDefaultEngineInPopup = true;
      break;
    }
  }
  Assert.ok(
    !foundDefaultEngineInPopup,
    "Hidden default engine does not appear in the popup"
  );

  await UrlbarTestUtils.promisePopupClose(window, () =>
    EventUtils.synthesizeKey("KEY_Escape")
  );

  defaultEngine.hidden = false;
});

/**
 * This test checks that if an engines alias is not prefixed with
 * @ it still appears in the popup when using the "@" token
 * alias in the search bar.
 */
add_task(async function nonPrefixedKeyword() {
  let name = "Custom";
  let alias = "customkeyword";
  let extension = await SearchTestUtils.installSearchExtension(
    {
      name,
      keyword: alias,
    },
    { skipUnload: true }
  );

  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@",
  });

  let foundEngineInPopup = false;

  // Checks that the default engine appears in the urlbar's popup.
  for (let i = 0; i < UrlbarTestUtils.getResultCount(window); i++) {
    let details = await UrlbarTestUtils.getDetailsOfResultAt(window, i);
    if (details.searchParams.engine === name) {
      foundEngineInPopup = true;
      break;
    }
  }
  Assert.ok(foundEngineInPopup, "Custom engine appears in the popup.");

  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@" + alias,
  });

  let keywordOfferResult = await UrlbarTestUtils.getDetailsOfResultAt(
    window,
    0
  );

  Assert.equal(
    keywordOfferResult.searchParams.engine,
    name,
    "The first result should be a keyword search result with the correct engine."
  );

  await extension.unload();
});

// Tests that we show all engines with a token alias that match the search
// string.
add_task(async function multipleMatchingEngines() {
  let extension = await SearchTestUtils.installSearchExtension(
    {
      name: "TestFoo",
      keyword: `${ALIAS}foo`,
    },
    { skipUnload: true }
  );

  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@te",
    fireInputEvent: true,
  });

  Assert.equal(
    UrlbarTestUtils.getResultCount(window),
    2,
    "Two results are shown."
  );
  Assert.equal(
    UrlbarTestUtils.getSelectedRowIndex(window),
    -1,
    "Neither result is selected."
  );
  let result = await UrlbarTestUtils.getDetailsOfResultAt(window, 0);
  Assert.ok(result.autofill, "The first result is autofilling.");
  Assert.equal(
    result.searchParams.keyword,
    ALIAS,
    "The autofilled engine is shown first."
  );

  result = await UrlbarTestUtils.getDetailsOfResultAt(window, 1);
  Assert.equal(
    result.searchParams.keyword,
    `${ALIAS}foo`,
    "The other engine is shown second."
  );

  EventUtils.synthesizeKey("KEY_Tab");
  Assert.equal(UrlbarTestUtils.getSelectedRowIndex(window), 0);
  Assert.equal(gURLBar.value, "", "Urlbar should be empty.");
  EventUtils.synthesizeKey("KEY_Tab");
  Assert.equal(UrlbarTestUtils.getSelectedRowIndex(window), 1);
  Assert.equal(gURLBar.value, "", "Urlbar should be empty.");
  EventUtils.synthesizeKey("KEY_Tab");
  Assert.equal(
    UrlbarTestUtils.getSelectedRowIndex(window),
    -1,
    "Tabbing all the way through the matching engines should return to the input."
  );
  Assert.equal(
    gURLBar.value,
    "@te",
    "Urlbar should contain the search string."
  );

  await extension.unload();
});

// Tests that UrlbarProviderTokenAliasEngines is disabled in search mode.
add_task(async function doNotShowInSearchMode() {
  // Do a search for "@" to show all the @ aliases.
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@",
  });

  // Find our test engine in the results.  It's probably last, but for
  // robustness don't assume it is.
  let testEngineItem;
  for (let i = 0; !testEngineItem; i++) {
    let details = await UrlbarTestUtils.getDetailsOfResultAt(window, i);
    if (details.searchParams && details.searchParams.keyword == ALIAS) {
      testEngineItem = await UrlbarTestUtils.waitForAutocompleteResultAt(
        window,
        i
      );
    }
  }

  Assert.equal(
    testEngineItem.result.payload.keyword,
    ALIAS,
    "Sanity check: we found our engine."
  );

  // Click it.
  let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
  EventUtils.synthesizeMouseAtCenter(testEngineItem, {});
  await searchPromise;
  await UrlbarTestUtils.assertSearchMode(window, {
    engineName: testEngineItem.result.payload.engine,
    entry: "keywordoffer",
  });

  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "@",
    fireInputEvent: true,
  });

  let resultCount = UrlbarTestUtils.getResultCount(window);
  for (let i = 0; i < resultCount; i++) {
    let result = await UrlbarTestUtils.getDetailsOfResultAt(window, i);
    Assert.ok(
      !result.searchParams.keyword,
      `Result at index ${i} is not a keywordoffer.`
    );
  }
});

async function assertFirstResultIsAlias(isAlias, expectedAlias) {
  let result = await UrlbarTestUtils.getDetailsOfResultAt(window, 0);
  Assert.equal(
    result.type,
    UrlbarUtils.RESULT_TYPE.SEARCH,
    "Should have the correct type"
  );

  if (isAlias) {
    Assert.equal(
      result.searchParams.keyword,
      expectedAlias,
      "Payload keyword should be the alias"
    );
  } else {
    Assert.notEqual(
      result.searchParams.keyword,
      expectedAlias,
      "Payload keyword should be absent or not the alias"
    );
  }
}

function assertHighlighted(highlighted, expectedAlias) {
  let selection = gURLBar.editor.selectionController.getSelection(
    Ci.nsISelectionController.SELECTION_FIND
  );
  Assert.ok(selection);
  if (!highlighted) {
    Assert.equal(selection.rangeCount, 0);
    return;
  }
  Assert.equal(selection.rangeCount, 1);
  let index = gURLBar.value.indexOf(expectedAlias);
  Assert.ok(
    index >= 0,
    `gURLBar.value="${gURLBar.value}" expectedAlias="${expectedAlias}"`
  );
  let range = selection.getRangeAt(0);
  Assert.ok(range);
  Assert.equal(range.startOffset, index);
  Assert.equal(range.endOffset, index + expectedAlias.length);
}

/**
 * Returns an array of code points in the given string.  Each code point is
 * returned as a hexidecimal string.
 *
 * @param {string} str
 *   The code points of this string will be returned.
 * @returns {Array}
 *   Array of code points in the string, where each is a hexidecimal string.
 */
function codePoints(str) {
  return str.split("").map(s => s.charCodeAt(0).toString(16));
}