summaryrefslogtreecommitdiffstats
path: root/toolkit/mozapps/update/tests/browser/head.js
blob: 7f77ad44df3aec9635b6e369623439639a4c92ea (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { AppConstants } = ChromeUtils.import(
  "resource://gre/modules/AppConstants.jsm"
);

ChromeUtils.defineModuleGetter(
  this,
  "AppMenuNotifications",
  "resource://gre/modules/AppMenuNotifications.jsm"
);
ChromeUtils.defineModuleGetter(
  this,
  "DownloadUtils",
  "resource://gre/modules/DownloadUtils.jsm"
);
ChromeUtils.defineModuleGetter(
  this,
  "UpdateListener",
  "resource://gre/modules/UpdateListener.jsm"
);
const { XPIInstall } = ChromeUtils.import(
  "resource://gre/modules/addons/XPIInstall.jsm"
);

const BIN_SUFFIX = AppConstants.platform == "win" ? ".exe" : "";
const FILE_UPDATER_BIN =
  "updater" + (AppConstants.platform == "macosx" ? ".app" : BIN_SUFFIX);
const FILE_UPDATER_BIN_BAK = FILE_UPDATER_BIN + ".bak";

const LOG_FUNCTION = info;

const MAX_UPDATE_COPY_ATTEMPTS = 10;

const DATA_URI_SPEC =
  "chrome://mochitests/content/browser/toolkit/mozapps/update/tests/browser/";
/* import-globals-from testConstants.js */
Services.scriptloader.loadSubScript(DATA_URI_SPEC + "testConstants.js", this);

var gURLData = URL_HOST + "/" + REL_PATH_DATA;
const URL_MANUAL_UPDATE = gURLData + "downloadPage.html";

const gBadSizeResult = Cr.NS_ERROR_UNEXPECTED.toString();

/* import-globals-from ../data/shared.js */
Services.scriptloader.loadSubScript(DATA_URI_SPEC + "shared.js", this);

let gOriginalUpdateAutoValue = null;

// Some elements append a trailing /. After the chrome tests are removed this
// code can be changed so URL_HOST already has a trailing /.
const gDetailsURL = URL_HOST + "/";
const gDefaultWhatsNewURL = URL_HTTP_UPDATE_SJS + "?uiURL=DETAILS";

// Set to true to log additional information for debugging. To log additional
// information for individual tests set gDebugTest to false here and to true
// globally in the test.
gDebugTest = false;

// This is to accommodate the TV task which runs the tests with --verify.
requestLongerTimeout(10);

/**
 * Common tasks to perform for all tests before each one has started.
 */
add_task(async function setupTestCommon() {
  await SpecialPowers.pushPrefEnv({
    set: [
      [PREF_APP_UPDATE_BADGEWAITTIME, 1800],
      [PREF_APP_UPDATE_DOWNLOAD_ATTEMPTS, 0],
      [PREF_APP_UPDATE_DOWNLOAD_MAXATTEMPTS, 2],
      [PREF_APP_UPDATE_LOG, gDebugTest],
      [PREF_APP_UPDATE_PROMPTWAITTIME, 3600],
      [PREF_APP_UPDATE_SERVICE_ENABLED, false],
      // Disable activity stream to prevent errors when opening pages during
      // TV runs. See bug 1548422 for an example.
      ["browser.library.activity-stream.enabled", false],
    ],
  });

  // We need to keep the update sync manager from thinking two instances are
  // running because of the mochitest parent instance, which means we need to
  // override the directory service with a fake executable path and then reset
  // the lock. But leaving the directory service overridden causes problems for
  // these tests, so we need to restore the real service immediately after.
  // To form the path, we'll use the real executable path with a token appended
  // (the path needs to be absolute, but not to point to a real file).
  // This block is loosely copied from adjustGeneralPaths() in another update
  // test file, xpcshellUtilsAUS.js, but this is a much more limited version;
  // it's been copied here both because the full function is overkill and also
  // because making it general enough to run in both xpcshell and mochitest
  // would have been unreasonably difficult.
  let exePath = Services.dirsvc.get(XRE_EXECUTABLE_FILE, Ci.nsIFile);
  let dirProvider = {
    getFile: function AGP_DP_getFile(aProp, aPersistent) {
      // Set the value of persistent to false so when this directory provider is
      // unregistered it will revert back to the original provider.
      aPersistent.value = false;
      switch (aProp) {
        case XRE_EXECUTABLE_FILE:
          exePath.append("browser-test");
          return exePath;
      }
      return null;
    },
    QueryInterface: ChromeUtils.generateQI(["nsIDirectoryServiceProvider"]),
  };
  let ds = Services.dirsvc.QueryInterface(Ci.nsIDirectoryService);
  ds.QueryInterface(Ci.nsIProperties).undefine(XRE_EXECUTABLE_FILE);
  ds.registerProvider(dirProvider);

  let syncManager = Cc["@mozilla.org/updates/update-sync-manager;1"].getService(
    Ci.nsIUpdateSyncManager
  );
  syncManager.resetLock();

  ds.unregisterProvider(dirProvider);

  setUpdateTimerPrefs();
  reloadUpdateManagerData(true);
  removeUpdateFiles(true);
  UpdateListener.reset();
  AppMenuNotifications.removeNotification(/.*/);
  // Most app update mochitest-browser-chrome tests expect auto update to be
  // enabled. Those that don't will explicitly change this.
  await setAppUpdateAutoEnabledHelper(true);
});

/**
 * Common tasks to perform for all tests after each one has finished.
 */
registerCleanupFunction(async () => {
  AppMenuNotifications.removeNotification(/.*/);
  gEnv.set("MOZ_TEST_SKIP_UPDATE_STAGE", "");
  gEnv.set("MOZ_TEST_SLOW_SKIP_UPDATE_STAGE", "");
  gEnv.set("MOZ_TEST_STAGING_ERROR", "");
  UpdateListener.reset();
  AppMenuNotifications.removeNotification(/.*/);
  reloadUpdateManagerData(true);
  // Pass false when the log files are needed for troubleshooting the tests.
  removeUpdateFiles(true);
  // Always try to restore the original updater files. If none of the updater
  // backup files are present then this is just a no-op.
  await finishTestRestoreUpdaterBackup();
  // Reset the update lock once again so that we know the lock we're
  // interested in here will be closed properly (normally that happens during
  // XPCOM shutdown, but that isn't consistent during tests).
  let syncManager = Cc["@mozilla.org/updates/update-sync-manager;1"].getService(
    Ci.nsIUpdateSyncManager
  );
  syncManager.resetLock();
});

/**
 * Overrides the add-ons manager language pack staging with a mocked version.
 * The returned promise resolves when language pack staging begins returning an
 * object with the new appVersion and platformVersion and functions to resolve
 * or reject the install.
 */
function mockLangpackInstall() {
  let original = XPIInstall.stageLangpacksForAppUpdate;
  registerCleanupFunction(() => {
    XPIInstall.stageLangpacksForAppUpdate = original;
  });

  let stagingCall = PromiseUtils.defer();
  XPIInstall.stageLangpacksForAppUpdate = (appVersion, platformVersion) => {
    let result = PromiseUtils.defer();
    stagingCall.resolve({
      appVersion,
      platformVersion,
      resolve: result.resolve,
      reject: result.reject,
    });

    return result.promise;
  };

  return stagingCall.promise;
}

/**
 * Creates and locks the app update write test file so it is possible to test
 * when the user doesn't have write access to update. Since this is only
 * possible on Windows the function throws when it is called on other platforms.
 * This uses registerCleanupFunction to remove the lock and the file when the
 * test completes.
 *
 * @throws If the function is called on a platform other than Windows.
 */
function lockWriteTestFile() {
  if (AppConstants.platform != "win") {
    throw new Error("Windows only test function called");
  }
  let file = getUpdateDirFile(FILE_UPDATE_TEST).QueryInterface(
    Ci.nsILocalFileWin
  );
  // Remove the file if it exists just in case.
  if (file.exists()) {
    file.fileAttributesWin |= file.WFA_READWRITE;
    file.fileAttributesWin &= ~file.WFA_READONLY;
    file.remove(false);
  }
  file.create(file.NORMAL_FILE_TYPE, 0o444);
  file.fileAttributesWin |= file.WFA_READONLY;
  file.fileAttributesWin &= ~file.WFA_READWRITE;
  registerCleanupFunction(() => {
    file.fileAttributesWin |= file.WFA_READWRITE;
    file.fileAttributesWin &= ~file.WFA_READONLY;
    file.remove(false);
  });
}

/**
 * Closes the update mutex handle in nsUpdateService.js if it exists and then
 * creates a new update mutex handle so the update code thinks there is another
 * instance of the application handling updates.
 *
 * @throws If the function is called on a platform other than Windows.
 */
function setOtherInstanceHandlingUpdates() {
  if (AppConstants.platform != "win") {
    throw new Error("Windows only test function called");
  }
  gAUS.observe(null, "test-close-handle-update-mutex", "");
  let handle = createMutex(getPerInstallationMutexName());
  registerCleanupFunction(() => {
    closeHandle(handle);
  });
}

/**
 * Gets the update version info for the update url parameters to send to
 * app_update.sjs.
 *
 * @param  aAppVersion (optional)
 *         The application version for the update snippet. If not specified the
 *         current application version will be used.
 * @return The url parameters for the application and platform version to send
 *         to app_update.sjs.
 */
function getVersionParams(aAppVersion) {
  let appInfo = Services.appinfo;
  return "&appVersion=" + (aAppVersion ? aAppVersion : appInfo.version);
}

/**
 * Prevent nsIUpdateTimerManager from notifying nsIApplicationUpdateService
 * to check for updates by setting the app update last update time to the
 * current time minus one minute in seconds and the interval time to 12 hours
 * in seconds.
 */
function setUpdateTimerPrefs() {
  let now = Math.round(Date.now() / 1000) - 60;
  Services.prefs.setIntPref(PREF_APP_UPDATE_LASTUPDATETIME, now);
  Services.prefs.setIntPref(PREF_APP_UPDATE_INTERVAL, 43200);
}

/*
 * Sets the value of the App Auto Update setting and sets it back to the
 * original value at the start of the test when the test finishes.
 *
 * @param  enabled
 *         The value to set App Auto Update to.
 */
async function setAppUpdateAutoEnabledHelper(enabled) {
  if (gOriginalUpdateAutoValue == null) {
    gOriginalUpdateAutoValue = await UpdateUtils.getAppUpdateAutoEnabled();
    registerCleanupFunction(async () => {
      await UpdateUtils.setAppUpdateAutoEnabled(gOriginalUpdateAutoValue);
    });
  }
  await UpdateUtils.setAppUpdateAutoEnabled(enabled);
}

/**
 * Gets the specified button for the notification.
 *
 * @param  win
 *         The window to get the notification button for.
 * @param  notificationId
 *         The ID of the notification to get the button for.
 * @param  button
 *         The anonid of the button to get.
 * @return The button element.
 */
function getNotificationButton(win, notificationId, button) {
  let notification = win.document.getElementById(
    `appMenu-${notificationId}-notification`
  );
  ok(!notification.hidden, `${notificationId} notification is showing`);
  return notification[button];
}

/**
 * Ensures that the "What's new" link with the provided ID is displayed and
 * matches the url parameter provided.
 *
 * @param  win
 *         The window to get the "What's new" link for.
 * @param  id
 *         The ID of the "What's new" link element.
 * @param  url
 *         The URL to check against.
 */
function checkWhatsNewLink(win, id, url) {
  let whatsNewLink = win.document.getElementById(id);
  ok(!whatsNewLink.hidden, "What's new link is not hidden.");
  is(whatsNewLink.href, url, `What's new link href should equal ${url}`);
}

/**
 * For staging tests the test updater must be used and this restores the backed
 * up real updater if it exists and tries again on failure since Windows debug
 * builds at times leave the file in use. After success moveRealUpdater is
 * called to continue the setup of the test updater.
 */
function setupTestUpdater() {
  return (async function() {
    if (Services.prefs.getBoolPref(PREF_APP_UPDATE_STAGING_ENABLED)) {
      try {
        restoreUpdaterBackup();
      } catch (e) {
        logTestInfo(
          "Attempt to restore the backed up updater failed... " +
            "will try again, Exception: " +
            e
        );
        await TestUtils.waitForTick();
        await setupTestUpdater();
        return;
      }
      await moveRealUpdater();
    }
  })();
}

/**
 * Backs up the real updater and tries again on failure since Windows debug
 * builds at times leave the file in use. After success it will call
 * copyTestUpdater to continue the setup of the test updater.
 */
function moveRealUpdater() {
  return (async function() {
    try {
      // Move away the real updater
      let greBinDir = getGREBinDir();
      let updater = greBinDir.clone();
      updater.append(FILE_UPDATER_BIN);
      updater.moveTo(greBinDir, FILE_UPDATER_BIN_BAK);

      let greDir = getGREDir();
      let updateSettingsIni = greDir.clone();
      updateSettingsIni.append(FILE_UPDATE_SETTINGS_INI);
      if (updateSettingsIni.exists()) {
        updateSettingsIni.moveTo(greDir, FILE_UPDATE_SETTINGS_INI_BAK);
      }

      let precomplete = greDir.clone();
      precomplete.append(FILE_PRECOMPLETE);
      if (precomplete.exists()) {
        precomplete.moveTo(greDir, FILE_PRECOMPLETE_BAK);
      }
    } catch (e) {
      logTestInfo(
        "Attempt to move the real updater out of the way failed... " +
          "will try again, Exception: " +
          e
      );
      await TestUtils.waitForTick();
      await moveRealUpdater();
      return;
    }

    await copyTestUpdater();
  })();
}

/**
 * Copies the test updater and tries again on failure since Windows debug builds
 * at times leave the file in use.
 */
function copyTestUpdater(attempt = 0) {
  return (async function() {
    try {
      // Copy the test updater
      let greBinDir = getGREBinDir();
      let testUpdaterDir = Services.dirsvc.get("CurWorkD", Ci.nsIFile);
      let relPath = REL_PATH_DATA;
      let pathParts = relPath.split("/");
      for (let i = 0; i < pathParts.length; ++i) {
        testUpdaterDir.append(pathParts[i]);
      }

      let testUpdater = testUpdaterDir.clone();
      testUpdater.append(FILE_UPDATER_BIN);
      testUpdater.copyToFollowingLinks(greBinDir, FILE_UPDATER_BIN);

      let greDir = getGREDir();
      let updateSettingsIni = greDir.clone();
      updateSettingsIni.append(FILE_UPDATE_SETTINGS_INI);
      writeFile(updateSettingsIni, UPDATE_SETTINGS_CONTENTS);

      let precomplete = greDir.clone();
      precomplete.append(FILE_PRECOMPLETE);
      writeFile(precomplete, PRECOMPLETE_CONTENTS);
    } catch (e) {
      if (attempt < MAX_UPDATE_COPY_ATTEMPTS) {
        logTestInfo(
          "Attempt to copy the test updater failed... " +
            "will try again, Exception: " +
            e
        );
        await TestUtils.waitForTick();
        await copyTestUpdater(attempt++);
      }
    }
  })();
}

/**
 * Restores the updater and updater related file that if there a backup exists.
 * This is called in setupTestUpdater before the backup of the real updater is
 * done in case the previous test failed to restore the file when a test has
 * finished. This is also called in finishTestRestoreUpdaterBackup to restore
 * the files when a test finishes.
 */
function restoreUpdaterBackup() {
  let greBinDir = getGREBinDir();
  let updater = greBinDir.clone();
  let updaterBackup = greBinDir.clone();
  updater.append(FILE_UPDATER_BIN);
  updaterBackup.append(FILE_UPDATER_BIN_BAK);
  if (updaterBackup.exists()) {
    if (updater.exists()) {
      updater.remove(true);
    }
    updaterBackup.moveTo(greBinDir, FILE_UPDATER_BIN);
  }

  let greDir = getGREDir();
  let updateSettingsIniBackup = greDir.clone();
  updateSettingsIniBackup.append(FILE_UPDATE_SETTINGS_INI_BAK);
  if (updateSettingsIniBackup.exists()) {
    let updateSettingsIni = greDir.clone();
    updateSettingsIni.append(FILE_UPDATE_SETTINGS_INI);
    if (updateSettingsIni.exists()) {
      updateSettingsIni.remove(false);
    }
    updateSettingsIniBackup.moveTo(greDir, FILE_UPDATE_SETTINGS_INI);
  }

  let precomplete = greDir.clone();
  let precompleteBackup = greDir.clone();
  precomplete.append(FILE_PRECOMPLETE);
  precompleteBackup.append(FILE_PRECOMPLETE_BAK);
  if (precompleteBackup.exists()) {
    if (precomplete.exists()) {
      precomplete.remove(false);
    }
    precompleteBackup.moveTo(greDir, FILE_PRECOMPLETE);
  } else if (precomplete.exists()) {
    if (readFile(precomplete) == PRECOMPLETE_CONTENTS) {
      precomplete.remove(false);
    }
  }
}

/**
 * When a test finishes this will repeatedly attempt to restore the real updater
 * and the other files for the updater if a backup of the file exists.
 */
function finishTestRestoreUpdaterBackup() {
  return (async function() {
    try {
      // Windows debug builds keep the updater file in use for a short period of
      // time after the updater process exits.
      restoreUpdaterBackup();
    } catch (e) {
      logTestInfo(
        "Attempt to restore the backed up updater failed... " +
          "will try again, Exception: " +
          e
      );

      await TestUtils.waitForTick();
      await finishTestRestoreUpdaterBackup();
    }
  })();
}

/**
 * Waits for the About Dialog to load.
 *
 * @return A promise that returns the domWindow for the About Dialog and
 *         resolves when the About Dialog loads.
 */
function waitForAboutDialog() {
  return new Promise(resolve => {
    var listener = {
      onOpenWindow: aXULWindow => {
        debugDump("About dialog shown...");
        Services.wm.removeListener(listener);

        async function aboutDialogOnLoad() {
          domwindow.removeEventListener("load", aboutDialogOnLoad, true);
          let chromeURI = "chrome://browser/content/aboutDialog.xhtml";
          is(
            domwindow.document.location.href,
            chromeURI,
            "About dialog appeared"
          );
          resolve(domwindow);
        }

        var domwindow = aXULWindow.docShell.domWindow;
        domwindow.addEventListener("load", aboutDialogOnLoad, true);
      },
      onCloseWindow: aXULWindow => {},
    };

    Services.wm.addListener(listener);
    openAboutDialog();
  });
}

/**
 * Return the first UpdatePatch with the given type.
 *
 * @param   type
 *          The type of the patch ("complete" or "partial")
 * @param   update
 *          The nsIUpdate to select a patch from.
 * @return  A nsIUpdatePatch object matching the type specified
 */
function getPatchOfType(type, update) {
  if (update) {
    for (let i = 0; i < update.patchCount; ++i) {
      let patch = update.getPatchAt(i);
      if (patch && patch.type == type) {
        return patch;
      }
    }
  }
  return null;
}

/**
 * Runs a Doorhanger update test. This will set various common prefs for
 * updating and runs the provided list of steps.
 *
 * @param  params
 *         An object containing parameters used to run the test.
 * @param  steps
 *         An array of test steps to perform. A step will either be an object
 *         containing expected conditions and actions or a function to call.
 * @return A promise which will resolve once all of the steps have been run.
 */
function runDoorhangerUpdateTest(params, steps) {
  function processDoorhangerStep(step) {
    if (typeof step == "function") {
      return step();
    }

    const { notificationId, button, checkActiveUpdate, pageURLs } = step;
    return (async function() {
      if (!params.popupShown && !PanelUI.isNotificationPanelOpen) {
        await BrowserTestUtils.waitForEvent(
          PanelUI.notificationPanel,
          "popupshown"
        );
      }
      const shownNotificationId = AppMenuNotifications.activeNotification.id;
      is(
        shownNotificationId,
        notificationId,
        "The right notification showed up."
      );

      if (checkActiveUpdate) {
        let activeUpdate =
          checkActiveUpdate.state == STATE_DOWNLOADING
            ? gUpdateManager.downloadingUpdate
            : gUpdateManager.readyUpdate;
        ok(!!activeUpdate, "There should be an active update");
        is(
          activeUpdate.state,
          checkActiveUpdate.state,
          `The active update state should equal ${checkActiveUpdate.state}`
        );
      } else {
        ok(
          !gUpdateManager.downloadingUpdate,
          "There should not be a downloading update"
        );
        ok(!gUpdateManager.readyUpdate, "There should not be a ready update");
      }

      if (pageURLs && pageURLs.whatsNew !== undefined) {
        checkWhatsNewLink(
          window,
          `${notificationId}-whats-new`,
          pageURLs.whatsNew
        );
      }

      let buttonEl = getNotificationButton(window, notificationId, button);
      buttonEl.click();

      if (pageURLs && pageURLs.manual !== undefined) {
        await BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
        is(
          gBrowser.selectedBrowser.currentURI.spec,
          pageURLs.manual,
          `The page's url should equal ${pageURLs.manual}`
        );
        gBrowser.removeTab(gBrowser.selectedTab);
      }
    })();
  }

  return (async function() {
    if (params.slowStaging) {
      gEnv.set("MOZ_TEST_SLOW_SKIP_UPDATE_STAGE", "1");
    } else {
      gEnv.set("MOZ_TEST_SKIP_UPDATE_STAGE", "1");
    }
    await SpecialPowers.pushPrefEnv({
      set: [
        [PREF_APP_UPDATE_DISABLEDFORTESTING, false],
        [PREF_APP_UPDATE_URL_DETAILS, gDetailsURL],
        [PREF_APP_UPDATE_URL_MANUAL, URL_MANUAL_UPDATE],
      ],
    });

    await setupTestUpdater();

    let queryString = params.queryString ? params.queryString : "";
    let updateURL =
      URL_HTTP_UPDATE_SJS +
      "?detailsURL=" +
      gDetailsURL +
      queryString +
      getVersionParams(params.version);
    setUpdateURL(updateURL);

    if (params.checkAttempts) {
      // Perform a background check doorhanger test.
      executeSoon(() => {
        (async function() {
          gAUS.checkForBackgroundUpdates();
          for (var i = 0; i < params.checkAttempts - 1; i++) {
            await waitForEvent("update-error", "check-attempt-failed");
            gAUS.checkForBackgroundUpdates();
          }
        })();
      });
    } else {
      // Perform a startup processing doorhanger test.
      writeStatusFile(STATE_FAILED_CRC_ERROR);
      writeUpdatesToXMLFile(getLocalUpdatesXMLString(params.updates), true);
      reloadUpdateManagerData();
      testPostUpdateProcessing();
    }

    for (let step of steps) {
      await processDoorhangerStep(step);
    }
  })();
}

/**
 * Runs an About Dialog update test. This will set various common prefs for
 * updating and runs the provided list of steps.
 *
 * @param  params
 *         An object containing parameters used to run the test.
 * @param  steps
 *         An array of test steps to perform. A step will either be an object
 *         containing expected conditions and actions or a function to call.
 * @return A promise which will resolve once all of the steps have been run.
 */
function runAboutDialogUpdateTest(params, steps) {
  let aboutDialog;
  function processAboutDialogStep(step) {
    if (typeof step == "function") {
      return step(aboutDialog);
    }

    const { panelId, checkActiveUpdate, continueFile, downloadInfo } = step;
    return (async function() {
      let updateDeck = aboutDialog.document.getElementById("updateDeck");
      await TestUtils.waitForCondition(
        () =>
          updateDeck.selectedPanel && updateDeck.selectedPanel.id == panelId,
        "Waiting for the expected panel ID: " + panelId,
        undefined,
        200
      ).catch(e => {
        // Instead of throwing let the check below fail the test so the panel
        // ID and the expected panel ID is printed in the log.
        logTestInfo(e);
      });
      let selectedPanel = updateDeck.selectedPanel;
      is(selectedPanel.id, panelId, "The panel ID should equal " + panelId);

      if (checkActiveUpdate) {
        let activeUpdate =
          checkActiveUpdate.state == STATE_DOWNLOADING
            ? gUpdateManager.downloadingUpdate
            : gUpdateManager.readyUpdate;
        ok(!!activeUpdate, "There should be an active update");
        is(
          activeUpdate.state,
          checkActiveUpdate.state,
          "The active update state should equal " + checkActiveUpdate.state
        );
      } else {
        ok(
          !gUpdateManager.downloadingUpdate,
          "There should not be a downloading update"
        );
        ok(!gUpdateManager.readyUpdate, "There should not be a ready update");
      }

      if (panelId == "downloading") {
        for (let i = 0; i < downloadInfo.length; ++i) {
          let data = downloadInfo[i];
          // The About Dialog tests always specify a continue file.
          await continueFileHandler(continueFile);
          let patch = getPatchOfType(
            data.patchType,
            gUpdateManager.downloadingUpdate
          );
          // The update is removed early when the last download fails so check
          // that there is a patch before proceeding.
          let isLastPatch = i == downloadInfo.length - 1;
          if (!isLastPatch || patch) {
            let resultName = data.bitsResult ? "bitsResult" : "internalResult";
            patch.QueryInterface(Ci.nsIWritablePropertyBag);
            await TestUtils.waitForCondition(
              () => patch.getProperty(resultName) == data[resultName],
              "Waiting for expected patch property " +
                resultName +
                " value: " +
                data[resultName],
              undefined,
              200
            ).catch(e => {
              // Instead of throwing let the check below fail the test so the
              // property value and the expected property value is printed in
              // the log.
              logTestInfo(e);
            });
            is(
              "" + patch.getProperty(resultName),
              data[resultName],
              "The patch property " +
                resultName +
                " value should equal " +
                data[resultName]
            );

            // Check the download status text.  It should be something like,
            // "1.4 of 1.4 KB".
            let expectedText = DownloadUtils.getTransferTotal(
              data[resultName] == gBadSizeResult ? 0 : patch.size,
              patch.size
            );
            Assert.ok(
              expectedText,
              "Sanity check: Expected download status text should be non-empty"
            );
            Assert.equal(
              aboutDialog.downloadStatus.textContent,
              expectedText,
              "Download status text should be correct"
            );
          }
        }
      } else if (continueFile) {
        await continueFileHandler(continueFile);
      }

      let linkPanels = ["downloadFailed", "manualUpdate", "unsupportedSystem"];
      if (linkPanels.includes(panelId)) {
        // The unsupportedSystem panel uses the update's detailsURL and the
        // downloadFailed and manualUpdate panels use the app.update.url.manual
        // preference.
        let link = selectedPanel.querySelector("label.text-link");
        is(
          link.href,
          gDetailsURL,
          `The panel's link href should equal ${gDetailsURL}`
        );
      }

      let buttonPanels = ["downloadAndInstall", "apply"];
      if (buttonPanels.includes(panelId)) {
        let buttonEl = selectedPanel.querySelector("button");
        await TestUtils.waitForCondition(
          () => aboutDialog.document.activeElement == buttonEl,
          "The button should receive focus"
        );
        ok(!buttonEl.disabled, "The button should be enabled");
        // Don't click the button on the apply panel since this will restart the
        // application.
        if (panelId != "apply") {
          buttonEl.click();
        }
      }
    })();
  }

  return (async function() {
    gEnv.set("MOZ_TEST_SLOW_SKIP_UPDATE_STAGE", "1");
    await SpecialPowers.pushPrefEnv({
      set: [
        [PREF_APP_UPDATE_DISABLEDFORTESTING, false],
        [PREF_APP_UPDATE_URL_MANUAL, gDetailsURL],
      ],
    });

    await setupTestUpdater();

    let queryString = params.queryString ? params.queryString : "";
    let updateURL =
      URL_HTTP_UPDATE_SJS +
      "?detailsURL=" +
      gDetailsURL +
      queryString +
      getVersionParams(params.version);
    if (params.backgroundUpdate) {
      setUpdateURL(updateURL);
      gAUS.checkForBackgroundUpdates();
      if (params.continueFile) {
        await continueFileHandler(params.continueFile);
      }
      if (params.waitForUpdateState) {
        let whichUpdate =
          params.waitForUpdateState == STATE_DOWNLOADING
            ? "downloadingUpdate"
            : "readyUpdate";
        await TestUtils.waitForCondition(
          () =>
            gUpdateManager[whichUpdate] &&
            gUpdateManager[whichUpdate].state == params.waitForUpdateState,
          "Waiting for update state: " + params.waitForUpdateState,
          undefined,
          200
        ).catch(e => {
          // Instead of throwing let the check below fail the test so the panel
          // ID and the expected panel ID is printed in the log.
          logTestInfo(e);
        });
        // Display the UI after the update state equals the expected value.
        is(
          gUpdateManager[whichUpdate].state,
          params.waitForUpdateState,
          "The update state value should equal " + params.waitForUpdateState
        );
      }
    } else {
      updateURL += "&slowUpdateCheck=1&useSlowDownloadMar=1";
      setUpdateURL(updateURL);
    }

    aboutDialog = await waitForAboutDialog();
    registerCleanupFunction(() => {
      aboutDialog.close();
    });

    for (let step of steps) {
      await processAboutDialogStep(step);
    }
  })();
}

/**
 * Runs an about:preferences update test. This will set various common prefs for
 * updating and runs the provided list of steps.
 *
 * @param  params
 *         An object containing parameters used to run the test.
 * @param  steps
 *         An array of test steps to perform. A step will either be an object
 *         containing expected conditions and actions or a function to call.
 * @return A promise which will resolve once all of the steps have been run.
 */
function runAboutPrefsUpdateTest(params, steps) {
  let tab;
  function processAboutPrefsStep(step) {
    if (typeof step == "function") {
      return step(tab);
    }

    const { panelId, checkActiveUpdate, continueFile, downloadInfo } = step;
    return (async function() {
      await SpecialPowers.spawn(
        tab.linkedBrowser,
        [{ panelId }],
        async ({ panelId }) => {
          let updateDeck = content.document.getElementById("updateDeck");
          await ContentTaskUtils.waitForCondition(
            () =>
              updateDeck.selectedPanel &&
              updateDeck.selectedPanel.id == panelId,
            "Waiting for the expected panel ID: " + panelId,
            undefined,
            200
          ).catch(e => {
            // Instead of throwing let the check below fail the test so the panel
            // ID and the expected panel ID is printed in the log. Use info here
            // instead of logTestInfo since logTestInfo isn't available in the
            // content task.
            info(e);
          });
          is(
            updateDeck.selectedPanel.id,
            panelId,
            "The panel ID should equal " + panelId
          );
        }
      );

      if (checkActiveUpdate) {
        let activeUpdate =
          checkActiveUpdate.state == STATE_DOWNLOADING
            ? gUpdateManager.downloadingUpdate
            : gUpdateManager.readyUpdate;
        ok(!!activeUpdate, "There should be an active update");
        is(
          activeUpdate.state,
          checkActiveUpdate.state,
          "The active update state should equal " + checkActiveUpdate.state
        );
      } else {
        ok(
          !gUpdateManager.downloadingUpdate,
          "There should not be a downloading update"
        );
        ok(!gUpdateManager.readyUpdate, "There should not be a ready update");
      }

      if (panelId == "downloading") {
        for (let i = 0; i < downloadInfo.length; ++i) {
          let data = downloadInfo[i];
          // The About Dialog tests always specify a continue file.
          await continueFileHandler(continueFile);
          let patch = getPatchOfType(
            data.patchType,
            gUpdateManager.downloadingUpdate
          );
          // The update is removed early when the last download fails so check
          // that there is a patch before proceeding.
          let isLastPatch = i == downloadInfo.length - 1;
          if (!isLastPatch || patch) {
            let resultName = data.bitsResult ? "bitsResult" : "internalResult";
            patch.QueryInterface(Ci.nsIWritablePropertyBag);
            await TestUtils.waitForCondition(
              () => patch.getProperty(resultName) == data[resultName],
              "Waiting for expected patch property " +
                resultName +
                " value: " +
                data[resultName],
              undefined,
              200
            ).catch(e => {
              // Instead of throwing let the check below fail the test so the
              // property value and the expected property value is printed in
              // the log.
              logTestInfo(e);
            });
            is(
              "" + patch.getProperty(resultName),
              data[resultName],
              "The patch property " +
                resultName +
                " value should equal " +
                data[resultName]
            );

            // Check the download status text.  It should be something like,
            // "Downloading update — 1.4 of 1.4 KB".  We check only the second
            // part to make sure that the downloaded size is updated correctly.
            let actualText = await SpecialPowers.spawn(
              tab.linkedBrowser,
              [],
              () => content.document.getElementById("downloading").textContent
            );
            let expectedSuffix = DownloadUtils.getTransferTotal(
              data[resultName] == gBadSizeResult ? 0 : patch.size,
              patch.size
            );
            Assert.ok(
              expectedSuffix,
              "Sanity check: Expected download status text should be non-empty"
            );
            Assert.ok(
              actualText.endsWith(expectedSuffix),
              "Download status text should end as expected: " +
                JSON.stringify({ actualText, expectedSuffix })
            );
          }
        }
      } else if (continueFile) {
        await continueFileHandler(continueFile);
      }

      await SpecialPowers.spawn(
        tab.linkedBrowser,
        [{ panelId, gDetailsURL }],
        async ({ panelId, gDetailsURL }) => {
          let linkPanels = [
            "downloadFailed",
            "manualUpdate",
            "unsupportedSystem",
          ];
          if (linkPanels.includes(panelId)) {
            let selectedPanel = content.document.getElementById("updateDeck")
              .selectedPanel;
            // The unsupportedSystem panel uses the update's detailsURL and the
            // downloadFailed and manualUpdate panels use the app.update.url.manual
            // preference.
            let selector = "label.text-link";
            // The downloadFailed panel in about:preferences uses an anchor
            // instead of a label for the link.
            if (selectedPanel.id == "downloadFailed") {
              selector = "a.text-link";
            }
            let link = selectedPanel.querySelector(selector);
            is(
              link.href,
              gDetailsURL,
              `The panel's link href should equal ${gDetailsURL}`
            );
          }

          let buttonPanels = ["downloadAndInstall", "apply"];
          if (buttonPanels.includes(panelId)) {
            let selectedPanel = content.document.getElementById("updateDeck")
              .selectedPanel;
            let buttonEl = selectedPanel.querySelector("button");
            // Note: The about:preferences doesn't focus the button like the
            // About Dialog does.
            ok(!buttonEl.disabled, "The button should be enabled");
            // Don't click the button on the apply panel since this will restart
            // the application.
            if (selectedPanel.id != "apply") {
              buttonEl.click();
            }
          }
        }
      );
    })();
  }

  return (async function() {
    gEnv.set("MOZ_TEST_SLOW_SKIP_UPDATE_STAGE", "1");
    await SpecialPowers.pushPrefEnv({
      set: [
        [PREF_APP_UPDATE_DISABLEDFORTESTING, false],
        [PREF_APP_UPDATE_URL_MANUAL, gDetailsURL],
      ],
    });

    await setupTestUpdater();

    let queryString = params.queryString ? params.queryString : "";
    let updateURL =
      URL_HTTP_UPDATE_SJS +
      "?detailsURL=" +
      gDetailsURL +
      queryString +
      getVersionParams(params.version);
    if (params.backgroundUpdate) {
      setUpdateURL(updateURL);
      gAUS.checkForBackgroundUpdates();
      if (params.continueFile) {
        await continueFileHandler(params.continueFile);
      }
      if (params.waitForUpdateState) {
        // Wait until the update state equals the expected value before
        // displaying the UI.
        let whichUpdate =
          params.waitForUpdateState == STATE_DOWNLOADING
            ? "downloadingUpdate"
            : "readyUpdate";
        await TestUtils.waitForCondition(
          () =>
            gUpdateManager[whichUpdate] &&
            gUpdateManager[whichUpdate].state == params.waitForUpdateState,
          "Waiting for update state: " + params.waitForUpdateState,
          undefined,
          200
        ).catch(e => {
          // Instead of throwing let the check below fail the test so the panel
          // ID and the expected panel ID is printed in the log.
          logTestInfo(e);
        });
        is(
          gUpdateManager[whichUpdate].state,
          params.waitForUpdateState,
          "The update state value should equal " + params.waitForUpdateState
        );
      }
    } else {
      updateURL += "&slowUpdateCheck=1&useSlowDownloadMar=1";
      setUpdateURL(updateURL);
    }

    tab = await BrowserTestUtils.openNewForegroundTab(
      gBrowser,
      "about:preferences"
    );
    registerCleanupFunction(async () => {
      await BrowserTestUtils.removeTab(tab);
    });

    // Scroll the UI into view so it is easier to troubleshoot tests.
    await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
      content.document.getElementById("updatesCategory").scrollIntoView();
    });

    for (let step of steps) {
      await processAboutPrefsStep(step);
    }
  })();
}

