Bug 1444680: Part 5: Convert test_ext_webRequest_set_cookie to xpcshell. r?mixedpuppy draft
authorKris Maglione <maglione.k@gmail.com>
Sat, 10 Mar 2018 19:08:54 -0800
changeset 765939 28198b6b577b98fd2f358c2dcba5538b85094620
parent 765938 f19da1c1bffea4c5f894b6bc04c9636c96e830a2
child 765940 449141397a2f4c13969b2c0f13d6f088ee08b542
push id102183
push usermaglione.k@gmail.com
push dateSun, 11 Mar 2018 06:57:39 +0000
reviewersmixedpuppy
bugs1444680
milestone60.0a1
Bug 1444680: Part 5: Convert test_ext_webRequest_set_cookie to xpcshell. r?mixedpuppy MozReview-Commit-ID: 8hTlHqB0KX7
toolkit/components/extensions/test/mochitest/file_webrequestblocking_set_cookie.html
toolkit/components/extensions/test/mochitest/file_webrequestblocking_set_cookie.html^headers^
toolkit/components/extensions/test/mochitest/mochitest-common.ini
toolkit/components/extensions/test/mochitest/test_ext_webrequestblocking_set_cookie.html
toolkit/components/extensions/test/xpcshell/test_ext_webRequest_set_cookie.js
toolkit/components/extensions/test/xpcshell/xpcshell-common.ini
deleted file mode 100644
--- a/toolkit/components/extensions/test/mochitest/file_webrequestblocking_set_cookie.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-    <head>
-        <meta charset="utf-8">
-        <title>Set Cookie Example</title>
-    </head>
-    <body>
-    </body>
-</html>
deleted file mode 100644
--- a/toolkit/components/extensions/test/mochitest/file_webrequestblocking_set_cookie.html^headers^
+++ /dev/null
@@ -1,1 +0,0 @@
-Set-Cookie: reqcookie=reqvalue
--- a/toolkit/components/extensions/test/mochitest/mochitest-common.ini
+++ b/toolkit/components/extensions/test/mochitest/mochitest-common.ini
@@ -35,18 +35,16 @@ support-files =
   file_webNavigation_clientRedirect.html
   file_webNavigation_clientRedirect_httpHeaders.html
   file_webNavigation_clientRedirect_httpHeaders.html^headers^
   file_webNavigation_frameClientRedirect.html
   file_webNavigation_frameRedirect.html
   file_webNavigation_manualSubframe.html
   file_webNavigation_manualSubframe_page1.html
   file_webNavigation_manualSubframe_page2.html
-  file_webrequestblocking_set_cookie.html
-  file_webrequestblocking_set_cookie.html^headers^
   file_with_about_blank.html
   head.js
   head_cookies.js
   head_unlimitedStorage.js
   head_webrequest.js
   hsts.sjs
   lorem.html.gz
   lorem.html.gz^headers^
@@ -148,17 +146,16 @@ skip-if = webrender # bug 1424752
 skip-if = os == 'android' && debug # bug 1397615
 [test_ext_webnavigation.html]
 skip-if = os == 'android' && debug # bug 1397615
 [test_ext_webnavigation_filters.html]
 skip-if = os == 'android' && debug # bug 1397615
 [test_ext_webrequest_auth.html]
 skip-if = os == 'android'
 [test_ext_webrequest_background_events.html]
-[test_ext_webrequestblocking_set_cookie.html]
 [test_ext_webrequest_basic.html]
 skip-if = os == 'android' && debug # bug 1397615
 [test_ext_webrequest_errors.html]
 [test_ext_webrequest_filter.html]
 [test_ext_webrequest_frameId.html]
 [test_ext_webrequest_hsts.html]
 [test_ext_webrequest_responseBody.html]
 skip-if = os == 'android' || os == 'linux' # linux, bug 1398120
