summaryrefslogtreecommitdiffstats
path: root/browser/components/urlbar/tests/browser/browser_urlbar_telemetry.js
blob: 4e48a946d526374efe065f71c8b92e2549d8122a (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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
/* 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";
const SCALAR_SEARCHMODE = "browser.engagement.navigation.urlbar_searchmode";

// The preference to enable suggestions in the urlbar.
const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";

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

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

/**
 * Click one of the entries in the urlbar suggestion popup.
 *
 * @param {string} resultTitle
 *        The title of the result to click on.
 * @param {number} button [optional]
 *        which button to click.
 * @returns {number}
 *          The index of the result that was clicked, or -1 if not found.
 */
async function clickURLBarSuggestion(resultTitle, button = 1) {
  await UrlbarTestUtils.promiseSearchComplete(window);

  const count = UrlbarTestUtils.getResultCount(window);
  for (let i = 0; i < count; i++) {
    let result = await UrlbarTestUtils.getDetailsOfResultAt(window, i);
    if (result.displayed.title == resultTitle) {
      // This entry is the search suggestion we're looking for.
      let element = await UrlbarTestUtils.waitForAutocompleteResultAt(
        window,
        i
      );
      if (button == 1) {
        EventUtils.synthesizeMouseAtCenter(element, {});
      } else if (button == 2) {
        EventUtils.synthesizeMouseAtCenter(element, {
          type: "mousedown",
          button: 2,
        });
      }
      return i;
    }
  }
  return -1;
}

/**
 * Create an engine to generate search suggestions and add it as default
 * for this test.
 *
 * @param {Function} taskFn
 *   The function to run with the new search engine as default.
 */
async function withNewSearchEngine(taskFn) {
  let suggestionEngine = await SearchTestUtils.promiseNewSearchEngine({
    url: getRootDirectory(gTestPath) + "urlbarTelemetrySearchSuggestions.xml",
  });
  let previousEngine = await Services.search.getDefault();
  await Services.search.setDefault(
    suggestionEngine,
    Ci.nsISearchService.CHANGE_REASON_UNKNOWN
  );

  try {
    await taskFn(suggestionEngine);
  } finally {
    await Services.search.setDefault(
      previousEngine,
      Ci.nsISearchService.CHANGE_REASON_UNKNOWN
    );
    await Services.search.removeEngine(suggestionEngine);
  }
}

add_setup(async function () {
  await SearchTestUtils.installSearchExtension(
    {
      name: "MozSearch",
      keyword: "mozalias",
      search_url: "https://example.com/",
    },
    { setAsDefault: true }
  );

  // Make it the first one-off engine.
  let engine = Services.search.getEngineByName("MozSearch");
  await Services.search.moveEngine(engine, 0);

  // Enable search suggestions in the urlbar.
  let suggestionsEnabled = Services.prefs.getBoolPref(SUGGEST_URLBAR_PREF);
  Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true);

  // Enable local telemetry recording for the duration of the tests.
  let oldCanRecord = Services.telemetry.canRecordExtended;
  Services.telemetry.canRecordExtended = true;

  // Enable event recording for the events tested here.
  Services.telemetry.setEventRecordingEnabled("navigation", true);

  // 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();

  // Clear historical search suggestions to avoid interference from previous
  // tests.
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.maxHistoricalSearchSuggestions", 0]],
  });

  // This test assumes that general results are shown before suggestions.
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.showSearchSuggestionsFirst", false]],
  });

  // Make sure to restore the engine once we're done.
  registerCleanupFunction(async function () {
    Services.telemetry.canRecordExtended = oldCanRecord;
    Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, suggestionsEnabled);
    await PlacesUtils.history.clear();
    await UrlbarTestUtils.formHistory.clear();
    Services.telemetry.setEventRecordingEnabled("navigation", false);
  });
});

add_task(async function test_simpleQuery() {
  Services.telemetry.clearScalars();
  Services.telemetry.clearEvents();

  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );
  let search_hist =
    TelemetryTestUtils.getAndClearKeyedHistogram("SEARCH_COUNTS");

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

  info("Simulate entering a simple search.");
  let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
  await searchInAwesomebar("simple query");
  EventUtils.synthesizeKey("KEY_Enter");
  await p;

  // Check if the scalars contain the expected values.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, false);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    SCALAR_URLBAR,
    "search_enter",
    1
  );
  Assert.equal(
    Object.keys(scalars[SCALAR_URLBAR]).length,
    1,
    "This search must only increment one entry in the scalar."
  );

  // SEARCH_COUNTS should be incremented, but only the urlbar source since an
  // internal @search keyword was not used.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar",
    1
  );
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.alias",
    undefined
  );

  // Also check events.
  TelemetryTestUtils.assertEvents(
    [
      [
        "navigation",
        "search",
        "urlbar",
        "enter",
        { engine: "other-MozSearch" },
      ],
    ],
    { category: "navigation", method: "search" }
  );

  TelemetryTestUtils.assertHistogram(
    resultMethodHist,
    UrlbarTestUtils.SELECTED_RESULT_METHODS.enter,
    1
  );

  BrowserTestUtils.removeTab(tab);
});

add_task(async function test_searchMode_enter() {
  Services.telemetry.clearScalars();
  Services.telemetry.clearEvents();

  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

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

  info("Enter search mode using an alias and a query.");
  let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
  await searchInAwesomebar("mozalias query");
  EventUtils.synthesizeKey("KEY_Enter");
  await p;

  // Check if the scalars contain the expected values.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, false);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    SCALAR_SEARCHMODE,
    "search_enter",
    1
  );
  Assert.equal(
    Object.keys(scalars[SCALAR_SEARCHMODE]).length,
    1,
    "This search must only increment one entry in the scalar."
  );

  // Also check events.
  TelemetryTestUtils.assertEvents(
    [
      [
        "navigation",
        "search",
        "urlbar_searchmode",
        "enter",
        { engine: "other-MozSearch" },
      ],
    ],
    { category: "navigation", method: "search" }
  );

  TelemetryTestUtils.assertHistogram(
    resultMethodHist,
    UrlbarTestUtils.SELECTED_RESULT_METHODS.enter,
    1
  );

  BrowserTestUtils.removeTab(tab);
});

// Performs a search using the first result, a one-off button, and the Return
// (Enter) key.
add_task(async function test_oneOff_enter() {
  Services.telemetry.clearScalars();
  Services.telemetry.clearEvents();

  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );
  let search_hist =
    TelemetryTestUtils.getAndClearKeyedHistogram("SEARCH_COUNTS");

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

  info("Perform a one-off search using the first engine.");
  let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
  await searchInAwesomebar("query");

  info("Pressing Alt+Down to take us to the first one-off engine.");
  let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
  EventUtils.synthesizeKey("KEY_ArrowDown", { altKey: true });
  let engine =
    UrlbarTestUtils.getOneOffSearchButtons(window).selectedButton.engine;
  EventUtils.synthesizeKey("KEY_Enter");
  await searchPromise;

  await UrlbarTestUtils.assertSearchMode(window, {
    engineName: engine.name,
    entry: "oneoff",
  });

  // Now that we're in search mode, execute the search.
  EventUtils.synthesizeKey("KEY_Enter");
  await p;

  // Check if the scalars contain the expected values.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, false);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    SCALAR_SEARCHMODE,
    "search_enter",
    1
  );
  Assert.equal(
    Object.keys(scalars[SCALAR_SEARCHMODE]).length,
    1,
    "This search must only increment one entry in the scalar."
  );

  // SEARCH_COUNTS should be incremented, but only the urlbar-searchmode source
  // since aliases aren't counted separately in search mode.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar-searchmode",
    1
  );
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.alias",
    undefined
  );

  // Also check events.
  TelemetryTestUtils.assertEvents(
    [
      [
        "navigation",
        "search",
        "urlbar_searchmode",
        "enter",
        { engine: "other-MozSearch" },
      ],
    ],
    { category: "navigation", method: "search" }
  );

  TelemetryTestUtils.assertHistogram(
    resultMethodHist,
    UrlbarTestUtils.SELECTED_RESULT_METHODS.enter,
    1
  );

  BrowserTestUtils.removeTab(tab);
});

