Bug 1530961 - Move waitForSearchNotification from head_search.js to SearchTestUtils.jsm. r=adw
authorMark Banner <standard8@mozilla.com>
Thu, 07 Mar 2019 12:46:28 +0000
changeset 462883 a5c70252fc387405156d12c2dd8e8e80c1daa8d0
parent 462882 8e01745bb65d8856b6ebbd8360e4fbad50f8a80b
child 462884 3815b3ac18232c4a827e2e7d2ad990704ea797e3
push id79892
push usermbanner@mozilla.com
push dateThu, 07 Mar 2019 12:50:42 +0000
treeherderautoland@3815b3ac1823 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersadw
bugs1530961
milestone67.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1530961 - Move waitForSearchNotification from head_search.js to SearchTestUtils.jsm. r=adw Differential Revision: https://phabricator.services.mozilla.com/D22352
toolkit/components/search/tests/SearchTestUtils.jsm
toolkit/components/search/tests/xpcshell/head_search.js
toolkit/components/search/tests/xpcshell/test_geodefaults.js
toolkit/components/search/tests/xpcshell/test_list_json_locale.js
toolkit/components/search/tests/xpcshell/test_location_timeout.js
toolkit/components/search/tests/xpcshell/test_location_timeout_xhr.js
toolkit/components/search/tests/xpcshell/test_reloadEngines.js
toolkit/components/search/tests/xpcshell/test_require_engines_in_cache.js
--- a/toolkit/components/search/tests/SearchTestUtils.jsm
+++ b/toolkit/components/search/tests/SearchTestUtils.jsm
@@ -26,9 +26,34 @@ var SearchTestUtils = Object.freeze({
    * @returns {Promise} Returns a promise that is resolved with the new engine
    *                    or rejected if it fails.
    */
   async promiseNewSearchEngine(url) {
     let engine = await Services.search.addEngine(url, "", false);
     gTestGlobals.registerCleanupFunction(async () => Services.search.removeEngine(engine));
     return engine;
   },
+
+  /**
+   * Returns a promise that is resolved when an observer notification from the
+   * search service fires with the specified data.
+   *
+   * @param {*} expectedData
+   *        The value the observer notification sends that causes us to resolve
+   *        the promise.
+   * @param {string} topic
+   *        The notification topic to observe. Defaults to 'browser-search-service'.
+   * @returns {Promise}
+   *        Returns a promise that is resolved with the subject of the
+   *        topic once the topic with the data has been observed.
+   */
+  promiseSearchNotification(expectedData, topic = "browser-search-service") {
+    return new Promise(resolve => {
+      Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
+        if (aData != expectedData)
+          return;
+
+        Services.obs.removeObserver(observer, topic);
+        resolve(aSubject);
+      }, topic);
+    });
+  },
 });
--- a/toolkit/components/search/tests/xpcshell/head_search.js
+++ b/toolkit/components/search/tests/xpcshell/head_search.js
@@ -1,24 +1,28 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et: */
 
-var {FileUtils} = ChromeUtils.import("resource://gre/modules/FileUtils.jsm");
+const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+  FileUtils: "resource://gre/modules/FileUtils.jsm",
+  NetUtil: "resource://gre/modules/NetUtil.jsm",
+  SearchTestUtils: "resource://testing-common/SearchTestUtils.jsm",
+  Services: "resource://gre/modules/Services.jsm",
+  setTimeout: "resource://gre/modules/Timer.jsm",
+  TestUtils: "resource://testing-common/TestUtils.jsm",
+});
+
 var {OS, require} = ChromeUtils.import("resource://gre/modules/osfile.jsm");