/**
 * Removes the modified update-settings.ini file so the updater will fail to
 * stage an update.
 */
function removeUpdateSettingsIni() {
  if (Services.prefs.getBoolPref(PREF_APP_UPDATE_STAGING_ENABLED)) {
    let greDir = getGREDir();
    let updateSettingsIniBak = greDir.clone();
    updateSettingsIniBak.append(FILE_UPDATE_SETTINGS_INI_BAK);
    if (updateSettingsIniBak.exists()) {
      let updateSettingsIni = greDir.clone();
      updateSettingsIni.append(FILE_UPDATE_SETTINGS_INI);
      updateSettingsIni.remove(false);
    }
  }
}

/**
 * Runs a telemetry update test. This will set various common prefs for
 * updating, checks for an update, and waits for the specified observer
 * notification.
 *
 * @param  updateParams
 *         Params which will be sent to app_update.sjs.
 * @param  event
 *         The observer notification to wait for before proceeding.
 * @param  stageFailure (optional)
 *         Whether to force a staging failure by removing the modified
 *         update-settings.ini file.
 * @return A promise which will resolve after the .
 */
function runTelemetryUpdateTest(updateParams, event, stageFailure = false) {
  return (async function() {
    Services.telemetry.clearScalars();
    gEnv.set("MOZ_TEST_SKIP_UPDATE_STAGE", "1");
    await SpecialPowers.pushPrefEnv({
      set: [[PREF_APP_UPDATE_DISABLEDFORTESTING, false]],
    });

    await setupTestUpdater();

    if (stageFailure) {
      removeUpdateSettingsIni();
    }

    let updateURL =
      URL_HTTP_UPDATE_SJS +
      "?detailsURL=" +
      gDetailsURL +
      updateParams +
      getVersionParams();
    setUpdateURL(updateURL);
    gAUS.checkForBackgroundUpdates();
    await waitForEvent(event);
  })();
}