// Performs a search using the second result, a one-off button, and the Return
// (Enter) key.  This only tests the FX_URLBAR_SELECTED_RESULT_METHOD histogram
// since test_oneOff_enter covers everything else.
add_task(async function test_oneOff_enterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

  await withNewSearchEngine(async function () {
    await SpecialPowers.pushPrefEnv({
      set: [["browser.urlbar.maxHistoricalSearchSuggestions", 1]],
    });

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

    info("Type a query. Suggestions should be generated by the test engine.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("query");

    info(
      "Select the second result, press Alt+Down to take us to the first one-off engine."
    );
    let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
    EventUtils.synthesizeKey("KEY_ArrowDown", { altKey: true });
    let engine =
      UrlbarTestUtils.getOneOffSearchButtons(window).selectedButton.engine;
    EventUtils.synthesizeKey("KEY_Enter");
    await searchPromise;

    await UrlbarTestUtils.assertSearchMode(window, {
      engineName: engine.name,
      entry: "oneoff",
    });

    // Now that we're in search mode, execute the search.
    EventUtils.synthesizeKey("KEY_ArrowDown");
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.arrowEnterSelection,
      1
    );

    await SpecialPowers.popPrefEnv();
    BrowserTestUtils.removeTab(tab);
  });
});

// Performs a search using a click on a one-off button.  This only tests the
// FX_URLBAR_SELECTED_RESULT_METHOD histogram since test_oneOff_enter covers
// everything else.
add_task(async function test_oneOff_click() {
  Services.telemetry.clearScalars();

  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

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

  info("Type a query.");
  let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
  await searchInAwesomebar("query");

  info("Click the first one-off button.");
  let searchPromise = UrlbarTestUtils.promiseSearchComplete(window);
  let oneOffButton =
    UrlbarTestUtils.getOneOffSearchButtons(window).getSelectableButtons(
      false
    )[0];
  oneOffButton.click();
  await searchPromise;

  await UrlbarTestUtils.assertSearchMode(window, {
    engineName: oneOffButton.engine.name,
    entry: "oneoff",
  });

  // Now that we're in search mode, execute the search.
  let element = await UrlbarTestUtils.waitForAutocompleteResultAt(window, 0);
  Assert.ok(element, "Found result after entering search mode.");
  EventUtils.synthesizeMouseAtCenter(element, {});
  await p;

  TelemetryTestUtils.assertHistogram(
    resultMethodHist,
    UrlbarTestUtils.SELECTED_RESULT_METHODS.click,
    1
  );

  BrowserTestUtils.removeTab(tab);
});

// Clicks the first suggestion offered by the test search engine.
add_task(async function test_suggestion_click() {
  Services.telemetry.clearScalars();
  Services.telemetry.clearEvents();
  await UrlbarTestUtils.formHistory.clear();

  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );
  let search_hist =
    TelemetryTestUtils.getAndClearKeyedHistogram("SEARCH_COUNTS");

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

    info("Type a query. Suggestions should be generated by the test engine.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("query");
    info("Clicking the urlbar suggestion.");
    await clickURLBarSuggestion("queryfoo");
    await p;

    // Check if the scalars contain the expected values.
    const scalars = TelemetryTestUtils.getProcessScalars("parent", true, false);
    TelemetryTestUtils.assertKeyedScalar(
      scalars,
      SCALAR_URLBAR,
      "search_suggestion",
      1
    );
    Assert.equal(
      Object.keys(scalars[SCALAR_URLBAR]).length,
      1,
      "This search must only increment one entry in the scalar."
    );

    // SEARCH_COUNTS should be incremented.
    let searchEngineId = "other-" + engine.name;
    TelemetryTestUtils.assertKeyedHistogramSum(
      search_hist,
      searchEngineId + ".urlbar",
      1
    );

    // Also check events.
    TelemetryTestUtils.assertEvents(
      [
        [
          "navigation",
          "search",
          "urlbar",
          "suggestion",
          { engine: searchEngineId },
        ],
      ],
      { category: "navigation", method: "search" }
    );

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.click,
      1
    );

    BrowserTestUtils.removeTab(tab);
  });
});

// Selects and presses the Return (Enter) key on the first suggestion offered by
// the test search engine.  This only tests the FX_URLBAR_SELECTED_RESULT_METHOD
// histogram since test_suggestion_click covers everything else.
add_task(async function test_suggestion_arrowEnterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

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

    info("Type a query. Suggestions should be generated by the test engine.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("query");
    info("Select the second result and press Return.");
    EventUtils.synthesizeKey("KEY_ArrowDown");
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.arrowEnterSelection,
      1
    );

    BrowserTestUtils.removeTab(tab);
  });
});

// Selects through tab and presses the Return (Enter) key on the first
// suggestion offered by the test search engine.
add_task(async function test_suggestion_tabEnterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

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

    info("Type a query. Suggestions should be generated by the test engine.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("query");
    info("Select the second result and press Return.");
    EventUtils.synthesizeKey("KEY_Tab");
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.tabEnterSelection,
      1
    );

    BrowserTestUtils.removeTab(tab);
  });
});

// Selects through code and presses the Return (Enter) key on the first
// suggestion offered by the test search engine.
add_task(async function test_suggestion_enterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

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

    info("Type a query. Suggestions should be generated by the test engine.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("query");
    info("Select the second result and press Return.");
    UrlbarTestUtils.setSelectedRowIndex(window, 1);
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.enterSelection,
      1
    );

    BrowserTestUtils.removeTab(tab);
  });
});

// Clicks the first suggestion offered by the test search engine when in search
// mode.
add_task(async function test_searchmode_suggestion_click() {
  Services.telemetry.clearScalars();
  Services.telemetry.clearEvents();

  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );
  let search_hist =
    TelemetryTestUtils.getAndClearKeyedHistogram("SEARCH_COUNTS");

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

    info("Type a query. Suggestions should be generated by the test engine.");
    await searchInAwesomebar("query");
    await UrlbarTestUtils.enterSearchMode(window, {
      engineName: engine.name,
    });
    info("Clicking the urlbar suggestion.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await clickURLBarSuggestion("queryfoo");
    await p;

    // Check if the scalars contain the expected values.
    const scalars = TelemetryTestUtils.getProcessScalars("parent", true, false);
    TelemetryTestUtils.assertKeyedScalar(
      scalars,
      SCALAR_SEARCHMODE,
      "search_suggestion",
      1
    );
    Assert.equal(
      Object.keys(scalars[SCALAR_SEARCHMODE]).length,
      1,
      "This search must only increment one entry in the scalar."
    );

    // SEARCH_COUNTS should be incremented.
    let searchEngineId = "other-" + engine.name;
    TelemetryTestUtils.assertKeyedHistogramSum(
      search_hist,
      searchEngineId + ".urlbar-searchmode",
      1
    );

    // Also check events.
    TelemetryTestUtils.assertEvents(
      [
        [
          "navigation",
          "search",
          "urlbar_searchmode",
          "suggestion",
          { engine: searchEngineId },
        ],
      ],
      { category: "navigation", method: "search" }
    );

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.click,
      1
    );

    BrowserTestUtils.removeTab(tab);
  });
});

