diff --git a/dom/imptests/WebIDLParser.js b/dom/imptests/WebIDLParser.js index 286009d32ac..7dd56b55ef2 100644 --- a/dom/imptests/WebIDLParser.js +++ b/dom/imptests/WebIDLParser.js @@ -31,7 +31,7 @@ return tokens; }; - var parse = function (tokens) { + var parse = function (tokens, opt) { var line = 1; tokens = tokens.slice(); @@ -82,14 +82,41 @@ } }; - var all_ws = function () { + var all_ws = function (store, pea) { // pea == post extended attribute, tpea = same for types var t = { type: "whitespace", value: "" }; while (true) { var w = ws(); if (!w) break; t.value += w.value; } - if (t.value.length > 0) return t; + if (t.value.length > 0) { + if (store) { + var w = t.value + , re = { + "ws": /^([\t\n\r ]+)/ + , "line-comment": /^\/\/(.*)\n?/m + , "multiline-comment": /^\/\*((?:.|\n|\r)*?)\*\// + } + , wsTypes = [] + ; + for (var k in re) wsTypes.push(k); + while (w.length) { + var matched = false; + for (var i = 0, n = wsTypes.length; i < n; i++) { + var type = wsTypes[i]; + w = w.replace(re[type], function (tok, m1) { + store.push({ type: type + (pea ? ("-" + pea) : ""), value: m1 }); + matched = true; + return ""; + }); + if (matched) break; + } + if (matched) continue; + throw new Error("Surprising white space construct."); // this shouldn't happen + } + } + return t; + } }; var integer_type = function () { @@ -151,8 +178,15 @@ else if (consume(OTHER, "[")) { all_ws(); consume(OTHER, "]") || error("Unterminated array type"); - if (!obj.array) obj.array = 1; - else obj.array++; + if (!obj.array) { + obj.array = 1; + obj.nullableArray = [obj.nullable]; + } + else { + obj.array++; + obj.nullableArray.push(obj.nullable); + } + obj.nullable = false; } else return; } @@ -160,40 +194,46 @@ var single_type = function () { var prim = primitive_type() - , ret = { sequence: false, nullable: false, array: false, union: false } + , ret = { sequence: false, generic: null, nullable: false, array: false, union: false } + , name + , value ; if (prim) { ret.idlType = prim; } - else if (consume(ID, "sequence")) { + else if (name = consume(ID)) { + value = name.value; all_ws(); - if (!consume(OTHER, "<")) { - ret.idlType = "sequence"; - } - else { - ret.sequence = true; - ret.idlType = type() || error("Error parsing sequence type"); + // Generic types + if (consume(OTHER, "<")) { + // backwards compat + if (value === "sequence") { + ret.sequence = true; + } + ret.generic = value; + ret.idlType = type() || error("Error parsing generic type " + value); all_ws(); - if (!consume(OTHER, ">")) error("Unterminated sequence"); + if (!consume(OTHER, ">")) error("Unterminated generic type " + value); all_ws(); if (consume(OTHER, "?")) ret.nullable = true; return ret; } + else { + ret.idlType = value; + } } else { - var name = consume(ID); - if (!name) return; - ret.idlType = name.value; + return; } type_suffix(ret); - if (ret.nullable && ret.idlType === "any") error("Type any cannot be made nullable"); + if (ret.nullable && !ret.array && ret.idlType === "any") error("Type any cannot be made nullable"); return ret; }; var union_type = function () { all_ws(); if (!consume(OTHER, "(")) return; - var ret = { sequence: false, nullable: false, array: false, union: true, idlType: [] }; + var ret = { sequence: false, generic: null, nullable: false, array: false, union: true, idlType: [] }; var fst = type() || error("Union type with no content"); ret.idlType.push(fst); while (true) { @@ -211,16 +251,21 @@ return single_type() || union_type(); }; - var argument = function () { + var argument = function (store) { var ret = { optional: false, variadic: false }; - ret.extAttrs = extended_attrs(); - all_ws(); - if (consume(ID, "optional")) { + ret.extAttrs = extended_attrs(store); + all_ws(store, "pea"); + var opt_token = consume(ID, "optional"); + if (opt_token) { ret.optional = true; all_ws(); } ret.idlType = type(); - if (!ret.idlType) return; + if (!ret.idlType) { + if (opt_token) tokens.unshift(opt_token); + return; + } + var type_token = last_token; if (!ret.optional) { all_ws(); if (tokens.length >= 3 && @@ -235,7 +280,12 @@ } } all_ws(); - var name = consume(ID) || error("No name in argument"); + var name = consume(ID); + if (!name) { + if (opt_token) tokens.unshift(opt_token); + tokens.unshift(type_token); + return; + } ret.name = name.value; if (ret.optional) { all_ws(); @@ -244,20 +294,33 @@ return ret; }; - var argument_list = function () { - var arg = argument(), ret = []; - if (!arg) return ret; + var argument_list = function (store) { + var ret = [] + , arg = argument(store ? ret : null) + ; + if (!arg) return; ret.push(arg); while (true) { - all_ws(); + all_ws(store ? ret : null); if (!consume(OTHER, ",")) return ret; - all_ws(); - var nxt = argument() || error("Trailing comma in arguments list"); + var nxt = argument(store ? ret : null) || error("Trailing comma in arguments list"); ret.push(nxt); } }; - var simple_extended_attr = function () { + var type_pair = function () { + all_ws(); + var k = type(); + if (!k) return; + all_ws() + if (!consume(OTHER, ",")) return; + all_ws(); + var v = type(); + if (!v) return; + return [k, v]; + }; + + var simple_extended_attr = function (store) { all_ws(); var name = consume(ID); if (!name) return; @@ -274,24 +337,35 @@ } all_ws(); if (consume(OTHER, "(")) { - ret["arguments"] = argument_list(); + var args, pair; + // [Constructor(DOMString str)] + if (args = argument_list(store)) { + ret["arguments"] = args; + } + // [MapClass(DOMString, DOMString)] + else if (pair = type_pair()) { + ret.typePair = pair; + } + // [Constructor()] + else { + ret["arguments"] = []; + } all_ws(); - consume(OTHER, ")") || error("Unclosed argument in extended attribute"); + consume(OTHER, ")") || error("Unexpected token in extended attribute argument list or type pair"); } return ret; }; // Note: we parse something simpler than the official syntax. It's all that ever // seems to be used - var extended_attrs = function () { + var extended_attrs = function (store) { var eas = []; - all_ws(); + all_ws(store); if (!consume(OTHER, "[")) return eas; - eas[0] = simple_extended_attr() || error("Extended attribute with not content"); + eas[0] = simple_extended_attr(store) || error("Extended attribute with not content"); all_ws(); while (consume(OTHER, ",")) { - all_ws(); - eas.push(simple_extended_attr() || error("Trailing comma in extended attribute")); + eas.push(simple_extended_attr(store) || error("Trailing comma in extended attribute")); all_ws(); } consume(OTHER, "]") || error("No end of extended attribute"); @@ -314,8 +388,8 @@ } }; - var const_ = function () { - all_ws(); + var const_ = function (store) { + all_ws(store, "pea"); if (!consume(ID, "const")) return; var ret = { type: "const", nullable: false }; all_ws(); @@ -352,14 +426,14 @@ } }; - var operation_rest = function (ret) { + var operation_rest = function (ret, store) { all_ws(); if (!ret) ret = {}; var name = consume(ID); ret.name = name ? name.value : null; all_ws(); consume(OTHER, "(") || error("Invalid operation"); - ret["arguments"] = argument_list(); + ret["arguments"] = argument_list(store) || []; all_ws(); consume(OTHER, ")") || error("Unterminated operation"); all_ws(); @@ -367,8 +441,8 @@ return ret; }; - var callback = function () { - all_ws(); + var callback = function (store) { + all_ws(store, "pea"); var ret; if (!consume(ID, "callback")) return; all_ws(); @@ -387,7 +461,7 @@ ret.idlType = return_type(); all_ws(); consume(OTHER, "(") || error("No arguments in callback"); - ret["arguments"] = argument_list(); + ret["arguments"] = argument_list(store) || []; all_ws(); consume(OTHER, ")") || error("Unterminated callback"); all_ws(); @@ -395,8 +469,8 @@ return ret; }; - var attribute = function () { - all_ws(); + var attribute = function (store) { + all_ws(store, "pea"); var grabbed = [] , ret = { type: "attribute" @@ -454,8 +528,8 @@ return typ; }; - var operation = function () { - all_ws(); + var operation = function (store) { + all_ws(store, "pea"); var ret = { type: "operation" , getter: false @@ -478,13 +552,13 @@ if (ret.getter || ret.setter || ret.creator || ret.deleter || ret.legacycaller) { all_ws(); ret.idlType = return_type(); - operation_rest(ret); + operation_rest(ret, store); return ret; } if (consume(ID, "static")) { ret["static"] = true; ret.idlType = return_type(); - operation_rest(ret); + operation_rest(ret, store); return ret; } else if (consume(ID, "stringifier")) { @@ -492,7 +566,7 @@ all_ws(); if (consume(OTHER, ";")) return ret; ret.idlType = return_type(); - operation_rest(ret); + operation_rest(ret, store); return ret; } ret.idlType = return_type(); @@ -513,7 +587,7 @@ return ret; } else { - operation_rest(ret); + operation_rest(ret, store); return ret; } }; @@ -530,8 +604,8 @@ } }; - var serialiser = function () { - all_ws(); + var serialiser = function (store) { + all_ws(store, "pea"); if (!consume(ID, "serializer")) return; var ret = { type: "serializer" }; all_ws(); @@ -589,77 +663,84 @@ else { ret.idlType = return_type(); all_ws(); - ret.operation = operation_rest(); + ret.operation = operation_rest(null, store); } return ret; }; - var interface_ = function (isPartial) { - all_ws(); + var interface_ = function (isPartial, store) { + all_ws(isPartial ? null : store, "pea"); if (!consume(ID, "interface")) return; all_ws(); var name = consume(ID) || error("No name for interface"); - var ret = { + var mems = [] + , ret = { type: "interface" , name: name.value , partial: false - , members: [] + , members: mems }; if (!isPartial) ret.inheritance = inheritance() || null; all_ws(); consume(OTHER, "{") || error("Bodyless interface"); while (true) { - all_ws(); + all_ws(store ? mems : null); if (consume(OTHER, "}")) { all_ws(); consume(OTHER, ";") || error("Missing semicolon after interface"); return ret; } - var ea = extended_attrs(); + var ea = extended_attrs(store ? mems : null); all_ws(); - var cnt = const_(); + var cnt = const_(store ? mems : null); if (cnt) { cnt.extAttrs = ea; ret.members.push(cnt); continue; } - var mem = serialiser() || attribute() || operation() || error("Unknown member"); + var mem = serialiser(store ? mems : null) || + attribute(store ? mems : null) || + operation(store ? mems : null) || + error("Unknown member"); mem.extAttrs = ea; ret.members.push(mem); } }; - var partial = function () { - all_ws(); + var partial = function (store) { + all_ws(store, "pea"); if (!consume(ID, "partial")) return; - var thing = dictionary(true) || interface_(true) || error("Partial doesn't apply to anything"); + var thing = dictionary(true, store) || + interface_(true, store) || + error("Partial doesn't apply to anything"); thing.partial = true; return thing; }; - var dictionary = function (isPartial) { - all_ws(); + var dictionary = function (isPartial, store) { + all_ws(isPartial ? null : store, "pea"); if (!consume(ID, "dictionary")) return; all_ws(); var name = consume(ID) || error("No name for dictionary"); - var ret = { + var mems = [] + , ret = { type: "dictionary" , name: name.value , partial: false - , members: [] + , members: mems }; if (!isPartial) ret.inheritance = inheritance() || null; all_ws(); consume(OTHER, "{") || error("Bodyless dictionary"); while (true) { - all_ws(); + all_ws(store ? mems : null); if (consume(OTHER, "}")) { all_ws(); consume(OTHER, ";") || error("Missing semicolon after dictionary"); return ret; } - var ea = extended_attrs(); - all_ws(); + var ea = extended_attrs(store ? mems : null); + all_ws(store ? mems : null, "pea"); var typ = type() || error("No type for dictionary member"); all_ws(); var name = consume(ID) || error("No name for dictionary member"); @@ -675,28 +756,29 @@ } }; - var exception = function () { - all_ws(); + var exception = function (store) { + all_ws(store, "pea"); if (!consume(ID, "exception")) return; all_ws(); var name = consume(ID) || error("No name for exception"); - var ret = { + var mems = [] + , ret = { type: "exception" , name: name.value - , members: [] + , members: mems }; ret.inheritance = inheritance() || null; all_ws(); consume(OTHER, "{") || error("Bodyless exception"); while (true) { - all_ws(); + all_ws(store ? mems : null); if (consume(OTHER, "}")) { all_ws(); consume(OTHER, ";") || error("Missing semicolon after exception"); return ret; } - var ea = extended_attrs(); - all_ws(); + var ea = extended_attrs(store ? mems : null); + all_ws(store ? mems : null, "pea"); var cnt = const_(); if (cnt) { cnt.extAttrs = ea; @@ -718,21 +800,22 @@ } }; - var enum_ = function () { - all_ws(); + var enum_ = function (store) { + all_ws(store, "pea"); if (!consume(ID, "enum")) return; all_ws(); var name = consume(ID) || error("No name for enum"); - var ret = { + var vals = [] + , ret = { type: "enum" , name: name.value - , values: [] + , values: vals }; all_ws(); consume(OTHER, "{") || error("No curly for enum"); var saw_comma = false; while (true) { - all_ws(); + all_ws(store ? vals : null); if (consume(OTHER, "}")) { all_ws(); if (saw_comma) error("Trailing comma in enum"); @@ -741,9 +824,10 @@ } var val = consume(STR) || error("Unexpected value in enum"); ret.values.push(val.value.replace(/"/g, "")); - all_ws(); + all_ws(store ? vals : null); if (consume(OTHER, ",")) { - all_ws(); + if (store) vals.push({ type: "," }); + all_ws(store ? vals : null); saw_comma = true; } else { @@ -752,15 +836,15 @@ } }; - var typedef = function () { - all_ws(); + var typedef = function (store) { + all_ws(store, "pea"); if (!consume(ID, "typedef")) return; var ret = { type: "typedef" }; all_ws(); ret.typeExtAttrs = extended_attrs(); - all_ws(); + all_ws(store, "tpea"); ret.idlType = type() || error("No type in typedef"); all_ws(); var name = consume(ID) || error("No name in typedef"); @@ -770,8 +854,8 @@ return ret; }; - var implements_ = function () { - all_ws(); + var implements_ = function (store) { + all_ws(store, "pea"); var target = consume(ID); if (!target) return; var w = all_ws(); @@ -794,24 +878,24 @@ } }; - var definition = function () { - return callback() || - interface_() || - partial() || - dictionary() || - exception() || - enum_() || - typedef() || - implements_() + var definition = function (store) { + return callback(store) || + interface_(false, store) || + partial(store) || + dictionary(false, store) || + exception(store) || + enum_(store) || + typedef(store) || + implements_(store) ; }; - var definitions = function () { + var definitions = function (store) { if (!tokens.length) return []; var defs = []; while (true) { - var ea = extended_attrs() - , def = definition(); + var ea = extended_attrs(store ? defs : null) + , def = definition(store ? defs : null); if (!def) { if (ea.length) error("Stray extended attributes"); break; @@ -821,21 +905,20 @@ } return defs; }; - var res = definitions(); + var res = definitions(opt.ws); if (tokens.length) error("Unrecognised tokens"); return res; }; - var obj = { - parse: function (str) { - var tokens = tokenise(str); - return parse(tokens); - } + var inNode = typeof module !== "undefined" && module.exports + , obj = { + parse: function (str, opt) { + if (!opt) opt = {}; + var tokens = tokenise(str); + return parse(tokens, opt); + } }; - if (typeof module !== "undefined" && module.exports) { - module.exports = obj; - } - else { - window.WebIDL2 = obj; - } + + if (inNode) module.exports = obj; + else window.WebIDL2 = obj; }()); diff --git a/dom/imptests/idlharness.js b/dom/imptests/idlharness.js index 613da0cb4c0..b6c02a3f8dd 100644 --- a/dom/imptests/idlharness.js +++ b/dom/imptests/idlharness.js @@ -8,131 +8,7 @@ policies and contribution forms [3]. [3] http://www.w3.org/2004/10/27-testcases */ -/* - * This file automatically generates browser tests for WebIDL interfaces, using - * the testharness.js framework. To use, first include the following: - * - * - * - * - * - * - * Then you'll need some type of IDLs. Here's some script that can be run on a - * spec written in HTML, which will grab all the elements with class="idl", - * concatenate them, and replace the body so you can copy-paste: - * - var s = ""; - [].forEach.call(document.getElementsByClassName("idl"), function(idl) { - //https://www.w3.org/Bugs/Public/show_bug.cgi?id=14914 - if (!idl.classList.contains("extract")) - { - s += idl.textContent + "\n\n"; - } - }); - document.body.innerHTML = '
';
-     document.body.firstChild.textContent = s;
- *
- * (TODO: write this in Python or something so that it can be done from the
- * command line instead.)
- *
- * Once you have that, put it in your script somehow.  The easiest way is to
- * embed it literally in an HTML file with 
- * 
- *
- * Within each file one may define one or more tests. Each test is atomic
- * in the sense that a single test has a single result (pass/fail/timeout).
- * Within each test one may have a number of asserts. The test fails at the
- * first failing assert, and the remainder of the test is (typically) not run.
- *
- * If the file containing the tests is a HTML file with an element of id "log"
- * this will be populated with a table containing the test results after all
- * the tests have run.
- *
- * NOTE: By default tests must be created before the load event fires. For ways
- *       to create tests after the load event, see "Determining when all tests
- *       are complete", below
- *
- * == Synchronous Tests ==
- *
- * To create a synchronous test use the test() function:
- *
- * test(test_function, name, properties)
- *
- * test_function is a function that contains the code to test. For example a
- * trivial passing test would be:
- *
- * test(function() {assert_true(true)}, "assert_true with true")
- *
- * The function passed in is run in the test() call.
- *
- * properties is an object that overrides default test properties. The
- * recognised properties are:
- *    timeout - the test timeout in ms
- *
- * e.g.
- * test(test_function, "Sample test", {timeout:1000})
- *
- * would run test_function with a timeout of 1s.
- *
- * Additionally, test-specific metadata can be passed in the properties. These
- * are used when the individual test has different metadata from that stored
- * in the .
- * The recognized metadata properties are:
- *
- *    help - The url of the part of the specification being tested
- *
- *    assert - A human readable description of what the test is attempting
- *             to prove
- *
- *    author - Name and contact information for the author of the test in the
- *             format: "Name " or "Name http://contact/url"
- *
- * == Asynchronous Tests ==
- *
- * Testing asynchronous features is somewhat more complex since the result of
- * a test may depend on one or more events or other callbacks. The API provided
- * for testing these features is indended to be rather low-level but hopefully
- * applicable to many situations.
- *
- * To create a test, one starts by getting a Test object using async_test:
- *
- * async_test(name, properties)
- *
- * e.g.
- * var t = async_test("Simple async test")
- *
- * Assertions can be added to the test by calling the step method of the test
- * object with a function containing the test assertions:
- *
- * t.step(function() {assert_true(true)});
- *
- * When all the steps are complete, the done() method must be called:
- *
- * t.done();
- *
- * As a convenience, async_test can also takes a function as first argument.
- * This function is called with the test object as both its `this` object and
- * first argument. The above example can be rewritten as:
- *
- * async_test(function(t) {
- *     object.some_event = function() {
- *         t.step(function (){assert_true(true); t.done();});
- *     };
- * }, "Simple async test");
- *
- * which avoids cluttering the global scope with references to async
- * tests instances.
- *
- * The properties argument is identical to that for test().
- *
- * In many cases it is convenient to run a step in response to an event or a
- * callback. A convenient method of doing this is through the step_func method
- * which returns a function that, when called runs a test step. For example
- *
- * object.some_event = t.step_func(function(e) {assert_true(e.a)});
- *
- * == Making assertions ==
- *
- * Functions for making assertions start assert_
- * The best way to get a list is to look in this file for functions names
- * matching that pattern. The general signature is
- *
- * assert_something(actual, expected, description)
- *
- * although not all assertions precisely match this pattern e.g. assert_true
- * only takes actual and description as arguments.
- *
- * The description parameter is used to present more useful error messages when
- * a test fails
- *
- * NOTE: All asserts must be located in a test() or a step of an async_test().
- *       asserts outside these places won't be detected correctly by the harness
- *       and may cause a file to stop testing.
- *
- * == Harness Timeout ==
- * 
- * The overall harness admits two timeout values "normal" (the
- * default) and "long", used for tests which have an unusually long
- * runtime. After the timeout is reached, the harness will stop
- * waiting for further async tests to complete. By default the
- * timeouts are set to 10s and 60s, respectively, but may be changed
- * when the test is run on hardware with different performance
- * characteristics to a common desktop computer.  In order to opt-in
- * to the longer test timeout, the test must specify a meta element:
- * 
- *
- * == Setup ==
- *
- * Sometimes tests require non-trivial setup that may fail. For this purpose
- * there is a setup() function, that may be called with one or two arguments.
- * The two argument version is:
- *
- * setup(func, properties)
- *
- * The one argument versions may omit either argument.
- * func is a function to be run synchronously. setup() becomes a no-op once
- * any tests have returned results. Properties are global properties of the test
- * harness. Currently recognised properties are:
- *
- *
- * explicit_done - Wait for an explicit call to done() before declaring all
- *                 tests complete (see below)
- *
- * output_document - The document to which results should be logged. By default
- *                   this is the current document but could be an ancestor
- *                   document in some cases e.g. a SVG test loaded in an HTML
- *                   wrapper
- *
- * explicit_timeout - disable file timeout; only stop waiting for results
- *                    when the timeout() function is called (typically for
- *                    use when integrating with some existing test framework
- *                    that has its own timeout mechanism).
- *
- * allow_uncaught_exception - don't treat an uncaught exception as an error;
- *                            needed when e.g. testing the window.onerror
- *                            handler.
- *
- * timeout_multiplier - Multiplier to apply to per-test timeouts.
- *
- * == Determining when all tests are complete ==
- *
- * By default the test harness will assume there are no more results to come
- * when:
- * 1) There are no Test objects that have been created but not completed
- * 2) The load event on the document has fired
- *
- * This behaviour can be overridden by setting the explicit_done property to
- * true in a call to setup(). If explicit_done is true, the test harness will
- * not assume it is done until the global done() function is called. Once done()
- * is called, the two conditions above apply like normal.
- *
- * == Generating tests ==
- *
- * NOTE: this functionality may be removed
- *
- * There are scenarios in which is is desirable to create a large number of
- * (synchronous) tests that are internally similar but vary in the parameters
- * used. To make this easier, the generate_tests function allows a single
- * function to be called with each set of parameters in a list:
- *
- * generate_tests(test_function, parameter_lists, properties)
- *
- * For example:
- *
- * generate_tests(assert_equals, [
- *     ["Sum one and one", 1+1, 2],
- *     ["Sum one and zero", 1+0, 1]
- *     ])
- *
- * Is equivalent to:
- *
- * test(function() {assert_equals(1+1, 2)}, "Sum one and one")
- * test(function() {assert_equals(1+0, 1)}, "Sum one and zero")
- *
- * Note that the first item in each parameter list corresponds to the name of
- * the test.
- *
- * The properties argument is identical to that for test(). This may be a
- * single object (used for all generated tests) or an array.
- *
- * == Callback API ==
- *
- * The framework provides callbacks corresponding to 3 events:
- *
- * start - happens when the first Test is created
- * result - happens when a test result is recieved
- * complete - happens when all results are recieved
- *
- * The page defining the tests may add callbacks for these events by calling
- * the following methods:
- *
- *   add_start_callback(callback) - callback called with no arguments
- *   add_result_callback(callback) - callback called with a test argument
- *   add_completion_callback(callback) - callback called with an array of tests
- *                                       and an status object
- *
- * tests have the following properties:
- *   status: A status code. This can be compared to the PASS, FAIL, TIMEOUT and
- *           NOTRUN properties on the test object
- *   message: A message indicating the reason for failure. In the future this
- *            will always be a string
- *
- *  The status object gives the overall status of the harness. It has the
- *  following properties:
- *    status: Can be compared to the OK, ERROR and TIMEOUT properties
- *    message: An error message set when the status is ERROR
- *
- * == External API ==
- *
- * In order to collect the results of multiple pages containing tests, the test
- * harness will, when loaded in a nested browsing context, attempt to call
- * certain functions in each ancestor and opener browsing context:
- *
- * start - start_callback
- * result - result_callback
- * complete - completion_callback
- *
- * These are given the same arguments as the corresponding internal callbacks
- * described above.
- *
- * == External API through cross-document messaging ==
- *
- * Where supported, the test harness will also send messages using
- * cross-document messaging to each ancestor and opener browsing context. Since
- * it uses the wildcard keyword (*), cross-origin communication is enabled and
- * script on different origins can collect the results.
- *
- * This API follows similar conventions as those described above only slightly
- * modified to accommodate message event API. Each message is sent by the harness
- * is passed a single vanilla object, available as the `data` property of the
- * event object. These objects are structures as follows:
- *
- * start - { type: "start" }
- * result - { type: "result", test: Test }
- * complete - { type: "complete", tests: [Test, ...], status: TestsStatus }
- *
- * == List of assertions ==
- *
- * assert_true(actual, description)
- *   asserts that /actual/ is strictly true
- *
- * assert_false(actual, description)
- *   asserts that /actual/ is strictly false
- *
- * assert_equals(actual, expected, description)
- *   asserts that /actual/ is the same value as /expected/
- *
- * assert_not_equals(actual, expected, description)
- *   asserts that /actual/ is a different value to /expected/. Yes, this means
- *   that "expected" is a misnomer
- *
- * assert_in_array(actual, expected, description)
- *   asserts that /expected/ is an Array, and /actual/ is equal to one of the
- *   members -- expected.indexOf(actual) != -1
- *
- * assert_array_equals(actual, expected, description)
- *   asserts that /actual/ and /expected/ have the same length and the value of
- *   each indexed property in /actual/ is the strictly equal to the corresponding
- *   property value in /expected/
- *
- * assert_approx_equals(actual, expected, epsilon, description)
- *   asserts that /actual/ is a number within +/- /epsilon/ of /expected/
- *
- * assert_less_than(actual, expected, description)
- *   asserts that /actual/ is a number less than /expected/
- *
- * assert_greater_than(actual, expected, description)
- *   asserts that /actual/ is a number greater than /expected/
- *
- * assert_less_than_equal(actual, expected, description)
- *   asserts that /actual/ is a number less than or equal to /expected/
- *
- * assert_greater_than_equal(actual, expected, description)
- *   asserts that /actual/ is a number greater than or equal to /expected/
- *
- * assert_regexp_match(actual, expected, description)
- *   asserts that /actual/ matches the regexp /expected/
- *
- * assert_class_string(object, class_name, description)
- *   asserts that the class string of /object/ as returned in
- *   Object.prototype.toString is equal to /class_name/.
- *
- * assert_own_property(object, property_name, description)
- *   assert that object has own property property_name
- *
- * assert_inherits(object, property_name, description)
- *   assert that object does not have an own property named property_name
- *   but that property_name is present in the prototype chain for object
- *
- * assert_idl_attribute(object, attribute_name, description)
- *   assert that an object that is an instance of some interface has the
- *   attribute attribute_name following the conditions specified by WebIDL
- *
- * assert_readonly(object, property_name, description)
- *   assert that property property_name on object is readonly
- *
- * assert_throws(code, func, description)
- *   code - the expected exception:
- *     o string: the thrown exception must be a DOMException with the given
- *               name, e.g., "TimeoutError" (for compatibility with existing
- *               tests, a constant is also supported, e.g., "TIMEOUT_ERR")
- *     o object: the thrown exception must have a property called "name" that
- *               matches code.name
- *     o null:   allow any exception (in general, one of the options above
- *               should be used)
- *   func - a function that should throw
- *
- * assert_unreached(description)
- *   asserts if called. Used to ensure that some codepath is *not* taken e.g.
- *   an event does not fire.
- *
- * assert_any(assert_func, actual, expected_array, extra_arg_1, ... extra_arg_N)
- *   asserts that one assert_func(actual, expected_array_N, extra_arg1, ..., extra_arg_N)
- *   is true for some expected_array_N in expected_array. This only works for assert_func
- *   with signature assert_func(actual, expected, args_1, ..., args_N). Note that tests
- *   with multiple allowed pass conditions are bad practice unless the spec specifically
- *   allows multiple behaviours. Test authors should not use this method simply to hide
- *   UA bugs.
- *
- * assert_exists(object, property_name, description)
- *   *** deprecated ***
- *   asserts that object has an own property property_name
- *
- * assert_not_exists(object, property_name, description)
- *   *** deprecated ***
- *   assert that object does not have own property property_name
- */
+/* Documentation is in docs/api.md */
 
 (function ()
 {
     var debug = false;
     // default timeout is 10 seconds, test can override if needed
     var settings = {
-      output:true,
-      harness_timeout:{"normal":10000,
-                       "long":60000},
-      test_timeout:null
+        output:true,
+        harness_timeout:{
+            "normal":10000,
+            "long":60000
+        },
+        test_timeout:null
     };
 
     var xhtml_ns = "http://www.w3.org/1999/xhtml";
 
-    // script_prefix is used by Output.prototype.show_results() to figure out
-    // where to get testharness.css from.  It's enclosed in an extra closure to
-    // not pollute the library's namespace with variables like "src".
-    var script_prefix = null;
-    (function ()
-    {
-        var scripts = document.getElementsByTagName("script");
-        for (var i = 0; i < scripts.length; i++)
-        {
-            if (scripts[i].src)
-            {
-                var src = scripts[i].src;
+    /*
+     * TestEnvironment is an abstraction for the environment in which the test
+     * harness is used. Each implementation of a test environment has to provide
+     * the following interface:
+     *
+     * interface TestEnvironment {
+     *   // Invoked after the global 'tests' object has been created and it's
+     *   // safe to call add_*_callback() to register event handlers.
+     *   void on_tests_ready();
+     *
+     *   // Invoked after setup() has been called to notify the test environment
+     *   // of changes to the test harness properties.
+     *   void on_new_harness_properties(object properties);
+     *
+     *   // Should return a new unique default test name.
+     *   DOMString next_default_test_name();
+     *
+     *   // Should return the test harness timeout duration in milliseconds.
+     *   float test_timeout();
+     *
+     *   // Should return the global scope object.
+     *   object global_scope();
+     * };
+     */
+
+    /*
+     * A test environment with a DOM. The global object is 'window'. By default
+     * test results are displayed in a table. Any parent windows receive
+     * callbacks or messages via postMessage() when test events occur. See
+     * apisample11.html and apisample12.html.
+     */
+    function WindowTestEnvironment() {
+        this.name_counter = 0;
+        this.window_cache = null;
+        this.output_handler = null;
+        this.all_loaded = false;
+        var this_obj = this;
+        on_event(window, 'load', function() {
+            this_obj.all_loaded = true;
+        });
+    }
+
+    WindowTestEnvironment.prototype._dispatch = function(selector, callback_args, message_arg) {
+        this._forEach_windows(
+                function(w, is_same_origin) {
+                    if (is_same_origin && selector in w) {
+                        try {
+                            w[selector].apply(undefined, callback_args);
+                        } catch (e) {
+                            if (debug) {
+                                throw e;
+                            }
+                        }
+                    }
+                    if (supports_post_message(w) && w !== self) {
+                        w.postMessage(message_arg, "*");
+                    }
+                });
+    };
+
+    WindowTestEnvironment.prototype._forEach_windows = function(callback) {
+        // Iterate of the the windows [self ... top, opener]. The callback is passed
+        // two objects, the first one is the windows object itself, the second one
+        // is a boolean indicating whether or not its on the same origin as the
+        // current window.
+        var cache = this.window_cache;
+        if (!cache) {
+            cache = [[self, true]];
+            var w = self;
+            var i = 0;
+            var so;
+            var origins = location.ancestorOrigins;
+            while (w != w.parent) {
+                w = w.parent;
+                // In WebKit, calls to parent windows' properties that aren't on the same
+                // origin cause an error message to be displayed in the error console but
+                // don't throw an exception. This is a deviation from the current HTML5
+                // spec. See: https://bugs.webkit.org/show_bug.cgi?id=43504
+                // The problem with WebKit's behavior is that it pollutes the error console
+                // with error messages that can't be caught.
+                //
+                // This issue can be mitigated by relying on the (for now) proprietary
+                // `location.ancestorOrigins` property which returns an ordered list of
+                // the origins of enclosing windows. See:
+                // http://trac.webkit.org/changeset/113945.
+                if (origins) {
+                    so = (location.origin == origins[i]);
+                } else {
+                    so = is_same_origin(w);
+                }
+                cache.push([w, so]);
+                i++;
             }
-            else if (scripts[i].href)
-            {
-                //SVG case
-                var src = scripts[i].href.baseVal;
+            w = window.opener;
+            if (w) {
+                // window.opener isn't included in the `location.ancestorOrigins` prop.
+                // We'll just have to deal with a simple check and an error msg on WebKit
+                // browsers in this case.
+                cache.push([w, is_same_origin(w)]);
             }
-            if (src && src.slice(src.length - "testharness.js".length) === "testharness.js")
-            {
-                script_prefix = src.slice(0, src.length - "testharness.js".length);
+            this.window_cache = cache;
+        }
+
+        forEach(cache,
+                function(a) {
+                    callback.apply(null, a);
+                });
+    };
+
+    WindowTestEnvironment.prototype.on_tests_ready = function() {
+        var output = new Output();
+        this.output_handler = output;
+
+        var this_obj = this;
+        add_start_callback(function (properties) {
+            this_obj.output_handler.init(properties);
+            this_obj._dispatch("start_callback", [properties],
+                           { type: "start", properties: properties });
+        });
+        add_test_state_callback(function(test) {
+            this_obj.output_handler.show_status();
+            this_obj._dispatch("test_state_callback", [test],
+                               { type: "test_state", test: test.structured_clone() });
+        });
+        add_result_callback(function (test) {
+            this_obj.output_handler.show_status();
+            this_obj._dispatch("result_callback", [test],
+                               { type: "result", test: test.structured_clone() });
+        });
+        add_completion_callback(function (tests, harness_status) {
+            this_obj.output_handler.show_results(tests, harness_status);
+            var cloned_tests = map(tests, function(test) { return test.structured_clone(); });
+            this_obj._dispatch("completion_callback", [tests, harness_status],
+                               { type: "complete", tests: cloned_tests,
+                                 status: harness_status.structured_clone() });
+        });
+    };
+
+    WindowTestEnvironment.prototype.next_default_test_name = function() {
+        //Don't use document.title to work around an Opera bug in XHTML documents
+        var title = document.getElementsByTagName("title")[0];
+        var prefix = (title && title.firstChild && title.firstChild.data) || "Untitled";
+        var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
+        this.name_counter++;
+        return prefix + suffix;
+    };
+
+    WindowTestEnvironment.prototype.on_new_harness_properties = function(properties) {
+        this.output_handler.setup(properties);
+    };
+
+    WindowTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
+        on_event(window, 'load', callback);
+    };
+
+    WindowTestEnvironment.prototype.test_timeout = function() {
+        var metas = document.getElementsByTagName("meta");
+        for (var i = 0; i < metas.length; i++) {
+            if (metas[i].name == "timeout") {
+                if (metas[i].content == "long") {
+                    return settings.harness_timeout.long;
+                }
                 break;
             }
         }
-    })();
+        return settings.harness_timeout.normal;
+    };
+
+    WindowTestEnvironment.prototype.global_scope = function() {
+        return window;
+    };
+
+    /*
+     * Base TestEnvironment implementation for a generic web worker.
+     *
+     * Workers accumulate test results. One or more clients can connect and
+     * retrieve results from a worker at any time.
+     *
+     * WorkerTestEnvironment supports communicating with a client via a
+     * MessagePort.  The mechanism for determining the appropriate MessagePort
+     * for communicating with a client depends on the type of worker and is
+     * implemented by the various specializations of WorkerTestEnvironment
+     * below.
+     *
+     * A client document using testharness can use fetch_tests_from_worker() to
+     * retrieve results from a worker. See apisample16.html.
+     */
+    function WorkerTestEnvironment() {
+        this.name_counter = 0;
+        this.all_loaded = true;
+        this.message_list = [];
+        this.message_ports = [];
+    }
+
+    WorkerTestEnvironment.prototype._dispatch = function(message) {
+        this.message_list.push(message);
+        for (var i = 0; i < this.message_ports.length; ++i)
+        {
+            this.message_ports[i].postMessage(message);
+        }
+    };
+
+    // The only requirement is that port has a postMessage() method. It doesn't
+    // have to be an instance of a MessagePort, and often isn't.
+    WorkerTestEnvironment.prototype._add_message_port = function(port) {
+        this.message_ports.push(port);
+        for (var i = 0; i < this.message_list.length; ++i)
+        {
+            port.postMessage(this.message_list[i]);
+        }
+    };
+
+    WorkerTestEnvironment.prototype.next_default_test_name = function() {
+        var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
+        this.name_counter++;
+        return "Untitled" + suffix;
+    };
+
+    WorkerTestEnvironment.prototype.on_new_harness_properties = function() {};
+
+    WorkerTestEnvironment.prototype.on_tests_ready = function() {
+        var this_obj = this;
+        add_start_callback(
+                function(properties) {
+                    this_obj._dispatch({
+                        type: "start",
+                        properties: properties,
+                    });
+                });
+        add_test_state_callback(
+                function(test) {
+                    this_obj._dispatch({
+                        type: "test_state",
+                        test: test.structured_clone()
+                    });
+                });
+        add_result_callback(
+                function(test) {
+                    this_obj._dispatch({
+                        type: "result",
+                        test: test.structured_clone()
+                    });
+                });
+        add_completion_callback(
+                function(tests, harness_status) {
+                    this_obj._dispatch({
+                        type: "complete",
+                        tests: map(tests,
+                            function(test) {
+                                return test.structured_clone();
+                            }),
+                        status: harness_status.structured_clone()
+                    });
+                });
+    };
+
+    WorkerTestEnvironment.prototype.add_on_loaded_callback = function() {};
+
+    WorkerTestEnvironment.prototype.test_timeout = function() {
+        // Tests running in a worker don't have a default timeout. I.e. all
+        // worker tests behave as if settings.explicit_timeout is true.
+        return null;
+    };
+
+    WorkerTestEnvironment.prototype.global_scope = function() {
+        return self;
+    };
+
+    /*
+     * Dedicated web workers.
+     * https://html.spec.whatwg.org/multipage/workers.html#dedicatedworkerglobalscope
+     *
+     * This class is used as the test_environment when testharness is running
+     * inside a dedicated worker.
+     */
+    function DedicatedWorkerTestEnvironment() {
+        WorkerTestEnvironment.call(this);
+        // self is an instance of DedicatedWorkerGlobalScope which exposes
+        // a postMessage() method for communicating via the message channel
+        // established when the worker is created.
+        this._add_message_port(self);
+    }
+    DedicatedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
+
+    DedicatedWorkerTestEnvironment.prototype.on_tests_ready = function() {
+        WorkerTestEnvironment.prototype.on_tests_ready.call(this);
+        // In the absence of an onload notification, we a require dedicated
+        // workers to explicitly signal when the tests are done.
+        tests.wait_for_finish = true;
+    };
+
+    /*
+     * Shared web workers.
+     * https://html.spec.whatwg.org/multipage/workers.html#sharedworkerglobalscope
+     *
+     * This class is used as the test_environment when testharness is running
+     * inside a shared web worker.
+     */
+    function SharedWorkerTestEnvironment() {
+        WorkerTestEnvironment.call(this);
+        var this_obj = this;
+        // Shared workers receive message ports via the 'onconnect' event for
+        // each connection.
+        self.addEventListener("connect",
+                function(message_event) {
+                    this_obj._add_message_port(message_event.source);
+                });
+    }
+    SharedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
+
+    SharedWorkerTestEnvironment.prototype.on_tests_ready = function() {
+        WorkerTestEnvironment.prototype.on_tests_ready.call(this);
+        // In the absence of an onload notification, we a require shared
+        // workers to explicitly signal when the tests are done.
+        tests.wait_for_finish = true;
+    };
+
+    /*
+     * Service workers.
+     * http://www.w3.org/TR/service-workers/
+     *
+     * This class is used as the test_environment when testharness is running
+     * inside a service worker.
+     */
+    function ServiceWorkerTestEnvironment() {
+        WorkerTestEnvironment.call(this);
+        this.all_loaded = false;
+        this.on_loaded_callback = null;
+        var this_obj = this;
+        self.addEventListener("message",
+                function(event) {
+                    if (event.data.type && event.data.type === "connect") {
+                        this_obj._add_message_port(event.ports[0]);
+                        event.ports[0].start();
+                    }
+                });
+
+        // The oninstall event is received after the service worker script and
+        // all imported scripts have been fetched and executed. It's the
+        // equivalent of an onload event for a document. All tests should have
+        // been added by the time this event is received, thus it's not
+        // necessary to wait until the onactivate event.
+        on_event(self, "install",
+                function(event) {
+                    this_obj.all_loaded = true;
+                    if (this_obj.on_loaded_callback) {
+                        this_obj.on_loaded_callback();
+                    }
+                });
+    }
+    ServiceWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
+
+    ServiceWorkerTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
+        if (this.all_loaded) {
+            callback();
+        } else {
+            this.on_loaded_callback = callback;
+        }
+    };
+
+    function create_test_environment() {
+        if ('document' in self) {
+            return new WindowTestEnvironment();
+        }
+        if ('DedicatedWorkerGlobalScope' in self &&
+            self instanceof DedicatedWorkerGlobalScope) {
+            return new DedicatedWorkerTestEnvironment();
+        }
+        if ('SharedWorkerGlobalScope' in self &&
+            self instanceof SharedWorkerGlobalScope) {
+            return new SharedWorkerTestEnvironment();
+        }
+        if ('ServiceWorkerGlobalScope' in self &&
+            self instanceof ServiceWorkerGlobalScope) {
+            return new ServiceWorkerTestEnvironment();
+        }
+        throw new Error("Unsupported test environment");
+    }
+
+    var test_environment = create_test_environment();
+
+    function is_shared_worker(worker) {
+        return 'SharedWorker' in self && worker instanceof SharedWorker;
+    }
+
+    function is_service_worker(worker) {
+        return 'ServiceWorker' in self && worker instanceof ServiceWorker;
+    }
 
     /*
      * API functions
      */
 
-    var name_counter = 0;
-    function next_default_name()
-    {
-        //Don't use document.title to work around an Opera bug in XHTML documents
-        var title = document.getElementsByTagName("title")[0];
-        var prefix = (title && title.firstChild && title.firstChild.data) || "Untitled";
-        var suffix = name_counter > 0 ? " " + name_counter : "";
-        name_counter++;
-        return prefix + suffix;
-    }
-
     function test(func, name, properties)
     {
-        var test_name = name ? name : next_default_name();
+        var test_name = name ? name : test_environment.next_default_test_name();
         properties = properties ? properties : {};
         var test_obj = new Test(test_name, properties);
-        test_obj.step(func);
+        test_obj.step(func, test_obj, test_obj);
         if (test_obj.phase === test_obj.phases.STARTED) {
             test_obj.done();
         }
@@ -439,7 +438,7 @@ policies and contribution forms [3].
             name = func;
             func = null;
         }
-        var test_name = name ? name : next_default_name();
+        var test_name = name ? name : test_environment.next_default_test_name();
         properties = properties ? properties : {};
         var test_obj = new Test(test_name, properties);
         if (func) {
@@ -448,6 +447,23 @@ policies and contribution forms [3].
         return test_obj;
     }
 
+    function promise_test(func, name, properties) {
+        var test = async_test(name, properties);
+        Promise.resolve(test.step(func, test, test))
+            .then(
+                function() {
+                    test.done();
+                })
+            .catch(test.step_func(
+                function(value) {
+                    if (value instanceof AssertionError) {
+                        throw value;
+                    }
+                    assert(false, "promise_test", null,
+                           "Unhandled rejection with value: ${value}", {value:value});
+                }));
+    }
+
     function setup(func_or_properties, maybe_properties)
     {
         var func = null;
@@ -455,16 +471,22 @@ policies and contribution forms [3].
         if (arguments.length === 2) {
             func = func_or_properties;
             properties = maybe_properties;
-        } else if (func_or_properties instanceof Function){
+        } else if (func_or_properties instanceof Function) {
             func = func_or_properties;
         } else {
             properties = func_or_properties;
         }
         tests.setup(func, properties);
-        output.setup(properties);
+        test_environment.on_new_harness_properties(properties);
     }
 
     function done() {
+        if (tests.tests.length === 0) {
+            tests.set_file_is_test();
+        }
+        if (tests.file_is_test) {
+            tests.tests[0].done();
+        }
         tests.end_wait();
     }
 
@@ -483,11 +505,12 @@ policies and contribution forms [3].
 
     function on_event(object, event, callback)
     {
-      object.addEventListener(event, callback, false);
+        object.addEventListener(event, callback, false);
     }
 
     expose(test, 'test');
     expose(async_test, 'async_test');
+    expose(promise_test, 'promise_test');
     expose(generate_tests, 'generate_tests');
     expose(setup, 'setup');
     expose(done, 'done');
@@ -514,17 +537,13 @@ policies and contribution forms [3].
         // instanceof doesn't work if the node is from another window (like an
         // iframe's contentWindow):
         // http://www.w3.org/Bugs/Public/show_bug.cgi?id=12295
-        if ("nodeType" in object
-        && "nodeName" in object
-        && "nodeValue" in object
-        && "childNodes" in object)
-        {
-            try
-            {
+        if ("nodeType" in object &&
+            "nodeName" in object &&
+            "nodeValue" in object &&
+            "childNodes" in object) {
+            try {
                 object.nodeType;
-            }
-            catch (e)
-            {
+            } catch (e) {
                 // The object is probably Node.prototype or another prototype
                 // object that inherits from it, and not a Node instance.
                 return false;
@@ -542,25 +561,20 @@ policies and contribution forms [3].
         if (!seen) {
             seen = [];
         }
-        if (typeof val === "object" && val !== null)
-        {
-            if (seen.indexOf(val) >= 0)
-            {
+        if (typeof val === "object" && val !== null) {
+            if (seen.indexOf(val) >= 0) {
                 return "[...]";
             }
             seen.push(val);
         }
-        if (Array.isArray(val))
-        {
-            return "[" + val.map(function(x) {return format_value(x, seen)}).join(", ") + "]";
+        if (Array.isArray(val)) {
+            return "[" + val.map(function(x) {return format_value(x, seen);}).join(", ") + "]";
         }
 
-        switch (typeof val)
-        {
+        switch (typeof val) {
         case "string":
             val = val.replace("\\", "\\\\");
-            for (var i = 0; i < 32; i++)
-            {
+            for (var i = 0; i < 32; i++) {
                 var replace = "\\";
                 switch (i) {
                 case 0: replace += "0"; break;
@@ -605,30 +619,25 @@ policies and contribution forms [3].
         case "number":
             // In JavaScript, -0 === 0 and String(-0) == "0", so we have to
             // special-case.
-            if (val === -0 && 1/val === -Infinity)
-            {
+            if (val === -0 && 1/val === -Infinity) {
                 return "-0";
             }
             return String(val);
         case "object":
-            if (val === null)
-            {
+            if (val === null) {
                 return "null";
             }
 
             // Special-case Node objects, since those come up a lot in my tests.  I
             // ignore namespaces.
-            if (is_node(val))
-            {
-                switch (val.nodeType)
-                {
+            if (is_node(val)) {
+                switch (val.nodeType) {
                 case Node.ELEMENT_NODE:
-                    var ret = "<" + val.tagName.toLowerCase();
-                    for (var i = 0; i < val.attributes.length; i++)
-                    {
+                    var ret = "<" + val.localName;
+                    for (var i = 0; i < val.attributes.length; i++) {
                         ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"';
                     }
-                    ret += ">" + val.innerHTML + "";
+                    ret += ">" + val.innerHTML + "";
                     return "Element node " + truncate(ret, 60);
                 case Node.TEXT_NODE:
                     return 'Text node "' + truncate(val.data, 60) + '"';
@@ -647,7 +656,7 @@ policies and contribution forms [3].
                 }
             }
 
-            // Fall through to default
+        /* falls through */
         default:
             return typeof val + ' "' + truncate(String(val), 60) + '"';
         }
@@ -662,31 +671,26 @@ policies and contribution forms [3].
     {
         assert(actual === true, "assert_true", description,
                                 "expected true got ${actual}", {actual:actual});
-    };
+    }
     expose(assert_true, "assert_true");
 
     function assert_false(actual, description)
     {
         assert(actual === false, "assert_false", description,
                                  "expected false got ${actual}", {actual:actual});
-    };
+    }
     expose(assert_false, "assert_false");
 
     function same_value(x, y) {
-        if (y !== y)
-        {
+        if (y !== y) {
             //NaN case
             return x !== x;
         }
-        else if (x === 0 && y === 0) {
+        if (x === 0 && y === 0) {
             //Distinguish +0 and -0
             return 1/x === 1/y;
         }
-        else
-        {
-            //typical case
-            return x === y;
-        }
+        return x === y;
     }
 
     function assert_equals(actual, expected, description)
@@ -695,8 +699,7 @@ policies and contribution forms [3].
           * Test if two primitives are equal or two objects
           * are the same object
           */
-        if (typeof actual != typeof expected)
-        {
+        if (typeof actual != typeof expected) {
             assert(false, "assert_equals", description,
                           "expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}",
                           {expected:expected, actual:actual});
@@ -705,7 +708,7 @@ policies and contribution forms [3].
         assert(same_value(actual, expected), "assert_equals", description,
                                              "expected ${expected} but got ${actual}",
                                              {expected:expected, actual:actual});
-    };
+    }
     expose(assert_equals, "assert_equals");
 
     function assert_not_equals(actual, expected, description)
@@ -717,7 +720,7 @@ policies and contribution forms [3].
         assert(!same_value(actual, expected), "assert_not_equals", description,
                                               "got disallowed value ${actual}",
                                               {actual:actual});
-    };
+    }
     expose(assert_not_equals, "assert_not_equals");
 
     function assert_in_array(actual, expected, description)
@@ -736,27 +739,21 @@ policies and contribution forms [3].
              stack.push(actual);
 
              var p;
-             for (p in actual)
-             {
+             for (p in actual) {
                  assert(expected.hasOwnProperty(p), "assert_object_equals", description,
                                                     "unexpected property ${p}", {p:p});
 
-                 if (typeof actual[p] === "object" && actual[p] !== null)
-                 {
-                     if (stack.indexOf(actual[p]) === -1)
-                     {
+                 if (typeof actual[p] === "object" && actual[p] !== null) {
+                     if (stack.indexOf(actual[p]) === -1) {
                          check_equal(actual[p], expected[p], stack);
                      }
-                 }
-                 else
-                 {
+                 } else {
                      assert(same_value(actual[p], expected[p]), "assert_object_equals", description,
                                                        "property ${p} expected ${expected} got ${actual}",
                                                        {p:p, expected:expected, actual:actual});
                  }
              }
-             for (p in expected)
-             {
+             for (p in expected) {
                  assert(actual.hasOwnProperty(p),
                         "assert_object_equals", description,
                         "expected property ${p} missing", {p:p});
@@ -764,7 +761,7 @@ policies and contribution forms [3].
              stack.pop();
          }
          check_equal(actual, expected, []);
-    };
+    }
     expose(assert_object_equals, "assert_object_equals");
 
     function assert_array_equals(actual, expected, description)
@@ -774,8 +771,7 @@ policies and contribution forms [3].
                "lengths differ, expected ${expected} got ${actual}",
                {expected:expected.length, actual:actual.length});
 
-        for (var i=0; i < actual.length; i++)
-        {
+        for (var i = 0; i < actual.length; i++) {
             assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),
                    "assert_array_equals", description,
                    "property ${i}, property expected to be $expected but was $actual",
@@ -803,7 +799,7 @@ policies and contribution forms [3].
                "assert_approx_equals", description,
                "expected ${expected} +/- ${epsilon} but got ${actual}",
                {expected:expected, actual:actual, epsilon:epsilon});
-    };
+    }
     expose(assert_approx_equals, "assert_approx_equals");
 
     function assert_less_than(actual, expected, description)
@@ -820,7 +816,7 @@ policies and contribution forms [3].
                "assert_less_than", description,
                "expected a number less than ${expected} but got ${actual}",
                {expected:expected, actual:actual});
-    };
+    }
     expose(assert_less_than, "assert_less_than");
 
     function assert_greater_than(actual, expected, description)
@@ -837,7 +833,7 @@ policies and contribution forms [3].
                "assert_greater_than", description,
                "expected a number greater than ${expected} but got ${actual}",
                {expected:expected, actual:actual});
-    };
+    }
     expose(assert_greater_than, "assert_greater_than");
 
     function assert_less_than_equal(actual, expected, description)
@@ -854,7 +850,7 @@ policies and contribution forms [3].
                "assert_less_than", description,
                "expected a number less than or equal to ${expected} but got ${actual}",
                {expected:expected, actual:actual});
-    };
+    }
     expose(assert_less_than_equal, "assert_less_than_equal");
 
     function assert_greater_than_equal(actual, expected, description)
@@ -871,7 +867,7 @@ policies and contribution forms [3].
                "assert_greater_than_equal", description,
                "expected a number greater than or equal to ${expected} but got ${actual}",
                {expected:expected, actual:actual});
-    };
+    }
     expose(assert_greater_than_equal, "assert_greater_than_equal");
 
     function assert_regexp_match(actual, expected, description) {
@@ -908,7 +904,7 @@ policies and contribution forms [3].
         assert(!object.hasOwnProperty(property_name),
                "assert_not_exists", description,
                "unexpected property ${p} found", {p:property_name});
-    };
+    }
     expose(assert_not_exists, "assert_not_exists");
 
     function _assert_inherits(name) {
@@ -947,33 +943,26 @@ policies and contribution forms [3].
                     "assert_readonly", description,
                     "changing property ${p} succeeded",
                     {p:property_name});
-         }
-         finally
-         {
+         } finally {
              object[property_name] = initial_value;
          }
-    };
+    }
     expose(assert_readonly, "assert_readonly");
 
     function assert_throws(code, func, description)
     {
-        try
-        {
+        try {
             func.call(this);
             assert(false, "assert_throws", description,
                    "${func} did not throw", {func:func});
-        }
-        catch(e)
-        {
+        } catch (e) {
             if (e instanceof AssertionError) {
-                throw(e);
+                throw e;
             }
-            if (code === null)
-            {
+            if (code === null) {
                 return;
             }
-            if (typeof code === "object")
-            {
+            if (typeof code === "object") {
                 assert(typeof e == "object" && "name" in e && e.name == code.name,
                        "assert_throws", description,
                        "${func} threw ${actual} (${actual_name}) expected ${expected} (${expected_name})",
@@ -1040,16 +1029,14 @@ policies and contribution forms [3].
                 VersionError: 0
             };
 
-            if (!(name in name_code_map))
-            {
+            if (!(name in name_code_map)) {
                 throw new AssertionError('Test bug: unrecognized DOMException code "' + code + '" passed to assert_throws()');
             }
 
             var required_props = { code: name_code_map[name] };
 
-            if (required_props.code === 0
-            || ("name" in e && e.name !== e.name.toUpperCase() && e.name !== "DOMException"))
-            {
+            if (required_props.code === 0 ||
+               ("name" in e && e.name !== e.name.toUpperCase() && e.name !== "DOMException")) {
                 // New style exception: also test the name property.
                 required_props.name = name;
             }
@@ -1064,8 +1051,7 @@ policies and contribution forms [3].
                    "${func} threw ${e} with type ${type}, not an object",
                    {func:func, e:e, type:typeof e});
 
-            for (var prop in required_props)
-            {
+            for (var prop in required_props) {
                 assert(typeof e == "object" && prop in e && e[prop] == required_props[prop],
                        "assert_throws", description,
                        "${func} threw ${e} that is not a DOMException " + code + ": property ${prop} is equal to ${actual}, expected ${expected}",
@@ -1083,16 +1069,16 @@ policies and contribution forms [3].
 
     function assert_any(assert_func, actual, expected_array)
     {
-        var args = [].slice.call(arguments, 3)
-        var errors = []
+        var args = [].slice.call(arguments, 3);
+        var errors = [];
         var passed = false;
         forEach(expected_array,
                 function(expected)
                 {
                     try {
-                        assert_func.apply(this, [actual, expected].concat(args))
+                        assert_func.apply(this, [actual, expected].concat(args));
                         passed = true;
-                    } catch(e) {
+                    } catch (e) {
                         errors.push(e.message);
                     }
                 });
@@ -1104,22 +1090,20 @@ policies and contribution forms [3].
 
     function Test(name, properties)
     {
+        if (tests.file_is_test && tests.tests.length) {
+            throw new Error("Tried to create a test with file_is_test");
+        }
         this.name = name;
 
-        this.phases = {
-            INITIAL:0,
-            STARTED:1,
-            HAS_RESULT:2,
-            COMPLETE:3
-        };
         this.phase = this.phases.INITIAL;
 
         this.status = this.NOTRUN;
         this.timeout_id = null;
+        this.index = null;
 
         this.properties = properties;
-        var timeout = properties.timeout ? properties.timeout : settings.test_timeout
-        if (timeout != null) {
+        var timeout = properties.timeout ? properties.timeout : settings.test_timeout;
+        if (timeout !== null) {
             this.timeout_length = timeout * tests.timeout_multiplier;
         } else {
             this.timeout_length = null;
@@ -1127,9 +1111,10 @@ policies and contribution forms [3].
 
         this.message = null;
 
-        var this_obj = this;
         this.steps = [];
 
+        this.cleanup_callbacks = [];
+
         tests.push(this);
     }
 
@@ -1142,53 +1127,55 @@ policies and contribution forms [3].
 
     Test.prototype = merge({}, Test.statuses);
 
+    Test.prototype.phases = {
+        INITIAL:0,
+        STARTED:1,
+        HAS_RESULT:2,
+        COMPLETE:3
+    };
+
     Test.prototype.structured_clone = function()
     {
-        if(!this._structured_clone)
-        {
+        if (!this._structured_clone) {
             var msg = this.message;
             msg = msg ? String(msg) : msg;
             this._structured_clone = merge({
                 name:String(this.name),
-                status:this.status,
-                message:msg
+                properties:merge({}, this.properties),
             }, Test.statuses);
         }
+        this._structured_clone.status = this.status;
+        this._structured_clone.message = this.message;
+        this._structured_clone.index = this.index;
         return this._structured_clone;
     };
 
     Test.prototype.step = function(func, this_obj)
     {
-        if (this.phase > this.phases.STARTED)
-        {
-          return;
+        if (this.phase > this.phases.STARTED) {
+            return;
         }
         this.phase = this.phases.STARTED;
         //If we don't get a result before the harness times out that will be a test timout
         this.set_status(this.TIMEOUT, "Test timed out");
 
         tests.started = true;
+        tests.notify_test_state(this);
 
-        if (this.timeout_id === null)
-        {
+        if (this.timeout_id === null) {
             this.set_timeout();
         }
 
         this.steps.push(func);
 
-        if (arguments.length === 1)
-        {
+        if (arguments.length === 1) {
             this_obj = this;
         }
 
-        try
-        {
+        try {
             return func.apply(this_obj, Array.prototype.slice.call(arguments, 2));
-        }
-        catch(e)
-        {
-            if (this.phase >= this.phases.HAS_RESULT)
-            {
+        } catch (e) {
+            if (this.phase >= this.phases.HAS_RESULT) {
                 return;
             }
             var message = (typeof e === "object" && e !== null) ? e.message : e;
@@ -1209,14 +1196,13 @@ policies and contribution forms [3].
     {
         var test_this = this;
 
-        if (arguments.length === 1)
-        {
+        if (arguments.length === 1) {
             this_obj = test_this;
         }
 
         return function()
         {
-            test_this.step.apply(test_this, [func, this_obj].concat(
+            return test_this.step.apply(test_this, [func, this_obj].concat(
                 Array.prototype.slice.call(arguments)));
         };
     };
@@ -1225,41 +1211,57 @@ policies and contribution forms [3].
     {
         var test_this = this;
 
-        if (arguments.length === 1)
-        {
+        if (arguments.length === 1) {
             this_obj = test_this;
         }
 
         return function()
         {
-            test_this.step.apply(test_this, [func, this_obj].concat(
-                Array.prototype.slice.call(arguments)));
+            if (func) {
+                test_this.step.apply(test_this, [func, this_obj].concat(
+                    Array.prototype.slice.call(arguments)));
+            }
             test_this.done();
         };
-    }
+    };
+
+    Test.prototype.unreached_func = function(description)
+    {
+        return this.step_func(function() {
+            assert_unreached(description);
+        });
+    };
+
+    Test.prototype.add_cleanup = function(callback) {
+        this.cleanup_callbacks.push(callback);
+    };
+
+    Test.prototype.force_timeout = function() {
+        this.set_status(this.TIMEOUT);
+        this.phase = this.phases.HAS_RESULT;
+    };
 
     Test.prototype.set_timeout = function()
     {
-        if (this.timeout_length !== null)
-        {
+        if (this.timeout_length !== null) {
             var this_obj = this;
             this.timeout_id = setTimeout(function()
                                          {
                                              this_obj.timeout();
                                          }, this.timeout_length);
         }
-    }
+    };
 
     Test.prototype.set_status = function(status, message)
     {
         this.status = status;
         this.message = message;
-    }
+    };
 
     Test.prototype.timeout = function()
     {
         this.timeout_id = null;
-        this.set_status(this.TIMEOUT, "Test timed out")
+        this.set_status(this.TIMEOUT, "Test timed out");
         this.phase = this.phases.HAS_RESULT;
         this.done();
     };
@@ -1268,22 +1270,164 @@ policies and contribution forms [3].
     {
         if (this.phase == this.phases.COMPLETE) {
             return;
-        } else if (this.phase <= this.phases.STARTED)
-        {
-            this.set_status(this.PASS, null);
         }
 
-        if (this.status == this.NOTRUN)
-        {
-            alert(this.phase);
+        if (this.phase <= this.phases.STARTED) {
+            this.set_status(this.PASS, null);
         }
 
         this.phase = this.phases.COMPLETE;
 
         clearTimeout(this.timeout_id);
         tests.result(this);
+        this.cleanup();
     };
 
+    Test.prototype.cleanup = function() {
+        forEach(this.cleanup_callbacks,
+                function(cleanup_callback) {
+                    cleanup_callback();
+                });
+    };
+
+    /*
+     * A RemoteTest object mirrors a Test object on a remote worker. The
+     * associated RemoteWorker updates the RemoteTest object in response to
+     * received events. In turn, the RemoteTest object replicates these events
+     * on the local document. This allows listeners (test result reporting
+     * etc..) to transparently handle local and remote events.
+     */
+    function RemoteTest(clone) {
+        var this_obj = this;
+        Object.keys(clone).forEach(
+                function(key) {
+                    this_obj[key] = clone[key];
+                });
+        this.index = null;
+        this.phase = this.phases.INITIAL;
+        this.update_state_from(clone);
+        tests.push(this);
+    }
+
+    RemoteTest.prototype.structured_clone = function() {
+        var clone = {};
+        Object.keys(this).forEach(
+                function(key) {
+                    if (typeof(this[key]) === "object") {
+                        clone[key] = merge({}, this[key]);
+                    } else {
+                        clone[key] = this[key];
+                    }
+                });
+        clone.phases = merge({}, this.phases);
+        return clone;
+    };
+
+    RemoteTest.prototype.cleanup = function() {};
+    RemoteTest.prototype.phases = Test.prototype.phases;
+    RemoteTest.prototype.update_state_from = function(clone) {
+        this.status = clone.status;
+        this.message = clone.message;
+        if (this.phase === this.phases.INITIAL) {
+            this.phase = this.phases.STARTED;
+        }
+    };
+    RemoteTest.prototype.done = function() {
+        this.phase = this.phases.COMPLETE;
+    }
+
+    /*
+     * A RemoteWorker listens for test events from a worker. These events are
+     * then used to construct and maintain RemoteTest objects that mirror the
+     * tests running on the remote worker.
+     */
+    function RemoteWorker(worker) {
+        this.running = true;
+        this.tests = new Array();
+
+        var this_obj = this;
+        worker.onerror = function(error) { this_obj.worker_error(error); };
+
+        var message_port;
+
+        if (is_service_worker(worker)) {
+            // The ServiceWorker's implicit MessagePort is currently not
+            // reliably accessible from the ServiceWorkerGlobalScope due to
+            // Blink setting MessageEvent.source to null for messages sent via
+            // ServiceWorker.postMessage(). Until that's resolved, create an
+            // explicit MessageChannel and pass one end to the worker.
+            var message_channel = new MessageChannel();
+            message_port = message_channel.port1;
+            message_port.start();
+            worker.postMessage({type: "connect"}, [message_channel.port2]);
+        } else if (is_shared_worker(worker)) {
+            message_port = worker.port;
+        } else {
+            message_port = worker;
+        }
+
+        // Keeping a reference to the worker until worker_done() is seen
+        // prevents the Worker object and its MessageChannel from going away
+        // before all the messages are dispatched.
+        this.worker = worker;
+
+        message_port.onmessage =
+            function(message) {
+                if (this_obj.running && (message.data.type in this_obj.message_handlers)) {
+                    this_obj.message_handlers[message.data.type].call(this_obj, message.data);
+                }
+            };
+    }
+
+    RemoteWorker.prototype.worker_error = function(error) {
+        var message = error.message || String(error);
+        var filename = (error.filename ? " " + error.filename: "");
+        // FIXME: Display worker error states separately from main document
+        // error state.
+        this.worker_done({
+            status: {
+                status: tests.status.ERROR,
+                message: "Error in worker" + filename + ": " + message
+            }
+        });
+        error.preventDefault();
+    };
+
+    RemoteWorker.prototype.test_state = function(data) {
+        var remote_test = this.tests[data.test.index];
+        if (!remote_test) {
+            remote_test = new RemoteTest(data.test);
+            this.tests[data.test.index] = remote_test;
+        }
+        remote_test.update_state_from(data.test);
+        tests.notify_test_state(remote_test);
+    };
+
+    RemoteWorker.prototype.test_done = function(data) {
+        var remote_test = this.tests[data.test.index];
+        remote_test.update_state_from(data.test);
+        remote_test.done();
+        tests.result(remote_test);
+    };
+
+    RemoteWorker.prototype.worker_done = function(data) {
+        if (tests.status.status === null &&
+            data.status.status !== data.status.OK) {
+            tests.status.status = data.status.status;
+            tests.status.message = data.status.message;
+        }
+        this.running = false;
+        this.worker = null;
+        if (tests.all_done()) {
+            tests.complete();
+        }
+    };
+
+    RemoteWorker.prototype.message_handlers = {
+        test_state: RemoteWorker.prototype.test_state,
+        result: RemoteWorker.prototype.test_done,
+        complete: RemoteWorker.prototype.worker_done
+    };
 
     /*
      * Harness
@@ -1305,8 +1449,7 @@ policies and contribution forms [3].
 
     TestsStatus.prototype.structured_clone = function()
     {
-        if(!this._structured_clone)
-        {
+        if (!this._structured_clone) {
             var msg = this.message;
             msg = msg ? String(msg) : msg;
             this._structured_clone = merge({
@@ -1333,114 +1476,93 @@ policies and contribution forms [3].
 
         this.properties = {};
 
-        //All tests can't be done until the load event fires
-        this.all_loaded = false;
         this.wait_for_finish = false;
         this.processing_callbacks = false;
 
         this.allow_uncaught_exception = false;
 
+        this.file_is_test = false;
+
         this.timeout_multiplier = 1;
-        this.timeout_length = this.get_timeout();
+        this.timeout_length = test_environment.test_timeout();
         this.timeout_id = null;
 
         this.start_callbacks = [];
+        this.test_state_callbacks = [];
         this.test_done_callbacks = [];
         this.all_done_callbacks = [];
 
+        this.pending_workers = [];
+
         this.status = new TestsStatus();
 
         var this_obj = this;
 
-        on_event(window, "load",
-                 function()
-                 {
-                     this_obj.all_loaded = true;
-                     if (this_obj.all_done())
-                     {
-                         this_obj.complete();
-                     }
-                 });
+        test_environment.add_on_loaded_callback(function() {
+            if (this_obj.all_done()) {
+                this_obj.complete();
+            }
+        });
 
         this.set_timeout();
     }
 
     Tests.prototype.setup = function(func, properties)
     {
-        if (this.phase >= this.phases.HAVE_RESULTS)
-        {
+        if (this.phase >= this.phases.HAVE_RESULTS) {
             return;
         }
-        if (this.phase < this.phases.SETUP)
-        {
+
+        if (this.phase < this.phases.SETUP) {
             this.phase = this.phases.SETUP;
         }
 
         this.properties = properties;
 
-        for (var p in properties)
-        {
-            if (properties.hasOwnProperty(p))
-            {
-                var value = properties[p]
+        for (var p in properties) {
+            if (properties.hasOwnProperty(p)) {
+                var value = properties[p];
                 if (p == "allow_uncaught_exception") {
                     this.allow_uncaught_exception = value;
-                }
-                else if (p == "explicit_done" && value)
-                {
+                } else if (p == "explicit_done" && value) {
                     this.wait_for_finish = true;
-                }
-                else if (p == "explicit_timeout" && value) {
+                } else if (p == "explicit_timeout" && value) {
                     this.timeout_length = null;
                     if (this.timeout_id)
                     {
                         clearTimeout(this.timeout_id);
                     }
-                }
-                else if (p == "timeout_multiplier")
-                {
+                } else if (p == "timeout_multiplier") {
                     this.timeout_multiplier = value;
                 }
             }
         }
 
-        if (func)
-        {
-            try
-            {
+        if (func) {
+            try {
                 func();
-            } catch(e)
-            {
+            } catch (e) {
                 this.status.status = this.status.ERROR;
-                this.status.message = e;
-            };
+                this.status.message = String(e);
+            }
         }
         this.set_timeout();
     };
 
-    Tests.prototype.get_timeout = function()
-    {
-        var metas = document.getElementsByTagName("meta");
-        for (var i=0; i 0) {
+            throw new Error("Tried to set file as test after creating a test");
         }
-        return settings.harness_timeout.normal;
-    }
+        this.wait_for_finish = true;
+        this.file_is_test = true;
+        // Create the test, which will add it to the list of tests
+        async_test();
+    };
 
-    Tests.prototype.set_timeout = function()
-    {
+    Tests.prototype.set_timeout = function() {
         var this_obj = this;
         clearTimeout(this.timeout_id);
-        if (this.timeout_length !== null)
-        {
+        if (this.timeout_length !== null) {
             this.timeout_id = setTimeout(function() {
                                              this_obj.timeout();
                                          }, this.timeout_length);
@@ -1448,7 +1570,9 @@ policies and contribution forms [3].
     };
 
     Tests.prototype.timeout = function() {
-        this.status.status = this.status.TIMEOUT;
+        if (this.status.status === null) {
+            this.status.status = this.status.TIMEOUT;
+        }
         this.complete();
     };
 
@@ -1466,12 +1590,23 @@ policies and contribution forms [3].
             this.start();
         }
         this.num_pending++;
-        this.tests.push(test);
+        test.index = this.tests.push(test);
+        this.notify_test_state(test);
+    };
+
+    Tests.prototype.notify_test_state = function(test) {
+        var this_obj = this;
+        forEach(this.test_state_callbacks,
+                function(callback) {
+                    callback(test, this_obj);
+                });
     };
 
     Tests.prototype.all_done = function() {
-        return (this.all_loaded && this.num_pending === 0 &&
-                !this.wait_for_finish && !this.processing_callbacks);
+        return (this.tests.length > 0 && test_environment.all_loaded &&
+                this.num_pending === 0 && !this.wait_for_finish &&
+                !this.processing_callbacks &&
+                !this.pending_workers.some(function(w) { return w.running; }));
     };
 
     Tests.prototype.start = function() {
@@ -1486,37 +1621,11 @@ policies and contribution forms [3].
                  {
                      callback(this_obj.properties);
                  });
-        forEach_windows(
-                function(w, is_same_origin)
-                {
-                    if(is_same_origin && w.start_callback)
-                    {
-                        try
-                        {
-                            w.start_callback(this_obj.properties);
-                        }
-                        catch(e)
-                        {
-                            if (debug)
-                            {
-                                throw(e);
-                            }
-                        }
-                    }
-                    if (supports_post_message(w) && w !== self)
-                    {
-                        w.postMessage({
-                            type: "start",
-                            properties: this_obj.properties
-                        }, "*");
-                    }
-                });
     };
 
     Tests.prototype.result = function(test)
     {
-        if (this.phase > this.phases.HAVE_RESULTS)
-        {
+        if (this.phase > this.phases.HAVE_RESULTS) {
             return;
         }
         this.phase = this.phases.HAVE_RESULTS;
@@ -1532,34 +1641,8 @@ policies and contribution forms [3].
                 {
                     callback(test, this_obj);
                 });
-
-        forEach_windows(
-                function(w, is_same_origin)
-                {
-                    if(is_same_origin && w.result_callback)
-                    {
-                        try
-                        {
-                            w.result_callback(test);
-                        }
-                        catch(e)
-                        {
-                            if(debug) {
-                                throw e;
-                            }
-                        }
-                    }
-                    if (supports_post_message(w) && w !== self)
-                    {
-                        w.postMessage({
-                            type: "result",
-                            test: test.structured_clone()
-                        }, "*");
-                    }
-                });
         this.processing_callbacks = false;
-        if (this_obj.all_done())
-        {
+        if (this_obj.all_done()) {
             this_obj.complete();
         }
     };
@@ -1573,26 +1656,19 @@ policies and contribution forms [3].
         this.tests.forEach(
             function(x)
             {
-                if(x.status === x.NOTRUN)
-                {
+                if (x.phase < x.phases.COMPLETE) {
                     this_obj.notify_result(x);
+                    x.cleanup();
+                    x.phase = x.phases.COMPLETE;
                 }
             }
         );
         this.notify_complete();
     };
 
-    Tests.prototype.notify_complete = function()
-    {
-        clearTimeout(this.timeout_id);
+    Tests.prototype.notify_complete = function() {
         var this_obj = this;
-        var tests = map(this_obj.tests,
-                        function(test)
-                        {
-                            return test.structured_clone();
-                        });
-        if (this.status.status === null)
-        {
+        if (this.status.status === null) {
             this.status.status = this.status.OK;
         }
 
@@ -1601,49 +1677,23 @@ policies and contribution forms [3].
                  {
                      callback(this_obj.tests, this_obj.status);
                  });
-
-        forEach_windows(
-                function(w, is_same_origin)
-                {
-                    if(is_same_origin && w.completion_callback)
-                    {
-                        try
-                        {
-                            w.completion_callback(this_obj.tests, this_obj.status);
-                        }
-                        catch(e)
-                        {
-                            if (debug)
-                            {
-                                throw e;
-                            }
-                        }
-                    }
-                    if (supports_post_message(w) && w !== self)
-                    {
-                        w.postMessage({
-                            type: "complete",
-                            tests: tests,
-                            status: this_obj.status.structured_clone()
-                        }, "*");
-                    }
-                });
     };
 
-    var tests = new Tests();
-
-    window.onerror = function(msg) {
-        if (!tests.allow_uncaught_exception)
-        {
-            tests.status.status = tests.status.ERROR;
-            tests.status.message = msg;
-            tests.complete();
+    Tests.prototype.fetch_tests_from_worker = function(worker) {
+        if (this.phase >= this.phases.COMPLETE) {
+            return;
         }
+
+        this.pending_workers.push(new RemoteWorker(worker));
+    };
+
+    function fetch_tests_from_worker(port) {
+        tests.fetch_tests_from_worker(port);
     }
+    expose(fetch_tests_from_worker, 'fetch_tests_from_worker');
 
     function timeout() {
-        if (tests.timeout_length === null)
-        {
+        if (tests.timeout_length === null) {
             tests.timeout();
         }
     }
@@ -1653,6 +1703,10 @@ policies and contribution forms [3].
         tests.start_callbacks.push(callback);
     }
 
+    function add_test_state_callback(callback) {
+        tests.test_state_callbacks.push(callback);
+    }
+
     function add_result_callback(callback)
     {
         tests.test_done_callbacks.push(callback);
@@ -1664,6 +1718,7 @@ policies and contribution forms [3].
     }
 
     expose(add_start_callback, 'add_start_callback');
+    expose(add_test_state_callback, 'add_test_state_callback');
     expose(add_result_callback, 'add_result_callback');
     expose(add_completion_callback, 'add_completion_callback');
 
@@ -1672,11 +1727,10 @@ policies and contribution forms [3].
     */
 
     function Output() {
-      this.output_document = document;
-      this.output_node = null;
-      this.done_count = 0;
-      this.enabled = settings.output;
-      this.phase = this.INITIAL;
+        this.output_document = document;
+        this.output_node = null;
+        this.enabled = settings.output;
+        this.phase = this.INITIAL;
     }
 
     Output.prototype.INITIAL = 0;
@@ -1695,8 +1749,7 @@ policies and contribution forms [3].
                                         properties.output : settings.output);
     };
 
-    Output.prototype.init = function(properties)
-    {
+    Output.prototype.init = function(properties) {
         if (this.phase >= this.STARTED) {
             return;
         }
@@ -1708,63 +1761,57 @@ policies and contribution forms [3].
         this.phase = this.STARTED;
     };
 
-    Output.prototype.resolve_log = function()
-    {
+    Output.prototype.resolve_log = function() {
         var output_document;
-        if (typeof this.output_document === "function")
-        {
+        if (typeof this.output_document === "function") {
             output_document = this.output_document.apply(undefined);
-        } else 
-        {
+        } else {
             output_document = this.output_document;
         }
-        if (!output_document)
-        {
+        if (!output_document) {
             return;
         }
         var node = output_document.getElementById("log");
-        if (node)
-        {
-            this.output_document = output_document;
-            this.output_node = node;
+        if (!node) {
+            if (!document.body || document.readyState == "loading") {
+                return;
+            }
+            node = output_document.createElement("div");
+            node.id = "log";
+            output_document.body.appendChild(node);
         }
+        this.output_document = output_document;
+        this.output_node = node;
     };
 
-    Output.prototype.show_status = function(test)
-    {
-        if (this.phase < this.STARTED)
-        {
+    Output.prototype.show_status = function() {
+        if (this.phase < this.STARTED) {
             this.init();
         }
-        if (!this.enabled)
-        {
+        if (!this.enabled) {
             return;
         }
-        if (this.phase < this.HAVE_RESULTS)
-        {
+        if (this.phase < this.HAVE_RESULTS) {
             this.resolve_log();
             this.phase = this.HAVE_RESULTS;
         }
-        this.done_count++;
-        if (this.output_node)
-        {
-            if (this.done_count < 100
-            || (this.done_count < 1000 && this.done_count % 100 == 0)
-            || this.done_count % 1000 == 0) {
-                this.output_node.textContent = "Running, "
-                    + this.done_count + " complete, "
-                    + tests.num_pending + " remain";
+        var done_count = tests.tests.length - tests.num_pending;
+        if (this.output_node) {
+            if (done_count < 100 ||
+                (done_count < 1000 && done_count % 100 === 0) ||
+                done_count % 1000 === 0) {
+                this.output_node.textContent = "Running, " +
+                    done_count + " complete, " +
+                    tests.num_pending + " remain";
             }
         }
     };
 
-    Output.prototype.show_results = function (tests, harness_status)
-    {
+    Output.prototype.show_results = function (tests, harness_status) {
         if (this.phase >= this.COMPLETE) {
             return;
         }
-        if (!this.enabled)
-        {
+        if (!this.enabled) {
             return;
         }
         if (!this.output_node) {
@@ -1773,18 +1820,34 @@ policies and contribution forms [3].
         this.phase = this.COMPLETE;
 
         var log = this.output_node;
-        if (!log)
-        {
+        if (!log) {
             return;
         }
         var output_document = this.output_document;
 
-        while (log.lastChild)
-        {
+        while (log.lastChild) {
             log.removeChild(log.lastChild);
         }
 
-        if (script_prefix != null) {
+        var script_prefix = null;
+        var scripts = document.getElementsByTagName("script");
+        for (var i = 0; i < scripts.length; i++) {
+            var src;
+            if (scripts[i].src) {
+                src = scripts[i].src;
+            } else if (scripts[i].href) {
+                //SVG case
+                src = scripts[i].href.baseVal;
+            }
+
+            var matches = src && src.match(/^(.*\/|)testharness\.js$/);
+            if (matches) {
+                script_prefix = matches[1];
+                break;
+            }
+        }
+
+        if (script_prefix !== null) {
             var stylesheet = output_document.createElementNS(xhtml_ns, "link");
             stylesheet.setAttribute("rel", "stylesheet");
             stylesheet.setAttribute("href", script_prefix + "testharness.css");
@@ -1806,10 +1869,10 @@ policies and contribution forms [3].
         status_text[Test.prototype.NOTRUN] = "Not Run";
 
         var status_number = {};
-        forEach(tests, function(test) {
+        forEach(tests,
+                function(test) {
                     var status = status_text[test.status];
-                    if (status_number.hasOwnProperty(status))
-                    {
+                    if (status_number.hasOwnProperty(status)) {
                         status_number[status] += 1;
                     } else {
                         status_number[status] = 1;
@@ -1823,38 +1886,28 @@ policies and contribution forms [3].
 
         var summary_template = ["section", {"id":"summary"},
                                 ["h2", {}, "Summary"],
-                                function(vars)
+                                function()
                                 {
-                                    if (harness_status.status === harness_status.OK)
-                                    {
-                                        return null;
-                                    }
-                                    else
-                                    {
-                                        var status = status_text_harness[harness_status.status];
-                                        var rv = [["p", {"class":status_class(status)}]];
 
-                                        if (harness_status.status === harness_status.ERROR)
-                                        {
-                                            rv[0].push("Harness encountered an error:");
-                                            rv.push(["pre", {}, harness_status.message]);
-                                        }
-                                        else if (harness_status.status === harness_status.TIMEOUT)
-                                        {
-                                            rv[0].push("Harness timed out.");
-                                        }
-                                        else
-                                        {
-                                            rv[0].push("Harness got an unexpected status.");
-                                        }
+                                    var status = status_text_harness[harness_status.status];
+                                    var rv = [["section", {},
+                                               ["p", {},
+                                                "Harness status: ",
+                                                ["span", {"class":status_class(status)},
+                                                 status
+                                                ],
+                                               ]
+                                              ]];
 
-                                        return rv;
+                                    if (harness_status.status === harness_status.ERROR) {
+                                        rv[0].push(["pre", {}, harness_status.message]);
                                     }
+                                    return rv;
                                 },
                                 ["p", {}, "Found ${num_tests} tests"],
-                                function(vars) {
+                                function() {
                                     var rv = [["div", {}]];
-                                    var i=0;
+                                    var i = 0;
                                     while (status_text.hasOwnProperty(i)) {
                                         if (status_number.hasOwnProperty(status_text[i])) {
                                             var status = status_text[i];
@@ -1866,7 +1919,8 @@ policies and contribution forms [3].
                                         i++;
                                     }
                                     return rv;
-                                }];
+                                },
+                               ];
 
         log.appendChild(render(summary_template, {num_tests:tests.length}, output_document));
 
@@ -1876,8 +1930,7 @@ policies and contribution forms [3].
                     on_event(element, "click",
                              function(e)
                              {
-                                 if (output_document.getElementById("results") === null)
-                                 {
+                                 if (output_document.getElementById("results") === null) {
                                      e.preventDefault();
                                      return;
                                  }
@@ -1930,22 +1983,22 @@ policies and contribution forms [3].
 
         log.appendChild(document.createElementNS(xhtml_ns, "section"));
         var assertions = has_assertions();
-        var html = "

Details

" - + "" - + (assertions ? "" : "") - + "" - + ""; + var html = "

Details

ResultTest NameAssertionMessage
" + + "" + + (assertions ? "" : "") + + "" + + ""; for (var i = 0; i < tests.length; i++) { - html += '"; + html += '"; } html += "
ResultTest NameAssertionMessage
' - + escape_html(status_text[tests[i].status]) - + "" - + escape_html(tests[i].name) - + "" - + (assertions ? escape_html(get_assertion(tests[i])) + "" : "") - + escape_html(tests[i].message ? tests[i].message : " ") - + "
' + + escape_html(status_text[tests[i].status]) + + "" + + escape_html(tests[i].name) + + "" + + (assertions ? escape_html(get_assertion(tests[i])) + "" : "") + + escape_html(tests[i].message ? tests[i].message : " ") + + "
"; try { @@ -1958,11 +2011,6 @@ policies and contribution forms [3]. } }; - var output = new Output(); - add_start_callback(function (properties) {output.init(properties);}); - add_result_callback(function (test) {output.show_status(tests);}); - add_completion_callback(function (tests, harness_status) {output.show_results(tests, harness_status);}); - /* * Template code * @@ -2005,41 +2053,64 @@ policies and contribution forms [3]. { if (typeof template === "function") { var replacement = template(substitutions); - if (replacement) - { - var rv = substitute(replacement, substitutions); - return rv; - } - else - { + if (!replacement) { return null; } + + return substitute(replacement, substitutions); } - else if (is_single_node(template)) - { + + if (is_single_node(template)) { return substitute_single(template, substitutions); } - else - { - return filter(map(template, function(x) { - return substitute(x, substitutions); - }), function(x) {return x !== null;}); - } + + return filter(map(template, function(x) { + return substitute(x, substitutions); + }), function(x) {return x !== null;}); } function substitute_single(template, substitutions) { - var substitution_re = /\${([^ }]*)}/g; + var substitution_re = /\$\{([^ }]*)\}/g; function do_substitution(input) { var components = input.split(substitution_re); var rv = []; - for (var i=0; i= test.phases.HAS_RESULT) { + return; + } + var message = e.message; + test.set_status(test.FAIL, message); + test.phase = test.phases.HAS_RESULT; + test.done(); + done(); + } else if (!tests.allow_uncaught_exception) { + tests.status.status = tests.status.ERROR; + tests.status.message = e.message; + } + }); + + test_environment.on_tests_ready(); + })(); // vim: set expandtab shiftwidth=4 tabstop=4: