Bug 1796551 [wpt PR 36570] - WebKit export of https://bugs.webkit.org/show_bug.cgi...
[gecko.git] / netwerk / test / unit / test_pac_reload_after_network_change.js
blob784f1c97fcfd4bc6e23e353ec863cad6cac78ad7
1 "use strict";
3 const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js");
4 XPCOMUtils.defineLazyServiceGetter(
5   this,
6   "gProxyService",
7   "@mozilla.org/network/protocol-proxy-service;1",
8   "nsIProtocolProxyService"
9 );
10 var { setTimeout } = ChromeUtils.importESModule(
11   "resource://gre/modules/Timer.sys.mjs"
14 let pacServer;
15 const proxyPort = 4433;
17 add_setup(async function() {
18   pacServer = new HttpServer();
19   pacServer.registerPathHandler("/proxy.pac", function handler(
20     metadata,
21     response
22   ) {
23     let content = `function FindProxyForURL(url, host) { return "HTTPS localhost:${proxyPort}"; }`;
24     response.setHeader("Content-Length", `${content.length}`);
25     response.bodyOutputStream.write(content, content.length);
26   });
27   pacServer.start(-1);
28 });
30 registerCleanupFunction(async () => {
31   Services.prefs.clearUserPref("network.proxy.type");
32   Services.prefs.clearUserPref("network.proxy.autoconfig_url");
33   Services.prefs.clearUserPref("network.proxy.reload_pac_delay");
34 });
36 async function getProxyInfo() {
37   return new Promise((resolve, reject) => {
38     let uri = Services.io.newURI("http://www.mozilla.org/");
39     gProxyService.asyncResolve(uri, 0, {
40       onProxyAvailable(_req, _uri, pi, _status) {
41         resolve(pi);
42       },
43     });
44   });
47 // Test if we can successfully get PAC when the PAC server is available.
48 add_task(async function testPAC() {
49   // Configure PAC
50   Services.prefs.setIntPref("network.proxy.type", 2);
51   Services.prefs.setCharPref(
52     "network.proxy.autoconfig_url",
53     `http://localhost:${pacServer.identity.primaryPort}/proxy.pac`
54   );
56   let pi = await getProxyInfo();
57   Assert.equal(pi.port, proxyPort, "Expected proxy port to be the same");
58   Assert.equal(pi.type, "https", "Expected proxy type to be https");
59 });
61 // When PAC server is down, we should not use proxy at all.
62 add_task(async function testWhenPACServerDown() {
63   Services.prefs.setIntPref("network.proxy.reload_pac_delay", 0);
64   await new Promise(resolve => pacServer.stop(resolve));
66   Services.obs.notifyObservers(null, "network:link-status-changed", "changed");
68   // eslint-disable-next-line mozilla/no-arbitrary-setTimeout
69   await new Promise(resolve => setTimeout(resolve, 3000));
71   let pi = await getProxyInfo();
72   Assert.equal(pi, null, "should have no proxy");
73 });