// Selects and presses the Return (Enter) key on the first suggestion offered by
// the test search engine in search mode.  This only tests the
// FX_URLBAR_SELECTED_RESULT_METHOD histogram since
// test_searchmode_suggestion_click covers everything else.
add_task(async function test_searchmode_suggestion_arrowEnterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

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

    info("Type a query. Suggestions should be generated by the test engine.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("query");
    await UrlbarTestUtils.enterSearchMode(window, {
      engineName: engine.name,
    });
    info("Select the second result and press Return.");
    EventUtils.synthesizeKey("KEY_ArrowDown");
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.arrowEnterSelection,
      1
    );
    BrowserTestUtils.removeTab(tab);
  });
});

// Selects through tab and presses the Return (Enter) key on the first
// suggestion offered by the test search engine in search mode.
add_task(async function test_suggestion_tabEnterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

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

    info("Type a query. Suggestions should be generated by the test engine.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("query");
    await UrlbarTestUtils.enterSearchMode(window, {
      engineName: engine.name,
    });
    info("Select the second result and press Return.");
    EventUtils.synthesizeKey("KEY_Tab");
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.tabEnterSelection,
      1
    );

    BrowserTestUtils.removeTab(tab);
  });
});

// Selects through code and presses the Return (Enter) key on the first
// suggestion offered by the test search engine in search mode.
add_task(async function test_suggestion_enterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

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

    info("Type a query. Suggestions should be generated by the test engine.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("query");
    await UrlbarTestUtils.enterSearchMode(window, {
      engineName: engine.name,
    });
    info("Select the second result and press Return.");
    UrlbarTestUtils.setSelectedRowIndex(window, 1);
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.enterSelection,
      1
    );

    BrowserTestUtils.removeTab(tab);
  });
});

// Clicks a form history result.
add_task(async function test_formHistory_click() {
  Services.telemetry.clearScalars();
  Services.telemetry.clearEvents();
  await UrlbarTestUtils.formHistory.clear();
  await UrlbarTestUtils.formHistory.add(["foobar"]);

  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.maxHistoricalSearchSuggestions", 1]],
  });

  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );
  let search_hist =
    TelemetryTestUtils.getAndClearKeyedHistogram("SEARCH_COUNTS");

  await withNewSearchEngine(async engine => {
    let tab = await BrowserTestUtils.openNewForegroundTab(
      gBrowser,
      "about:blank"
    );

    info("Type a query. There should be form history.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("foo");
    info("Clicking the form history.");
    await clickURLBarSuggestion("foobar");
    await p;

    // Check if the scalars contain the expected values.
    const scalars = TelemetryTestUtils.getProcessScalars("parent", true, false);
    TelemetryTestUtils.assertKeyedScalar(
      scalars,
      SCALAR_URLBAR,
      "search_formhistory",
      1
    );
    Assert.equal(
      Object.keys(scalars[SCALAR_URLBAR]).length,
      1,
      "This search must only increment one entry in the scalar."
    );

    // SEARCH_COUNTS should be incremented.
    let searchEngineId = "other-" + engine.name;
    TelemetryTestUtils.assertKeyedHistogramSum(
      search_hist,
      searchEngineId + ".urlbar",
      1
    );

    // Also check events.
    TelemetryTestUtils.assertEvents(
      [
        [
          "navigation",
          "search",
          "urlbar",
          "formhistory",
          { engine: searchEngineId },
        ],
      ],
      { category: "navigation", method: "search" }
    );

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.click,
      1
    );

    BrowserTestUtils.removeTab(tab);
    await UrlbarTestUtils.formHistory.clear();
    await SpecialPowers.popPrefEnv();
  });
});

// Selects and presses the Return (Enter) key on a form history result.  This
// only tests the FX_URLBAR_SELECTED_RESULT_METHOD histogram since
// test_formHistory_click covers everything else.
add_task(async function test_formHistory_arrowEnterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

  await UrlbarTestUtils.formHistory.clear();
  await UrlbarTestUtils.formHistory.add(["foobar"]);
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.maxHistoricalSearchSuggestions", 1]],
  });

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

    info("Type a query. There should be form history.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("foo");
    info("Select the form history result and press Return.");
    while (gURLBar.untrimmedValue != "foobar") {
      EventUtils.synthesizeKey("KEY_ArrowDown");
    }
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.arrowEnterSelection,
      1
    );

    BrowserTestUtils.removeTab(tab);
    await UrlbarTestUtils.formHistory.clear();
    await SpecialPowers.popPrefEnv();
  });
});

// Selects through tab and presses the Return (Enter) key on a form history
// result.
add_task(async function test_formHistory_tabEnterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

  await UrlbarTestUtils.formHistory.clear();
  await UrlbarTestUtils.formHistory.add(["foobar"]);
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.maxHistoricalSearchSuggestions", 1]],
  });

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

    info("Type a query. There should be form history.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("foo");
    info("Select the form history result and press Return.");
    while (gURLBar.untrimmedValue != "foobar") {
      EventUtils.synthesizeKey("KEY_Tab");
    }
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.tabEnterSelection,
      1
    );

    BrowserTestUtils.removeTab(tab);
    await UrlbarTestUtils.formHistory.clear();
    await SpecialPowers.popPrefEnv();
  });
});

// Selects through code and presses the Return (Enter) key on a form history
// result.
add_task(async function test_formHistory_enterSelection() {
  Services.telemetry.clearScalars();
  let resultMethodHist = TelemetryTestUtils.getAndClearHistogram(
    "FX_URLBAR_SELECTED_RESULT_METHOD"
  );

  await UrlbarTestUtils.formHistory.clear();
  await UrlbarTestUtils.formHistory.add(["foobar"]);
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.maxHistoricalSearchSuggestions", 1]],
  });

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

    info("Type a query. There should be form history.");
    let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
    await searchInAwesomebar("foo");
    info("Select the second result and press Return.");
    let index = 1;
    while (gURLBar.untrimmedValue != "foobar") {
      UrlbarTestUtils.setSelectedRowIndex(window, index++);
    }
    EventUtils.synthesizeKey("KEY_Enter");
    await p;

    TelemetryTestUtils.assertHistogram(
      resultMethodHist,
      UrlbarTestUtils.SELECTED_RESULT_METHODS.enterSelection,
      1
    );

    BrowserTestUtils.removeTab(tab);
    await UrlbarTestUtils.formHistory.clear();
    await SpecialPowers.popPrefEnv();
  });
});

