DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (b3ecb5aef45a)

VCS Links

Line Code
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 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

/* eslint "mozilla/no-aArgs": 1 */
/* eslint "no-unused-vars": [2, {"args": "none", "varsIgnorePattern": "^(Cc|Ci|Cr|Cu|EXPORTED_SYMBOLS)$"}] */
/* eslint "semi": [2, "always"] */
/* eslint "valid-jsdoc": [2, {requireReturn: false}] */

var EXPORTED_SYMBOLS = ["AddonTestUtils", "MockAsyncShutdown"];

const CERTDB_CONTRACTID = "@mozilla.org/security/x509certdb;1";

Cu.importGlobalProperties(["fetch"]);

const { AsyncShutdown } = ChromeUtils.import(
  "resource://gre/modules/AsyncShutdown.jsm"
);
const { FileUtils } = ChromeUtils.import(
  "resource://gre/modules/FileUtils.jsm"
);
const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { setTimeout } = ChromeUtils.import("resource://gre/modules/Timer.jsm");
const { XPCOMUtils } = ChromeUtils.import(
  "resource://gre/modules/XPCOMUtils.jsm"
);

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

ChromeUtils.defineModuleGetter(
  this,
  "AMTelemetry",
  "resource://gre/modules/AddonManager.jsm"
);
ChromeUtils.defineModuleGetter(
  this,
  "ExtensionTestCommon",
  "resource://testing-common/ExtensionTestCommon.jsm"
);
ChromeUtils.defineModuleGetter(
  this,
  "Management",
  "resource://gre/modules/Extension.jsm"
);
ChromeUtils.defineModuleGetter(
  this,
  "UninstallObserver",
  "resource://gre/modules/Extension.jsm"
);

ChromeUtils.defineModuleGetter(
  this,
  "FileTestUtils",
  "resource://testing-common/FileTestUtils.jsm"
);
ChromeUtils.defineModuleGetter(
  this,
  "HttpServer",
  "resource://testing-common/httpd.js"
);
ChromeUtils.defineModuleGetter(
  this,
  "MockRegistrar",
  "resource://testing-common/MockRegistrar.jsm"
);

XPCOMUtils.defineLazyServiceGetters(this, {
  aomStartup: [
    "@mozilla.org/addons/addon-manager-startup;1",
    "amIAddonManagerStartup",
  ],
  proxyService: [
    "@mozilla.org/network/protocol-proxy-service;1",
    "nsIProtocolProxyService",
  ],
  uuidGen: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});

XPCOMUtils.defineLazyGetter(this, "AppInfo", () => {
  let AppInfo = {};
  ChromeUtils.import("resource://testing-common/AppInfo.jsm", AppInfo);
  return AppInfo;
});

const PREF_DISABLE_SECURITY =
  "security.turn_off_all_security_so_that_" +
  "viruses_can_take_over_this_computer";

const ArrayBufferInputStream = Components.Constructor(
  "@mozilla.org/io/arraybuffer-input-stream;1",
  "nsIArrayBufferInputStream",
  "setData"
);

const nsFile = Components.Constructor(
  "@mozilla.org/file/local;1",
  "nsIFile",
  "initWithPath"
);

const ZipReader = Components.Constructor(
  "@mozilla.org/libjar/zip-reader;1",
  "nsIZipReader",
  "open"
);

const ZipWriter = Components.Constructor(
  "@mozilla.org/zipwriter;1",
  "nsIZipWriter",
  "open"
);

function isRegExp(val) {
  return val && typeof val === "object" && typeof val.test === "function";
}

// We need some internal bits of AddonManager
var AMscope = ChromeUtils.import(
  "resource://gre/modules/AddonManager.jsm",
  null
);
var { AddonManager, AddonManagerPrivate } = AMscope;

class MockBarrier {
  constructor(name) {
    this.name = name;
    this.blockers = [];
  }

  addBlocker(name, blocker, options) {
    this.blockers.push({ name, blocker, options });
  }

  async trigger() {
    await Promise.all(
      this.blockers.map(async ({ blocker, name }) => {
        try {
          if (typeof blocker == "function") {
            await blocker();
          } else {
            await blocker;
          }
        } catch (e) {
          Cu.reportError(e);
          dump(
            `Shutdown blocker '${name}' for ${this.name} threw error: ${e} :: ${
              e.stack
            }\n`
          );
        }
      })
    );

    this.blockers = [];
  }
}

// Mock out AddonManager's reference to the AsyncShutdown module so we can shut
// down AddonManager from the test
var MockAsyncShutdown = {
  profileBeforeChange: new MockBarrier("profileBeforeChange"),
  profileChangeTeardown: new MockBarrier("profileChangeTeardown"),
  quitApplicationGranted: new MockBarrier("quitApplicationGranted"),
  // We can use the real Barrier
  Barrier: AsyncShutdown.Barrier,
};

AMscope.AsyncShutdown = MockAsyncShutdown;

class MockBlocklist {
  constructor(addons) {
    if (ChromeUtils.getClassName(addons) === "Object") {
      addons = new Map(Object.entries(addons));
    }
    this.addons = addons;
    this.wrappedJSObject = this;

    // Copy blocklist constants.
    for (let [k, v] of Object.entries(Ci.nsIBlocklistService)) {
      if (typeof v === "number") {
        this[k] = v;
      }
    }

    this._xpidb = ChromeUtils.import(
      "resource://gre/modules/addons/XPIDatabase.jsm",
      null
    );
  }

  get contractID() {
    return "@mozilla.org/extensions/blocklist;1";
  }

  _reLazifyService() {
    XPCOMUtils.defineLazyServiceGetter(Services, "blocklist", this.contractID);
    ChromeUtils.defineModuleGetter(
      this._xpidb,
      "Blocklist",
      "resource://gre/modules/Blocklist.jsm"
    );
  }

  register() {
    this.originalCID = MockRegistrar.register(this.contractID, this);
    this._reLazifyService();
    this._xpidb.Blocklist = this;
  }

  unregister() {
    MockRegistrar.unregister(this.originalCID);
    this._reLazifyService();
  }

  async getAddonBlocklistState(addon, appVersion, toolkitVersion) {
    await new Promise(r => setTimeout(r, 150));
    return (
      this.addons.get(addon.id) || Ci.nsIBlocklistService.STATE_NOT_BLOCKED
    );
  }

  async getAddonBlocklistEntry(addon, appVersion, toolkitVersion) {
    let state = await this.getAddonBlocklistState(
      addon,
      appVersion,
      toolkitVersion
    );
    if (state != Ci.nsIBlocklistService.STATE_NOT_BLOCKED) {
      return {
        state,
        url: "http://example.com/",
      };
    }
    return null;
  }

  async getPluginBlocklistState(plugin, version, appVersion, toolkitVersion) {
    await new Promise(r => setTimeout(r, 150));
    return Ci.nsIBlocklistService.STATE_NOT_BLOCKED;
  }
}

