From 5f8de423f190bbb79a62f804151bc24824fa32d8 Mon Sep 17 00:00:00 2001 From: "Matt A. Tobin" Date: Fri, 2 Feb 2018 04:16:08 -0500 Subject: Add m-esr52 at 52.6.0 --- testing/xpcshell/README | 7 + testing/xpcshell/dbg-actors.js | 51 + testing/xpcshell/example/moz.build | 9 + testing/xpcshell/example/unit/check_profile.js | 52 + testing/xpcshell/example/unit/file.txt | 1 + testing/xpcshell/example/unit/import_module.jsm | 34 + .../xpcshell/example/unit/import_sub_module.jsm | 10 + testing/xpcshell/example/unit/load_subscript.js | 5 + testing/xpcshell/example/unit/location_load.js | 6 + testing/xpcshell/example/unit/subdir/file.txt | 1 + .../example/unit/test_check_nsIException.js | 11 + .../unit/test_check_nsIException_failing.js | 9 + .../xpcshell/example/unit/test_do_check_matches.js | 14 + .../example/unit/test_do_check_matches_failing.js | 12 + .../xpcshell/example/unit/test_do_check_null.js | 6 + .../example/unit/test_do_check_null_failing.js | 6 + .../xpcshell/example/unit/test_do_get_tempdir.js | 16 + testing/xpcshell/example/unit/test_execute_soon.js | 20 + testing/xpcshell/example/unit/test_fail.js | 8 + testing/xpcshell/example/unit/test_get_file.js | 33 + testing/xpcshell/example/unit/test_get_idle.js | 23 + .../xpcshell/example/unit/test_import_module.js | 22 + testing/xpcshell/example/unit/test_load.js | 21 + .../xpcshell/example/unit/test_load_httpd_js.js | 13 + testing/xpcshell/example/unit/test_location.js | 11 + testing/xpcshell/example/unit/test_profile.js | 11 + .../example/unit/test_profile_afterChange.js | 11 + testing/xpcshell/example/unit/test_sample.js | 21 + testing/xpcshell/example/unit/test_skip.js | 8 + testing/xpcshell/example/unit/xpcshell.ini | 47 + testing/xpcshell/head.js | 1663 ++++++++++++++++++++ testing/xpcshell/mach_commands.py | 274 ++++ testing/xpcshell/mach_test_package_commands.py | 64 + testing/xpcshell/moz-http2/http2-cert.pem | 79 + testing/xpcshell/moz-http2/http2-key.pem | 28 + testing/xpcshell/moz-http2/moz-http2.js | 786 +++++++++ testing/xpcshell/moz.build | 18 + testing/xpcshell/node-http2/.gitignore | 7 + testing/xpcshell/node-http2/.travis.yml | 5 + testing/xpcshell/node-http2/HISTORY.md | 258 +++ testing/xpcshell/node-http2/LICENSE | 22 + testing/xpcshell/node-http2/README.md | 171 ++ testing/xpcshell/node-http2/example/client.js | 48 + testing/xpcshell/node-http2/example/localhost.crt | 14 + testing/xpcshell/node-http2/example/localhost.key | 15 + testing/xpcshell/node-http2/example/server.js | 67 + testing/xpcshell/node-http2/lib/http.js | 1262 +++++++++++++++ testing/xpcshell/node-http2/lib/index.js | 52 + .../xpcshell/node-http2/lib/protocol/compressor.js | 1366 ++++++++++++++++ .../xpcshell/node-http2/lib/protocol/connection.js | 619 ++++++++ .../xpcshell/node-http2/lib/protocol/endpoint.js | 262 +++ testing/xpcshell/node-http2/lib/protocol/flow.js | 353 +++++ testing/xpcshell/node-http2/lib/protocol/framer.js | 1165 ++++++++++++++ testing/xpcshell/node-http2/lib/protocol/index.js | 91 ++ testing/xpcshell/node-http2/lib/protocol/stream.js | 659 ++++++++ testing/xpcshell/node-http2/package.json | 46 + testing/xpcshell/node-http2/test/compressor.js | 575 +++++++ testing/xpcshell/node-http2/test/connection.js | 237 +++ testing/xpcshell/node-http2/test/endpoint.js | 41 + testing/xpcshell/node-http2/test/flow.js | 260 +++ testing/xpcshell/node-http2/test/framer.js | 395 +++++ testing/xpcshell/node-http2/test/http.js | 793 ++++++++++ testing/xpcshell/node-http2/test/stream.js | 413 +++++ testing/xpcshell/node-http2/test/util.js | 89 ++ testing/xpcshell/remotexpcshelltests.py | 614 ++++++++ testing/xpcshell/runxpcshelltests.py | 1501 ++++++++++++++++++ testing/xpcshell/selftest.py | 1344 ++++++++++++++++ testing/xpcshell/xpcshell.eslintrc.js | 57 + testing/xpcshell/xpcshellcommandline.py | 166 ++ 69 files changed, 16378 insertions(+) create mode 100644 testing/xpcshell/README create mode 100644 testing/xpcshell/dbg-actors.js create mode 100644 testing/xpcshell/example/moz.build create mode 100644 testing/xpcshell/example/unit/check_profile.js create mode 100644 testing/xpcshell/example/unit/file.txt create mode 100644 testing/xpcshell/example/unit/import_module.jsm create mode 100644 testing/xpcshell/example/unit/import_sub_module.jsm create mode 100644 testing/xpcshell/example/unit/load_subscript.js create mode 100644 testing/xpcshell/example/unit/location_load.js create mode 100644 testing/xpcshell/example/unit/subdir/file.txt create mode 100644 testing/xpcshell/example/unit/test_check_nsIException.js create mode 100644 testing/xpcshell/example/unit/test_check_nsIException_failing.js create mode 100644 testing/xpcshell/example/unit/test_do_check_matches.js create mode 100644 testing/xpcshell/example/unit/test_do_check_matches_failing.js create mode 100644 testing/xpcshell/example/unit/test_do_check_null.js create mode 100644 testing/xpcshell/example/unit/test_do_check_null_failing.js create mode 100644 testing/xpcshell/example/unit/test_do_get_tempdir.js create mode 100644 testing/xpcshell/example/unit/test_execute_soon.js create mode 100644 testing/xpcshell/example/unit/test_fail.js create mode 100644 testing/xpcshell/example/unit/test_get_file.js create mode 100644 testing/xpcshell/example/unit/test_get_idle.js create mode 100644 testing/xpcshell/example/unit/test_import_module.js create mode 100644 testing/xpcshell/example/unit/test_load.js create mode 100644 testing/xpcshell/example/unit/test_load_httpd_js.js create mode 100644 testing/xpcshell/example/unit/test_location.js create mode 100644 testing/xpcshell/example/unit/test_profile.js create mode 100644 testing/xpcshell/example/unit/test_profile_afterChange.js create mode 100644 testing/xpcshell/example/unit/test_sample.js create mode 100644 testing/xpcshell/example/unit/test_skip.js create mode 100644 testing/xpcshell/example/unit/xpcshell.ini create mode 100644 testing/xpcshell/head.js create mode 100644 testing/xpcshell/mach_commands.py create mode 100644 testing/xpcshell/mach_test_package_commands.py create mode 100644 testing/xpcshell/moz-http2/http2-cert.pem create mode 100644 testing/xpcshell/moz-http2/http2-key.pem create mode 100644 testing/xpcshell/moz-http2/moz-http2.js create mode 100644 testing/xpcshell/moz.build create mode 100644 testing/xpcshell/node-http2/.gitignore create mode 100644 testing/xpcshell/node-http2/.travis.yml create mode 100644 testing/xpcshell/node-http2/HISTORY.md create mode 100644 testing/xpcshell/node-http2/LICENSE create mode 100644 testing/xpcshell/node-http2/README.md create mode 100644 testing/xpcshell/node-http2/example/client.js create mode 100644 testing/xpcshell/node-http2/example/localhost.crt create mode 100644 testing/xpcshell/node-http2/example/localhost.key create mode 100644 testing/xpcshell/node-http2/example/server.js create mode 100644 testing/xpcshell/node-http2/lib/http.js create mode 100644 testing/xpcshell/node-http2/lib/index.js create mode 100644 testing/xpcshell/node-http2/lib/protocol/compressor.js create mode 100644 testing/xpcshell/node-http2/lib/protocol/connection.js create mode 100644 testing/xpcshell/node-http2/lib/protocol/endpoint.js create mode 100644 testing/xpcshell/node-http2/lib/protocol/flow.js create mode 100644 testing/xpcshell/node-http2/lib/protocol/framer.js create mode 100644 testing/xpcshell/node-http2/lib/protocol/index.js create mode 100644 testing/xpcshell/node-http2/lib/protocol/stream.js create mode 100644 testing/xpcshell/node-http2/package.json create mode 100644 testing/xpcshell/node-http2/test/compressor.js create mode 100644 testing/xpcshell/node-http2/test/connection.js create mode 100644 testing/xpcshell/node-http2/test/endpoint.js create mode 100644 testing/xpcshell/node-http2/test/flow.js create mode 100644 testing/xpcshell/node-http2/test/framer.js create mode 100644 testing/xpcshell/node-http2/test/http.js create mode 100644 testing/xpcshell/node-http2/test/stream.js create mode 100644 testing/xpcshell/node-http2/test/util.js create mode 100644 testing/xpcshell/remotexpcshelltests.py create mode 100755 testing/xpcshell/runxpcshelltests.py create mode 100755 testing/xpcshell/selftest.py create mode 100644 testing/xpcshell/xpcshell.eslintrc.js create mode 100644 testing/xpcshell/xpcshellcommandline.py (limited to 'testing/xpcshell') diff --git a/testing/xpcshell/README b/testing/xpcshell/README new file mode 100644 index 000000000..a359b3c8d --- /dev/null +++ b/testing/xpcshell/README @@ -0,0 +1,7 @@ +Simple xpcshell-based test harness + +converted from netwerk/test/unit + +Some documentation at http://developer.mozilla.org/en/docs/Writing_xpcshell-based_unit_tests +See also http://wiki.mozilla.org/SoftwareTesting:Tools:Simple_xpcshell_test_harness + diff --git a/testing/xpcshell/dbg-actors.js b/testing/xpcshell/dbg-actors.js new file mode 100644 index 000000000..dd6b388a4 --- /dev/null +++ b/testing/xpcshell/dbg-actors.js @@ -0,0 +1,51 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +'use strict'; + +const { Promise } = Cu.import("resource://gre/modules/Promise.jsm", {}); +var { Services } = Cu.import("resource://gre/modules/Services.jsm", {}); +const { devtools } = Cu.import("resource://devtools/shared/Loader.jsm", {}); +const { RootActor } = devtools.require("devtools/server/actors/root"); +const { BrowserTabList } = devtools.require("devtools/server/actors/webbrowser"); + +/** + * xpcshell-test (XPCST) specific actors. + * + */ + +/** + * Construct a root actor appropriate for use in a server running xpcshell + * tests. :) + */ +function createRootActor(connection) +{ + let parameters = { + tabList: new XPCSTTabList(connection), + globalActorFactories: DebuggerServer.globalActorFactories, + onShutdown() { + // If the user never switches to the "debugger" tab we might get a + // shutdown before we've attached. + Services.obs.notifyObservers(null, "xpcshell-test-devtools-shutdown", null); + } + }; + return new RootActor(connection, parameters); +} + +/** + * A "stub" TabList implementation that provides no tabs. + */ + +function XPCSTTabList(connection) +{ + BrowserTabList.call(this, connection); +} + +XPCSTTabList.prototype = Object.create(BrowserTabList.prototype); + +XPCSTTabList.prototype.constructor = XPCSTTabList; + +XPCSTTabList.prototype.getList = function() { + return Promise.resolve([]); +}; diff --git a/testing/xpcshell/example/moz.build b/testing/xpcshell/example/moz.build new file mode 100644 index 000000000..078d8cd63 --- /dev/null +++ b/testing/xpcshell/example/moz.build @@ -0,0 +1,9 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# This is a list of directories containing tests to run, separated by spaces. +# Most likely, tho, you won't use more than one directory here. +XPCSHELL_TESTS_MANIFESTS += ['unit/xpcshell.ini'] diff --git a/testing/xpcshell/example/unit/check_profile.js b/testing/xpcshell/example/unit/check_profile.js new file mode 100644 index 000000000..b2451c5f9 --- /dev/null +++ b/testing/xpcshell/example/unit/check_profile.js @@ -0,0 +1,52 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var {classes: Cc, interfaces: Ci} = Components; + +function check_profile_dir(profd) +{ + Assert.ok(profd.exists()); + Assert.ok(profd.isDirectory()); + let dirSvc = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties); + let profd2 = dirSvc.get("ProfD", Ci.nsILocalFile); + Assert.ok(profd2.exists()); + Assert.ok(profd2.isDirectory()); + // make sure we got the same thing back... + Assert.ok(profd.equals(profd2)); +} + +function check_do_get_profile(fireProfileAfterChange) +{ + const observedTopics = new Map([ + ["profile-do-change", 0], + ["profile-after-change", 0], + ]); + const expectedTopics = new Map(observedTopics); + + const obs = Cc["@mozilla.org/observer-service;1"] + .getService(Ci.nsIObserverService); + for (let [topic,] of observedTopics) { + obs.addObserver(() => { + let val = observedTopics.get(topic) + 1; + observedTopics.set(topic, val); + }, topic, false); + } + + // Trigger profile creation. + let profd = do_get_profile(); + check_profile_dir(profd); + + // Check the observed topics + expectedTopics.set("profile-do-change", 1); + if (fireProfileAfterChange) { + expectedTopics.set("profile-after-change", 1); + } + Assert.deepEqual(observedTopics, expectedTopics); + + // A second do_get_profile() should not trigger more notifications. + profd = do_get_profile(); + check_profile_dir(profd); + Assert.deepEqual(observedTopics, expectedTopics); +} diff --git a/testing/xpcshell/example/unit/file.txt b/testing/xpcshell/example/unit/file.txt new file mode 100644 index 000000000..ce0136250 --- /dev/null +++ b/testing/xpcshell/example/unit/file.txt @@ -0,0 +1 @@ +hello diff --git a/testing/xpcshell/example/unit/import_module.jsm b/testing/xpcshell/example/unit/import_module.jsm new file mode 100644 index 000000000..3b1ddaf9f --- /dev/null +++ b/testing/xpcshell/example/unit/import_module.jsm @@ -0,0 +1,34 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// Module used by test_import_module.js + +const EXPORTED_SYMBOLS = [ "MODULE_IMPORTED", "MODULE_URI", "SUBMODULE_IMPORTED", "same_scope", "SUBMODULE_IMPORTED_TO_SCOPE" ]; + +const MODULE_IMPORTED = true; +const MODULE_URI = __URI__; + +// Will import SUBMODULE_IMPORTED into scope. +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); +XPCOMUtils.importRelative(this, "import_sub_module.jsm"); + +// Prepare two scopes that we can import the submodule into. +var scope1 = { __URI__: __URI__ }; +var scope2 = { __URI__: __URI__ }; +// First one is the regular path. +XPCOMUtils.importRelative(scope1, "import_sub_module.jsm"); +scope1.test_obj.i++; +// Second one is with a different path (leads to the same file). +XPCOMUtils.importRelative(scope2, "duh/../import_sub_module.jsm"); +// test_obj belongs to import_sub_module.jsm and has a mutable field name i, if +// the two modules are actually the same, then they'll share the same value. +// We'll leave it up to test_import_module.js to check that this variable is +// true. +var same_scope = (scope1.test_obj.i == scope2.test_obj.i); + +// Check that importRelative can also import into a given scope +var testScope = {}; +XPCOMUtils.importRelative(this, "import_sub_module.jsm", testScope); +var SUBMODULE_IMPORTED_TO_SCOPE = testScope.SUBMODULE_IMPORTED; + diff --git a/testing/xpcshell/example/unit/import_sub_module.jsm b/testing/xpcshell/example/unit/import_sub_module.jsm new file mode 100644 index 000000000..164951717 --- /dev/null +++ b/testing/xpcshell/example/unit/import_sub_module.jsm @@ -0,0 +1,10 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// Module used by import_module.jsm + +var EXPORTED_SYMBOLS = [ "SUBMODULE_IMPORTED", "test_obj" ]; + +const SUBMODULE_IMPORTED = true; +var test_obj = { i: 0 }; diff --git a/testing/xpcshell/example/unit/load_subscript.js b/testing/xpcshell/example/unit/load_subscript.js new file mode 100644 index 000000000..d62603897 --- /dev/null +++ b/testing/xpcshell/example/unit/load_subscript.js @@ -0,0 +1,5 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +subscriptLoaded = true; diff --git a/testing/xpcshell/example/unit/location_load.js b/testing/xpcshell/example/unit/location_load.js new file mode 100644 index 000000000..2357ed44f --- /dev/null +++ b/testing/xpcshell/example/unit/location_load.js @@ -0,0 +1,6 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// Gets loaded via test_location.js +do_check_eq(__LOCATION__.leafName, "location_load.js"); diff --git a/testing/xpcshell/example/unit/subdir/file.txt b/testing/xpcshell/example/unit/subdir/file.txt new file mode 100644 index 000000000..c4f6b5f70 --- /dev/null +++ b/testing/xpcshell/example/unit/subdir/file.txt @@ -0,0 +1 @@ +subdir hello diff --git a/testing/xpcshell/example/unit/test_check_nsIException.js b/testing/xpcshell/example/unit/test_check_nsIException.js new file mode 100644 index 000000000..115542fca --- /dev/null +++ b/testing/xpcshell/example/unit/test_check_nsIException.js @@ -0,0 +1,11 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + let env = Components.classes["@mozilla.org/process/environment;1"] + .getService(Components.interfaces.nsIEnvironment); + do_check_throws_nsIException(function () { + env.QueryInterface(Components.interfaces.nsIFile); + }, "NS_NOINTERFACE"); +} + diff --git a/testing/xpcshell/example/unit/test_check_nsIException_failing.js b/testing/xpcshell/example/unit/test_check_nsIException_failing.js new file mode 100644 index 000000000..4e562b6d8 --- /dev/null +++ b/testing/xpcshell/example/unit/test_check_nsIException_failing.js @@ -0,0 +1,9 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + do_check_throws_nsIException(function () { + throw Error("I find your relaxed dishabille unpalatable"); + }, "NS_NOINTERFACE"); +} + diff --git a/testing/xpcshell/example/unit/test_do_check_matches.js b/testing/xpcshell/example/unit/test_do_check_matches.js new file mode 100644 index 000000000..51d720b0c --- /dev/null +++ b/testing/xpcshell/example/unit/test_do_check_matches.js @@ -0,0 +1,14 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + do_check_matches({x:1}, {x:1}); + + // Property order is irrelevant. + do_check_matches({x:"foo", y:"bar"}, {y:"bar", x:"foo"});// pass + + // Patterns nest. + do_check_matches({a:1, b:{c:2,d:3}}, {a:1, b:{c:2,d:3}}); + + do_check_matches([3,4,5], [3,4,5]); +} diff --git a/testing/xpcshell/example/unit/test_do_check_matches_failing.js b/testing/xpcshell/example/unit/test_do_check_matches_failing.js new file mode 100644 index 000000000..21c70c968 --- /dev/null +++ b/testing/xpcshell/example/unit/test_do_check_matches_failing.js @@ -0,0 +1,12 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + do_check_matches({x:1}, {}); // fail: all pattern props required + do_check_matches({x:1}, {x:2}); // fail: values must match + do_check_matches({x:undefined}, {}); + + // 'length' property counts, even if non-enumerable. + do_check_matches([3,4,5], [3,5,5]); // fail; value doesn't match + do_check_matches([3,4,5], [3,4,5,6]);// fail; length doesn't match +} diff --git a/testing/xpcshell/example/unit/test_do_check_null.js b/testing/xpcshell/example/unit/test_do_check_null.js new file mode 100644 index 000000000..67a2fd967 --- /dev/null +++ b/testing/xpcshell/example/unit/test_do_check_null.js @@ -0,0 +1,6 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + do_check_null(null); +} diff --git a/testing/xpcshell/example/unit/test_do_check_null_failing.js b/testing/xpcshell/example/unit/test_do_check_null_failing.js new file mode 100644 index 000000000..7b800f65f --- /dev/null +++ b/testing/xpcshell/example/unit/test_do_check_null_failing.js @@ -0,0 +1,6 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + do_check_null(0); +} diff --git a/testing/xpcshell/example/unit/test_do_get_tempdir.js b/testing/xpcshell/example/unit/test_do_get_tempdir.js new file mode 100644 index 000000000..44b780f84 --- /dev/null +++ b/testing/xpcshell/example/unit/test_do_get_tempdir.js @@ -0,0 +1,16 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +/* This tests that do_get_tempdir returns a directory that we can write to. */ + +var Ci = Components.interfaces; + +function run_test() { + let tmpd = do_get_tempdir(); + do_check_true(tmpd.exists()); + tmpd.append("testfile"); + tmpd.create(Ci.nsIFile.NORMAL_FILE_TYPE, 600); + do_check_true(tmpd.exists()); +} diff --git a/testing/xpcshell/example/unit/test_execute_soon.js b/testing/xpcshell/example/unit/test_execute_soon.js new file mode 100644 index 000000000..0520583f3 --- /dev/null +++ b/testing/xpcshell/example/unit/test_execute_soon.js @@ -0,0 +1,20 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* ***** BEGIN LICENSE BLOCK ***** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/licenses/publicdomain/ + * ***** END LICENSE BLOCK ***** */ + +var complete = false; + +function run_test() { + dump("Starting test\n"); + do_register_cleanup(function() { + dump("Checking test completed\n"); + do_check_true(complete); + }); + + do_execute_soon(function execute_soon_callback() { + dump("do_execute_soon callback\n"); + complete = true; + }); +} diff --git a/testing/xpcshell/example/unit/test_fail.js b/testing/xpcshell/example/unit/test_fail.js new file mode 100644 index 000000000..8d9fea2ad --- /dev/null +++ b/testing/xpcshell/example/unit/test_fail.js @@ -0,0 +1,8 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +function run_test() { + // This test expects to fail. + do_check_true(false); +} diff --git a/testing/xpcshell/example/unit/test_get_file.js b/testing/xpcshell/example/unit/test_get_file.js new file mode 100644 index 000000000..3fe80255a --- /dev/null +++ b/testing/xpcshell/example/unit/test_get_file.js @@ -0,0 +1,33 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var subscriptLoaded = false; + +function run_test() { + var lf = do_get_file("file.txt"); + do_check_true(lf.exists()); + do_check_true(lf.isFile()); + // check that allowNonexistent works + lf = do_get_file("file.txt.notfound", true); + do_check_false(lf.exists()); + // check that we can get a file from a subdirectory + lf = do_get_file("subdir/file.txt"); + do_check_true(lf.exists()); + do_check_true(lf.isFile()); + // and that we can get a handle to a directory itself + lf = do_get_file("subdir/"); + do_check_true(lf.exists()); + do_check_true(lf.isDirectory()); + // check that we can go up a level + lf = do_get_file(".."); + do_check_true(lf.exists()); + lf.append("unit"); + lf.append("file.txt"); + do_check_true(lf.exists()); + // check that do_get_cwd works + lf = do_get_cwd(); + do_check_true(lf.exists()); + do_check_true(lf.isDirectory()); +} diff --git a/testing/xpcshell/example/unit/test_get_idle.js b/testing/xpcshell/example/unit/test_get_idle.js new file mode 100644 index 000000000..fe0a42f06 --- /dev/null +++ b/testing/xpcshell/example/unit/test_get_idle.js @@ -0,0 +1,23 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +function run_test() { + print("Init the fake idle service and check its identity."); + let fakeIdleService = Components.classes["@mozilla.org/widget/idleservice;1"]. + getService(Components.interfaces.nsIIdleService); + try { + fakeIdleService.QueryInterface(Components.interfaces.nsIFactory); + } catch (ex) { + do_throw("The fake idle service implements nsIFactory."); + } + // We need at least one PASS, thus sanity check the idle time. + do_check_eq(fakeIdleService.idleTime, 0); + + print("Init the real idle service and check its identity."); + let realIdleService = do_get_idle(); + try { + realIdleService.QueryInterface(Components.interfaces.nsIFactory); + do_throw("The real idle service does not implement nsIFactory."); + } catch (ex) {} +} diff --git a/testing/xpcshell/example/unit/test_import_module.js b/testing/xpcshell/example/unit/test_import_module.js new file mode 100644 index 000000000..280d63ad2 --- /dev/null +++ b/testing/xpcshell/example/unit/test_import_module.js @@ -0,0 +1,22 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/** + * Ensures that tests can import a module in the same folder through: + * Components.utils.import("resource://test/module.jsm"); + */ + +function run_test() { + do_check_true(typeof(this['MODULE_IMPORTED']) == "undefined"); + do_check_true(typeof(this['MODULE_URI']) == "undefined"); + let uri = "resource://test/import_module.jsm"; + Components.utils.import(uri); + do_check_true(MODULE_URI == uri); + do_check_true(MODULE_IMPORTED); + do_check_true(SUBMODULE_IMPORTED); + do_check_true(same_scope); + do_check_true(SUBMODULE_IMPORTED_TO_SCOPE); +} diff --git a/testing/xpcshell/example/unit/test_load.js b/testing/xpcshell/example/unit/test_load.js new file mode 100644 index 000000000..4f9962600 --- /dev/null +++ b/testing/xpcshell/example/unit/test_load.js @@ -0,0 +1,21 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var subscriptLoaded = false; + +function run_test() { + load("load_subscript.js"); + do_check_true(subscriptLoaded); + subscriptLoaded = false; + try { + load("file_that_does_not_exist.js"); + subscriptLoaded = true; + } + catch (ex) { + do_check_eq(ex.message.substring(0,16), "cannot open file"); + } + do_check_false(subscriptLoaded, "load() should throw an error"); +} diff --git a/testing/xpcshell/example/unit/test_load_httpd_js.js b/testing/xpcshell/example/unit/test_load_httpd_js.js new file mode 100644 index 000000000..fbba83300 --- /dev/null +++ b/testing/xpcshell/example/unit/test_load_httpd_js.js @@ -0,0 +1,13 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +Components.utils.import("resource://testing-common/httpd.js"); + +function run_test() { + var httpserver = new HttpServer(); + do_check_neq(httpserver, null); + do_check_neq(httpserver.QueryInterface(Components.interfaces.nsIHttpServer), null); +} diff --git a/testing/xpcshell/example/unit/test_location.js b/testing/xpcshell/example/unit/test_location.js new file mode 100644 index 000000000..8c17b1dec --- /dev/null +++ b/testing/xpcshell/example/unit/test_location.js @@ -0,0 +1,11 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +function run_test() { + do_check_eq(__LOCATION__.leafName, "test_location.js"); + // also check that __LOCATION__ works via load() + load("location_load.js"); +} diff --git a/testing/xpcshell/example/unit/test_profile.js b/testing/xpcshell/example/unit/test_profile.js new file mode 100644 index 000000000..29a34c7c8 --- /dev/null +++ b/testing/xpcshell/example/unit/test_profile.js @@ -0,0 +1,11 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +function run_test() +{ + load("check_profile.js"); + check_do_get_profile(false); +} diff --git a/testing/xpcshell/example/unit/test_profile_afterChange.js b/testing/xpcshell/example/unit/test_profile_afterChange.js new file mode 100644 index 000000000..d3c4ce031 --- /dev/null +++ b/testing/xpcshell/example/unit/test_profile_afterChange.js @@ -0,0 +1,11 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +function run_test() +{ + load("check_profile.js"); + check_do_get_profile(true); +} diff --git a/testing/xpcshell/example/unit/test_sample.js b/testing/xpcshell/example/unit/test_sample.js new file mode 100644 index 000000000..2e7b7dbb6 --- /dev/null +++ b/testing/xpcshell/example/unit/test_sample.js @@ -0,0 +1,21 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* This is the most basic testcase. It makes some trivial assertions, + * then sets a timeout, and exits the test harness when that timeout + * fires. This is meant to demonstrate that there is a complete event + * system available to test scripts. + * Available functions are described at: + * http://developer.mozilla.org/en/docs/Writing_xpcshell-based_unit_tests + */ +function run_test() { + do_check_eq(57, 57) + do_check_neq(1, 2) + do_check_true(true); + + do_test_pending(); + do_timeout(100, do_test_finished); +} diff --git a/testing/xpcshell/example/unit/test_skip.js b/testing/xpcshell/example/unit/test_skip.js new file mode 100644 index 000000000..8d9fea2ad --- /dev/null +++ b/testing/xpcshell/example/unit/test_skip.js @@ -0,0 +1,8 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +function run_test() { + // This test expects to fail. + do_check_true(false); +} diff --git a/testing/xpcshell/example/unit/xpcshell.ini b/testing/xpcshell/example/unit/xpcshell.ini new file mode 100644 index 000000000..3af6770af --- /dev/null +++ b/testing/xpcshell/example/unit/xpcshell.ini @@ -0,0 +1,47 @@ +; This Source Code Form is subject to the terms of the Mozilla Public +; License, v. 2.0. If a copy of the MPL was not distributed with this +; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +[DEFAULT] +head = +tail = +skip-if = toolkit == 'gonk' +support-files = + subdir/file.txt + file.txt + import_module.jsm + import_sub_module.jsm + load_subscript.js + location_load.js + check_profile.js + +[test_check_nsIException.js] +[test_check_nsIException_failing.js] +fail-if = true + +[test_do_get_tempdir.js] +[test_execute_soon.js] +[test_get_file.js] +[test_get_idle.js] +[test_import_module.js] +[test_load.js] +[test_load_httpd_js.js] +[test_location.js] +[test_profile.js] +[test_profile_afterChange.js] +[test_sample.js] + +[test_fail.js] +fail-if = true + +[test_skip.js] +skip-if = true + +[test_do_check_null.js] + +[test_do_check_null_failing.js] +fail-if = true + +[test_do_check_matches.js] +[test_do_check_matches_failing.js] +fail-if = true diff --git a/testing/xpcshell/head.js b/testing/xpcshell/head.js new file mode 100644 index 000000000..74fd482cf --- /dev/null +++ b/testing/xpcshell/head.js @@ -0,0 +1,1663 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * This file contains common code that is loaded before each test file(s). + * See http://developer.mozilla.org/en/docs/Writing_xpcshell-based_unit_tests + * for more information. + */ + +var _quit = false; +var _passed = true; +var _tests_pending = 0; +var _cleanupFunctions = []; +var _pendingTimers = []; +var _profileInitialized = false; + +// Register the testing-common resource protocol early, to have access to its +// modules. +_register_modules_protocol_handler(); + +var _Promise = Components.utils.import("resource://gre/modules/Promise.jsm", {}).Promise; +var _PromiseTestUtils = Components.utils.import("resource://testing-common/PromiseTestUtils.jsm", {}).PromiseTestUtils; +Components.utils.importGlobalProperties(["XMLHttpRequest"]); + +// Support a common assertion library, Assert.jsm. +var AssertCls = Components.utils.import("resource://testing-common/Assert.jsm", null).Assert; +// Pass a custom report function for xpcshell-test style reporting. +var Assert = new AssertCls(function(err, message, stack) { + if (err) { + do_report_result(false, err.message, err.stack); + } else { + do_report_result(true, message, stack); + } +}); + + +var _add_params = function (params) { + if (typeof _XPCSHELL_PROCESS != "undefined") { + params.xpcshell_process = _XPCSHELL_PROCESS; + } +}; + +var _dumpLog = function (raw_msg) { + dump("\n" + JSON.stringify(raw_msg) + "\n"); +} + +var _LoggerClass = Components.utils.import("resource://testing-common/StructuredLog.jsm", null).StructuredLogger; +var _testLogger = new _LoggerClass("xpcshell/head.js", _dumpLog, [_add_params]); + +// Disable automatic network detection, so tests work correctly when +// not connected to a network. +{ + let ios = Components.classes["@mozilla.org/network/io-service;1"] + .getService(Components.interfaces.nsIIOService2); + ios.manageOfflineStatus = false; + ios.offline = false; +} + +// Determine if we're running on parent or child +var runningInParent = true; +try { + runningInParent = Components.classes["@mozilla.org/xre/runtime;1"]. + getService(Components.interfaces.nsIXULRuntime).processType + == Components.interfaces.nsIXULRuntime.PROCESS_TYPE_DEFAULT; +} +catch (e) { } + +// Only if building of places is enabled. +if (runningInParent && + "mozIAsyncHistory" in Components.interfaces) { + // Ensure places history is enabled for xpcshell-tests as some non-FF + // apps disable it. + let prefs = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefBranch); + prefs.setBoolPref("places.history.enabled", true); +} + +try { + if (runningInParent) { + let prefs = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefBranch); + + // disable necko IPC security checks for xpcshell, as they lack the + // docshells needed to pass them + prefs.setBoolPref("network.disable.ipc.security", true); + + // Disable IPv6 lookups for 'localhost' on windows. + if ("@mozilla.org/windows-registry-key;1" in Components.classes) { + prefs.setCharPref("network.dns.ipv4OnlyDomains", "localhost"); + } + } +} +catch (e) { } + +// Configure crash reporting, if possible +// We rely on the Python harness to set MOZ_CRASHREPORTER, +// MOZ_CRASHREPORTER_NO_REPORT, and handle checking for minidumps. +// Note that if we're in a child process, we don't want to init the +// crashreporter component. +try { + if (runningInParent && + "@mozilla.org/toolkit/crash-reporter;1" in Components.classes) { + let crashReporter = + Components.classes["@mozilla.org/toolkit/crash-reporter;1"] + .getService(Components.interfaces.nsICrashReporter); + crashReporter.UpdateCrashEventsDir(); + crashReporter.minidumpPath = do_get_minidumpdir(); + } +} +catch (e) { } + +// Configure a console listener so messages sent to it are logged as part +// of the test. +try { + let levelNames = {} + for (let level of ["debug", "info", "warn", "error"]) { + levelNames[Components.interfaces.nsIConsoleMessage[level]] = level; + } + + let listener = { + QueryInterface : function(iid) { + if (!iid.equals(Components.interfaces.nsISupports) && + !iid.equals(Components.interfaces.nsIConsoleListener)) { + throw Components.results.NS_NOINTERFACE; + } + return this; + }, + observe : function (msg) { + if (typeof do_print === "function") + do_print("CONSOLE_MESSAGE: (" + levelNames[msg.logLevel] + ") " + msg.toString()); + } + }; + Components.classes["@mozilla.org/consoleservice;1"] + .getService(Components.interfaces.nsIConsoleService) + .registerListener(listener); +} catch (e) {} +/** + * Date.now() is not necessarily monotonically increasing (insert sob story + * about times not being the right tool to use for measuring intervals of time, + * robarnold can tell all), so be wary of error by erring by at least + * _timerFuzz ms. + */ +const _timerFuzz = 15; + +function _Timer(func, delay) { + delay = Number(delay); + if (delay < 0) + do_throw("do_timeout() delay must be nonnegative"); + + if (typeof func !== "function") + do_throw("string callbacks no longer accepted; use a function!"); + + this._func = func; + this._start = Date.now(); + this._delay = delay; + + var timer = Components.classes["@mozilla.org/timer;1"] + .createInstance(Components.interfaces.nsITimer); + timer.initWithCallback(this, delay + _timerFuzz, timer.TYPE_ONE_SHOT); + + // Keep timer alive until it fires + _pendingTimers.push(timer); +} +_Timer.prototype = { + QueryInterface: function(iid) { + if (iid.equals(Components.interfaces.nsITimerCallback) || + iid.equals(Components.interfaces.nsISupports)) + return this; + + throw Components.results.NS_ERROR_NO_INTERFACE; + }, + + notify: function(timer) { + _pendingTimers.splice(_pendingTimers.indexOf(timer), 1); + + // The current nsITimer implementation can undershoot, but even if it + // couldn't, paranoia is probably a virtue here given the potential for + // random orange on tinderboxen. + var end = Date.now(); + var elapsed = end - this._start; + if (elapsed >= this._delay) { + try { + this._func.call(null); + } catch (e) { + do_throw("exception thrown from do_timeout callback: " + e); + } + return; + } + + // Timer undershot, retry with a little overshoot to try to avoid more + // undershoots. + var newDelay = this._delay - elapsed; + do_timeout(newDelay, this._func); + } +}; + +function _do_main() { + if (_quit) + return; + + _testLogger.info("running event loop"); + + var thr = Components.classes["@mozilla.org/thread-manager;1"] + .getService().currentThread; + + while (!_quit) + thr.processNextEvent(true); + + while (thr.hasPendingEvents()) + thr.processNextEvent(true); +} + +function _do_quit() { + _testLogger.info("exiting test"); + _quit = true; +} + +/** + * Overrides idleService with a mock. Idle is commonly used for maintenance + * tasks, thus if a test uses a service that requires the idle service, it will + * start handling them. + * This behaviour would cause random failures and slowdown tests execution, + * for example by running database vacuum or cleanups for each test. + * + * @note Idle service is overridden by default. If a test requires it, it will + * have to call do_get_idle() function at least once before use. + */ +var _fakeIdleService = { + get registrar() { + delete this.registrar; + return this.registrar = + Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar); + }, + contractID: "@mozilla.org/widget/idleservice;1", + get CID() { + return this.registrar.contractIDToCID(this.contractID); + }, + + activate: function FIS_activate() + { + if (!this.originalFactory) { + // Save original factory. + this.originalFactory = + Components.manager.getClassObject(Components.classes[this.contractID], + Components.interfaces.nsIFactory); + // Unregister original factory. + this.registrar.unregisterFactory(this.CID, this.originalFactory); + // Replace with the mock. + this.registrar.registerFactory(this.CID, "Fake Idle Service", + this.contractID, this.factory + ); + } + }, + + deactivate: function FIS_deactivate() + { + if (this.originalFactory) { + // Unregister the mock. + this.registrar.unregisterFactory(this.CID, this.factory); + // Restore original factory. + this.registrar.registerFactory(this.CID, "Idle Service", + this.contractID, this.originalFactory); + delete this.originalFactory; + } + }, + + factory: { + // nsIFactory + createInstance: function (aOuter, aIID) + { + if (aOuter) { + throw Components.results.NS_ERROR_NO_AGGREGATION; + } + return _fakeIdleService.QueryInterface(aIID); + }, + lockFactory: function (aLock) { + throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + }, + QueryInterface: function(aIID) { + if (aIID.equals(Components.interfaces.nsIFactory) || + aIID.equals(Components.interfaces.nsISupports)) { + return this; + } + throw Components.results.NS_ERROR_NO_INTERFACE; + } + }, + + // nsIIdleService + get idleTime() { + return 0; + }, + addIdleObserver: function () {}, + removeIdleObserver: function () {}, + + QueryInterface: function(aIID) { + // Useful for testing purposes, see test_get_idle.js. + if (aIID.equals(Components.interfaces.nsIFactory)) { + return this.factory; + } + if (aIID.equals(Components.interfaces.nsIIdleService) || + aIID.equals(Components.interfaces.nsISupports)) { + return this; + } + throw Components.results.NS_ERROR_NO_INTERFACE; + } +} + +/** + * Restores the idle service factory if needed and returns the service's handle. + * @return A handle to the idle service. + */ +function do_get_idle() { + _fakeIdleService.deactivate(); + return Components.classes[_fakeIdleService.contractID] + .getService(Components.interfaces.nsIIdleService); +} + +// Map resource://test/ to current working directory and +// resource://testing-common/ to the shared test modules directory. +function _register_protocol_handlers() { + let ios = Components.classes["@mozilla.org/network/io-service;1"] + .getService(Components.interfaces.nsIIOService); + let protocolHandler = + ios.getProtocolHandler("resource") + .QueryInterface(Components.interfaces.nsIResProtocolHandler); + + let curDirURI = ios.newFileURI(do_get_cwd()); + protocolHandler.setSubstitution("test", curDirURI); + + _register_modules_protocol_handler(); +} + +function _register_modules_protocol_handler() { + if (!_TESTING_MODULES_DIR) { + throw new Error("Please define a path where the testing modules can be " + + "found in a variable called '_TESTING_MODULES_DIR' before " + + "head.js is included."); + } + + let ios = Components.classes["@mozilla.org/network/io-service;1"] + .getService(Components.interfaces.nsIIOService); + let protocolHandler = + ios.getProtocolHandler("resource") + .QueryInterface(Components.interfaces.nsIResProtocolHandler); + + let modulesFile = Components.classes["@mozilla.org/file/local;1"]. + createInstance(Components.interfaces.nsILocalFile); + modulesFile.initWithPath(_TESTING_MODULES_DIR); + + if (!modulesFile.exists()) { + throw new Error("Specified modules directory does not exist: " + + _TESTING_MODULES_DIR); + } + + if (!modulesFile.isDirectory()) { + throw new Error("Specified modules directory is not a directory: " + + _TESTING_MODULES_DIR); + } + + let modulesURI = ios.newFileURI(modulesFile); + + protocolHandler.setSubstitution("testing-common", modulesURI); +} + +/* Debugging support */ +// Used locally and by our self-tests. +function _setupDebuggerServer(breakpointFiles, callback) { + let prefs = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefBranch); + + // Always allow remote debugging. + prefs.setBoolPref("devtools.debugger.remote-enabled", true); + + // for debugging-the-debugging, let an env var cause log spew. + let env = Components.classes["@mozilla.org/process/environment;1"] + .getService(Components.interfaces.nsIEnvironment); + if (env.get("DEVTOOLS_DEBUGGER_LOG")) { + prefs.setBoolPref("devtools.debugger.log", true); + } + if (env.get("DEVTOOLS_DEBUGGER_LOG_VERBOSE")) { + prefs.setBoolPref("devtools.debugger.log.verbose", true); + } + + let require; + try { + ({ require } = Components.utils.import("resource://devtools/shared/Loader.jsm", {})); + } catch (e) { + throw new Error("resource://devtools appears to be inaccessible from the " + + "xpcshell environment.\n" + + "This can usually be resolved by adding:\n" + + " firefox-appdir = browser\n" + + "to the xpcshell.ini manifest.\n" + + "It is possible for this to alter test behevior by " + + "triggering additional browser code to run, so check " + + "test behavior after making this change.\n" + + "See also https://bugzil.la/1215378.") + } + let { DebuggerServer } = require("devtools/server/main"); + let { OriginalLocation } = require("devtools/server/actors/common"); + DebuggerServer.init(); + DebuggerServer.addBrowserActors(); + DebuggerServer.addActors("resource://testing-common/dbg-actors.js"); + DebuggerServer.allowChromeProcess = true; + + // An observer notification that tells us when we can "resume" script + // execution. + let obsSvc = Components.classes["@mozilla.org/observer-service;1"]. + getService(Components.interfaces.nsIObserverService); + + const TOPICS = ["devtools-thread-resumed", "xpcshell-test-devtools-shutdown"]; + let observe = function(subject, topic, data) { + switch (topic) { + case "devtools-thread-resumed": + // Exceptions in here aren't reported and block the debugger from + // resuming, so... + try { + // Add a breakpoint for the first line in our test files. + let threadActor = subject.wrappedJSObject; + for (let file of breakpointFiles) { + // Pass an empty `source` object to workaround `source` function assertion + let sourceActor = threadActor.sources.source({originalUrl: file, source: {}}); + sourceActor._getOrCreateBreakpointActor(new OriginalLocation(sourceActor, 1)); + } + } catch (ex) { + do_print("Failed to initialize breakpoints: " + ex + "\n" + ex.stack); + } + break; + case "xpcshell-test-devtools-shutdown": + // the debugger has shutdown before we got a resume event - nothing + // special to do here. + break; + } + for (let topicToRemove of TOPICS) { + obsSvc.removeObserver(observe, topicToRemove); + } + callback(); + }; + + for (let topic of TOPICS) { + obsSvc.addObserver(observe, topic, false); + } + return DebuggerServer; +} + +function _initDebugging(port) { + let initialized = false; + let DebuggerServer = _setupDebuggerServer(_TEST_FILE, () => {initialized = true;}); + + do_print(""); + do_print("*******************************************************************"); + do_print("Waiting for the debugger to connect on port " + port) + do_print("") + do_print("To connect the debugger, open a Firefox instance, select 'Connect'"); + do_print("from the Developer menu and specify the port as " + port); + do_print("*******************************************************************"); + do_print("") + + let AuthenticatorType = DebuggerServer.Authenticators.get("PROMPT"); + let authenticator = new AuthenticatorType.Server(); + authenticator.allowConnection = () => { + return DebuggerServer.AuthenticationResult.ALLOW; + }; + + let listener = DebuggerServer.createListener(); + listener.portOrPath = port; + listener.authenticator = authenticator; + listener.open(); + + // spin an event loop until the debugger connects. + let thr = Components.classes["@mozilla.org/thread-manager;1"] + .getService().currentThread; + while (!initialized) { + do_print("Still waiting for debugger to connect..."); + thr.processNextEvent(true); + } + // NOTE: if you want to debug the harness itself, you can now add a 'debugger' + // statement anywhere and it will stop - but we've already added a breakpoint + // for the first line of the test scripts, so we just continue... + do_print("Debugger connected, starting test execution"); +} + +function _execute_test() { + // _JSDEBUGGER_PORT is dynamically defined by . + if (_JSDEBUGGER_PORT) { + try { + _initDebugging(_JSDEBUGGER_PORT); + } catch (ex) { + // Fail the test run immediately if debugging is requested but fails, so + // that the failure state is more obvious. + do_throw(`Failed to initialize debugging: ${ex}`, ex.stack); + } + } + + _register_protocol_handlers(); + + // Override idle service by default. + // Call do_get_idle() to restore the factory and get the service. + _fakeIdleService.activate(); + + _PromiseTestUtils.init(); + _PromiseTestUtils.Assert = Assert; + + let coverageCollector = null; + if (typeof _JSCOV_DIR === 'string') { + let _CoverageCollector = Components.utils.import("resource://testing-common/CoverageUtils.jsm", {}).CoverageCollector; + coverageCollector = new _CoverageCollector(_JSCOV_DIR); + } + + // _HEAD_FILES is dynamically defined by . + _load_files(_HEAD_FILES); + // _TEST_FILE is dynamically defined by . + _load_files(_TEST_FILE); + + // Tack Assert.jsm methods to the current scope. + this.Assert = Assert; + for (let func in Assert) { + this[func] = Assert[func].bind(Assert); + } + + if (_gTestHasOnly) { + _gTests = _gTests.filter(([props,]) => { + return ("_only" in props) && props._only; + }); + } + + try { + do_test_pending("MAIN run_test"); + // Check if run_test() is defined. If defined, run it. + // Else, call run_next_test() directly to invoke tests + // added by add_test() and add_task(). + if (typeof run_test === "function") { + run_test(); + } else { + run_next_test(); + } + + if (coverageCollector != null) { + coverageCollector.recordTestCoverage(_TEST_FILE[0]); + } + + do_test_finished("MAIN run_test"); + _do_main(); + _PromiseTestUtils.assertNoUncaughtRejections(); + } catch (e) { + _passed = false; + // do_check failures are already logged and set _quit to true and throw + // NS_ERROR_ABORT. If both of those are true it is likely this exception + // has already been logged so there is no need to log it again. It's + // possible that this will mask an NS_ERROR_ABORT that happens after a + // do_check failure though. + if (coverageCollector != null) { + coverageCollector.recordTestCoverage(_TEST_FILE[0]); + } + + if (!_quit || e != Components.results.NS_ERROR_ABORT) { + let extra = {}; + if (e.fileName) { + extra.source_file = e.fileName; + if (e.lineNumber) { + extra.line_number = e.lineNumber; + } + } else { + extra.source_file = "xpcshell/head.js"; + } + let message = _exception_message(e); + if (e.stack) { + extra.stack = _format_stack(e.stack); + } + _testLogger.error(message, extra); + } + } + + if (coverageCollector != null) { + coverageCollector.finalize(); + } + + // _TAIL_FILES is dynamically defined by . + _load_files(_TAIL_FILES); + + // Execute all of our cleanup functions. + let reportCleanupError = function(ex) { + let stack, filename; + if (ex && typeof ex == "object" && "stack" in ex) { + stack = ex.stack; + } else { + stack = Components.stack.caller; + } + if (stack instanceof Components.interfaces.nsIStackFrame) { + filename = stack.filename; + } else if (ex.fileName) { + filename = ex.fileName; + } + _testLogger.error(_exception_message(ex), + { + stack: _format_stack(stack), + source_file: filename + }); + }; + + let func; + while ((func = _cleanupFunctions.pop())) { + let result; + try { + result = func(); + } catch (ex) { + reportCleanupError(ex); + continue; + } + if (result && typeof result == "object" + && "then" in result && typeof result.then == "function") { + // This is a promise, wait until it is satisfied before proceeding + let complete = false; + let promise = result.then(null, reportCleanupError); + promise = promise.then(() => complete = true); + let thr = Components.classes["@mozilla.org/thread-manager;1"] + .getService().currentThread; + while (!complete) { + thr.processNextEvent(true); + } + } + } + + // Restore idle service to avoid leaks. + _fakeIdleService.deactivate(); + + if (_profileInitialized) { + // Since we have a profile, we will notify profile shutdown topics at + // the end of the current test, to ensure correct cleanup on shutdown. + let obs = Components.classes["@mozilla.org/observer-service;1"] + .getService(Components.interfaces.nsIObserverService); + obs.notifyObservers(null, "profile-change-net-teardown", null); + obs.notifyObservers(null, "profile-change-teardown", null); + obs.notifyObservers(null, "profile-before-change", null); + obs.notifyObservers(null, "profile-before-change-qm", null); + + _profileInitialized = false; + } + + try { + _PromiseTestUtils.ensureDOMPromiseRejectionsProcessed(); + _PromiseTestUtils.assertNoUncaughtRejections(); + _PromiseTestUtils.assertNoMoreExpectedRejections(); + } finally { + // It's important to terminate the module to avoid crashes on shutdown. + _PromiseTestUtils.uninit(); + } +} + +/** + * Loads files. + * + * @param aFiles Array of files to load. + */ +function _load_files(aFiles) { + function load_file(element, index, array) { + try { + load(element); + } catch (e) { + let extra = { + source_file: element + } + if (e.stack) { + extra.stack = _format_stack(e.stack); + } + _testLogger.error(_exception_message(e), extra); + } + } + + aFiles.forEach(load_file); +} + +function _wrap_with_quotes_if_necessary(val) { + return typeof val == "string" ? '"' + val + '"' : val; +} + +/************** Functions to be used from the tests **************/ + +/** + * Prints a message to the output log. + */ +function do_print(msg, data) { + msg = _wrap_with_quotes_if_necessary(msg); + data = data ? data : null; + _testLogger.info(msg, data); +} + +/** + * Calls the given function at least the specified number of milliseconds later. + * The callback will not undershoot the given time, but it might overshoot -- + * don't expect precision! + * + * @param delay : uint + * the number of milliseconds to delay + * @param callback : function() : void + * the function to call + */ +function do_timeout(delay, func) { + new _Timer(func, Number(delay)); +} + +function do_execute_soon(callback, aName) { + let funcName = (aName ? aName : callback.name); + do_test_pending(funcName); + var tm = Components.classes["@mozilla.org/thread-manager;1"] + .getService(Components.interfaces.nsIThreadManager); + + tm.mainThread.dispatch({ + run: function() { + try { + callback(); + } catch (e) { + // do_check failures are already logged and set _quit to true and throw + // NS_ERROR_ABORT. If both of those are true it is likely this exception + // has already been logged so there is no need to log it again. It's + // possible that this will mask an NS_ERROR_ABORT that happens after a + // do_check failure though. + if (!_quit || e != Components.results.NS_ERROR_ABORT) { + let stack = e.stack ? _format_stack(e.stack) : null; + _testLogger.testStatus(_TEST_NAME, + funcName, + 'FAIL', + 'PASS', + _exception_message(e), + stack); + _do_quit(); + } + } + finally { + do_test_finished(funcName); + } + } + }, Components.interfaces.nsIThread.DISPATCH_NORMAL); +} + +/** + * Shows an error message and the current stack and aborts the test. + * + * @param error A message string or an Error object. + * @param stack null or nsIStackFrame object or a string containing + * \n separated stack lines (as in Error().stack). + */ +function do_throw(error, stack) { + let filename = ""; + // If we didn't get passed a stack, maybe the error has one + // otherwise get it from our call context + stack = stack || error.stack || Components.stack.caller; + + if (stack instanceof Components.interfaces.nsIStackFrame) + filename = stack.filename; + else if (error.fileName) + filename = error.fileName; + + _testLogger.error(_exception_message(error), + { + source_file: filename, + stack: _format_stack(stack) + }); + _abort_failed_test(); +} + +function _abort_failed_test() { + // Called to abort the test run after all failures are logged. + _passed = false; + _do_quit(); + throw Components.results.NS_ERROR_ABORT; +} + +function _format_stack(stack) { + let normalized; + if (stack instanceof Components.interfaces.nsIStackFrame) { + let frames = []; + for (let frame = stack; frame; frame = frame.caller) { + frames.push(frame.filename + ":" + frame.name + ":" + frame.lineNumber); + } + normalized = frames.join("\n"); + } else { + normalized = "" + stack; + } + return _Task.Debugging.generateReadableStack(normalized, " "); +} + +// Make a nice display string from an object that behaves +// like Error +function _exception_message(ex) { + let message = ""; + if (ex.name) { + message = ex.name + ": "; + } + if (ex.message) { + message += ex.message; + } + if (ex.fileName) { + message += (" at " + ex.fileName); + if (ex.lineNumber) { + message += (":" + ex.lineNumber); + } + } + if (message !== "") { + return message; + } + // Force ex to be stringified + return "" + ex; +} + +function do_report_unexpected_exception(ex, text) { + let filename = Components.stack.caller.filename; + text = text ? text + " - " : ""; + + _passed = false; + _testLogger.error(text + "Unexpected exception " + _exception_message(ex), + { + source_file: filename, + stack: _format_stack(ex.stack) + }); + _do_quit(); + throw Components.results.NS_ERROR_ABORT; +} + +function do_note_exception(ex, text) { + let filename = Components.stack.caller.filename; + _testLogger.info(text + "Swallowed exception " + _exception_message(ex), + { + source_file: filename, + stack: _format_stack(ex.stack) + }); +} + +function _do_check_neq(left, right, stack, todo) { + Assert.notEqual(left, right); +} + +function do_check_neq(left, right, stack) { + if (!stack) + stack = Components.stack.caller; + + _do_check_neq(left, right, stack, false); +} + +function todo_check_neq(left, right, stack) { + if (!stack) + stack = Components.stack.caller; + + _do_check_neq(left, right, stack, true); +} + +function do_report_result(passed, text, stack, todo) { + while (stack.filename.includes("head.js") && stack.caller) { + stack = stack.caller; + } + + let name = _gRunningTest ? _gRunningTest.name : stack.name; + let message; + if (name) { + message = "[" + name + " : " + stack.lineNumber + "] " + text; + } else { + message = text; + } + + if (passed) { + if (todo) { + _testLogger.testStatus(_TEST_NAME, + name, + "PASS", + "FAIL", + message, + _format_stack(stack)); + _abort_failed_test(); + } else { + _testLogger.testStatus(_TEST_NAME, + name, + "PASS", + "PASS", + message); + } + } else { + if (todo) { + _testLogger.testStatus(_TEST_NAME, + name, + "FAIL", + "FAIL", + message); + } else { + _testLogger.testStatus(_TEST_NAME, + name, + "FAIL", + "PASS", + message, + _format_stack(stack)); + _abort_failed_test(); + } + } +} + +function _do_check_eq(left, right, stack, todo) { + if (!stack) + stack = Components.stack.caller; + + var text = _wrap_with_quotes_if_necessary(left) + " == " + + _wrap_with_quotes_if_necessary(right); + do_report_result(left == right, text, stack, todo); +} + +function do_check_eq(left, right, stack) { + Assert.equal(left, right); +} + +function todo_check_eq(left, right, stack) { + if (!stack) + stack = Components.stack.caller; + + _do_check_eq(left, right, stack, true); +} + +function do_check_true(condition, stack) { + Assert.ok(condition, stack); +} + +function todo_check_true(condition, stack) { + if (!stack) + stack = Components.stack.caller; + + todo_check_eq(condition, true, stack); +} + +function do_check_false(condition, stack) { + Assert.ok(!condition, stack); +} + +function todo_check_false(condition, stack) { + if (!stack) + stack = Components.stack.caller; + + todo_check_eq(condition, false, stack); +} + +function do_check_null(condition, stack) { + Assert.equal(condition, null); +} + +function todo_check_null(condition, stack=Components.stack.caller) { + todo_check_eq(condition, null, stack); +} +function do_check_matches(pattern, value) { + Assert.deepEqual(pattern, value); +} + +// Check that |func| throws an nsIException that has +// |Components.results[resultName]| as the value of its 'result' property. +function do_check_throws_nsIException(func, resultName, + stack=Components.stack.caller, todo=false) +{ + let expected = Components.results[resultName]; + if (typeof expected !== 'number') { + do_throw("do_check_throws_nsIException requires a Components.results" + + " property name, not " + uneval(resultName), stack); + } + + let msg = ("do_check_throws_nsIException: func should throw" + + " an nsIException whose 'result' is Components.results." + + resultName); + + try { + func(); + } catch (ex) { + if (!(ex instanceof Components.interfaces.nsIException) || + ex.result !== expected) { + do_report_result(false, msg + ", threw " + legible_exception(ex) + + " instead", stack, todo); + } + + do_report_result(true, msg, stack, todo); + return; + } + + // Call this here, not in the 'try' clause, so do_report_result's own + // throw doesn't get caught by our 'catch' clause. + do_report_result(false, msg + ", but returned normally", stack, todo); +} + +// Produce a human-readable form of |exception|. This looks up +// Components.results values, tries toString methods, and so on. +function legible_exception(exception) +{ + switch (typeof exception) { + case 'object': + if (exception instanceof Components.interfaces.nsIException) { + return "nsIException instance: " + uneval(exception.toString()); + } + return exception.toString(); + + case 'number': + for (let name in Components.results) { + if (exception === Components.results[name]) { + return "Components.results." + name; + } + } + + // Fall through. + default: + return uneval(exception); + } +} + +function do_check_instanceof(value, constructor, + stack=Components.stack.caller, todo=false) { + do_report_result(value instanceof constructor, + "value should be an instance of " + constructor.name, + stack, todo); +} + +function todo_check_instanceof(value, constructor, + stack=Components.stack.caller) { + do_check_instanceof(value, constructor, stack, true); +} + +function do_test_pending(aName) { + ++_tests_pending; + + _testLogger.info("(xpcshell/head.js) | test" + + (aName ? " " + aName : "") + + " pending (" + _tests_pending + ")"); +} + +function do_test_finished(aName) { + _testLogger.info("(xpcshell/head.js) | test" + + (aName ? " " + aName : "") + + " finished (" + _tests_pending + ")"); + if (--_tests_pending == 0) + _do_quit(); +} + +function do_get_file(path, allowNonexistent) { + try { + let lf = Components.classes["@mozilla.org/file/directory_service;1"] + .getService(Components.interfaces.nsIProperties) + .get("CurWorkD", Components.interfaces.nsILocalFile); + + let bits = path.split("/"); + for (let i = 0; i < bits.length; i++) { + if (bits[i]) { + if (bits[i] == "..") + lf = lf.parent; + else + lf.append(bits[i]); + } + } + + if (!allowNonexistent && !lf.exists()) { + // Not using do_throw(): caller will continue. + _passed = false; + var stack = Components.stack.caller; + _testLogger.error("[" + stack.name + " : " + stack.lineNumber + "] " + + lf.path + " does not exist"); + } + + return lf; + } + catch (ex) { + do_throw(ex.toString(), Components.stack.caller); + } + + return null; +} + +// do_get_cwd() isn't exactly self-explanatory, so provide a helper +function do_get_cwd() { + return do_get_file(""); +} + +function do_load_manifest(path) { + var lf = do_get_file(path); + const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar; + do_check_true(Components.manager instanceof nsIComponentRegistrar); + // Previous do_check_true() is not a test check. + Components.manager.autoRegister(lf); +} + +/** + * Parse a DOM document. + * + * @param aPath File path to the document. + * @param aType Content type to use in DOMParser. + * + * @return nsIDOMDocument from the file. + */ +function do_parse_document(aPath, aType) { + switch (aType) { + case "application/xhtml+xml": + case "application/xml": + case "text/xml": + break; + + default: + do_throw("type: expected application/xhtml+xml, application/xml or text/xml," + + " got '" + aType + "'", + Components.stack.caller); + } + + let file = do_get_file(aPath), + ios = Components.classes['@mozilla.org/network/io-service;1'] + .getService(Components.interfaces.nsIIOService), + url = ios.newFileURI(file).spec; + file = null; + return new Promise((resolve, reject) => { + let xhr = new XMLHttpRequest(); + xhr.open("GET", url); + xhr.responseType = "document"; + xhr.onerror = reject; + xhr.onload = () => { + resolve(xhr.response); + }; + xhr.send(); + }); +} + +/** + * Registers a function that will run when the test harness is done running all + * tests. + * + * @param aFunction + * The function to be called when the test harness has finished running. + */ +function do_register_cleanup(aFunction) +{ + _cleanupFunctions.push(aFunction); +} + +/** + * Returns the directory for a temp dir, which is created by the + * test harness. Every test gets its own temp dir. + * + * @return nsILocalFile of the temporary directory + */ +function do_get_tempdir() { + let env = Components.classes["@mozilla.org/process/environment;1"] + .getService(Components.interfaces.nsIEnvironment); + // the python harness sets this in the environment for us + let path = env.get("XPCSHELL_TEST_TEMP_DIR"); + let file = Components.classes["@mozilla.org/file/local;1"] + .createInstance(Components.interfaces.nsILocalFile); + file.initWithPath(path); + return file; +} + +/** + * Returns the directory for crashreporter minidumps. + * + * @return nsILocalFile of the minidump directory + */ +function do_get_minidumpdir() { + let env = Components.classes["@mozilla.org/process/environment;1"] + .getService(Components.interfaces.nsIEnvironment); + // the python harness may set this in the environment for us + let path = env.get("XPCSHELL_MINIDUMP_DIR"); + if (path) { + let file = Components.classes["@mozilla.org/file/local;1"] + .createInstance(Components.interfaces.nsILocalFile); + file.initWithPath(path); + return file; + } else { + return do_get_tempdir(); + } +} + +/** + * Registers a directory with the profile service, + * and return the directory as an nsILocalFile. + * + * @param notifyProfileAfterChange Whether to notify for "profile-after-change". + * @return nsILocalFile of the profile directory. + */ +function do_get_profile(notifyProfileAfterChange = false) { + if (!runningInParent) { + _testLogger.info("Ignoring profile creation from child process."); + return null; + } + + let env = Components.classes["@mozilla.org/process/environment;1"] + .getService(Components.interfaces.nsIEnvironment); + // the python harness sets this in the environment for us + let profd = env.get("XPCSHELL_TEST_PROFILE_DIR"); + let file = Components.classes["@mozilla.org/file/local;1"] + .createInstance(Components.interfaces.nsILocalFile); + file.initWithPath(profd); + + let dirSvc = Components.classes["@mozilla.org/file/directory_service;1"] + .getService(Components.interfaces.nsIProperties); + let provider = { + getFile: function(prop, persistent) { + persistent.value = true; + if (prop == "ProfD" || prop == "ProfLD" || prop == "ProfDS" || + prop == "ProfLDS" || prop == "TmpD") { + return file.clone(); + } + return null; + }, + QueryInterface: function(iid) { + if (iid.equals(Components.interfaces.nsIDirectoryServiceProvider) || + iid.equals(Components.interfaces.nsISupports)) { + return this; + } + throw Components.results.NS_ERROR_NO_INTERFACE; + } + }; + dirSvc.QueryInterface(Components.interfaces.nsIDirectoryService) + .registerProvider(provider); + + let obsSvc = Components.classes["@mozilla.org/observer-service;1"]. + getService(Components.interfaces.nsIObserverService); + + // We need to update the crash events directory when the profile changes. + if (runningInParent && + "@mozilla.org/toolkit/crash-reporter;1" in Components.classes) { + let crashReporter = + Components.classes["@mozilla.org/toolkit/crash-reporter;1"] + .getService(Components.interfaces.nsICrashReporter); + crashReporter.UpdateCrashEventsDir(); + } + + if (!_profileInitialized) { + obsSvc.notifyObservers(null, "profile-do-change", "xpcshell-do-get-profile"); + _profileInitialized = true; + if (notifyProfileAfterChange) { + obsSvc.notifyObservers(null, "profile-after-change", "xpcshell-do-get-profile"); + } + } + + // The methods of 'provider' will retain this scope so null out everything + // to avoid spurious leak reports. + env = null; + profd = null; + dirSvc = null; + provider = null; + obsSvc = null; + return file.clone(); +} + +/** + * This function loads head.js (this file) in the child process, so that all + * functions defined in this file (do_throw, etc) are available to subsequent + * sendCommand calls. It also sets various constants used by these functions. + * + * (Note that you may use sendCommand without calling this function first; you + * simply won't have any of the functions in this file available.) + */ +function do_load_child_test_harness() +{ + // Make sure this isn't called from child process + if (!runningInParent) { + do_throw("run_test_in_child cannot be called from child!"); + } + + // Allow to be called multiple times, but only run once + if (typeof do_load_child_test_harness.alreadyRun != "undefined") + return; + do_load_child_test_harness.alreadyRun = 1; + + _XPCSHELL_PROCESS = "parent"; + + let command = + "const _HEAD_JS_PATH=" + uneval(_HEAD_JS_PATH) + "; " + + "const _HEAD_FILES=" + uneval(_HEAD_FILES) + "; " + + "const _MOZINFO_JS_PATH=" + uneval(_MOZINFO_JS_PATH) + "; " + + "const _TAIL_FILES=" + uneval(_TAIL_FILES) + "; " + + "const _TEST_NAME=" + uneval(_TEST_NAME) + "; " + // We'll need more magic to get the debugger working in the child + + "const _JSDEBUGGER_PORT=0; " + + "const _XPCSHELL_PROCESS='child';"; + + if (typeof _JSCOV_DIR === 'string') { + command += " const _JSCOV_DIR=" + uneval(_JSCOV_DIR) + ";"; + } + + if (_TESTING_MODULES_DIR) { + command += " const _TESTING_MODULES_DIR=" + uneval(_TESTING_MODULES_DIR) + ";"; + } + + command += " load(_HEAD_JS_PATH);"; + sendCommand(command); +} + +/** + * Runs an entire xpcshell unit test in a child process (rather than in chrome, + * which is the default). + * + * This function returns immediately, before the test has completed. + * + * @param testFile + * The name of the script to run. Path format same as load(). + * @param optionalCallback. + * Optional function to be called (in parent) when test on child is + * complete. If provided, the function must call do_test_finished(); + * @return Promise Resolved when the test in the child is complete. + */ +function run_test_in_child(testFile, optionalCallback) +{ + return new Promise((resolve) => { + var callback = () => { + resolve(); + if (typeof optionalCallback == 'undefined') { + do_test_finished(); + } else { + optionalCallback(); + } + }; + + do_load_child_test_harness(); + + var testPath = do_get_file(testFile).path.replace(/\\/g, "/"); + do_test_pending("run in child"); + sendCommand("_testLogger.info('CHILD-TEST-STARTED'); " + + "const _TEST_FILE=['" + testPath + "']; " + + "_execute_test(); " + + "_testLogger.info('CHILD-TEST-COMPLETED');", + callback); + }); +} + +/** + * Execute a given function as soon as a particular cross-process message is received. + * Must be paired with do_send_remote_message or equivalent ProcessMessageManager calls. + * + * @param optionalCallback + * Optional callback that is invoked when the message is received. If provided, + * the function must call do_test_finished(). + * @return Promise Promise that is resolved when the message is received. + */ +function do_await_remote_message(name, optionalCallback) +{ + return new Promise((resolve) => { + var listener = { + receiveMessage: function(message) { + if (message.name == name) { + mm.removeMessageListener(name, listener); + resolve(); + if (optionalCallback) { + optionalCallback(); + } else { + do_test_finished(); + } + } + } + }; + + var mm; + if (runningInParent) { + mm = Cc["@mozilla.org/parentprocessmessagemanager;1"].getService(Ci.nsIMessageBroadcaster); + } else { + mm = Cc["@mozilla.org/childprocessmessagemanager;1"].getService(Ci.nsISyncMessageSender); + } + do_test_pending(); + mm.addMessageListener(name, listener); + }); +} + +/** + * Asynchronously send a message to all remote processes. Pairs with do_await_remote_message + * or equivalent ProcessMessageManager listeners. + */ +function do_send_remote_message(name) { + var mm; + var sender; + if (runningInParent) { + mm = Cc["@mozilla.org/parentprocessmessagemanager;1"].getService(Ci.nsIMessageBroadcaster); + sender = 'broadcastAsyncMessage'; + } else { + mm = Cc["@mozilla.org/childprocessmessagemanager;1"].getService(Ci.nsISyncMessageSender); + sender = 'sendAsyncMessage'; + } + mm[sender](name); +} + +/** + * Helper function to add the _only property to add_task/add_test function when + * running it as add_task.only(...). + * + * @param addFunc + * The parent function to call, e.g. add_task or add_test. + * @param funcOrProperties + * A function to be run or an object represents test properties. + * @param func + * A function to be run only if the funcOrProperies is not a function. + */ +function _add_only(addFunc, funcOrProperties, func) { + _gTestHasOnly = true; + if (typeof funcOrProperties == "function") { + func = funcOrProperties; + funcOrProperties = {}; + } + + if (typeof funcOrProperties == "object") { + funcOrProperties._only = true; + } + return addFunc(funcOrProperties, func); +} + +/** + * Helper function to skip the test using e.g. add_task.skip(...) + * + * @param addFunc + * The parent function to call, e.g. add_task or add_test. + * @param funcOrProperties + * A function to be run or an object represents test properties. + * @param func + * A function to be run only if the funcOrProperies is not a function. + */ +function _add_skip(addFunc, funcOrProperties, func) { + if (typeof funcOrProperties == "function") { + func = funcOrProperties; + funcOrProperties = {}; + } + + if (typeof funcOrProperties == "object") { + funcOrProperties.skip_if = () => true; + } + return addFunc(funcOrProperties, func); +} + +/** + * Add a test function to the list of tests that are to be run asynchronously. + * + * @param funcOrProperties + * A function to be run or an object represents test properties. + * Supported properties: + * skip_if : An arrow function which has an expression to be + * evaluated whether the test is skipped or not. + * @param func + * A function to be run only if the funcOrProperies is not a function. + * + * Each test function must call run_next_test() when it's done. Test files + * should call run_next_test() in their run_test function to execute all + * async tests. + * + * @return the test function that was passed in. + */ +var _gTests = []; +function add_test(funcOrProperties, func) { + if (typeof funcOrProperties == "function") { + _gTests.push([{ _isTask: false }, funcOrProperties]); + } else if (typeof funcOrProperties == "object") { + funcOrProperties._isTask = false; + _gTests.push([funcOrProperties, func]); + } else { + do_throw("add_test() should take a function or an object and a function"); + } + return func; +} +add_test.only = _add_only.bind(undefined, add_test); +add_test.skip = _add_skip.bind(undefined, add_test); + +/** + * Add a test function which is a Task function. + * + * @param funcOrProperties + * A generator function to be run or an object represents test + * properties. + * Supported properties: + * skip_if : An arrow function which has an expression to be + * evaluated whether the test is skipped or not. + * @param func + * A generator function to be run only if the funcOrProperies is not a + * function. + * + * Task functions are functions fed into Task.jsm's Task.spawn(). They are + * generators that emit promises. + * + * If an exception is thrown, a do_check_* comparison fails, or if a rejected + * promise is yielded, the test function aborts immediately and the test is + * reported as a failure. + * + * Unlike add_test(), there is no need to call run_next_test(). The next test + * will run automatically as soon the task function is exhausted. To trigger + * premature (but successful) termination of the function, simply return or + * throw a Task.Result instance. + * + * Example usage: + * + * add_task(function* test() { + * let result = yield Promise.resolve(true); + * + * do_check_true(result); + * + * let secondary = yield someFunctionThatReturnsAPromise(result); + * do_check_eq(secondary, "expected value"); + * }); + * + * add_task(function* test_early_return() { + * let result = yield somethingThatReturnsAPromise(); + * + * if (!result) { + * // Test is ended immediately, with success. + * return; + * } + * + * do_check_eq(result, "foo"); + * }); + * + * add_task({ + * skip_if: () => !("@mozilla.org/telephony/volume-service;1" in Components.classes), + * }, function* test_volume_service() { + * let volumeService = Cc["@mozilla.org/telephony/volume-service;1"] + * .getService(Ci.nsIVolumeService); + * ... + * }); + */ +function add_task(funcOrProperties, func) { + if (typeof funcOrProperties == "function") { + _gTests.push([{ _isTask: true }, funcOrProperties]); + } else if (typeof funcOrProperties == "object") { + funcOrProperties._isTask = true; + _gTests.push([funcOrProperties, func]); + } else { + do_throw("add_task() should take a function or an object and a function"); + } +} +add_task.only = _add_only.bind(undefined, add_task); +add_task.skip = _add_skip.bind(undefined, add_task); + +var _Task = Components.utils.import("resource://gre/modules/Task.jsm", {}).Task; +_Task.Debugging.maintainStack = true; + + +/** + * Runs the next test function from the list of async tests. + */ +var _gRunningTest = null; +var _gTestIndex = 0; // The index of the currently running test. +var _gTaskRunning = false; +var _gTestHasOnly = false; +function run_next_test() +{ + if (_gTaskRunning) { + throw new Error("run_next_test() called from an add_task() test function. " + + "run_next_test() should not be called from inside add_task() " + + "under any circumstances!"); + } + + function _run_next_test() + { + if (_gTestIndex < _gTests.length) { + // Check for uncaught rejections as early and often as possible. + _PromiseTestUtils.assertNoUncaughtRejections(); + let _properties; + [_properties, _gRunningTest,] = _gTests[_gTestIndex++]; + if (typeof(_properties.skip_if) == "function" && _properties.skip_if()) { + let _condition = _properties.skip_if.toSource().replace(/\(\)\s*=>\s*/, ""); + let _message = _gRunningTest.name + + " skipped because the following conditions were" + + " met: (" + _condition + ")"; + _testLogger.testStatus(_TEST_NAME, + _gRunningTest.name, + "SKIP", + "SKIP", + _message); + do_execute_soon(run_next_test); + return; + } + _testLogger.info(_TEST_NAME + " | Starting " + _gRunningTest.name); + do_test_pending(_gRunningTest.name); + + if (_properties._isTask) { + _gTaskRunning = true; + _Task.spawn(_gRunningTest).then(() => { + _gTaskRunning = false; + run_next_test(); + }, ex => { + _gTaskRunning = false; + try { + do_report_unexpected_exception(ex); + } catch (ex) { + // The above throws NS_ERROR_ABORT and we don't want this to show up + // as an unhandled rejection later. + } + }); + } else { + // Exceptions do not kill asynchronous tests, so they'll time out. + try { + _gRunningTest(); + } catch (e) { + do_throw(e); + } + } + } + } + + // For sane stacks during failures, we execute this code soon, but not now. + // We do this now, before we call do_test_finished(), to ensure the pending + // counter (_tests_pending) never reaches 0 while we still have tests to run + // (do_execute_soon bumps that counter). + do_execute_soon(_run_next_test, "run_next_test " + _gTestIndex); + + if (_gRunningTest !== null) { + // Close the previous test do_test_pending call. + do_test_finished(_gRunningTest.name); + } +} + +try { + if (runningInParent) { + // Always use network provider for geolocation tests + // so we bypass the OSX dialog raised by the corelocation provider + let prefs = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefBranch); + + prefs.setBoolPref("geo.provider.testing", true); + } +} catch (e) { } + +// We need to avoid hitting the network with certain components. +try { + if (runningInParent) { + let prefs = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefBranch); + + prefs.setCharPref("media.gmp-manager.url.override", "http://%(server)s/dummy-gmp-manager.xml"); + prefs.setCharPref("media.gmp-manager.updateEnabled", false); + prefs.setCharPref("extensions.systemAddon.update.url", "http://%(server)s/dummy-system-addons.xml"); + prefs.setCharPref("browser.selfsupport.url", "https://%(server)s/selfsupport-dummy/"); + prefs.setCharPref("toolkit.telemetry.server", "https://%(server)s/telemetry-dummy"); + prefs.setCharPref("browser.search.geoip.url", "https://%(server)s/geoip-dummy"); + } +} catch (e) { } + +// Make tests run consistently on DevEdition (which has a lightweight theme +// selected by default). +try { + if (runningInParent) { + let prefs = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefBranch); + + prefs.deleteBranch("lightweightThemes.selectedThemeID"); + prefs.deleteBranch("browser.devedition.theme.enabled"); + } +} catch (e) { } + +function _load_mozinfo() { + let mozinfoFile = Components.classes["@mozilla.org/file/local;1"] + .createInstance(Components.interfaces.nsIFile); + mozinfoFile.initWithPath(_MOZINFO_JS_PATH); + let stream = Components.classes["@mozilla.org/network/file-input-stream;1"] + .createInstance(Components.interfaces.nsIFileInputStream); + stream.init(mozinfoFile, -1, 0, 0); + let json = Components.classes["@mozilla.org/dom/json;1"] + .createInstance(Components.interfaces.nsIJSON); + let mozinfo = json.decodeFromStream(stream, stream.available()); + stream.close(); + return mozinfo; +} + +Object.defineProperty(this, "mozinfo", { + configurable: true, + get() { + let _mozinfo = _load_mozinfo(); + Object.defineProperty(this, "mozinfo", { + configurable: false, + value: _mozinfo + }); + return _mozinfo; + } +}); diff --git a/testing/xpcshell/mach_commands.py b/testing/xpcshell/mach_commands.py new file mode 100644 index 000000000..d821ff46f --- /dev/null +++ b/testing/xpcshell/mach_commands.py @@ -0,0 +1,274 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# Integrates the xpcshell test runner with mach. + +from __future__ import absolute_import, unicode_literals, print_function + +import argparse +import errno +import os +import sys + +from mozlog import structured + +from mozbuild.base import ( + MachCommandBase, + MozbuildObject, + MachCommandConditions as conditions, +) + +from mach.decorators import ( + CommandProvider, + Command, +) + +from xpcshellcommandline import parser_desktop, parser_remote + +here = os.path.abspath(os.path.dirname(__file__)) + +if sys.version_info[0] < 3: + unicode_type = unicode +else: + unicode_type = str + + +# This should probably be consolidated with similar classes in other test +# runners. +class InvalidTestPathError(Exception): + """Exception raised when the test path is not valid.""" + + +class XPCShellRunner(MozbuildObject): + """Run xpcshell tests.""" + def run_suite(self, **kwargs): + return self._run_xpcshell_harness(**kwargs) + + def run_test(self, **kwargs): + """Runs an individual xpcshell test.""" + + # TODO Bug 794506 remove once mach integrates with virtualenv. + build_path = os.path.join(self.topobjdir, 'build') + if build_path not in sys.path: + sys.path.append(build_path) + + src_build_path = os.path.join(self.topsrcdir, 'mozilla', 'build') + if os.path.isdir(src_build_path): + sys.path.append(src_build_path) + + return self.run_suite(**kwargs) + + def _run_xpcshell_harness(self, **kwargs): + # Obtain a reference to the xpcshell test runner. + import runxpcshelltests + + log = kwargs.pop("log") + + xpcshell = runxpcshelltests.XPCShellTests(log=log) + self.log_manager.enable_unstructured() + + tests_dir = os.path.join(self.topobjdir, '_tests', 'xpcshell') + # We want output from the test to be written immediately if we are only + # running a single test. + single_test = (len(kwargs["testPaths"]) == 1 and + os.path.isfile(kwargs["testPaths"][0]) or + kwargs["manifest"] and + (len(kwargs["manifest"].test_paths()) == 1)) + + if single_test: + kwargs["verbose"] = True + + if kwargs["xpcshell"] is None: + kwargs["xpcshell"] = self.get_binary_path('xpcshell') + + if kwargs["mozInfo"] is None: + kwargs["mozInfo"] = os.path.join(self.topobjdir, 'mozinfo.json') + + if kwargs["symbolsPath"] is None: + kwargs["symbolsPath"] = os.path.join(self.distdir, 'crashreporter-symbols') + + if kwargs["logfiles"] is None: + kwargs["logfiles"] = False + + if kwargs["profileName"] is None: + kwargs["profileName"] = "firefox" + + if kwargs["pluginsPath"] is None: + kwargs['pluginsPath'] = os.path.join(self.distdir, 'plugins') + + if kwargs["testingModulesDir"] is None: + kwargs["testingModulesDir"] = os.path.join(self.topobjdir, '_tests/modules') + + if kwargs["utility_path"] is None: + kwargs['utility_path'] = self.bindir + + if kwargs["manifest"] is None: + kwargs["manifest"] = os.path.join(tests_dir, "xpcshell.ini") + + if kwargs["failure_manifest"] is None: + kwargs["failure_manifest"] = os.path.join(self.statedir, 'xpcshell.failures.ini') + + # Use the object directory for the temp directory to minimize the chance + # of file scanning. The overhead from e.g. search indexers and anti-virus + # scanners like Windows Defender can add tons of overhead to test execution. + # We encourage people to disable these things in the object directory. + temp_dir = os.path.join(self.topobjdir, 'temp') + try: + os.mkdir(temp_dir) + except OSError as e: + if e.errno != errno.EEXIST: + raise + kwargs['tempDir'] = temp_dir + + # Python through 2.7.2 has issues with unicode in some of the + # arguments. Work around that. + filtered_args = {} + for k, v in kwargs.iteritems(): + if isinstance(v, unicode_type): + v = v.encode('utf-8') + + if isinstance(k, unicode_type): + k = k.encode('utf-8') + + filtered_args[k] = v + + result = xpcshell.runTests(**filtered_args) + + self.log_manager.disable_unstructured() + + if not result and not xpcshell.sequential: + print("Tests were run in parallel. Try running with --sequential " + "to make sure the failures were not caused by this.") + return int(not result) + + +class AndroidXPCShellRunner(MozbuildObject): + """Get specified DeviceManager""" + def get_devicemanager(self, devicemanager, ip, port, remote_test_root): + import mozdevice + dm = None + if devicemanager == "adb": + if ip: + dm = mozdevice.DroidADB(ip, port, packageName=None, deviceRoot=remote_test_root) + else: + dm = mozdevice.DroidADB(packageName=None, deviceRoot=remote_test_root) + else: + if ip: + dm = mozdevice.DroidSUT(ip, port, deviceRoot=remote_test_root) + else: + raise Exception("You must provide a device IP to connect to via the --ip option") + return dm + + """Run Android xpcshell tests.""" + def run_test(self, **kwargs): + # TODO Bug 794506 remove once mach integrates with virtualenv. + build_path = os.path.join(self.topobjdir, 'build') + if build_path not in sys.path: + sys.path.append(build_path) + + import remotexpcshelltests + + dm = self.get_devicemanager(kwargs["dm_trans"], kwargs["deviceIP"], kwargs["devicePort"], + kwargs["remoteTestRoot"]) + + log = kwargs.pop("log") + self.log_manager.enable_unstructured() + + if kwargs["xpcshell"] is None: + kwargs["xpcshell"] = "xpcshell" + + if not kwargs["objdir"]: + kwargs["objdir"] = self.topobjdir + + if not kwargs["localLib"]: + kwargs["localLib"] = os.path.join(self.topobjdir, 'dist/fennec') + + if not kwargs["localBin"]: + kwargs["localBin"] = os.path.join(self.topobjdir, 'dist/bin') + + if not kwargs["testingModulesDir"]: + kwargs["testingModulesDir"] = os.path.join(self.topobjdir, '_tests/modules') + + if not kwargs["mozInfo"]: + kwargs["mozInfo"] = os.path.join(self.topobjdir, 'mozinfo.json') + + if not kwargs["manifest"]: + kwargs["manifest"] = os.path.join(self.topobjdir, '_tests/xpcshell/xpcshell.ini') + + if not kwargs["symbolsPath"]: + kwargs["symbolsPath"] = os.path.join(self.distdir, 'crashreporter-symbols') + + if not kwargs["localAPK"]: + for file_name in os.listdir(os.path.join(kwargs["objdir"], "dist")): + if file_name.endswith(".apk") and file_name.startswith("fennec"): + kwargs["localAPK"] = os.path.join(kwargs["objdir"], "dist", file_name) + print ("using APK: %s" % kwargs["localAPK"]) + break + else: + raise Exception("APK not found in objdir. You must specify an APK.") + + if not kwargs["sequential"]: + kwargs["sequential"] = True + + options = argparse.Namespace(**kwargs) + xpcshell = remotexpcshelltests.XPCShellRemote(dm, options, log) + + result = xpcshell.runTests(testClass=remotexpcshelltests.RemoteXPCShellTestThread, + mobileArgs=xpcshell.mobileArgs, + **vars(options)) + + self.log_manager.disable_unstructured() + + return int(not result) + + +def get_parser(): + build_obj = MozbuildObject.from_environment(cwd=here) + if conditions.is_android(build_obj): + return parser_remote() + else: + return parser_desktop() + + +@CommandProvider +class MachCommands(MachCommandBase): + @Command('xpcshell-test', category='testing', + description='Run XPCOM Shell tests (API direct unit testing)', + conditions=[lambda *args: True], + parser=get_parser) + def run_xpcshell_test(self, test_objects=None, **params): + from mozbuild.controller.building import BuildDriver + + if test_objects is not None: + from manifestparser import TestManifest + m = TestManifest() + m.tests.extend(test_objects) + params['manifest'] = m + + driver = self._spawn(BuildDriver) + driver.install_tests(test_objects) + + # We should probably have a utility function to ensure the tree is + # ready to run tests. Until then, we just create the state dir (in + # case the tree wasn't built with mach). + self._ensure_state_subdir_exists('.') + + params['log'] = structured.commandline.setup_logging("XPCShellTests", + params, + {"mach": sys.stdout}, + {"verbose": True}) + + if conditions.is_android(self): + from mozrunner.devices.android_device import verify_android_device + verify_android_device(self) + xpcshell = self._spawn(AndroidXPCShellRunner) + else: + xpcshell = self._spawn(XPCShellRunner) + xpcshell.cwd = self._mach_context.cwd + + try: + return xpcshell.run_test(**params) + except InvalidTestPathError as e: + print(e.message) + return 1 diff --git a/testing/xpcshell/mach_test_package_commands.py b/testing/xpcshell/mach_test_package_commands.py new file mode 100644 index 000000000..fc7d27385 --- /dev/null +++ b/testing/xpcshell/mach_test_package_commands.py @@ -0,0 +1,64 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +from __future__ import unicode_literals + +import os +import sys +from argparse import Namespace +from functools import partial + + +import mozlog +from xpcshellcommandline import parser_desktop + +from mach.decorators import ( + CommandProvider, + Command, +) + + +def run_xpcshell(context, **kwargs): + args = Namespace(**kwargs) + args.appPath = args.appPath or os.path.dirname(context.firefox_bin) + args.e10s = context.mozharness_config.get('e10s', args.e10s) + args.utility_path = context.bin_dir + args.testingModulesDir = context.modules_dir + + if not args.xpcshell: + args.xpcshell = os.path.join(args.appPath, 'xpcshell') + + if not args.pluginsPath: + for path in context.ancestors(args.appPath, depth=2): + test = os.path.join(path, 'plugins') + if os.path.isdir(test): + args.pluginsPath = test + break + + log = mozlog.commandline.setup_logging("XPCShellTests", + args, + {"mach": sys.stdout}, + {"verbose": True}) + + if args.testPaths: + test_root = os.path.join(context.package_root, 'xpcshell', 'tests') + normalize = partial(context.normalize_test_path, test_root) + args.testPaths = map(normalize, args.testPaths) + + import runxpcshelltests + xpcshell = runxpcshelltests.XPCShellTests(log=log) + return xpcshell.runTests(**vars(args)) + + +@CommandProvider +class MochitestCommands(object): + + def __init__(self, context): + self.context = context + + @Command('xpcshell-test', category='testing', + description='Run the xpcshell harness.', + parser=parser_desktop) + def xpcshell(self, **kwargs): + return run_xpcshell(self.context, **kwargs) diff --git a/testing/xpcshell/moz-http2/http2-cert.pem b/testing/xpcshell/moz-http2/http2-cert.pem new file mode 100644 index 000000000..d5944e531 --- /dev/null +++ b/testing/xpcshell/moz-http2/http2-cert.pem @@ -0,0 +1,79 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 1 (0x1) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=US, ST=Maine, O=CA Example + Validity + Not Before: Apr 29 05:29:19 2015 GMT + Not After : Apr 26 05:29:19 2025 GMT + Subject: C=US, ST=Maine, O=Example Com, CN=foo.example.com + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:cf:ff:c0:27:3b:a3:11:b5:7f:5d:4f:22:f9:75: + 48:47:d9:3a:ce:9b:66:82:4e:e4:ae:ab:78:d3:4c: + 3a:9a:5c:37:97:b2:7b:4e:2a:54:77:16:2a:3e:6f: + 52:ee:4b:49:46:1d:6b:18:9a:ed:b1:ad:64:9f:8b: + e5:fa:e4:60:7b:39:0e:db:e8:b4:2d:4b:e8:ab:37: + e8:90:ec:eb:0f:3e:6b:40:7a:d1:da:e6:68:b3:f4: + f6:68:54:5b:27:90:6d:c2:c3:04:de:85:23:2b:3c: + 66:4e:06:79:58:93:a1:71:d7:ec:74:55:a4:84:9d: + 41:22:2a:7a:76:ae:56:b1:6f:15:2d:f2:f5:9c:64: + 3e:4f:0f:6e:8f:b6:28:66:e9:89:04:5d:1d:21:77: + f8:03:d3:89:ed:7c:f4:3b:42:02:c8:8d:de:47:74: + 1f:4a:5d:fe:8d:d1:57:37:08:54:bf:89:d8:f7:27: + 22:a7:2a:5d:aa:d5:b0:61:22:9b:96:75:ee:ab:09: + ca:a9:cb:2b:1e:88:7c:5a:53:7e:5f:88:c4:43:ea: + e8:a7:db:35:6c:b2:89:ad:98:e0:96:c9:83:c4:c1: + e7:2a:5c:f8:99:5c:9e:01:9c:e6:99:bd:18:5c:69: + d4:10:f1:46:88:37:0b:4e:76:5f:6a:1a:21:c2:a4: + 16:d1 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Key Identifier: + 76:BC:13:90:F7:85:1B:1C:24:A1:CC:65:8A:4F:4C:0C:7F:10:D3:F5 + X509v3 Authority Key Identifier: + keyid:F7:FC:76:AF:C5:1A:E9:C9:42:6C:38:DF:8B:07:9E:2B:2C:E5:8E:20 + + X509v3 Basic Constraints: + CA:FALSE + X509v3 Key Usage: + Digital Signature, Key Encipherment + Signature Algorithm: sha256WithRSAEncryption + 03:ab:2a:9e:e5:cd:5c:88:5a:6c:f7:4b:7a:7c:ef:85:2c:31: + df:03:79:31:a6:c5:c8:2b:c6:21:a5:33:2b:a0:4b:e2:7e:0a: + 86:9b:72:25:b6:75:43:41:7c:30:9f:15:b4:9f:34:50:57:eb: + 87:f9:1e:9f:b6:cd:81:36:92:61:66:d5:fe:e2:c5:ed:de:f1: + ce:85:0b:f9:6a:2b:32:4d:29:f1:a9:94:57:a3:0f:74:93:12: + c9:0a:28:5e:72:9f:4f:0f:78:f5:84:11:5a:9f:d7:1c:4c:fd: + 13:d8:3d:4c:f8:dd:4c:c6:1c:fd:63:ee:f5:d5:96:f5:00:2c: + e6:bb:c9:4c:d8:6a:19:59:58:2b:d4:05:ab:57:47:1c:49:d6: + c5:56:1a:e3:64:10:19:9b:44:3e:74:8b:19:73:28:86:96:b4: + d1:2a:49:23:07:25:97:64:8f:1b:1c:64:76:12:e0:df:e3:cf: + 55:d5:7c:e9:77:d4:69:2f:c7:9a:fd:ce:1a:29:ab:d7:88:68: + 93:de:75:e4:d6:85:29:e2:b6:b7:59:20:e3:b5:20:b7:e8:0b: + 23:9b:4c:b4:e8:d9:90:cf:e9:2f:9e:a8:22:a2:ef:6a:68:65: + f6:c4:81:ed:75:77:88:01:f2:47:03:1a:de:1f:44:38:47:fa: + aa:69:f2:98 +-----BEGIN CERTIFICATE----- +MIIDVDCCAjygAwIBAgIBATANBgkqhkiG9w0BAQsFADAyMQswCQYDVQQGEwJVUzEO +MAwGA1UECAwFTWFpbmUxEzARBgNVBAoMCkNBIEV4YW1wbGUwHhcNMTUwNDI5MDUy +OTE5WhcNMjUwNDI2MDUyOTE5WjBNMQswCQYDVQQGEwJVUzEOMAwGA1UECAwFTWFp +bmUxFDASBgNVBAoMC0V4YW1wbGUgQ29tMRgwFgYDVQQDDA9mb28uZXhhbXBsZS5j +b20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDP/8AnO6MRtX9dTyL5 +dUhH2TrOm2aCTuSuq3jTTDqaXDeXsntOKlR3Fio+b1LuS0lGHWsYmu2xrWSfi+X6 +5GB7OQ7b6LQtS+irN+iQ7OsPPmtAetHa5miz9PZoVFsnkG3CwwTehSMrPGZOBnlY +k6Fx1+x0VaSEnUEiKnp2rlaxbxUt8vWcZD5PD26Ptihm6YkEXR0hd/gD04ntfPQ7 +QgLIjd5HdB9KXf6N0Vc3CFS/idj3JyKnKl2q1bBhIpuWde6rCcqpyyseiHxaU35f +iMRD6uin2zVssomtmOCWyYPEwecqXPiZXJ4BnOaZvRhcadQQ8UaINwtOdl9qGiHC +pBbRAgMBAAGjWjBYMB0GA1UdDgQWBBR2vBOQ94UbHCShzGWKT0wMfxDT9TAfBgNV +HSMEGDAWgBT3/HavxRrpyUJsON+LB54rLOWOIDAJBgNVHRMEAjAAMAsGA1UdDwQE +AwIFoDANBgkqhkiG9w0BAQsFAAOCAQEAA6sqnuXNXIhabPdLenzvhSwx3wN5MabF +yCvGIaUzK6BL4n4KhptyJbZ1Q0F8MJ8VtJ80UFfrh/ken7bNgTaSYWbV/uLF7d7x +zoUL+WorMk0p8amUV6MPdJMSyQooXnKfTw949YQRWp/XHEz9E9g9TPjdTMYc/WPu +9dWW9QAs5rvJTNhqGVlYK9QFq1dHHEnWxVYa42QQGZtEPnSLGXMohpa00SpJIwcl +l2SPGxxkdhLg3+PPVdV86XfUaS/Hmv3OGimr14hok9515NaFKeK2t1kg47Ugt+gL +I5tMtOjZkM/pL56oIqLvamhl9sSB7XV3iAHyRwMa3h9EOEf6qmnymA== +-----END CERTIFICATE----- diff --git a/testing/xpcshell/moz-http2/http2-key.pem b/testing/xpcshell/moz-http2/http2-key.pem new file mode 100644 index 000000000..387449ddc --- /dev/null +++ b/testing/xpcshell/moz-http2/http2-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDP/8AnO6MRtX9d +TyL5dUhH2TrOm2aCTuSuq3jTTDqaXDeXsntOKlR3Fio+b1LuS0lGHWsYmu2xrWSf +i+X65GB7OQ7b6LQtS+irN+iQ7OsPPmtAetHa5miz9PZoVFsnkG3CwwTehSMrPGZO +BnlYk6Fx1+x0VaSEnUEiKnp2rlaxbxUt8vWcZD5PD26Ptihm6YkEXR0hd/gD04nt +fPQ7QgLIjd5HdB9KXf6N0Vc3CFS/idj3JyKnKl2q1bBhIpuWde6rCcqpyyseiHxa +U35fiMRD6uin2zVssomtmOCWyYPEwecqXPiZXJ4BnOaZvRhcadQQ8UaINwtOdl9q +GiHCpBbRAgMBAAECggEBAKqcsQQ9cdQr2S4zpI+UuVZeBFPGun32srPn6TMA2y0U +qXEgMO574E7SepI+BHt8e70sklVbd89/WANa4Kk8vTs2IU8XAPwKwO347SY7f9BA +Nf9s/0gcKRQ7wgbv8tlwKehQyWSxNpjXcV9dBho29n2ITOdb/Jfe2bdpuowxEuF0 +rugkKh7P7LJTG1SAw01UTIszoOGIqHU2XlmYQOws4EvRov/BRTn9axBHH33top+m +dX+96ntgWxdHOJjTcoXLGhTu1c0ZlJgtgEaH03jjy0f+3Qc+jIgbaZ4WLZkF/oZh +hscL56XhsT3hR2Sdtxccw2zZ0exLO+qV1RykIAlUXkECgYEA7U+ljowyPxbREHnf +SRTauIZfJNP6IHT60MkslltlYn7jABvx+u2xCC/QhZxCJi/iAs6iNvkbXR6uK/MH +NrXwdk67SDUXaDZ9LM3rXPqjuwmvkc+e7P5an6KRtyzQD8K8mjbze1NfxbcGgKti +A+8GL8H3V29EQ6xp2+UxIF/3UNkCgYEA4GEm9NLbu4neP+A+1NpUS4tUgMCdTkPm +fiOECd4jjTizPZjjrk+zTin9aP+eBRYHharIGrDP2Uj98uv4kQ8u0rQbcjPwitog +8DgccMQ92E6DYGDGECh5Hg2Zu71+zQQNzOEJTyrFLx4Gf5SkBzLlbDZDpNhbuQc9 +zvRYBc11urkCgYBOu2Dy9SJqefhsnfJtfaS/GZ2RS16tzAG2qTfIvpPZZL2NOLhE +hv13+N0WpuvvXW1/fuykjmr8rwQcAqo/BYe8yIwr/alBYuqOpdbTZzhRAnqkRpy0 +hgKs+bOccRqqT/Jgu6B2JwgcQYe/wpxnL7L+vzx/XqPoS9hnIxf0ZMJZqQKBgQDa +KJuf3oQWS23z3Sw5+C2NZeK7bIuF1S795bozffBDFqXvdf+pM4S6ssjYlfAmMc0O +gYYdrVvpf7apwhTjtUdpRgSJfUabOopcBbJhUexvq6bAxlbMzw0z0zVt/EiVPSPN +198dQhCGR0M6OGNjPHEkTX5ngJVtyUSnO5t5yNJ2wQKBgQDheEUJYgo2UjLNsdTs +b4og5gHkyoKS3paWV64itJQbVBuri4HWeIExM9ayBB6nSJ2VvpZPyE6XfiYYGNhR +jOc394qlnrx+oi2KdSmIWfQU0I+rW3bMqpoyWPYxP/hN6w4LAwjnJOSOIMCACm5J +d8IebWjY2B3Zc6FFVzbmhXtlig== +-----END PRIVATE KEY----- diff --git a/testing/xpcshell/moz-http2/moz-http2.js b/testing/xpcshell/moz-http2/moz-http2.js new file mode 100644 index 000000000..760fef1ef --- /dev/null +++ b/testing/xpcshell/moz-http2/moz-http2.js @@ -0,0 +1,786 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// This module is the stateful server side of test_http2.js and is meant +// to have node be restarted in between each invocation + +var node_http2_root = '../node-http2'; +if (process.env.NODE_HTTP2_ROOT) { + node_http2_root = process.env.NODE_HTTP2_ROOT; +} +var http2 = require(node_http2_root); +var fs = require('fs'); +var url = require('url'); +var crypto = require('crypto'); + +// Hook into the decompression code to log the decompressed name-value pairs +var compression_module = node_http2_root + "/lib/protocol/compressor"; +var http2_compression = require(compression_module); +var HeaderSetDecompressor = http2_compression.HeaderSetDecompressor; +var originalRead = HeaderSetDecompressor.prototype.read; +var lastDecompressor; +var decompressedPairs; +HeaderSetDecompressor.prototype.read = function() { + if (this != lastDecompressor) { + lastDecompressor = this; + decompressedPairs = []; + } + var pair = originalRead.apply(this, arguments); + if (pair) { + decompressedPairs.push(pair); + } + return pair; +} + +var connection_module = node_http2_root + "/lib/protocol/connection"; +var http2_connection = require(connection_module); +var Connection = http2_connection.Connection; +var originalClose = Connection.prototype.close; +Connection.prototype.close = function (error, lastId) { + if (lastId !== undefined) { + this._lastIncomingStream = lastId; + } + + originalClose.apply(this, arguments); +} + +var framer_module = node_http2_root + "/lib/protocol/framer"; +var http2_framer = require(framer_module); +var Serializer = http2_framer.Serializer; +var originalTransform = Serializer.prototype._transform; +var newTransform = function (frame, encoding, done) { + if (frame.type == 'DATA') { + // Insert our empty DATA frame + emptyFrame = {}; + emptyFrame.type = 'DATA'; + emptyFrame.data = new Buffer(0); + emptyFrame.flags = []; + emptyFrame.stream = frame.stream; + var buffers = []; + Serializer['DATA'](emptyFrame, buffers); + Serializer.commonHeader(emptyFrame, buffers); + for (var i = 0; i < buffers.length; i++) { + this.push(buffers[i]); + } + + // Reset to the original version for later uses + Serializer.prototype._transform = originalTransform; + } + originalTransform.apply(this, arguments); +}; + +function getHttpContent(path) { + var content = '' + + '' + + 'HOORAY!' + + 'You Win! (by requesting' + path + ')' + + ''; + return content; +} + +function generateContent(size) { + var content = ''; + for (var i = 0; i < size; i++) { + content += '0'; + } + return content; +} + +/* This takes care of responding to the multiplexed request for us */ +var m = { + mp1res: null, + mp2res: null, + buf: null, + mp1start: 0, + mp2start: 0, + + checkReady: function() { + if (this.mp1res != null && this.mp2res != null) { + this.buf = generateContent(30*1024); + this.mp1start = 0; + this.mp2start = 0; + this.send(this.mp1res, 0); + setTimeout(this.send.bind(this, this.mp2res, 0), 5); + } + }, + + send: function(res, start) { + var end = Math.min(start + 1024, this.buf.length); + var content = this.buf.substring(start, end); + res.write(content); + if (end < this.buf.length) { + setTimeout(this.send.bind(this, res, end), 10); + } else { + res.end(); + } + } +}; + +var runlater = function() {}; +runlater.prototype = { + req : null, + resp : null, + + onTimeout : function onTimeout() { + this.resp.writeHead(200); + this.resp.end("It's all good 750ms."); + } +}; + +var moreData = function() {}; +moreData.prototype = { + req : null, + resp : null, + iter: 3, + + onTimeout : function onTimeout() { + // 1mb of data + content = generateContent(1024*1024); + this.resp.write(content); // 1mb chunk + this.iter--; + if (!this.iter) { + this.resp.end(); + } else { + setTimeout(executeRunLater, 1, this); + } + } +}; + +function executeRunLater(arg) { + arg.onTimeout(); +} + +var Compressor = http2_compression.Compressor; +var HeaderSetCompressor = http2_compression.HeaderSetCompressor; +var originalCompressHeaders = Compressor.prototype.compress; + +function insertSoftIllegalHpack(headers) { + var originalCompressed = originalCompressHeaders.apply(this, headers); + var illegalLiteral = new Buffer([ + 0x00, // Literal, no index + 0x08, // Name: not huffman encoded, 8 bytes long + 0x3a, 0x69, 0x6c, 0x6c, 0x65, 0x67, 0x61, 0x6c, // :illegal + 0x10, // Value: not huffman encoded, 16 bytes long + // REALLY NOT LEGAL + 0x52, 0x45, 0x41, 0x4c, 0x4c, 0x59, 0x20, 0x4e, 0x4f, 0x54, 0x20, 0x4c, 0x45, 0x47, 0x41, 0x4c + ]); + var newBufferLength = originalCompressed.length + illegalLiteral.length; + var concatenated = new Buffer(newBufferLength); + originalCompressed.copy(concatenated, 0); + illegalLiteral.copy(concatenated, originalCompressed.length); + return concatenated; +} + +function insertHardIllegalHpack(headers) { + var originalCompressed = originalCompressHeaders.apply(this, headers); + // Now we have to add an invalid header + var illegalIndexed = HeaderSetCompressor.integer(5000, 7); + // The above returns an array of buffers, but there's only one buffer, so + // get rid of the array. + illegalIndexed = illegalIndexed[0]; + // Set the first bit to 1 to signal this is an indexed representation + illegalIndexed[0] |= 0x80; + var newBufferLength = originalCompressed.length + illegalIndexed.length; + var concatenated = new Buffer(newBufferLength); + originalCompressed.copy(concatenated, 0); + illegalIndexed.copy(concatenated, originalCompressed.length); + return concatenated; +} + +var h11required_conn = null; +var h11required_header = "yes"; +var didRst = false; +var rstConnection = null; +var illegalheader_conn = null; + +function handleRequest(req, res) { + // We do this first to ensure nothing goes wonky in our tests that don't want + // the headers to have something illegal in them + Compressor.prototype.compress = originalCompressHeaders; + + var u = url.parse(req.url); + var content = getHttpContent(u.pathname); + var push, push1, push1a, push2, push3; + + // PushService tests. + var pushPushServer1, pushPushServer2, pushPushServer3, pushPushServer4; + + if (req.httpVersionMajor === 2) { + res.setHeader('X-Connection-Http2', 'yes'); + res.setHeader('X-Http2-StreamId', '' + req.stream.id); + } else { + res.setHeader('X-Connection-Http2', 'no'); + } + + if (u.pathname === '/exit') { + res.setHeader('Content-Type', 'text/plain'); + res.setHeader('Connection', 'close'); + res.writeHead(200); + res.end('ok'); + process.exit(); + } + + if (u.pathname === '/750ms') { + var rl = new runlater(); + rl.req = req; + rl.resp = res; + setTimeout(executeRunLater, 750, rl); + return; + } + + else if ((u.pathname === '/multiplex1') && (req.httpVersionMajor === 2)) { + res.setHeader('Content-Type', 'text/plain'); + res.writeHead(200); + m.mp1res = res; + m.checkReady(); + return; + } + + else if ((u.pathname === '/multiplex2') && (req.httpVersionMajor === 2)) { + res.setHeader('Content-Type', 'text/plain'); + res.writeHead(200); + m.mp2res = res; + m.checkReady(); + return; + } + + else if (u.pathname === "/header") { + var val = req.headers["x-test-header"]; + if (val) { + res.setHeader("X-Received-Test-Header", val); + } + } + + else if (u.pathname === "/doubleheader") { + res.setHeader('Content-Type', 'text/html'); + res.writeHead(200); + res.write(content); + res.writeHead(200); + res.end(); + return; + } + + else if (u.pathname === "/cookie_crumbling") { + res.setHeader("X-Received-Header-Pairs", JSON.stringify(decompressedPairs)); + } + + else if (u.pathname === "/push") { + push = res.push('/push.js'); + push.writeHead(200, { + 'content-type': 'application/javascript', + 'pushed' : 'yes', + 'content-length' : 11, + 'X-Connection-Http2': 'yes' + }); + push.end('// comments'); + content = '