-var {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
-var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
-var {setTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm");
-var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 var {getAppInfo, newAppInfo, updateAppInfo} = ChromeUtils.import("resource://testing-common/AppInfo.jsm");
 var {HTTP_400, HTTP_401, HTTP_402, HTTP_403, HTTP_404, HTTP_405, HTTP_406, HTTP_407,
      HTTP_408, HTTP_409, HTTP_410, HTTP_411, HTTP_412, HTTP_413, HTTP_414, HTTP_415,
      HTTP_417, HTTP_500, HTTP_501, HTTP_502, HTTP_503, HTTP_504, HTTP_505, HttpError,
      HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js");
-ChromeUtils.defineModuleGetter(this, "TestUtils",
-                               "resource://testing-common/TestUtils.jsm");
 
 const BROWSER_SEARCH_PREF = "browser.search.";
 const PREF_SEARCH_URL = "geoSpecificDefaults.url";
 const NS_APP_SEARCH_DIR = "SrchPlugns";
 
 const MODE_RDONLY = FileUtils.MODE_RDONLY;
 const MODE_WRONLY = FileUtils.MODE_WRONLY;
 const MODE_CREATE = FileUtils.MODE_CREATE;
@@ -269,17 +273,17 @@ function getDefaultEngineList(isUS) {
   return visibleDefaultEngines;
 }
 
 /**
  * Waits for the cache file to be saved.
  * @return {Promise} Resolved when the cache file is saved.
  */
 function promiseAfterCache() {
-  return waitForSearchNotification("write-cache-to-disk-complete");
+  return SearchTestUtils.promiseSearchNotification("write-cache-to-disk-complete");
 }
 
 function parseJsonFromStream(aInputStream) {
   let bytes = NetUtil.readInputStream(aInputStream, aInputStream.available());
   return JSON.parse((new TextDecoder()).decode(bytes));
 }
 
 /**
@@ -485,47 +489,25 @@ var addTestEngines = async function(aIte
  */
 function installTestEngine() {
   useHttpServer();
   return addTestEngines([
     { name: kTestEngineName, xmlFileName: "engine.xml" },
   ]);
 }
 
-/**
- * Returns a promise that is resolved when an observer notification from the
- * search service fires with the specified data.
- *
- * @param expectedData
- *        The value the observer notification sends that causes us to resolve
- *        the promise.
- * @param expectedData
- *        The notification topic to observe. Defaults to 'browser-search-service'.
- */
-function waitForSearchNotification(expectedData, topic = "browser-search-service") {
-  return new Promise(resolve => {
-    Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
-      if (aData != expectedData)
-        return;
-
-      Services.obs.removeObserver(observer, topic);
-      resolve(aSubject);
-    }, topic);
-  });
-}
-
 async function asyncInit() {
   await Services.search.init();
   Assert.ok(Services.search.isInitialized);
 }
 
 async function asyncReInit({ waitForRegionFetch = false } = {}) {
-  let promises = [waitForSearchNotification("reinit-complete")];
+  let promises = [SearchTestUtils.promiseSearchNotification("reinit-complete")];
   if (waitForRegionFetch) {
-    promises.push(waitForSearchNotification("ensure-known-region-done"));
+    promises.push(SearchTestUtils.promiseSearchNotification("ensure-known-region-done"));
   }
 
   Services.search.QueryInterface(Ci.nsIObserver)
           .observe(null, TOPIC_LOCALES_CHANGE, "test");
 
   await Promise.all(promises);
 }
 
--- a/toolkit/components/search/tests/xpcshell/test_geodefaults.js
+++ b/toolkit/components/search/tests/xpcshell/test_geodefaults.js
@@ -112,17 +112,17 @@ add_task(async function should_recheck_w
     let metadata = await promiseGlobalMetadata();
 
     // Break the hash.
     let hash = metadata.searchDefaultHash;
     metadata.searchDefaultHash = "broken";
     await promiseSaveGlobalMetadata(metadata);
 
     let commitPromise = promiseAfterCache();
-    let unInitPromise = waitForSearchNotification("uninit-complete");
+    let unInitPromise = SearchTestUtils.promiseSearchNotification("uninit-complete");
     let reInitPromise = asyncReInit({ waitForRegionFetch: true });
     await unInitPromise;
 
     await reInitPromise;
     checkRequest(requests);
     await commitPromise;
 
     // Check that the hash is back to its previous value.
--- a/toolkit/components/search/tests/xpcshell/test_list_json_locale.js
+++ b/toolkit/components/search/tests/xpcshell/test_list_json_locale.js
@@ -28,17 +28,17 @@ add_task(async function test_listJSONloc
 
   let sortedEngines = await Services.search.getEngines();
   Assert.equal(sortedEngines.length, 1, "Should have only one engine");
 });
 
 
 // Check that switching locale switches search engines
 add_task(async function test_listJSONlocaleSwitch() {
-  let promise = waitForSearchNotification("reinit-complete");
+  let promise = SearchTestUtils.promiseSearchNotification("reinit-complete");
 
   Services.locale.availableLocales = ["fr"];
   Services.locale.requestedLocales = ["fr"];
 
   await promise;
 
   Assert.ok(Services.search.isInitialized, "search initialized");
 
--- a/toolkit/components/search/tests/xpcshell/test_location_timeout.js
+++ b/toolkit/components/search/tests/xpcshell/test_location_timeout.js
@@ -45,17 +45,17 @@ function run_test() {
     // should have set the flag indicating we saw a timeout.
     let histogram = Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_TIMEOUT");
     let snapshot = histogram.snapshot();
     deepEqual(snapshot.values, {0: 0, 1: 1, 2: 0});
     // should not yet have SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS recorded as our
     // test server is still blocked on our promise.
     equal(getProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS"), 0);
 
-    waitForSearchNotification("geoip-lookup-xhr-complete").then(() => {
+    SearchTestUtils.promiseSearchNotification("geoip-lookup-xhr-complete").then(() => {
       // now we *should* have a report of how long the response took even though
       // it timed out.
       // The telemetry "sum" will be the actual time in ms - just check it's non-zero.
       ok(getProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS") != 0);
       // should have reported the fetch ended up being successful
       checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS);
 
       // and should have the result of the response that finally came in, and
--- a/toolkit/components/search/tests/xpcshell/test_location_timeout_xhr.js
+++ b/toolkit/components/search/tests/xpcshell/test_location_timeout_xhr.js
@@ -35,17 +35,17 @@ function run_test() {
     resolveContinuePromise = resolve;
   });
 
   let server = startServer(continuePromise);
   let url = "http://localhost:" + server.identity.primaryPort + "/lookup_country";
   Services.prefs.setCharPref("browser.search.geoip.url", url);
   // The timeout for the timer.
   Services.prefs.setIntPref("browser.search.geoip.timeout", 10);
-  let promiseXHRStarted = waitForSearchNotification("geoip-lookup-xhr-starting");
+  let promiseXHRStarted = SearchTestUtils.promiseSearchNotification("geoip-lookup-xhr-starting");
   Services.search.init().then(() => {
     ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
     // should be no result recorded at all.
     checkCountryResultTelemetry(null);
 
     // should have set the flag indicating we saw a timeout.
     let histogram = Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_TIMEOUT");
     let snapshot = histogram.snapshot();
@@ -55,17 +55,17 @@ function run_test() {
     // test server is still blocked on our promise.
     verifyProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS", 0);
 
     promiseXHRStarted.then(xhr => {
       // Set the timeout on the xhr object to an extremely low value, so it
       // should timeout immediately.
       xhr.timeout = 10;
       // wait for the xhr timeout to fire.
-      waitForSearchNotification("geoip-lookup-xhr-complete").then(() => {
+      SearchTestUtils.promiseSearchNotification("geoip-lookup-xhr-complete").then(() => {
         // should have the XHR timeout recorded.
         checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.XHRTIMEOUT);
         // still should not have a report of how long the response took as we
         // only record that on success responses.
         verifyProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS", 0);
         // and we still don't know the country code or region.
         ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
 
--- a/toolkit/components/search/tests/xpcshell/test_reloadEngines.js
+++ b/toolkit/components/search/tests/xpcshell/test_reloadEngines.js
@@ -11,18 +11,21 @@ add_task(async function test_regular_ini
     let reloadObserved = false;
     let obs = (subject, topic, data) => {
       if (data == "engines-reloaded") {
         reloadObserved = true;
       }
     };
     Services.obs.addObserver(obs, SEARCH_SERVICE_TOPIC);
 
-    await Promise.all([Services.search.init(),
-      waitForSearchNotification("ensure-known-region-done"), promiseAfterCache()]);
+    await Promise.all([
+      Services.search.init(),
+      SearchTestUtils.promiseSearchNotification("ensure-known-region-done"),
+      promiseAfterCache(),
+    ]);
     checkRequest(requests);
 
     // Install kTestEngineName and wait for it to reach the disk.
     await Promise.all([installTestEngine(), promiseAfterCache()]);
 
     Assert.equal(kTestEngineName, (await Services.search.getDefault()).name,
       "Geo defined default should be set");
     checkNoRequest(requests);
@@ -44,18 +47,21 @@ add_task(async function test_init_with_s
 
     // Break the hash.
     let metadata = await promiseGlobalMetadata();
     metadata.searchDefaultHash = "broken";
     await promiseSaveGlobalMetadata(metadata);
 
     // Kick off a re-init.
     await asyncReInit();
-    let otherPromises = [waitForSearchNotification("ensure-known-region-done"),
-      promiseAfterCache(), waitForSearchNotification("engine-default", SEARCH_ENGINE_TOPIC)];
+    let otherPromises = [
+      SearchTestUtils.promiseSearchNotification("ensure-known-region-done"),
+      promiseAfterCache(),
+      SearchTestUtils.promiseSearchNotification("engine-default", SEARCH_ENGINE_TOPIC),
+    ];
 
     // Make sure that the original default engine is put back in place.
     Services.search.resetToOriginalDefaultEngine();
     Assert.notEqual(Services.search.defaultEngine.name, kTestEngineName,
       "Test engine shouldn't be the default anymore");
 
     await Promise.all(otherPromises);
 
@@ -87,17 +93,18 @@ add_task(async function test_init_with_s
     Services.obs.addObserver(changeObs, SEARCH_ENGINE_TOPIC);
 
     // Break the hash.
     let metadata = await promiseGlobalMetadata();
     metadata.searchDefaultHash = "broken";
     await promiseSaveGlobalMetadata(metadata);
 
     // Kick off a re-init.
-    await Promise.all([asyncReInit(), waitForSearchNotification("ensure-known-region-done"),
+    await Promise.all([asyncReInit(),
+      SearchTestUtils.promiseSearchNotification("ensure-known-region-done"),
       promiseAfterCache()]);
 
     checkRequest(requests);
     // Ensure that correct engine is being reported as the default.
     Assert.equal(Services.search.defaultEngine.name, kTestEngineName,
       "Test engine should be the default, because region fetch succeeded");
 
     Assert.ok(reloadObserved, "Engines should be reloaded during test, because region fetch succeeded");
--- a/toolkit/components/search/tests/xpcshell/test_require_engines_in_cache.js
+++ b/toolkit/components/search/tests/xpcshell/test_require_engines_in_cache.js
@@ -26,44 +26,44 @@ add_task(async function ignore_cache_fil
   // Check that after an async re-initialization, we still have the same engine count.
   commitPromise = promiseAfterCache();
   await asyncReInit();
   Assert.equal(engineCount, (await Services.search.getEngines()).length);
   await commitPromise;
 
   // Check that after a sync re-initialization, we still have the same engine count.
   await promiseSaveCacheData(cache);
-  let unInitPromise = waitForSearchNotification("uninit-complete");
+  let unInitPromise = SearchTestUtils.promiseSearchNotification("uninit-complete");
   let reInitPromise = asyncReInit();
   await unInitPromise;
   Assert.ok(!Services.search.isInitialized);
   // Synchronously check the engine count; will force a sync init.
   Assert.equal(engineCount, (await Services.search.getEngines()).length);
   Assert.ok(Services.search.isInitialized);
   await reInitPromise;
 });
 
 add_task(async function skip_writing_cache_without_engines() {
-  let unInitPromise = waitForSearchNotification("uninit-complete");
+  let unInitPromise = SearchTestUtils.promiseSearchNotification("uninit-complete");
   let reInitPromise = asyncReInit();
   await unInitPromise;
 
   // Configure so that no engines will be found.
   Assert.ok(removeCacheFile());
   let resProt = Services.io.getProtocolHandler("resource")
                         .QueryInterface(Ci.nsIResProtocolHandler);
   resProt.setSubstitution("search-plugins",
                           Services.io.newURI("about:blank"));
 
   // Let the async-reInit happen.
   await reInitPromise;
   Assert.strictEqual(0, (await Services.search.getEngines()).length);
 
   // Trigger yet another re-init, to flush of any pending cache writing task.
-  unInitPromise = waitForSearchNotification("uninit-complete");
+  unInitPromise = SearchTestUtils.promiseSearchNotification("uninit-complete");
   reInitPromise = asyncReInit();
   await unInitPromise;
 
   // Now check that a cache file doesn't exist.
   Assert.ok(!removeCacheFile());
 
   await reInitPromise;
 });