rename from toolkit/components/extensions/test/mochitest/test_ext_webrequestblocking_set_cookie.html
rename to toolkit/components/extensions/test/xpcshell/test_ext_webRequest_set_cookie.js
--- a/toolkit/components/extensions/test/mochitest/test_ext_webrequestblocking_set_cookie.html
+++ b/toolkit/components/extensions/test/xpcshell/test_ext_webRequest_set_cookie.js
@@ -1,26 +1,26 @@
-<!DOCTYPE HTML>
-<html>
-<head>
-  <title>Testing modifying cookies in webRequest.onHeadersReceived</title>
-  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
-  <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
-  <script type="text/javascript" src="head.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<body>
-
-<script type="text/javascript">
 "use strict";
 
+const HOSTS = new Set([
+  "example.com",
+]);
+
+const server = createHttpServer({hosts: HOSTS});
+
+server.registerDirectory("/data/", do_get_file("data"));
+
+server.registerPathHandler("/file_webrequestblocking_set_cookie.html", (request, response) => {
+  response.setStatusLine(request.httpVersion, 200, "OK");
+  response.setHeader("Content-Type", "text/html", false);
+  response.setHeader("Set-Cookie", "reqcookie=reqvalue", false);
+  response.write("<!DOCTYPE html><html></html>");
+});
+
 add_task(async function test_modifying_cookies_from_onHeadersReceived() {
-  let extension;
-  SimpleTest.waitForExplicitFinish();
   async function background() {
     /**
      * Check that all the cookies described by `prefixes` are in the cookie jar.
      *
      * @param {Array.string} prefixes
      *   Zero or more prefixes, describing cookies that are expected to be set
      *   in the current cookie jar.  Each prefix describes both a cookie
      *   name and corresponding value.  For example, if the string "ext"
@@ -36,42 +36,39 @@ add_task(async function test_modifying_c
         let cookieName = `${cookiePrefix}cookie`;
         let expectedCookieValue = `${cookiePrefix}value`;
         let fetchedCookie = await browser.cookies.getAll({name: cookieName});
         browser.test.assertEq(1, fetchedCookie.length, `Found 1 cookie with name "${cookieName}"`);
         browser.test.assertEq(expectedCookieValue, fetchedCookie[0] && fetchedCookie[0].value, `Cookie "${cookieName}" has expected value of "${expectedCookieValue}"`);
       }
     }
 
+    function awaitMessage(expectedMsg) {
+      return new Promise(resolve => {
+        browser.test.onMessage.addListener(function listener(msg) {
+          if (msg === expectedMsg) {
+            browser.test.onMessage.removeListener(listener);
+            resolve();
+          }
+        });
+      });
+    }
+
     /**
-     * Opens up a new tab, loading the given file.
+     * Opens the given test file as a content page.
      *
      * @param {string} filename
-     *   The name of a html file in the
-     *   "toolkit/components/extensions/test/mochitest" directory.
+     *   The name of a html file relative to the test server root.
      *
-     * @returns {object}
-     *   An object with windowId and tabId properties, describing the tab
-     *   that was opened.
+     * @returns {Promise}
      */
-    async function openWindowAndTab(filename) {
-      const fileUrl = `http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/${filename}?nocache=${Math.random()}`;
-      const tabReadyPromise = new Promise(resolve => {
-        browser.webNavigation.onDOMContentLoaded.addListener(function listener({tabId}) {
-          browser.webNavigation.onDOMContentLoaded.removeListener(listener);
-          resolve(tabId);
-        }, {
-          url: [{
-            urlPrefix: fileUrl,
-          }],
-        });
-      });
-      const {id: windowId} = await browser.windows.create({url: fileUrl});
-      const tabId = await tabReadyPromise;
-      return {windowId, tabId};
+    function openContentPage(filename) {
+      let promise = awaitMessage("url-loaded");
+      browser.test.sendMessage("load-url", `http://example.com/${filename}?nocache=${Math.random()}`);
+      return promise;
     }
 
     /**
      * Tests that expected cookies are in the cookie jar after opening a file.
      *
      * @param {string} filename
      *   The name of a html file in the
      *   "toolkit/components/extensions/test/mochitest" directory.
@@ -86,26 +83,28 @@ add_task(async function test_modifying_c
      * @param {?Function} callback
      *   An optional async callback function that, if provided, will be called
      *   with an object that contains windowId and tabId parameters.
      *   Callers can use this callback to apply extra tests about the state of
      *   the cookie jar, or to query the state of the opened page.
      */
     async function testCookiesWithFile(filename, prefixes, callback) {
       await browser.browsingData.removeCookies({});
-      const tabDetails = await openWindowAndTab(filename);
+      await openContentPage(filename);
 
       if (prefixes !== undefined) {
         await checkCookies(prefixes);
       }
 
       if (callback !== undefined) {
-        await callback(tabDetails);
+        await callback();
       }
-      await browser.windows.remove(tabDetails.windowId);
+      let promise = awaitMessage("url-unloaded");
+      browser.test.sendMessage("unload-url");
+      await promise;
     }
 
     const filter = {
       urls: ["<all_urls>"],
       types: ["main_frame", "sub_frame"],
     };
 
     const headersReceivedInfoSpec = ["blocking", "responseHeaders"];
@@ -117,122 +116,128 @@ add_task(async function test_modifying_c
       });
 
       return {
         responseHeaders: details.responseHeaders,
       };
     };
     browser.webRequest.onHeadersReceived.addListener(onHeadersReceived, filter, headersReceivedInfoSpec);
 
-    if (browser.windows) {
-      // First, perform a request that should not set any cookies, and check
-      // that the cookie the extension sets is the only cookie in the
-      // cookie jar.
-      await testCookiesWithFile("file_sample.html", ["ext"]);
+    // First, perform a request that should not set any cookies, and check
+    // that the cookie the extension sets is the only cookie in the
+    // cookie jar.
+    await testCookiesWithFile("data/file_sample.html", ["ext"]);
 
-      // Next, preform a request that will set on cookie (reqcookie=reqvalue)
-      // and check that two cookies wind up in the cookie jar (the request
-      // set cookie, and the extension set cookie).
-      await testCookiesWithFile("file_webrequestblocking_set_cookie.html", ["ext", "req"]);
+    // Next, preform a request that will set on cookie (reqcookie=reqvalue)
+    // and check that two cookies wind up in the cookie jar (the request
+    // set cookie, and the extension set cookie).
+    await testCookiesWithFile("file_webrequestblocking_set_cookie.html", ["ext", "req"]);
 
-      // Third, register another onHeadersReceived handler that also
-      // sets a cookie (thirdcookie=thirdvalue), to make sure modifications from
-      // multiple onHeadersReceived listeners are merged correctly.
-      const thirdOnHeadersRecievedListener = details => {
-        details.responseHeaders.push({
-          name: "Set-Cookie",
-          value: "thirdcookie=thirdvalue",
-        });
+    // Third, register another onHeadersReceived handler that also
+    // sets a cookie (thirdcookie=thirdvalue), to make sure modifications from
+    // multiple onHeadersReceived listeners are merged correctly.
+    const thirdOnHeadersRecievedListener = details => {
+      details.responseHeaders.push({
+        name: "Set-Cookie",
+        value: "thirdcookie=thirdvalue",
+      });
 
-        browser.test.log(JSON.stringify(details.responseHeaders));
+      browser.test.log(JSON.stringify(details.responseHeaders));
 
-        return {
-          responseHeaders: details.responseHeaders,
-        };
+      return {
+        responseHeaders: details.responseHeaders,
       };
-      browser.webRequest.onHeadersReceived.addListener(thirdOnHeadersRecievedListener, filter, headersReceivedInfoSpec);
-      await testCookiesWithFile("file_webrequestblocking_set_cookie.html", ["ext", "req", "third"]);
-      browser.webRequest.onHeadersReceived.removeListener(onHeadersReceived);
-      browser.webRequest.onHeadersReceived.removeListener(thirdOnHeadersRecievedListener);
+    };
+    browser.webRequest.onHeadersReceived.addListener(thirdOnHeadersRecievedListener, filter, headersReceivedInfoSpec);
+    await testCookiesWithFile("file_webrequestblocking_set_cookie.html", ["ext", "req", "third"]);
+    browser.webRequest.onHeadersReceived.removeListener(onHeadersReceived);
+    browser.webRequest.onHeadersReceived.removeListener(thirdOnHeadersRecievedListener);
 
-      // Fourth, test to make sure that extensions can remove cookies
-      // using onHeadersReceived too, by 1. making a request that
-      // sets a cookie (reqcookie=reqvalue), 2. having the extension remove
-      // that cookie by removing that header, and 3. adding a new cookie
-      // (extcookie=extvalue).
-      const fourthOnHeadersRecievedListener = details => {
-        // Remove the cookie set by the request (reqcookie=reqvalue).
-        const newHeaders = details.responseHeaders.filter(cookie => cookie.name !== "set-cookie");
+    // Fourth, test to make sure that extensions can remove cookies
+    // using onHeadersReceived too, by 1. making a request that
+    // sets a cookie (reqcookie=reqvalue), 2. having the extension remove
+    // that cookie by removing that header, and 3. adding a new cookie
+    // (extcookie=extvalue).
+    const fourthOnHeadersRecievedListener = details => {
+      // Remove the cookie set by the request (reqcookie=reqvalue).
+      const newHeaders = details.responseHeaders.filter(cookie => cookie.name !== "set-cookie");
 
-        // And then add a new cookie in its place (extcookie=extvalue).
-        newHeaders.push({
-          name: "Set-Cookie",
-          value: "extcookie=extvalue",
-        });
+      // And then add a new cookie in its place (extcookie=extvalue).
+      newHeaders.push({
+        name: "Set-Cookie",
+        value: "extcookie=extvalue",
+      });
 
-        return {
-          responseHeaders: newHeaders,
-        };
+      return {
+        responseHeaders: newHeaders,
       };
-      browser.webRequest.onHeadersReceived.addListener(fourthOnHeadersRecievedListener, filter, headersReceivedInfoSpec);
-      await testCookiesWithFile("file_webrequestblocking_set_cookie.html", ["ext"]);
-      browser.webRequest.onHeadersReceived.removeListener(fourthOnHeadersRecievedListener);
+    };
+    browser.webRequest.onHeadersReceived.addListener(fourthOnHeadersRecievedListener, filter, headersReceivedInfoSpec);
+    await testCookiesWithFile("file_webrequestblocking_set_cookie.html", ["ext"]);
+    browser.webRequest.onHeadersReceived.removeListener(fourthOnHeadersRecievedListener);
 
-      // Fifth, check that extensions are able to overwrite headers set by
-      // pages. In this test, make a request that will set "reqcookie=reqvalue",
-      // and add a listener that sets "reqcookie=changedvalue".  Check
-      // to make sure that the cookie jar contains "reqcookie=changedvalue"
-      // and not "reqcookie=reqvalue".
-      const fifthOnHeadersRecievedListener = details => {
-        // Remove the cookie set by the request (reqcookie=reqvalue).
-        const newHeaders = details.responseHeaders.filter(cookie => cookie.name !== "set-cookie");
+    // Fifth, check that extensions are able to overwrite headers set by
+    // pages. In this test, make a request that will set "reqcookie=reqvalue",
+    // and add a listener that sets "reqcookie=changedvalue".  Check
+    // to make sure that the cookie jar contains "reqcookie=changedvalue"
+    // and not "reqcookie=reqvalue".
+    const fifthOnHeadersRecievedListener = details => {
+      // Remove the cookie set by the request (reqcookie=reqvalue).
+      const newHeaders = details.responseHeaders.filter(cookie => cookie.name !== "set-cookie");
 
-        // And then add a new cookie in its place (reqcookie=changedvalue).
-        newHeaders.push({
-          name: "Set-Cookie",
-          value: "reqcookie=changedvalue",
-        });
+      // And then add a new cookie in its place (reqcookie=changedvalue).
+      newHeaders.push({
+        name: "Set-Cookie",
+        value: "reqcookie=changedvalue",
+      });
 
-        return {
-          responseHeaders: newHeaders,
-        };
+      return {
+        responseHeaders: newHeaders,
       };
-      browser.webRequest.onHeadersReceived.addListener(fifthOnHeadersRecievedListener, filter, headersReceivedInfoSpec);
+    };
+    browser.webRequest.onHeadersReceived.addListener(fifthOnHeadersRecievedListener, filter, headersReceivedInfoSpec);
 
-      await testCookiesWithFile("file_webrequestblocking_set_cookie.html", undefined, async tabDetails => {
-        const currentCookies = await browser.cookies.getAll({});
-        browser.test.assertEq(1, currentCookies.length, `1 cookie was set`);
+    await testCookiesWithFile("file_webrequestblocking_set_cookie.html", undefined, async () => {
+      const currentCookies = await browser.cookies.getAll({});
+      browser.test.assertEq(1, currentCookies.length, `1 cookie was set`);
 
-        const cookieName = "reqcookie";
-        const expectedCookieValue = "changedvalue";
-        const fetchedCookie = await browser.cookies.getAll({name: cookieName});
+      const cookieName = "reqcookie";
+      const expectedCookieValue = "changedvalue";
+      const fetchedCookie = await browser.cookies.getAll({name: cookieName});
 
-        browser.test.assertEq(1, fetchedCookie.length, `Found 1 cookie with name "${cookieName}"`);
-        browser.test.assertEq(expectedCookieValue, fetchedCookie[0] && fetchedCookie[0].value, `Cookie "${cookieName}" has expected value of "${expectedCookieValue}"`);
-      });
-      browser.webRequest.onHeadersReceived.removeListener(fifthOnHeadersRecievedListener);
-    }
+      browser.test.assertEq(1, fetchedCookie.length, `Found 1 cookie with name "${cookieName}"`);
+      browser.test.assertEq(expectedCookieValue, fetchedCookie[0] && fetchedCookie[0].value, `Cookie "${cookieName}" has expected value of "${expectedCookieValue}"`);
+    });
+    browser.webRequest.onHeadersReceived.removeListener(fifthOnHeadersRecievedListener);
 
     browser.test.notifyPass("cookie modifying extension");
   }
 
-  extension = ExtensionTestUtils.loadExtension({
+  let extension = ExtensionTestUtils.loadExtension({
     manifest: {
       permissions: [
         "browsingData",
         "cookies",
         "webNavigation",
         "webRequest",
         "webRequestBlocking",
         "<all_urls>",
       ],
     },
     background,
   });
 
+  let contentPage = null;
+  extension.onMessage("load-url", async url => {
+    ok(!contentPage, "Should have no content page to unload");
+    contentPage = await ExtensionTestUtils.loadContentPage(url, {remote: true});
+    extension.sendMessage("url-loaded");
+  });
+  extension.onMessage("unload-url", async () => {
+    await contentPage.close();
+    contentPage = null;
+    extension.sendMessage("url-unloaded");
+  });
+
   await extension.startup();
   await extension.awaitFinish("cookie modifying extension");
   await extension.unload();
 });
-
-</script>
-</body>
-</html>
--- a/toolkit/components/extensions/test/xpcshell/xpcshell-common.ini
+++ b/toolkit/components/extensions/test/xpcshell/xpcshell-common.ini
@@ -78,16 +78,17 @@ skip-if = os == "android"
 skip-if = os == "android"
 [test_ext_storage_telemetry.js]
 skip-if = os == "android" # checking for telemetry needs to be updated: 1384923
 [test_ext_trustworthy_origin.js]
 [test_ext_topSites.js]
 skip-if = os == "android"
 [test_ext_webRequest_filterResponseData.js]
 [test_ext_webRequest_permission.js]
+[test_ext_webRequest_set_cookie.js]
 [test_ext_webRequest_suspend.js]
 [test_ext_webRequest_webSocket.js]
 [test_native_manifests.js]
 subprocess = true
 skip-if = os == "android"
 [test_ext_permissions.js]
 skip-if = os == "android" # Bug 1350559
 [test_proxy_listener.js]