add_task(async function test_privateWindow() {
  // This test assumes the showSearchTerms feature is not enabled,
  // as multiple searches are made one after another, relying on
  // urlbar as the keyed scalar SAP, not urlbar_persisted.
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.showSearchTerms.featureGate", false]],
  });

  // Override the search telemetry search provider info to
  // count in-content SEARCH_COUNTs telemetry for our test engine.
  SearchSERPTelemetry.overrideSearchTelemetryForTests([
    {
      telemetryId: "example",
      searchPageRegexp: "^https://example\\.com/",
      queryParamName: "q",
    },
  ]);

  let search_hist =
    TelemetryTestUtils.getAndClearKeyedHistogram("SEARCH_COUNTS");

  // First, do a bunch of searches in a private window.
  let win = await BrowserTestUtils.openNewBrowserWindow({ private: true });

  info("Search in a private window and the pref does not exist");
  let p = BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
  await searchInAwesomebar("query", win);
  EventUtils.synthesizeKey("KEY_Enter", undefined, win);
  await p;

  // SEARCH_COUNTS should be incremented.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar",
    1
  );
  let scalars = TelemetryTestUtils.getProcessScalars("parent", true);
  console.log(scalars);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "browser.search.content.urlbar",
    "example:organic:none",
    1
  );

  info("Search again in a private window after setting the pref to true");
  Services.prefs.setBoolPref("browser.engagement.search_counts.pbm", true);
  p = BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
  await searchInAwesomebar("another query", win);
  EventUtils.synthesizeKey("KEY_Enter", undefined, win);
  await p;

  // SEARCH_COUNTS should *not* be incremented.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar",
    1
  );
  scalars = TelemetryTestUtils.getProcessScalars("parent", true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "browser.search.content.urlbar",
    "example:organic:none",
    1
  );

  info("Search again in a private window after setting the pref to false");
  Services.prefs.setBoolPref("browser.engagement.search_counts.pbm", false);
  p = BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
  await searchInAwesomebar("another query", win);
  EventUtils.synthesizeKey("KEY_Enter", undefined, win);
  await p;

  // SEARCH_COUNTS should be incremented.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar",
    2
  );
  scalars = TelemetryTestUtils.getProcessScalars("parent", true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "browser.search.content.urlbar",
    "example:organic:none",
    2
  );

  info("Search again in a private window after clearing the pref");
  Services.prefs.clearUserPref("browser.engagement.search_counts.pbm");
  p = BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
  await searchInAwesomebar("another query", win);
  EventUtils.synthesizeKey("KEY_Enter", undefined, win);
  await p;

  // SEARCH_COUNTS should be incremented.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar",
    3
  );
  scalars = TelemetryTestUtils.getProcessScalars("parent", true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "browser.search.content.urlbar",
    "example:organic:none",
    3
  );

  await BrowserTestUtils.closeWindow(win);

  // Now, do a bunch of searches in a non-private window.  Telemetry should
  // always be recorded regardless of the pref's value.
  win = await BrowserTestUtils.openNewBrowserWindow();

  info("Search in a non-private window and the pref does not exist");
  p = BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
  await searchInAwesomebar("query", win);
  EventUtils.synthesizeKey("KEY_Enter", undefined, win);
  await p;

  // SEARCH_COUNTS should be incremented.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar",
    4
  );
  scalars = TelemetryTestUtils.getProcessScalars("parent", true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "browser.search.content.urlbar",
    "example:organic:none",
    4
  );

  info("Search again in a non-private window after setting the pref to true");
  Services.prefs.setBoolPref("browser.engagement.search_counts.pbm", true);
  p = BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
  await searchInAwesomebar("another query", win);
  EventUtils.synthesizeKey("KEY_Enter", undefined, win);
  await p;

  // SEARCH_COUNTS should be incremented.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar",
    5
  );
  scalars = TelemetryTestUtils.getProcessScalars("parent", true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "browser.search.content.urlbar",
    "example:organic:none",
    5
  );

  info("Search again in a non-private window after setting the pref to false");
  Services.prefs.setBoolPref("browser.engagement.search_counts.pbm", false);
  p = BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
  await searchInAwesomebar("another query", win);
  EventUtils.synthesizeKey("KEY_Enter", undefined, win);
  await p;

  // SEARCH_COUNTS should be incremented.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar",
    6
  );
  scalars = TelemetryTestUtils.getProcessScalars("parent", true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "browser.search.content.urlbar",
    "example:organic:none",
    6
  );

  info("Search again in a non-private window after clearing the pref");
  Services.prefs.clearUserPref("browser.engagement.search_counts.pbm");
  p = BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
  await searchInAwesomebar("another query", win);
  EventUtils.synthesizeKey("KEY_Enter", undefined, win);
  await p;

  // SEARCH_COUNTS should be incremented.
  TelemetryTestUtils.assertKeyedHistogramSum(
    search_hist,
    "other-MozSearch.urlbar",
    7
  );
  scalars = TelemetryTestUtils.getProcessScalars("parent", true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "browser.search.content.urlbar",
    "example:organic:none",
    7
  );

  await BrowserTestUtils.closeWindow(win);

  // Reset the search provider info.
  SearchSERPTelemetry.overrideSearchTelemetryForTests();
  await UrlbarTestUtils.formHistory.clear();
  await SpecialPowers.popPrefEnv();
});