MockBlocklist.prototype.QueryInterface = ChromeUtils.generateQI([
  "nsIBlocklistService",
]);

class AddonsList {
  constructor(file) {
    this.extensions = [];
    this.themes = [];
    this.xpis = [];

    if (!file.exists()) {
      return;
    }

    let data = aomStartup.readStartupData();

    for (let loc of Object.values(data)) {
      let dir = loc.path && new nsFile(loc.path);

      for (let addon of Object.values(loc.addons)) {
        let file;
        if (dir) {
          file = dir.clone();
          try {
            file.appendRelativePath(addon.path);
          } catch (e) {
            file = new nsFile(addon.path);
          }
        } else if (addon.path) {
          file = new nsFile(addon.path);
        }

        if (!file) {
          continue;
        }

        this.xpis.push(file);

        if (addon.enabled) {
          addon.type = addon.type || "extension";

          if (addon.type == "theme") {
            this.themes.push(file);
          } else {
            this.extensions.push(file);
          }
        }
      }
    }
  }

  hasItem(type, dir, id) {
    var path = dir.clone();
    path.append(id);

    var xpiPath = dir.clone();
    xpiPath.append(`${id}.xpi`);

    return this[type].some(file => {
      if (!file.exists()) {
        throw new Error(
          `Non-existent path found in addonStartup.json: ${file.path}`
        );
      }

      if (file.isDirectory()) {
        return file.equals(path);
      }
      if (file.isFile()) {
        return file.equals(xpiPath);
      }
      return false;
    });
  }

  hasTheme(dir, id) {
    return this.hasItem("themes", dir, id);
  }

  hasExtension(dir, id) {
    return this.hasItem("extensions", dir, id);
  }
}

var AddonTestUtils = {
  addonIntegrationService: null,
  addonsList: null,
  appInfo: null,
  addonStartup: null,
  collectedTelemetryEvents: [],
  testScope: null,
  testUnpacked: false,
  useRealCertChecks: false,
  usePrivilegedSignatures: true,
  overrideEntry: null,

  maybeInit(testScope) {
    if (this.testScope != testScope) {
      this.init(testScope);
    }
  },

  init(testScope, enableLogging = true) {
    if (this.testScope === testScope) {
      return;
    }
    this.testScope = testScope;

    // Get the profile directory for tests to use.
    this.profileDir = testScope.do_get_profile();

    this.profileExtensions = this.profileDir.clone();
    this.profileExtensions.append("extensions");

    this.addonStartup = this.profileDir.clone();
    this.addonStartup.append("addonStartup.json.lz4");

    // Register a temporary directory for the tests.
    this.tempDir = this.profileDir.clone();
    this.tempDir.append("temp");
    this.tempDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
    this.registerDirectory("TmpD", this.tempDir);

    // Create a replacement app directory for the tests.
    const appDirForAddons = this.profileDir.clone();
    appDirForAddons.append("appdir-addons");
    appDirForAddons.create(
      Ci.nsIFile.DIRECTORY_TYPE,
      FileUtils.PERMS_DIRECTORY
    );
    this.registerDirectory("XREAddonAppDir", appDirForAddons);

    // Enable more extensive EM logging.
    if (enableLogging) {
      Services.prefs.setBoolPref("extensions.logging.enabled", true);
    }

    // By default only load extensions from the profile install location
    Services.prefs.setIntPref(
      "extensions.enabledScopes",
      AddonManager.SCOPE_PROFILE
    );

    // By default don't disable add-ons from any scope
    Services.prefs.setIntPref("extensions.autoDisableScopes", 0);

    // And scan for changes at startup
    Services.prefs.setIntPref("extensions.startupScanScopes", 15);

    // By default, don't cache add-ons in AddonRepository.jsm
    Services.prefs.setBoolPref("extensions.getAddons.cache.enabled", false);

    // Point update checks to the local machine for fast failures
    Services.prefs.setCharPref(
      "extensions.update.url",
      "http://127.0.0.1/updateURL"
    );
    Services.prefs.setCharPref(
      "extensions.update.background.url",
      "http://127.0.0.1/updateBackgroundURL"
    );
    Services.prefs.setCharPref(
      "extensions.blocklist.url",
      "http://127.0.0.1/blocklistURL"
    );
    Services.prefs.setCharPref(
      "services.settings.server",
      "http://localhost/dummy-kinto/v1"
    );

    // By default ignore bundled add-ons
    Services.prefs.setBoolPref("extensions.installDistroAddons", false);

    // Ensure signature checks are enabled by default
    Services.prefs.setBoolPref("xpinstall.signatures.required", true);

    // Write out an empty blocklist.xml file to the profile to ensure nothing
    // is blocklisted by default
    var blockFile = OS.Path.join(this.profileDir.path, "blocklist.xml");

    var data =
      '<?xml version="1.0" encoding="UTF-8"?>\n' +
      '<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist">\n' +
      "</blocklist>\n";

    this.awaitPromise(
      OS.File.writeAtomic(blockFile, new TextEncoder().encode(data))
    );

    // Make sure that a given path does not exist
    function pathShouldntExist(file) {
      if (file.exists()) {
        throw new Error(
          `Test cleanup: path ${file.path} exists when it should not`
        );
      }
    }

    testScope.registerCleanupFunction(() => {
      this.cleanupTempXPIs();

      let ignoreEntries = new Set();
      {
        // FileTestUtils lazily creates a directory to hold the temporary files
        // it creates. If that directory exists, ignore it.
        let { value } = Object.getOwnPropertyDescriptor(
          FileTestUtils,
          "_globalTemporaryDirectory"
        );
        if (value) {
          ignoreEntries.add(value.leafName);
        }
      }

      // Check that the temporary directory is empty
      var entries = [];
      for (let { leafName } of this.iterDirectory(this.tempDir)) {
        if (!ignoreEntries.has(leafName)) {
          entries.push(leafName);
        }
      }
      if (entries.length) {
        throw new Error(
          `Found unexpected files in temporary directory: ${entries.join(", ")}`
        );
      }

      try {
        appDirForAddons.remove(true);
      } catch (ex) {
        testScope.info(`Got exception removing addon app dir: ${ex}`);
      }

      // ensure no leftover files in the system addon upgrade location
      let featuresDir = this.profileDir.clone();
      featuresDir.append("features");
      // upgrade directories will be in UUID folders under features/
      for (let dir of this.iterDirectory(featuresDir)) {
        dir.append("stage");
        pathShouldntExist(dir);
      }

      // ensure no leftover files in the user addon location
      let testDir = this.profileDir.clone();
      testDir.append("extensions");
      testDir.append("trash");
      pathShouldntExist(testDir);

      testDir.leafName = "staged";
      pathShouldntExist(testDir);

      return this.promiseShutdownManager();
    });
  },

  initMochitest(testScope) {
    if (this.testScope === testScope) {
      return;
    }
    this.testScope = testScope;

    this.profileDir = FileUtils.getDir("ProfD", []);

    this.profileExtensions = FileUtils.getDir("ProfD", ["extensions"]);

    this.tempDir = FileUtils.getDir("TmpD", []);
    this.tempDir.append("addons-mochitest");
    this.tempDir.createUnique(
      Ci.nsIFile.DIRECTORY_TYPE,
      FileUtils.PERMS_DIRECTORY
    );

    testScope.registerCleanupFunction(() => {
      // Defer testScope cleanup until the last cleanup function has run.
      testScope.registerCleanupFunction(() => {
        this.testScope = null;
      });
      this.cleanupTempXPIs();
      try {
        this.tempDir.remove(true);
      } catch (e) {
        Cu.reportError(e);
      }
    });
  },

  /**
   * Iterates over the entries in a given directory.
   *
   * Fails silently if the given directory does not exist.
   *
   * @param {nsIFile} dir
   *        Directory to iterate.
   */
  *iterDirectory(dir) {
    let dirEnum;
    try {
      dirEnum = dir.directoryEntries;
      let file;
      while ((file = dirEnum.nextFile)) {
        yield file;
      }
    } catch (e) {
      if (dir.exists()) {
        Cu.reportError(e);
      }
    } finally {
      if (dirEnum) {
        dirEnum.close();
      }
    }
  },

  /**
   * Creates a new HttpServer for testing, and begins listening on the
   * specified port. Automatically shuts down the server when the test
   * unit ends.
   *
   * @param {object} [options = {}]
   *        The options object.
   * @param {integer} [options.port = -1]
   *        The port to listen on. If omitted, listen on a random
   *        port. The latter is the preferred behavior.
   * @param {sequence<string>?} [options.hosts = null]
   *        A set of hosts to accept connections to. Support for this is
   *        implemented using a proxy filter.
   *
   * @returns {HttpServer}
   *        The HTTP server instance.
   */
  createHttpServer({ port = -1, hosts } = {}) {
    let server = new HttpServer();
    server.start(port);

    if (hosts) {
      hosts = new Set(hosts);
      const serverHost = "localhost";
      const serverPort = server.identity.primaryPort;

      for (let host of hosts) {
        server.identity.add("http", host, 80);
      }

      const proxyFilter = {
        proxyInfo: proxyService.newProxyInfo(
          "http",
          serverHost,
          serverPort,
          "",
          "",
          0,
          4096,
          null
        ),

        applyFilter(service, channel, defaultProxyInfo, callback) {
          if (hosts.has(channel.URI.host)) {
            callback.onProxyFilterResult(this.proxyInfo);
          } else {
            callback.onProxyFilterResult(defaultProxyInfo);
          }
        },
      };

      proxyService.registerChannelFilter(proxyFilter, 0);
      this.testScope.registerCleanupFunction(() => {
        proxyService.unregisterChannelFilter(proxyFilter);
      });
    }

    this.testScope.registerCleanupFunction(() => {
      return new Promise(resolve => {
        server.stop(resolve);
      });
    });

    return server;
  },

  registerJSON(server, path, obj) {
    server.registerPathHandler(path, (request, response) => {
      response.setHeader("content-type", "application/json", true);
      response.write(JSON.stringify(obj));
    });
  },

  info(msg) {
    // info() for mochitests, do_print for xpcshell.
    let print = this.testScope.info || this.testScope.do_print;
    print(msg);
  },

  cleanupTempXPIs() {
    for (let file of this.tempXPIs.splice(0)) {
      if (file.exists()) {
        try {
          Services.obs.notifyObservers(file, "flush-cache-entry");
          file.remove(false);
        } catch (e) {
          Cu.reportError(e);
        }
      }
    }
  },

  /**
   * Helper to spin the event loop until a promise resolves or rejects
   *
   * @param {Promise} promise
   *        The promise to wait on.
   * @returns {*} The promise's resolution value.
   * @throws The promise's rejection value, if it rejects.
   */
  awaitPromise(promise) {
    let done = false;
    let result;
    let error;
    promise
      .then(
        val => {
          result = val;
        },
        err => {
          error = err;
        }
      )
      .then(() => {
        done = true;
      });

    Services.tm.spinEventLoopUntil(() => done);

    if (error !== undefined) {
      throw error;
    }
    return result;
  },

  createAppInfo(ID, name, version, platformVersion = "1.0") {
    AppInfo.updateAppInfo({
      ID,
      name,
      version,
      platformVersion,
      crashReporter: true,
      extraProps: {
        browserTabsRemoteAutostart: false,
      },
    });
    this.appInfo = AppInfo.getAppInfo();
  },

  getManifestURI(file) {
    if (file.isDirectory()) {
      file.leafName = "manifest.json";
      if (file.exists()) {
        return NetUtil.newURI(file);
      }

      throw new Error("No manifest file present");
    }

    let zip = ZipReader(file);
    try {
      let uri = NetUtil.newURI(file);

      if (zip.hasEntry("manifest.json")) {
        return NetUtil.newURI(`jar:${uri.spec}!/manifest.json`);
      }

      throw new Error("No manifest file present");
    } finally {
      zip.close();
    }
  },

  getIDFromExtension(file) {
    return this.getIDFromManifest(this.getManifestURI(file));
  },

  async getIDFromManifest(manifestURI) {
    let body = await fetch(manifestURI.spec);
    let manifest = await body.json();
    try {
      return manifest.applications.gecko.id;
    } catch (e) {
      // IDs for WebExtensions are extracted from the certificate when
      // not present in the manifest, so just generate a random one.
      return uuidGen.generateUUID().number;
    }
  },

  overrideCertDB() {
    let verifyCert = async (file, result, cert, callback) => {
      if (
        result == Cr.NS_ERROR_SIGNED_JAR_NOT_SIGNED &&
        !this.useRealCertChecks &&
        callback.wrappedJSObject
      ) {
        // Bypassing XPConnect allows us to create a fake x509 certificate from JS
        callback = callback.wrappedJSObject;

        try {
          let id;
          try {
            let manifestURI = this.getManifestURI(file);
            id = await this.getIDFromManifest(manifestURI);
          } catch (err) {
            if (file.leafName.endsWith(".xpi")) {
              id = file.leafName.slice(0, -4);
            }
          }

          let fakeCert = { commonName: id };
          if (this.usePrivilegedSignatures) {
            let privileged =
              typeof this.usePrivilegedSignatures == "function"
                ? this.usePrivilegedSignatures(id)
                : this.usePrivilegedSignatures;
            if (privileged === "system") {
              fakeCert.organizationalUnit = "Mozilla Components";
            } else if (privileged) {
              fakeCert.organizationalUnit = "Mozilla Extensions";
            }
          }

          return [callback, Cr.NS_OK, fakeCert];
        } catch (e) {
          // If there is any error then just pass along the original results
        } finally {
          // Make sure to close the open zip file or it will be locked.
          if (file.isFile()) {
            Services.obs.notifyObservers(
              file,
              "flush-cache-entry",
              "cert-override"
            );
          }
        }
      }

      return [callback, result, cert];
    };

    let FakeCertDB = {
      init() {
        for (let property of Object.keys(
          this._genuine.QueryInterface(Ci.nsIX509CertDB)
        )) {
          if (property in this) {
            continue;
          }

          if (typeof this._genuine[property] == "function") {
            this[property] = this._genuine[property].bind(this._genuine);
          }
        }
      },

      openSignedAppFileAsync(root, file, callback) {
        // First try calling the real cert DB
        this._genuine.openSignedAppFileAsync(
          root,
          file,
          (result, zipReader, cert) => {
            verifyCert(file.clone(), result, cert, callback).then(
              ([callback, result, cert]) => {
                callback.openSignedAppFileFinished(result, zipReader, cert);
              }
            );
          }
        );
      },

      QueryInterface: ChromeUtils.generateQI([Ci.nsIX509CertDB]),
    };

    // Unregister the real database. This only works because the add-ons manager
    // hasn't started up and grabbed the certificate database yet.
    MockRegistrar.register(CERTDB_CONTRACTID, FakeCertDB);

    // Initialize the mock service.
    Cc[CERTDB_CONTRACTID].getService();
    FakeCertDB.init();
  },

  /**
   * Overrides the blocklist service, and returns the given blocklist
   * states for the given add-ons.
   *
   * @param {object|Map} addons
   *        A mapping of add-on IDs to their blocklist states.
   * @returns {MockBlocklist}
   *        A mock blocklist service, which should be unregistered when
   *        the test is complete.
   */
  overrideBlocklist(addons) {
    let mock = new MockBlocklist(addons);
    mock.register();
    return mock;
  },

  /**
   * Load the data from the specified files into the *real* blocklist providers.
   * Loads using loadBlocklistRawData, which will treat this as an update.
   *
   * @param {nsIFile} dir
   *        The directory in which the files live.
   * @param {string} prefix
   *        a prefix for the files which ought to be loaded.
   *        This method will suffix -extensions.json and -plugins.json
   *        to the prefix it is given, and attempt to load both.
   *        Insofar as either exists, their data will be dumped into
   *        the respective store, and the respective update handlers
   *        will be called.
   */
  async loadBlocklistData(dir, prefix) {
    let loadedData = {};
    for (let fileSuffix of ["extensions", "plugins"]) {
      const fileName = `${prefix}-${fileSuffix}.json`;
      let jsonStr = await OS.File.read(OS.Path.join(dir.path, fileName), {
        encoding: "UTF-8",
      }).catch(() => {});
      if (!jsonStr) {
        continue;
      }
      this.info(`Loaded ${fileName}`);

      loadedData[fileSuffix] = JSON.parse(jsonStr);
    }
    return this.loadBlocklistRawData(loadedData);
  },

  /**
   * Load the following data into the *real* blocklist providers.
   * While `overrideBlocklist` replaces the blocklist entirely with a mock
   * that returns dummy data, this method instead loads data into the actual
   * blocklist, fires update methods as would happen if this data came from
   * an actual blocklist update, etc.
   *
   * @param {object} data
   *        The data to load.
   */
  async loadBlocklistRawData(data) {
    const bsPass = ChromeUtils.import(
      "resource://gre/modules/Blocklist.jsm",
      null
    );
    const blocklistMapping = {
      extensions: bsPass.ExtensionBlocklistRS,
      plugins: bsPass.PluginBlocklistRS,
    };

    for (const [dataProp, blocklistObj] of Object.entries(blocklistMapping)) {
      let newData = data[dataProp];
      if (!newData) {
        continue;
      }
      if (!Array.isArray(newData)) {
        throw new Error(
          "Expected an array of new items to put in the " +
            dataProp +
            " blocklist!"
        );
      }
      for (let item of newData) {
        if (!item.id) {
          item.id = uuidGen.generateUUID().number.slice(1, -1);
        }
        if (!item.last_modified) {
          item.last_modified = Date.now();
        }
      }
      blocklistObj.ensureInitialized();
      let collection = await blocklistObj._client.openCollection();
      await collection.clear();
      await collection.loadDump(newData);
      // We manually call _onUpdate... which is evil, but at the moment kinto doesn't have
      // a better abstraction unless you want to mock your own http server to do the update.
      await blocklistObj._onUpdate();
    }
  },

  /**
   * Starts up the add-on manager as if it was started by the application.
   *
   * @param {string} [newVersion]
   *        If provided, the application version is changed to this string
   *        before the AddonManager is started.
   */
  async promiseStartupManager(newVersion) {
    if (this.addonIntegrationService) {
      throw new Error(
        "Attempting to startup manager that was already started."
      );
    }

    if (newVersion) {
      this.appInfo.version = newVersion;
      if (Cu.isModuleLoaded("resource://gre/modules/Blocklist.jsm")) {
        let bsPassBlocklist = ChromeUtils.import(
          "resource://gre/modules/Blocklist.jsm",
          null
        );
        Object.defineProperty(bsPassBlocklist, "gAppVersion", {
          value: newVersion,
        });
      }
    }
    // AddonListeners are removed when the addonManager is shutdown,
    // ensure the Extension observer is added.  We call uninit in
    // promiseShutdown to allow re-initialization.
    UninstallObserver.init();

    let XPIScope = ChromeUtils.import(
      "resource://gre/modules/addons/XPIProvider.jsm",
      null
    );
    XPIScope.AsyncShutdown = MockAsyncShutdown;

    XPIScope.XPIInternal.BootstrapScope.prototype._beforeCallBootstrapMethod = (
      method,
      params,
      reason
    ) => {
      try {
        this.emit("bootstrap-method", { method, params, reason });
      } catch (e) {
        try {
          this.testScope.do_throw(e);
        } catch (e) {
          // Le sigh.
        }
      }
    };

    this.addonIntegrationService = Cc[
      "@mozilla.org/addons/integration;1"
    ].getService(Ci.nsIObserver);

    this.addonIntegrationService.observe(null, "addons-startup", null);

    this.emit("addon-manager-started");

    await Promise.all(XPIScope.XPIProvider.startupPromises);

    // Load the add-ons list as it was after extension registration
    await this.loadAddonsList(true);

    // Wait for all add-ons to finish starting up before resolving.
    const { XPIProvider } = ChromeUtils.import(
      "resource://gre/modules/addons/XPIProvider.jsm"
    );
    await Promise.all(
      Array.from(
        XPIProvider.activeAddons.values(),
        addon => addon.startupPromise
      )
    );
  },

  async promiseShutdownManager(clearOverrides = true) {
    if (!this.addonIntegrationService) {
      return false;
    }

    if (this.overrideEntry && clearOverrides) {
      this.overrideEntry.destruct();
      this.overrideEntry = null;
    }

    Services.obs.notifyObservers(null, "quit-application-granted");
    await MockAsyncShutdown.quitApplicationGranted.trigger();
    await MockAsyncShutdown.profileBeforeChange.trigger();
    await MockAsyncShutdown.profileChangeTeardown.trigger();

    this.emit("addon-manager-shutdown");

    this.addonIntegrationService = null;

    // Load the add-ons list as it was after application shutdown
    await this.loadAddonsList();

    // Flush the jar cache entries for each bootstrapped XPI so that
    // we don't run into file locking issues on Windows.
    for (let file of this.addonsList.xpis) {
      Services.obs.notifyObservers(file, "flush-cache-entry");
    }

    // Clear any crash report annotations
    this.appInfo.annotations = {};

    // Force the XPIProvider provider to reload to better
    // simulate real-world usage.
    let XPIscope = ChromeUtils.import(
      "resource://gre/modules/addons/XPIProvider.jsm",
      null
    );
    // This would be cleaner if I could get it as the rejection reason from
    // the AddonManagerInternal.shutdown() promise
    let shutdownError = XPIscope.XPIDatabase._saveError;

    AddonManagerPrivate.unregisterProvider(XPIscope.XPIProvider);
    Cu.unload("resource://gre/modules/addons/XPIProvider.jsm");
    Cu.unload("resource://gre/modules/addons/XPIDatabase.jsm");
    Cu.unload("resource://gre/modules/addons/XPIInstall.jsm");

    let ExtensionScope = ChromeUtils.import(
      "resource://gre/modules/Extension.jsm",
      null
    );
    UninstallObserver.uninit();
    ChromeUtils.defineModuleGetter(
      ExtensionScope,
      "XPIProvider",
      "resource://gre/modules/addons/XPIProvider.jsm"
    );

    if (shutdownError) {
      throw shutdownError;
    }

    return true;
  },

  /**
   * Asynchronously restart the AddonManager.  If newVersion is provided,
   * simulate an application upgrade (or downgrade) where the version
   * is changed to newVersion when re-started.
   *
   * @param {string} [newVersion]
   *        If provided, the application version is changed to this string
   *        after the AddonManager is shut down, before it is re-started.
   */
  async promiseRestartManager(newVersion) {
    await this.promiseShutdownManager(false);
    await this.promiseStartupManager(newVersion);
  },

  async loadAddonsList(flush = false) {
    if (flush) {
      let XPIScope = ChromeUtils.import(
        "resource://gre/modules/addons/XPIProvider.jsm",
        null
      );
      XPIScope.XPIStates.save();
      await XPIScope.XPIStates._jsonFile._save();
    }

    this.addonsList = new AddonsList(this.addonStartup);
  },

  /**
   * Recursively create all directories up to and including the given
   * path, if they do not exist.
   *
   * @param {string} path The path of the directory to create.
   * @returns {Promise} Resolves when all directories have been created.
   */
  recursiveMakeDir(path) {
    let paths = [];
    for (
      let lastPath;
      path != lastPath;
      lastPath = path, path = OS.Path.dirname(path)
    ) {
      paths.push(path);
    }

    return Promise.all(
      paths
        .reverse()
        .map(path =>
          OS.File.makeDir(path, { ignoreExisting: true }).catch(() => {})
        )
    );
  },

  /**
   * Writes the given data to a file in the given zip file.
   *
   * @param {string|nsIFile} zipFile
   *        The zip file to write to.
   * @param {Object} files
   *        An object containing filenames and the data to write to the
   *        corresponding paths in the zip file.
   * @param {integer} [flags = 0]
   *        Additional flags to open the file with.
   */
  writeFilesToZip(zipFile, files, flags = 0) {
    if (typeof zipFile == "string") {
      zipFile = nsFile(zipFile);
    }

    var zipW = ZipWriter(
      zipFile,
      FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | flags
    );

    for (let [path, data] of Object.entries(files)) {
      if (
        typeof data === "object" &&
        ChromeUtils.getClassName(data) === "Object"
      ) {
        data = JSON.stringify(data);
      }
      if (!(data instanceof ArrayBuffer)) {
        data = new TextEncoder("utf-8").encode(data).buffer;
      }

      let stream = ArrayBufferInputStream(data, 0, data.byteLength);

      // Note these files are being created in the XPI archive with date "0" which is 1970-01-01.
      zipW.addEntryStream(
        path,
        0,
        Ci.nsIZipWriter.COMPRESSION_NONE,
        stream,
        false
      );
    }

    zipW.close();
  },

  async promiseWriteFilesToZip(zip, files, flags) {
    await this.recursiveMakeDir(OS.Path.dirname(zip));

    this.writeFilesToZip(zip, files, flags);

    return Promise.resolve(nsFile(zip));
  },

  async promiseWriteFilesToDir(dir, files) {
    await this.recursiveMakeDir(dir);

    for (let [path, data] of Object.entries(files)) {
      path = path.split("/");
      let leafName = path.pop();

      // Create parent directories, if necessary.
      let dirPath = dir;
      for (let subDir of path) {
        dirPath = OS.Path.join(dirPath, subDir);
        await OS.File.makeDir(dirPath, { ignoreExisting: true });
      }

      if (
        typeof data == "object" &&
        ChromeUtils.getClassName(data) == "Object"
      ) {
        data = JSON.stringify(data);
      }
      if (typeof data == "string") {
        data = new TextEncoder("utf-8").encode(data);
      }

      await OS.File.writeAtomic(OS.Path.join(dirPath, leafName), data);
    }

    return nsFile(dir);
  },

  promiseWriteFilesToExtension(dir, id, files, unpacked = this.testUnpacked) {
    if (unpacked) {
      let path = OS.Path.join(dir, id);

      return this.promiseWriteFilesToDir(path, files);
    }

    let xpi = OS.Path.join(dir, `${id}.xpi`);

    return this.promiseWriteFilesToZip(xpi, files);
  },

  tempXPIs: [],

  allocTempXPIFile() {
    let file = this.tempDir.clone();
    let uuid = uuidGen.generateUUID().number.slice(1, -1);
    file.append(`${uuid}.xpi`);

    this.tempXPIs.push(file);

    return file;
  },

  /**
   * Creates an XPI file for some manifest data in the temporary directory and
   * returns the nsIFile for it. The file will be deleted when the test completes.
   *
   * @param {object} files
   *          The object holding data about the add-on
   * @return {nsIFile} A file pointing to the created XPI file
   */
  createTempXPIFile(files) {
    let file = this.allocTempXPIFile();
    this.writeFilesToZip(file.path, files);
    return file;
  },

  /**
   * Creates an XPI file for some WebExtension data in the temporary directory and
   * returns the nsIFile for it. The file will be deleted when the test completes.
   *
   * @param {Object} data
   *        The object holding data about the add-on, as expected by
   *        |ExtensionTestCommon.generateXPI|.
   * @return {nsIFile} A file pointing to the created XPI file
   */
  createTempWebExtensionFile(data) {
    let file = ExtensionTestCommon.generateXPI(data);
    this.tempXPIs.push(file);
    return file;
  },

  /**
   * Creates an XPI with the given files and installs it.
   *
   * @param {object} files
   *        A files object as would be passed to {@see #createTempXPI}.
   * @returns {Promise}
   *        A promise which resolves when the add-on is installed.
   */
  promiseInstallXPI(files) {
    return this.promiseInstallFile(this.createTempXPIFile(files));
  },

  /**
   * Creates an extension proxy file.
   * See: https://developer.mozilla.org/en-US/Add-ons/Setting_up_extension_development_environment#Firefox_extension_proxy_file
   *
   * @param {nsIFile} dir
   *        The directory to add the proxy file to.
   * @param {nsIFile} addon
   *        An nsIFile for the add-on file that this is a proxy file for.
   * @param {string} id
   *        A string to use for the add-on ID.
   * @returns {Promise} Resolves when the file has been created.
   */
  promiseWriteProxyFileToDir(dir, addon, id) {
    let files = {
      [id]: addon.path,
    };

    return this.promiseWriteFilesToDir(dir.path, files);
  },

  /**
   * Manually installs an XPI file into an install location by either copying the
   * XPI there or extracting it depending on whether unpacking is being tested
   * or not.
   *
   * @param {nsIFile} xpiFile
   *        The XPI file to install.
   * @param {nsIFile} [installLocation = this.profileExtensions]
   *        The install location (an nsIFile) to install into.
   * @param {string} [id]
   *        The ID to install as.
   * @param {boolean} [unpacked = this.testUnpacked]
   *        If true, install as an unpacked directory, rather than a
   *        packed XPI.
   * @returns {nsIFile}
   *        A file pointing to the installed location of the XPI file or
   *        unpacked directory.
   */
  async manuallyInstall(
    xpiFile,
    installLocation = this.profileExtensions,
    id = null,
    unpacked = this.testUnpacked
  ) {
    if (id == null) {
      id = await this.getIDFromExtension(xpiFile);
    }

    if (unpacked) {
      let dir = installLocation.clone();
      dir.append(id);
      dir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);

      let zip = ZipReader(xpiFile);
      for (let entry of zip.findEntries(null)) {
        let target = dir.clone();
        for (let part of entry.split("/")) {
          target.append(part);
        }
        if (!target.parent.exists()) {
          target.parent.create(
            Ci.nsIFile.DIRECTORY_TYPE,
            FileUtils.PERMS_DIRECTORY
          );
        }
        try {
          zip.extract(entry, target);
        } catch (e) {
          if (
            e.result != Cr.NS_ERROR_FILE_DIR_NOT_EMPTY &&
            !(target.exists() && target.isDirectory())
          ) {
            throw e;
          }
        }
        target.permissions |= FileUtils.PERMS_FILE;
      }
      zip.close();

      return dir;
    }

    let target = installLocation.clone();
    target.append(`${id}.xpi`);
    xpiFile.copyTo(target.parent, target.leafName);
    return target;
  },

  /**
   * Manually uninstalls an add-on by removing its files from the install
   * location.
   *
   * @param {nsIFile} installLocation
   *        The nsIFile of the install location to remove from.
   * @param {string} id
   *        The ID of the add-on to remove.
   * @param {boolean} [unpacked = this.testUnpacked]
   *        If true, uninstall an unpacked directory, rather than a
   *        packed XPI.
   */
  manuallyUninstall(installLocation, id, unpacked = this.testUnpacked) {
    let file = this.getFileForAddon(installLocation, id, unpacked);

    // In reality because the app is restarted a flush isn't necessary for XPIs
    // removed outside the app, but for testing we must flush manually.
    if (file.isFile()) {
      Services.obs.notifyObservers(file, "flush-cache-entry");
    }

    file.remove(true);
  },

  /**
   * Gets the nsIFile for where an add-on is installed. It may point to a file or
   * a directory depending on whether add-ons are being installed unpacked or not.
   *
   * @param {nsIFile} dir
   *         The nsIFile for the install location
   * @param {string} id
   *        The ID of the add-on
   * @param {boolean} [unpacked = this.testUnpacked]
   *        If true, return the path to an unpacked directory, rather than a
   *        packed XPI.
   * @returns {nsIFile}
   *        A file pointing to the XPI file or unpacked directory where
   *        the add-on should be installed.
   */
  getFileForAddon(dir, id, unpacked = this.testUnpacked) {
    dir = dir.clone();
    if (unpacked) {
      dir.append(id);
    } else {
      dir.append(`${id}.xpi`);
    }
    return dir;
  },

  /**
   * Sets the last modified time of the extension, usually to trigger an update
   * of its metadata.
   *
   * @param {nsIFile} ext A file pointing to either the packed extension or its unpacked directory.
   * @param {number} time The time to which we set the lastModifiedTime of the extension
   *
   * @deprecated Please use promiseSetExtensionModifiedTime instead
   */
  setExtensionModifiedTime(ext, time) {
    ext.lastModifiedTime = time;
    if (ext.isDirectory()) {
      for (let file of this.iterDirectory(ext)) {
        this.setExtensionModifiedTime(file, time);
      }
    }
  },

  async promiseSetExtensionModifiedTime(path, time) {
    await OS.File.setDates(path, time, time);

    let iterator = new OS.File.DirectoryIterator(path);
    try {
      await iterator.forEach(entry => {
        return this.promiseSetExtensionModifiedTime(entry.path, time);
      });
    } catch (ex) {
      if (ex instanceof OS.File.Error) {
        return;
      }
      throw ex;
    } finally {
      iterator.close().catch(() => {});
    }
  },

  registerDirectory(key, dir) {
    var dirProvider = {
      getFile(prop, persistent) {
        persistent.value = false;
        if (prop == key) {
          return dir.clone();
        }
        return null;
      },

      QueryInterface: ChromeUtils.generateQI([Ci.nsIDirectoryServiceProvider]),
    };
    Services.dirsvc.registerProvider(dirProvider);

    try {
      Services.dirsvc.undefine(key);
    } catch (e) {
      // This throws if the key is not already registered, but that
      // doesn't matter.
      if (e.result != Cr.NS_ERROR_FAILURE) {
        throw e;
      }
    }
  },

  /**
   * Returns a promise that resolves when the given add-on event is fired. The
   * resolved value is an array of arguments passed for the event.
   *
   * @param {string} event
   *        The name of the AddonListener event handler method for which
   *        an event is expected.
   * @returns {Promise<Array>}
   *        Resolves to an array containing the event handler's
   *        arguments the first time it is called.
   */
  promiseAddonEvent(event) {
    return new Promise(resolve => {
      let listener = {
        [event](...args) {
          AddonManager.removeAddonListener(listener);
          resolve(args);
        },
      };

      AddonManager.addAddonListener(listener);
    });
  },

  promiseInstallEvent(event) {
    return new Promise(resolve => {
      let listener = {
        [event](...args) {
          AddonManager.removeInstallListener(listener);
          resolve(args);
        },
      };

      AddonManager.addInstallListener(listener);
    });
  },

  /**
   * A helper method to install AddonInstall and wait for completion.
   *
   * @param {AddonInstall} install
   *        The add-on to install.
   * @returns {Promise<AddonInstall>}
   *        Resolves when the install completes, either successfully or
   *        in failure.
   */
  promiseCompleteInstall(install) {
    let listener;
    return new Promise(resolve => {
      listener = {
        onDownloadFailed: resolve,
        onDownloadCancelled: resolve,
        onInstallFailed: resolve,
        onInstallCancelled: resolve,
        onInstallEnded: resolve,
        onInstallPostponed: resolve,
      };

      install.addListener(listener);
      install.install();
    }).then(() => {
      install.removeListener(listener);
      return install;
    });
  },

  /**
   * A helper method to install a file.
   *
   * @param {nsIFile} file
   *        The file to install
   * @param {boolean} [ignoreIncompatible = false]
   *        Optional parameter to ignore add-ons that are incompatible
   *        with the application
   * @param {Object} [installTelemetryInfo = undefined]
   *        Optional parameter to set the install telemetry info for the
   *        installed addon
   * @returns {Promise}
   *        Resolves when the install has completed.
   */
  async promiseInstallFile(
    file,
    ignoreIncompatible = false,
    installTelemetryInfo
  ) {
    let install = await AddonManager.getInstallForFile(
      file,
      null,
      installTelemetryInfo
    );
    if (!install) {
      throw new Error(`No AddonInstall created for ${file.path}`);
    }

    if (install.state != AddonManager.STATE_DOWNLOADED) {
      throw new Error(
        `Expected file to be downloaded for install of ${file.path}`
      );
    }

    if (ignoreIncompatible && install.addon.appDisabled) {
      return null;
    }

    await install.install();
    return install;
  },

  /**
   * A helper method to install an array of files.
   *
   * @param {Iterable<nsIFile>} files
   *        The files to install
   * @param {boolean} [ignoreIncompatible = false]
   *        Optional parameter to ignore add-ons that are incompatible
   *        with the application
   * @returns {Promise}
   *        Resolves when the installs have completed.
   */
  promiseInstallAllFiles(files, ignoreIncompatible = false) {
    return Promise.all(
      Array.from(files, file =>
        this.promiseInstallFile(file, ignoreIncompatible)
      )
    );
  },

  promiseCompleteAllInstalls(installs) {
    return Promise.all(Array.from(installs, this.promiseCompleteInstall));
  },

  /**
   * @property {number} updateReason
   *        The default update reason for {@see promiseFindAddonUpdates}
   *        calls. May be overwritten by tests which primarily check for
   *        updates with a particular reason.
   */
  updateReason: AddonManager.UPDATE_WHEN_PERIODIC_UPDATE,

  /**
   * Returns a promise that will be resolved when an add-on update check is
   * complete. The value resolved will be an AddonInstall if a new version was
   * found.
   *
   * @param {object} addon The add-on to find updates for.
   * @param {integer} reason The type of update to find.
   * @param {Array} args Additional args to pass to `checkUpdates` after
   *                     the update reason.
   * @return {Promise<object>} an object containing information about the update.
   */
  promiseFindAddonUpdates(
    addon,
    reason = AddonTestUtils.updateReason,
    ...args
  ) {
    let equal = this.testScope.equal;
    return new Promise((resolve, reject) => {
      let result = {};
      addon.findUpdates(
        {
          onNoCompatibilityUpdateAvailable(addon2) {
            if ("compatibilityUpdate" in result) {
              throw new Error("Saw multiple compatibility update events");
            }
            equal(addon, addon2, "onNoCompatibilityUpdateAvailable");
            result.compatibilityUpdate = false;
          },

          onCompatibilityUpdateAvailable(addon2) {
            if ("compatibilityUpdate" in result) {
              throw new Error("Saw multiple compatibility update events");
            }
            equal(addon, addon2, "onCompatibilityUpdateAvailable");
            result.compatibilityUpdate = true;
          },

          onNoUpdateAvailable(addon2) {
            if ("updateAvailable" in result) {
              throw new Error("Saw multiple update available events");
            }
            equal(addon, addon2, "onNoUpdateAvailable");
            result.updateAvailable = false;
          },

          onUpdateAvailable(addon2, install) {
            if ("updateAvailable" in result) {
              throw new Error("Saw multiple update available events");
            }
            equal(addon, addon2, "onUpdateAvailable");
            result.updateAvailable = install;
          },

          onUpdateFinished(addon2, error) {
            equal(addon, addon2, "onUpdateFinished");
            if (error == AddonManager.UPDATE_STATUS_NO_ERROR) {
              resolve(result);
            } else {
              result.error = error;
              reject(result);
            }
          },
        },
        reason,
        ...args
      );
    });
  },

  /**
   * Monitors console output for the duration of a task, and returns a promise
   * which resolves to a tuple containing a list of all console messages
   * generated during the task's execution, and the result of the task itself.
   *
   * @param {function} task
   *        The task to run while monitoring console output. May be
   *        an async function, or an ordinary function which returns a promose.
   * @return {Promise<[Array<nsIConsoleMessage>, *]>}
   *        Resolves to an object containing a `messages` property, with
   *        the array of console messages emitted during the execution
   *        of the task, and a `result` property, containing the task's
   *        return value.
   */
  async promiseConsoleOutput(task) {
    const DONE = "=== xpcshell test console listener done ===";

    let listener,
      messages = [];
    let awaitListener = new Promise(resolve => {
      listener = msg => {
        if (msg == DONE) {
          resolve();
        } else {
          msg instanceof Ci.nsIScriptError;
          messages.push(msg);
        }
      };
    });

    Services.console.registerListener(listener);
    try {
      let result = await task();

      Services.console.logStringMessage(DONE);
      await awaitListener;

      return { messages, result };
    } finally {
      Services.console.unregisterListener(listener);
    }
  },

  /**
   * An object describing an expected or forbidden console message. Each
   * property in the object corresponds to a property with the same name
   * in a console message. If the value in the pattern object is a
   * regular expression, it must match the value of the corresponding
   * console message property. If it is any other value, it must be
   * strictly equal to the correspondng console message property.
   *
   * @typedef {object} ConsoleMessagePattern
   */

  /**
   * Checks the list of messages returned from `promiseConsoleOutput`
   * against the given set of expected messages.
   *
   * This is roughly equivalent to the expected and forbidden message
   * matching functionality of SimpleTest.monitorConsole.
   *
   * @param {Array<object>} messages
   *        The array of console messages to match.
   * @param {object} options
   *        Options describing how to perform the match.
   * @param {Array<ConsoleMessagePattern>} [options.expected = []]
   *        An array of messages which must appear in `messages`. The
   *        matching messages in the `messages` array must appear in the
   *        same order as the patterns in the `expected` array.
   * @param {Array<ConsoleMessagePattern>} [options.forbidden = []]
   *        An array of messages which must not appear in the `messages`
   *        array.
   * @param {bool} [options.forbidUnexpected = false]
   *        If true, the `messages` array must not contain any messages
   *        which are not matched by the given `expected` patterns.
   */
  checkMessages(
    messages,
    { expected = [], forbidden = [], forbidUnexpected = false }
  ) {
    function msgMatches(msg, expectedMsg) {
      for (let [prop, pattern] of Object.entries(expectedMsg)) {
        if (isRegExp(pattern) && typeof msg[prop] === "string") {
          if (!pattern.test(msg[prop])) {
            return false;
          }
        } else if (msg[prop] !== pattern) {
          return false;
        }
      }
      return true;
    }

    let i = 0;
    for (let msg of messages) {
      if (forbidden.some(pat => msgMatches(msg, pat))) {
        this.testScope.ok(false, `Got forbidden console message: ${msg}`);
        continue;
      }

      if (i < expected.length && msgMatches(msg, expected[i])) {
        this.info(`Matched expected console message: ${msg}`);
        i++;
      } else if (forbidUnexpected) {
        this.testScope.ok(false, `Got unexpected console message: ${msg}`);
      }
    }
    for (let pat of expected.slice(i)) {
      this.testScope.ok(
        false,
        `Did not get expected console message: ${uneval(pat)}`
      );
    }
  },

  /**
   * Helper to wait for a webextension to completely start
   *
   * @param {string} [id]
   *        An optional extension id to look for.
   *
   * @returns {Promise<Extension>}
   *           A promise that resolves with the extension, once it is started.
   */
  promiseWebExtensionStartup(id) {
    return new Promise(resolve => {
      Management.on("ready", function listener(event, extension) {
        if (!id || extension.id == id) {
          Management.off("ready", listener);
          resolve(extension);
        }
      });
    });
  },

  /**
   * Wait until an extension with a search provider has been loaded.
   * This should be called after the extension has started, but before shutdown.
   *
   * @param {object} extension
   *        The return value of ExtensionTestUtils.loadExtension.
   *        For browser tests, see mochitest/tests/SimpleTest/ExtensionTestUtils.js
   *        For xpcshell tests, see toolkit/components/extensions/ExtensionXPCShellUtils.jsm
   * @param {object} [options]
   *        Optional options.
   * @param {boolean} [options.expectPending = false]
   *        Whether to expect the search provider to still be starting up.
   */
  async waitForSearchProviderStartup(
    extension,
    { expectPending = false } = {}
  ) {
    // In xpcshell tests, equal/ok are defined in the global scope.
    let { equal, ok } = this.testScope;
    if (!equal || !ok) {
      // In mochitests, these are available via Assert.jsm.
      let { Assert } = this.testScope;
      equal = Assert.equal.bind(Assert);
      ok = Assert.ok.bind(Assert);
    }

    equal(
      extension.state,
      "running",
      "Search provider extension should be running"
    );
    ok(extension.id, "Extension ID of search provider should be set");

    // The map of promises from browser/components/extensions/parent/ext-chrome-settings-overrides.js
    let { pendingSearchSetupTasks } = Management.global;
    let searchStartupPromise = pendingSearchSetupTasks.get(extension.id);
    if (expectPending) {
      ok(
        searchStartupPromise,
        "Search provider registration should be in progress"
      );
    }
    return searchStartupPromise;
  },

  /**
   * Initializes the URLPreloader, which is required in order to load
   * built_in_addons.json. This has the side-effect of setting
   * preferences which flip Cu.isInAutomation to true.
   */
  initializeURLPreloader() {
    Services.prefs.setBoolPref(PREF_DISABLE_SECURITY, true);
    aomStartup.initializeURLPreloader();
  },

  /**
   * Override chrome URL for specifying allowed built-in add-ons.
   *
   * @param {object} data - An object specifying which add-on IDs are permitted
   *                        to load, for instance: { "system": ["id1", "..."] }
   */
  async overrideBuiltIns(data) {
    // We need to set this in order load the URL preloader service, which
    // is only possible when running in automation.
    let prevPrefVal = Services.prefs.getBoolPref(PREF_DISABLE_SECURITY, false);
    this.initializeURLPreloader();

    let file = this.tempDir.clone();
    file.append("override.txt");
    this.tempXPIs.push(file);

    let manifest = Services.io.newFileURI(file);
    await OS.File.writeAtomic(
      file.path,
      new TextEncoder().encode(JSON.stringify(data))
    );
    this.overrideEntry = aomStartup.registerChrome(manifest, [
      [
        "override",
        "chrome://browser/content/built_in_addons.json",
        Services.io.newFileURI(file).spec,
      ],
    ]);
    Services.prefs.setBoolPref(PREF_DISABLE_SECURITY, prevPrefVal);
  },

  // AMTelemetry events helpers.

  /**
   * Redefine AMTelemetry.recordEvent to collect the recorded telemetry events and
   * ensure that there are no unexamined events after the test file is exiting.
   */
  hookAMTelemetryEvents() {
    let originalRecordEvent = AMTelemetry.recordEvent;
    AMTelemetry.recordEvent = event => {
      this.collectedTelemetryEvents.push(event);
    };
    this.testScope.registerCleanupFunction(() => {
      this.testScope.Assert.deepEqual(
        [],
        this.collectedTelemetryEvents,
        "No unexamined telemetry events after test is finished"
      );
      AMTelemetry.recordEvent = originalRecordEvent;
    });
  },

  /**
   * Retrive any AMTelemetry event collected and empty the array of the collected events.
   *
   * @returns {Array<Object>}
   *          The array of the collected telemetry data.
   */
  getAMTelemetryEvents() {
    let events = this.collectedTelemetryEvents;
    this.collectedTelemetryEvents = [];
    return events;
  },
};

for (let [key, val] of Object.entries(AddonTestUtils)) {
  if (typeof val == "function") {
    AddonTestUtils[key] = val.bind(AddonTestUtils);
  }
}

EventEmitter.decorate(AddonTestUtils);