`_. If a
- * number is passed it should be one of the numeric code values in
- * that table (e.g. 3, 4, etc). If a string is passed it can
- * either be an exception name (e.g. "HierarchyRequestError",
- * "WrongDocumentError") or the name of the corresponding error
- * code (e.g. "``HIERARCHY_REQUEST_ERR``", "``WRONG_DOCUMENT_ERR``").
- * @param {Function} descriptionOrFunc - The function expected to
- * throw (if the exception comes from another global), or the
- * optional description of the condition being tested (if the
- * exception comes from the current global).
- * @param {string} [description] - Description of the condition
- * being tested (if the exception comes from another global).
- *
- */
- function assert_throws_dom(type, funcOrConstructor, descriptionOrFunc, maybeDescription)
- {
- let constructor, func, description;
- if (funcOrConstructor.name === "DOMException") {
- constructor = funcOrConstructor;
- func = descriptionOrFunc;
- description = maybeDescription;
- } else {
- constructor = self.DOMException;
- func = funcOrConstructor;
- description = descriptionOrFunc;
- assert(maybeDescription === undefined,
- "Too many args pased to no-constructor version of assert_throws_dom");
- }
- assert_throws_dom_impl(type, func, description, "assert_throws_dom", constructor)
- }
- expose_assert(assert_throws_dom, "assert_throws_dom");
-
- /**
- * Similar to assert_throws_dom but allows specifying the assertion type
- * (assert_throws_dom or promise_rejects_dom, in practice). The
- * "constructor" argument must be the DOMException constructor from the
- * global we expect the exception to come from.
- */
- function assert_throws_dom_impl(type, func, description, assertion_type, constructor)
- {
- try {
- func.call(this);
- assert(false, assertion_type, description,
- "${func} did not throw", {func:func});
- } catch (e) {
- if (e instanceof AssertionError) {
- throw e;
- }
-
- // Basic sanity-checks on the thrown exception.
- assert(typeof e === "object",
- assertion_type, description,
- "${func} threw ${e} with type ${type}, not an object",
- {func:func, e:e, type:typeof e});
-
- assert(e !== null,
- assertion_type, description,
- "${func} threw null, not an object",
- {func:func});
-
- // Sanity-check our type
- assert(typeof type == "number" ||
- typeof type == "string",
- assertion_type, description,
- "${type} is not a number or string",
- {type:type});
-
- var codename_name_map = {
- INDEX_SIZE_ERR: 'IndexSizeError',
- HIERARCHY_REQUEST_ERR: 'HierarchyRequestError',
- WRONG_DOCUMENT_ERR: 'WrongDocumentError',
- INVALID_CHARACTER_ERR: 'InvalidCharacterError',
- NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',
- NOT_FOUND_ERR: 'NotFoundError',
- NOT_SUPPORTED_ERR: 'NotSupportedError',
- INUSE_ATTRIBUTE_ERR: 'InUseAttributeError',
- INVALID_STATE_ERR: 'InvalidStateError',
- SYNTAX_ERR: 'SyntaxError',
- INVALID_MODIFICATION_ERR: 'InvalidModificationError',
- NAMESPACE_ERR: 'NamespaceError',
- INVALID_ACCESS_ERR: 'InvalidAccessError',
- TYPE_MISMATCH_ERR: 'TypeMismatchError',
- SECURITY_ERR: 'SecurityError',
- NETWORK_ERR: 'NetworkError',
- ABORT_ERR: 'AbortError',
- URL_MISMATCH_ERR: 'URLMismatchError',
- QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
- TIMEOUT_ERR: 'TimeoutError',
- INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError',
- DATA_CLONE_ERR: 'DataCloneError'
- };
-
- var name_code_map = {
- IndexSizeError: 1,
- HierarchyRequestError: 3,
- WrongDocumentError: 4,
- InvalidCharacterError: 5,
- NoModificationAllowedError: 7,
- NotFoundError: 8,
- NotSupportedError: 9,
- InUseAttributeError: 10,
- InvalidStateError: 11,
- SyntaxError: 12,
- InvalidModificationError: 13,
- NamespaceError: 14,
- InvalidAccessError: 15,
- TypeMismatchError: 17,
- SecurityError: 18,
- NetworkError: 19,
- AbortError: 20,
- URLMismatchError: 21,
- QuotaExceededError: 22,
- TimeoutError: 23,
- InvalidNodeTypeError: 24,
- DataCloneError: 25,
-
- EncodingError: 0,
- NotReadableError: 0,
- UnknownError: 0,
- ConstraintError: 0,
- DataError: 0,
- TransactionInactiveError: 0,
- ReadOnlyError: 0,
- VersionError: 0,
- OperationError: 0,
- NotAllowedError: 0
- };
-
- var code_name_map = {};
- for (var key in name_code_map) {
- if (name_code_map[key] > 0) {
- code_name_map[name_code_map[key]] = key;
- }
- }
-
- var required_props = {};
- var name;
-
- if (typeof type === "number") {
- if (type === 0) {
- throw new AssertionError('Test bug: ambiguous DOMException code 0 passed to assert_throws_dom()');
- } else if (!(type in code_name_map)) {
- throw new AssertionError('Test bug: unrecognized DOMException code "' + type + '" passed to assert_throws_dom()');
- }
- name = code_name_map[type];
- required_props.code = type;
- } else if (typeof type === "string") {
- name = type in codename_name_map ? codename_name_map[type] : type;
- if (!(name in name_code_map)) {
- throw new AssertionError('Test bug: unrecognized DOMException code name or name "' + type + '" passed to assert_throws_dom()');
- }
-
- required_props.code = name_code_map[name];
- }
-
- 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;
- }
-
- for (var prop in required_props) {
- assert(prop in e && e[prop] == required_props[prop],
- assertion_type, description,
- "${func} threw ${e} that is not a DOMException " + type + ": property ${prop} is equal to ${actual}, expected ${expected}",
- {func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]});
- }
-
- // Check that the exception is from the right global. This check is last
- // so more specific, and more informative, checks on the properties can
- // happen in case a totally incorrect exception is thrown.
- assert(e.constructor === constructor,
- assertion_type, description,
- "${func} threw an exception from the wrong global",
- {func});
-
- }
- }
-
- /**
- * Assert the provided value is thrown.
- *
- * @param {value} exception The expected exception.
- * @param {Function} func Function which should throw.
- * @param {string} [description] Error description for the case that the error is not thrown.
- */
- function assert_throws_exactly(exception, func, description)
- {
- assert_throws_exactly_impl(exception, func, description,
- "assert_throws_exactly");
- }
- expose_assert(assert_throws_exactly, "assert_throws_exactly");
-
- /**
- * Like assert_throws_exactly but allows specifying the assertion type
- * (assert_throws_exactly or promise_rejects_exactly, in practice).
- */
- function assert_throws_exactly_impl(exception, func, description,
- assertion_type)
- {
- try {
- func.call(this);
- assert(false, assertion_type, description,
- "${func} did not throw", {func:func});
- } catch (e) {
- if (e instanceof AssertionError) {
- throw e;
- }
-
- assert(same_value(e, exception), assertion_type, description,
- "${func} threw ${e} but we expected it to throw ${exception}",
- {func:func, e:e, exception:exception});
- }
- }
-
- /**
- * Asserts if called. Used to ensure that a specific codepath is
- * not taken e.g. that an error event isn't fired.
- *
- * @param {string} [description] - Description of the condition being tested.
- */
- function assert_unreached(description) {
- assert(false, "assert_unreached", description,
- "Reached unreachable code");
- }
- expose_assert(assert_unreached, "assert_unreached");
-
- /**
- * @callback AssertFunc
- * @param {Any} actual
- * @param {Any} expected
- * @param {Any[]} args
- */
-
- /**
- * Asserts that ``actual`` matches at least one value of ``expected``
- * according to a comparison defined by ``assert_func``.
- *
- * 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.
- *
- * @param {AssertFunc} assert_func - Function to compare actual
- * and expected. It must throw when the comparison fails and
- * return when the comparison passes.
- * @param {Any} actual - Test value.
- * @param {Array} expected_array - Array of possible expected values.
- * @param {Any[]} args - Additional arguments to pass to ``assert_func``.
- */
- function assert_any(assert_func, actual, expected_array, ...args)
- {
- var errors = [];
- var passed = false;
- forEach(expected_array,
- function(expected)
- {
- try {
- assert_func.apply(this, [actual, expected].concat(args));
- passed = true;
- } catch (e) {
- errors.push(e.message);
- }
- });
- if (!passed) {
- throw new AssertionError(errors.join("\n\n"));
- }
- }
- // FIXME: assert_any cannot use expose_assert, because assert_wrapper does
- // not support nested assert calls (e.g. to assert_func). We need to
- // support bypassing assert_wrapper for the inner asserts here.
- expose(assert_any, "assert_any");
-
- /**
- * Assert that a feature is implemented, based on a 'truthy' condition.
- *
- * This function should be used to early-exit from tests in which there is
- * no point continuing without support for a non-optional spec or spec
- * feature. For example:
- *
- * assert_implements(window.Foo, 'Foo is not supported');
- *
- * @param {object} condition The truthy value to test
- * @param {string} [description] Error description for the case that the condition is not truthy.
- */
- function assert_implements(condition, description) {
- assert(!!condition, "assert_implements", description);
- }
- expose_assert(assert_implements, "assert_implements")
-
- /**
- * Assert that an optional feature is implemented, based on a 'truthy' condition.
- *
- * This function should be used to early-exit from tests in which there is
- * no point continuing without support for an explicitly optional spec or
- * spec feature. For example:
- *
- * assert_implements_optional(video.canPlayType("video/webm"),
- * "webm video playback not supported");
- *
- * @param {object} condition The truthy value to test
- * @param {string} [description] Error description for the case that the condition is not truthy.
- */
- function assert_implements_optional(condition, description) {
- if (!condition) {
- throw new OptionalFeatureUnsupportedError(description);
- }
- }
- expose_assert(assert_implements_optional, "assert_implements_optional");
-
- /**
- * @class
- *
- * A single subtest. A Test is not constructed directly but via the
- * :js:func:`test`, :js:func:`async_test` or :js:func:`promise_test` functions.
- *
- * @param {string} name - This must be unique in a given file and must be
- * invariant between runs.
- *
- */
- function Test(name, properties)
- {
- if (tests.file_is_test && tests.tests.length) {
- throw new Error("Tried to create a test with file_is_test");
- }
- /** The test name. */
- this.name = name;
-
- this.phase = (tests.is_aborted || tests.phase === tests.phases.COMPLETE) ?
- this.phases.COMPLETE : this.phases.INITIAL;
-
- /** The test status code.*/
- this.status = this.NOTRUN;
- this.timeout_id = null;
- this.index = null;
-
- this.properties = properties || {};
- this.timeout_length = settings.test_timeout;
- if (this.timeout_length !== null) {
- this.timeout_length *= tests.timeout_multiplier;
- }
-
- /** A message indicating the reason for test failure. */
- this.message = null;
- /** Stack trace in case of failure. */
- this.stack = null;
-
- this.steps = [];
- this._is_promise_test = false;
-
- this.cleanup_callbacks = [];
- this._user_defined_cleanup_count = 0;
- this._done_callbacks = [];
-
- // Tests declared following harness completion are likely an indication
- // of a programming error, but they cannot be reported
- // deterministically.
- if (tests.phase === tests.phases.COMPLETE) {
- return;
- }
-
- tests.push(this);
- }
-
- /**
- * Enum of possible test statuses.
- *
- * :values:
- * - ``PASS``
- * - ``FAIL``
- * - ``TIMEOUT``
- * - ``NOTRUN``
- * - ``PRECONDITION_FAILED``
- */
- Test.statuses = {
- PASS:0,
- FAIL:1,
- TIMEOUT:2,
- NOTRUN:3,
- PRECONDITION_FAILED:4
- };
-
- Test.prototype = merge({}, Test.statuses);
-
- Test.prototype.phases = {
- INITIAL:0,
- STARTED:1,
- HAS_RESULT:2,
- CLEANING:3,
- COMPLETE:4
- };
-
- Test.prototype.status_formats = {
- 0: "Pass",
- 1: "Fail",
- 2: "Timeout",
- 3: "Not Run",
- 4: "Optional Feature Unsupported",
- }
-
- Test.prototype.format_status = function() {
- return this.status_formats[this.status];
- }
-
- Test.prototype.structured_clone = function()
- {
- if (!this._structured_clone) {
- var msg = this.message;
- msg = msg ? String(msg) : msg;
- this._structured_clone = merge({
- name:String(this.name),
- properties:merge({}, this.properties),
- phases:merge({}, this.phases)
- }, Test.statuses);
- }
- this._structured_clone.status = this.status;
- this._structured_clone.message = this.message;
- this._structured_clone.stack = this.stack;
- this._structured_clone.index = this.index;
- this._structured_clone.phase = this.phase;
- return this._structured_clone;
- };
-
- /**
- * Run a single step of an ongoing test.
- *
- * @param {string} func - Callback function to run as a step. If
- * this throws an :js:func:`AssertionError`, or any other
- * exception, the :js:class:`Test` status is set to ``FAIL``.
- * @param {Object} [this_obj] - The object to use as the this
- * value when calling ``func``. Defaults to the :js:class:`Test` object.
- */
- Test.prototype.step = function(func, this_obj)
- {
- if (this.phase > this.phases.STARTED) {
- return;
- }
-
- if (settings.debug && this.phase !== this.phases.STARTED) {
- console.log("TEST START", this.name);
- }
- this.phase = this.phases.STARTED;
- //If we don't get a result before the harness times out that will be a test timeout
- this.set_status(this.TIMEOUT, "Test timed out");
-
- tests.started = true;
- tests.current_test = this;
- tests.notify_test_state(this);
-
- if (this.timeout_id === null) {
- this.set_timeout();
- }
-
- this.steps.push(func);
-
- if (arguments.length === 1) {
- this_obj = this;
- }
-
- if (settings.debug) {
- console.debug("TEST STEP", this.name);
- }
-
- try {
- return func.apply(this_obj, Array.prototype.slice.call(arguments, 2));
- } catch (e) {
- if (this.phase >= this.phases.HAS_RESULT) {
- return;
- }
- var status = e instanceof OptionalFeatureUnsupportedError ? this.PRECONDITION_FAILED : this.FAIL;
- var message = String((typeof e === "object" && e !== null) ? e.message : e);
- var stack = e.stack ? e.stack : null;
-
- this.set_status(status, message, stack);
- this.phase = this.phases.HAS_RESULT;
- this.done();
- } finally {
- this.current_test = null;
- }
- };
-
- /**
- * Wrap a function so that it runs as a step of the current test.
- *
- * This allows creating a callback function that will run as a
- * test step.
- *
- * @example
- * let t = async_test("Example");
- * onload = t.step_func(e => {
- * assert_equals(e.name, "load");
- * // Mark the test as complete.
- * t.done();
- * })
- *
- * @param {string} func - Function to run as a step. If this
- * throws an :js:func:`AssertionError`, or any other exception,
- * the :js:class:`Test` status is set to ``FAIL``.
- * @param {Object} [this_obj] - The object to use as the this
- * value when calling ``func``. Defaults to the :js:class:`Test` object.
- */
- Test.prototype.step_func = function(func, this_obj)
- {
- var test_this = this;
-
- if (arguments.length === 1) {
- this_obj = test_this;
- }
-
- return function()
- {
- return test_this.step.apply(test_this, [func, this_obj].concat(
- Array.prototype.slice.call(arguments)));
- };
- };
-
- /**
- * Wrap a function so that it runs as a step of the current test,
- * and automatically marks the test as complete if the function
- * returns without error.
- *
- * @param {string} func - Function to run as a step. If this
- * throws an :js:func:`AssertionError`, or any other exception,
- * the :js:class:`Test` status is set to ``FAIL``. If it returns
- * without error the status is set to ``PASS``.
- * @param {Object} [this_obj] - The object to use as the this
- * value when calling `func`. Defaults to the :js:class:`Test` object.
- */
- Test.prototype.step_func_done = function(func, this_obj)
- {
- var test_this = this;
-
- if (arguments.length === 1) {
- this_obj = test_this;
- }
-
- return function()
- {
- if (func) {
- test_this.step.apply(test_this, [func, this_obj].concat(
- Array.prototype.slice.call(arguments)));
- }
- test_this.done();
- };
- };
-
- /**
- * Return a function that automatically sets the current test to
- * ``FAIL`` if it's called.
- *
- * @param {string} [description] - Error message to add to assert
- * in case of failure.
- *
- */
- Test.prototype.unreached_func = function(description)
- {
- return this.step_func(function() {
- assert_unreached(description);
- });
- };
-
- /**
- * Run a function as a step of the test after a given timeout.
- *
- * This multiplies the timeout by the global timeout multiplier to
- * account for the expected execution speed of the current test
- * environment. For example ``test.step_timeout(f, 2000)`` with a
- * timeout multiplier of 2 will wait for 4000ms before calling ``f``.
- *
- * In general it's encouraged to use :js:func:`Test.step_wait` or
- * :js:func:`step_wait_func` in preference to this function where possible,
- * as they provide better test performance.
- *
- * @param {Function} func - Function to run as a test
- * step.
- * @param {number} timeout - Time in ms to wait before running the
- * test step. The actual wait time is ``timeout`` x
- * ``timeout_multiplier``.
- *
- */
- Test.prototype.step_timeout = function(func, timeout) {
- var test_this = this;
- var args = Array.prototype.slice.call(arguments, 2);
- return setTimeout(this.step_func(function() {
- return func.apply(test_this, args);
- }), timeout * tests.timeout_multiplier);
- };
-
- /**
- * Poll for a function to return true, and call a callback
- * function once it does, or assert if a timeout is
- * reached. This is preferred over a simple step_timeout
- * whenever possible since it allows the timeout to be longer
- * to reduce intermittents without compromising test execution
- * speed when the condition is quickly met.
- *
- * @example
- * async_test(t => {
- * const popup = window.open("resources/coop-coep.py?coop=same-origin&coep=&navigate=about:blank");
- * t.add_cleanup(() => popup.close());
- * assert_equals(window, popup.opener);
- *
- * popup.onload = t.step_func(() => {
- * assert_true(popup.location.href.endsWith("&navigate=about:blank"));
- * // Use step_wait_func_done as about:blank cannot message back.
- * t.step_wait_func_done(() => popup.location.href === "about:blank");
- * });
- * }, "Navigating a popup to about:blank");
- *
- * @param {Function} cond A function taking no arguments and
- * returning a boolean. The callback is called
- * when this function returns true.
- * @param {Function} func A function taking no arguments to call once
- * the condition is met.
- * @param {string} [description] Error message to add to assert in case of
- * failure.
- * @param {number} timeout Timeout in ms. This is multiplied by the global
- * timeout_multiplier
- * @param {number} interval Polling interval in ms
- *
- */
- Test.prototype.step_wait_func = function(cond, func, description,
- timeout=3000, interval=100) {
- var timeout_full = timeout * tests.timeout_multiplier;
- var remaining = Math.ceil(timeout_full / interval);
- var test_this = this;
-
- var wait_for_inner = test_this.step_func(() => {
- if (cond()) {
- func();
- } else {
- if(remaining === 0) {
- assert(false, "step_wait_func", description,
- "Timed out waiting on condition");
- }
- remaining--;
- setTimeout(wait_for_inner, interval);
- }
- });
-
- wait_for_inner();
- };
-
- /**
- * Poll for a function to return true, and invoke a callback
- * followed by this.done() once it does, or assert if a timeout
- * is reached. This is preferred over a simple step_timeout
- * whenever possible since it allows the timeout to be longer
- * to reduce intermittents without compromising test execution speed
- * when the condition is quickly met.
- *
- * @param {Function} cond A function taking no arguments and
- * returning a boolean. The callback is called
- * when this function returns true.
- * @param {Function} func A function taking no arguments to call once
- * the condition is met.
- * @param {string} [description] Error message to add to assert in case of
- * failure.
- * @param {number} timeout Timeout in ms. This is multiplied by the global
- * timeout_multiplier
- * @param {number} interval Polling interval in ms
- *
- */
- Test.prototype.step_wait_func_done = function(cond, func, description,
- timeout=3000, interval=100) {
- this.step_wait_func(cond, () => {
- if (func) {
- func();
- }
- this.done();
- }, description, timeout, interval);
- };
-
- /**
- * Poll for a function to return true, and resolve a promise
- * once it does, or assert if a timeout is reached. This is
- * preferred over a simple step_timeout whenever possible
- * since it allows the timeout to be longer to reduce
- * intermittents without compromising test execution speed
- * when the condition is quickly met.
- *
- * @example
- * promise_test(async t => {
- * // …
- * await t.step_wait(() => frame.contentDocument === null, "Frame navigated to a cross-origin document");
- * // …
- * }, "");
- *
- * @param {Function} cond A function taking no arguments and
- * returning a boolean.
- * @param {string} [description] Error message to add to assert in case of
- * failure.
- * @param {number} timeout Timeout in ms. This is multiplied by the global
- * timeout_multiplier
- * @param {number} interval Polling interval in ms
- * @returns {Promise} Promise resolved once cond is met.
- *
- */
- Test.prototype.step_wait = function(cond, description, timeout=3000, interval=100) {
- return new Promise(resolve => {
- this.step_wait_func(cond, resolve, description, timeout, interval);
- });
- }
-
- /*
- * Private method for registering cleanup functions. `testharness.js`
- * internals should use this method instead of the public `add_cleanup`
- * method in order to hide implementation details from the harness status
- * message in the case errors.
- */
- Test.prototype._add_cleanup = function(callback) {
- this.cleanup_callbacks.push(callback);
- };
-
- /**
- * Schedule a function to be run after the test result is known, regardless
- * of passing or failing state.
- *
- * The behavior of this function will not
- * influence the result of the test, but if an exception is thrown, the
- * test harness will report an error.
- *
- * @param {Function} callback - The cleanup function to run. This
- * is called with no arguments.
- */
- Test.prototype.add_cleanup = function(callback) {
- this._user_defined_cleanup_count += 1;
- this._add_cleanup(callback);
- };
-
- Test.prototype.set_timeout = function()
- {
- 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, stack)
- {
- this.status = status;
- this.message = message;
- this.stack = stack ? stack : null;
- };
-
- /**
- * Manually set the test status to ``TIMEOUT``.
- */
- Test.prototype.timeout = function()
- {
- this.timeout_id = null;
- this.set_status(this.TIMEOUT, "Test timed out");
- this.phase = this.phases.HAS_RESULT;
- this.done();
- };
-
- /**
- * Manually set the test status to ``TIMEOUT``.
- *
- * Alias for `Test.timeout <#Test.timeout>`_.
- */
- Test.prototype.force_timeout = function() {
- return this.timeout();
- };
-
- /**
- * Mark the test as complete.
- *
- * This sets the test status to ``PASS`` if no other status was
- * already recorded. Any subsequent attempts to run additional
- * test steps will be ignored.
- *
- * After setting the test status any test cleanup functions will
- * be run.
- */
- Test.prototype.done = function()
- {
- if (this.phase >= this.phases.CLEANING) {
- return;
- }
-
- if (this.phase <= this.phases.STARTED) {
- this.set_status(this.PASS, null);
- }
-
- if (global_scope.clearTimeout) {
- clearTimeout(this.timeout_id);
- }
-
- if (settings.debug) {
- console.log("TEST DONE",
- this.status,
- this.name);
- }
-
- this.cleanup();
- };
-
- function add_test_done_callback(test, callback)
- {
- if (test.phase === test.phases.COMPLETE) {
- callback();
- return;
- }
-
- test._done_callbacks.push(callback);
- }
-
- /*
- * Invoke all specified cleanup functions. If one or more produce an error,
- * the context is in an unpredictable state, so all further testing should
- * be cancelled.
- */
- Test.prototype.cleanup = function() {
- var errors = [];
- var bad_value_count = 0;
- function on_error(e) {
- errors.push(e);
- // Abort tests immediately so that tests declared within subsequent
- // cleanup functions are not run.
- tests.abort();
- }
- var this_obj = this;
- var results = [];
-
- this.phase = this.phases.CLEANING;
-
- forEach(this.cleanup_callbacks,
- function(cleanup_callback) {
- var result;
-
- try {
- result = cleanup_callback();
- } catch (e) {
- on_error(e);
- return;
- }
-
- if (!is_valid_cleanup_result(this_obj, result)) {
- bad_value_count += 1;
- // Abort tests immediately so that tests declared
- // within subsequent cleanup functions are not run.
- tests.abort();
- }
-
- results.push(result);
- });
-
- if (!this._is_promise_test) {
- cleanup_done(this_obj, errors, bad_value_count);
- } else {
- all_async(results,
- function(result, done) {
- if (result && typeof result.then === "function") {
- result
- .then(null, on_error)
- .then(done);
- } else {
- done();
- }
- },
- function() {
- cleanup_done(this_obj, errors, bad_value_count);
- });
- }
- };
-
- /*
- * Determine if the return value of a cleanup function is valid for a given
- * test. Any test may return the value `undefined`. Tests created with
- * `promise_test` may alternatively return "thenable" object values.
- */
- function is_valid_cleanup_result(test, result) {
- if (result === undefined) {
- return true;
- }
-
- if (test._is_promise_test) {
- return result && typeof result.then === "function";
- }
-
- return false;
- }
-
- function cleanup_done(test, errors, bad_value_count) {
- if (errors.length || bad_value_count) {
- var total = test._user_defined_cleanup_count;
-
- tests.status.status = tests.status.ERROR;
- tests.status.stack = null;
- tests.status.message = "Test named '" + test.name +
- "' specified " + total +
- " 'cleanup' function" + (total > 1 ? "s" : "");
-
- if (errors.length) {
- tests.status.message += ", and " + errors.length + " failed";
- tests.status.stack = ((typeof errors[0] === "object" &&
- errors[0].hasOwnProperty("stack")) ?
- errors[0].stack : null);
- }
-
- if (bad_value_count) {
- var type = test._is_promise_test ?
- "non-thenable" : "non-undefined";
- tests.status.message += ", and " + bad_value_count +
- " returned a " + type + " value";
- }
-
- tests.status.message += ".";
- }
-
- test.phase = test.phases.COMPLETE;
- tests.result(test);
- forEach(test._done_callbacks,
- function(callback) {
- callback();
- });
- test._done_callbacks.length = 0;
- }
-
- /**
- * 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);
- this._done_callbacks = [];
- tests.push(this);
- }
-
- RemoteTest.prototype.structured_clone = function() {
- var clone = {};
- Object.keys(this).forEach(
- (function(key) {
- var value = this[key];
- // `RemoteTest` instances are responsible for managing
- // their own "done" callback functions, so those functions
- // are not relevant in other execution contexts. Because of
- // this (and because Function values cannot be serialized
- // for cross-realm transmittance), the property should not
- // be considered when cloning instances.
- if (key === '_done_callbacks' ) {
- return;
- }
-
- if (typeof value === "object" && value !== null) {
- clone[key] = merge({}, value);
- } else {
- clone[key] = value;
- }
- }).bind(this));
- clone.phases = merge({}, this.phases);
- return clone;
- };
-
- /**
- * `RemoteTest` instances are objects which represent tests running in
- * another realm. They do not define "cleanup" functions (if necessary,
- * such functions are defined on the associated `Test` instance within the
- * external realm). However, `RemoteTests` may have "done" callbacks (e.g.
- * as attached by the `Tests` instance responsible for tracking the overall
- * test status in the parent realm). The `cleanup` method delegates to
- * `done` in order to ensure that such callbacks are invoked following the
- * completion of the `RemoteTest`.
- */
- RemoteTest.prototype.cleanup = function() {
- this.done();
- };
- RemoteTest.prototype.phases = Test.prototype.phases;
- RemoteTest.prototype.update_state_from = function(clone) {
- this.status = clone.status;
- this.message = clone.message;
- this.stack = clone.stack;
- if (this.phase === this.phases.INITIAL) {
- this.phase = this.phases.STARTED;
- }
- };
- RemoteTest.prototype.done = function() {
- this.phase = this.phases.COMPLETE;
-
- forEach(this._done_callbacks,
- function(callback) {
- callback();
- });
- }
-
- RemoteTest.prototype.format_status = function() {
- return Test.prototype.status_formats[this.status];
- }
-
- /*
- * A RemoteContext listens for test events from a remote test context, such
- * as another window or a worker. These events are then used to construct
- * and maintain RemoteTest objects that mirror the tests running in the
- * remote context.
- *
- * An optional third parameter can be used as a predicate to filter incoming
- * MessageEvents.
- */
- function RemoteContext(remote, message_target, message_filter) {
- this.running = true;
- this.started = false;
- this.tests = new Array();
- this.early_exception = null;
-
- var this_obj = this;
- // If remote context is cross origin assigning to onerror is not
- // possible, so silently catch those errors.
- try {
- remote.onerror = function(error) { this_obj.remote_error(error); };
- } catch (e) {
- // Ignore.
- }
-
- // Keeping a reference to the remote object and the message handler until
- // remote_done() is seen prevents the remote object and its message channel
- // from going away before all the messages are dispatched.
- this.remote = remote;
- this.message_target = message_target;
- this.message_handler = function(message) {
- var passesFilter = !message_filter || message_filter(message);
- // The reference to the `running` property in the following
- // condition is unnecessary because that value is only set to
- // `false` after the `message_handler` function has been
- // unsubscribed.
- // TODO: Simplify the condition by removing the reference.
- if (this_obj.running && message.data && passesFilter &&
- (message.data.type in this_obj.message_handlers)) {
- this_obj.message_handlers[message.data.type].call(this_obj, message.data);
- }
- };
-
- if (self.Promise) {
- this.done = new Promise(function(resolve) {
- this_obj.doneResolve = resolve;
- });
- }
-
- this.message_target.addEventListener("message", this.message_handler);
- }
-
- RemoteContext.prototype.remote_error = function(error) {
- if (error.preventDefault) {
- error.preventDefault();
- }
-
- // Defer interpretation of errors until the testing protocol has
- // started and the remote test's `allow_uncaught_exception` property
- // is available.
- if (!this.started) {
- this.early_exception = error;
- } else if (!this.allow_uncaught_exception) {
- this.report_uncaught(error);
- }
- };
-
- RemoteContext.prototype.report_uncaught = function(error) {
- var message = error.message || String(error);
- var filename = (error.filename ? " " + error.filename: "");
- // FIXME: Display remote error states separately from main document
- // error state.
- tests.set_status(tests.status.ERROR,
- "Error in remote" + filename + ": " + message,
- error.stack);
- };
-
- RemoteContext.prototype.start = function(data) {
- this.started = true;
- this.allow_uncaught_exception = data.properties.allow_uncaught_exception;
-
- if (this.early_exception && !this.allow_uncaught_exception) {
- this.report_uncaught(this.early_exception);
- }
- };
-
- RemoteContext.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);
- };
-
- RemoteContext.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);
- };
-
- RemoteContext.prototype.remote_done = function(data) {
- if (tests.status.status === null &&
- data.status.status !== data.status.OK) {
- tests.set_status(data.status.status, data.status.message, data.status.stack);
- }
-
- for (let assert of data.asserts) {
- var record = new AssertRecord();
- record.assert_name = assert.assert_name;
- record.args = assert.args;
- record.test = assert.test != null ? this.tests[assert.test.index] : null;
- record.status = assert.status;
- record.stack = assert.stack;
- tests.asserts_run.push(record);
- }
-
- this.message_target.removeEventListener("message", this.message_handler);
- this.running = false;
-
- // If remote context is cross origin assigning to onerror is not
- // possible, so silently catch those errors.
- try {
- this.remote.onerror = null;
- } catch (e) {
- // Ignore.
- }
-
- this.remote = null;
- this.message_target = null;
- if (this.doneResolve) {
- this.doneResolve();
- }
-
- if (tests.all_done()) {
- tests.complete();
- }
- };
-
- RemoteContext.prototype.message_handlers = {
- start: RemoteContext.prototype.start,
- test_state: RemoteContext.prototype.test_state,
- result: RemoteContext.prototype.test_done,
- complete: RemoteContext.prototype.remote_done
- };
-
- /**
- * @class
- * Status of the overall harness
- */
- function TestsStatus()
- {
- /** The status code */
- this.status = null;
- /** Message in case of failure */
- this.message = null;
- /** Stack trace in case of an exception. */
- this.stack = null;
- }
-
- /**
- * Enum of possible harness statuses.
- *
- * :values:
- * - ``OK``
- * - ``ERROR``
- * - ``TIMEOUT``
- * - ``PRECONDITION_FAILED``
- */
- TestsStatus.statuses = {
- OK:0,
- ERROR:1,
- TIMEOUT:2,
- PRECONDITION_FAILED:3
- };
-
- TestsStatus.prototype = merge({}, TestsStatus.statuses);
-
- TestsStatus.prototype.formats = {
- 0: "OK",
- 1: "Error",
- 2: "Timeout",
- 3: "Optional Feature Unsupported"
- };
-
- TestsStatus.prototype.structured_clone = function()
- {
- if (!this._structured_clone) {
- var msg = this.message;
- msg = msg ? String(msg) : msg;
- this._structured_clone = merge({
- status:this.status,
- message:msg,
- stack:this.stack
- }, TestsStatus.statuses);
- }
- return this._structured_clone;
- };
-
- TestsStatus.prototype.format_status = function() {
- return this.formats[this.status];
- };
-
- /**
- * @class
- * Record of an assert that ran.
- *
- * @param {Test} test - The test which ran the assert.
- * @param {string} assert_name - The function name of the assert.
- * @param {Any} args - The arguments passed to the assert function.
- */
- function AssertRecord(test, assert_name, args = []) {
- /** Name of the assert that ran */
- this.assert_name = assert_name;
- /** Test that ran the assert */
- this.test = test;
- // Avoid keeping complex objects alive
- /** Stringification of the arguments that were passed to the assert function */
- this.args = args.map(x => format_value(x).replace(/\n/g, " "));
- /** Status of the assert */
- this.status = null;
- }
-
- AssertRecord.prototype.structured_clone = function() {
- return {
- assert_name: this.assert_name,
- test: this.test ? this.test.structured_clone() : null,
- args: this.args,
- status: this.status,
- };
- };
-
- function Tests()
- {
- this.tests = [];
- this.num_pending = 0;
-
- this.phases = {
- INITIAL:0,
- SETUP:1,
- HAVE_TESTS:2,
- HAVE_RESULTS:3,
- COMPLETE:4
- };
- this.phase = this.phases.INITIAL;
-
- this.properties = {};
-
- this.wait_for_finish = false;
- this.processing_callbacks = false;
-
- this.allow_uncaught_exception = false;
-
- this.file_is_test = false;
- // This value is lazily initialized in order to avoid introducing a
- // dependency on ECMAScript 2015 Promises to all tests.
- this.promise_tests = null;
- this.promise_setup_called = false;
-
- this.timeout_multiplier = 1;
- 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.hide_test_state = false;
- this.pending_remotes = [];
-
- this.current_test = null;
- this.asserts_run = [];
-
- // Track whether output is enabled, and thus whether or not we should
- // track asserts.
- //
- // On workers we don't get properties set from testharnessreport.js, so
- // we don't know whether or not to track asserts. To avoid the
- // resulting performance hit, we assume we are not meant to. This means
- // that assert tracking does not function on workers.
- this.output = settings.output && 'document' in global_scope;
-
- this.status = new TestsStatus();
-
- var this_obj = this;
-
- 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) {
- return;
- }
-
- 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];
- if (p == "allow_uncaught_exception") {
- this.allow_uncaught_exception = value;
- } else if (p == "explicit_done" && value) {
- this.wait_for_finish = true;
- } else if (p == "explicit_timeout" && value) {
- this.timeout_length = null;
- if (this.timeout_id)
- {
- clearTimeout(this.timeout_id);
- }
- } else if (p == "single_test" && value) {
- this.set_file_is_test();
- } else if (p == "timeout_multiplier") {
- this.timeout_multiplier = value;
- if (this.timeout_length) {
- this.timeout_length *= this.timeout_multiplier;
- }
- } else if (p == "hide_test_state") {
- this.hide_test_state = value;
- } else if (p == "output") {
- this.output = value;
- } else if (p === "debug") {
- settings.debug = value;
- }
- }
- }
-
- if (func) {
- try {
- func();
- } catch (e) {
- this.status.status = e instanceof OptionalFeatureUnsupportedError ? this.status.PRECONDITION_FAILED : this.status.ERROR;
- this.status.message = String(e);
- this.status.stack = e.stack ? e.stack : null;
- this.complete();
- }
- }
- this.set_timeout();
- };
-
- Tests.prototype.set_file_is_test = function() {
- if (this.tests.length > 0) {
- throw new Error("Tried to set file as test after creating a test");
- }
- this.wait_for_finish = true;
- this.file_is_test = true;
- // Create the test, which will add it to the list of tests
- tests.current_test = async_test();
- };
-
- Tests.prototype.set_status = function(status, message, stack)
- {
- this.status.status = status;
- this.status.message = message;
- this.status.stack = stack ? stack : null;
- };
-
- Tests.prototype.set_timeout = function() {
- if (global_scope.clearTimeout) {
- var this_obj = this;
- clearTimeout(this.timeout_id);
- if (this.timeout_length !== null) {
- this.timeout_id = setTimeout(function() {
- this_obj.timeout();
- }, this.timeout_length);
- }
- }
- };
-
- Tests.prototype.timeout = function() {
- var test_in_cleanup = null;
-
- if (this.status.status === null) {
- forEach(this.tests,
- function(test) {
- // No more than one test is expected to be in the
- // "CLEANUP" phase at any time
- if (test.phase === test.phases.CLEANING) {
- test_in_cleanup = test;
- }
-
- test.phase = test.phases.COMPLETE;
- });
-
- // Timeouts that occur while a test is in the "cleanup" phase
- // indicate that some global state was not properly reverted. This
- // invalidates the overall test execution, so the timeout should be
- // reported as an error and cancel the execution of any remaining
- // tests.
- if (test_in_cleanup) {
- this.status.status = this.status.ERROR;
- this.status.message = "Timeout while running cleanup for " +
- "test named \"" + test_in_cleanup.name + "\".";
- tests.status.stack = null;
- } else {
- this.status.status = this.status.TIMEOUT;
- }
- }
-
- this.complete();
- };
-
- Tests.prototype.end_wait = function()
- {
- this.wait_for_finish = false;
- if (this.all_done()) {
- this.complete();
- }
- };
-
- Tests.prototype.push = function(test)
- {
- if (this.phase < this.phases.HAVE_TESTS) {
- this.start();
- }
- this.num_pending++;
- 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.tests.length > 0 || this.pending_remotes.length > 0) &&
- test_environment.all_loaded &&
- (this.num_pending === 0 || this.is_aborted) && !this.wait_for_finish &&
- !this.processing_callbacks &&
- !this.pending_remotes.some(function(w) { return w.running; });
- };
-
- Tests.prototype.start = function() {
- this.phase = this.phases.HAVE_TESTS;
- this.notify_start();
- };
-
- Tests.prototype.notify_start = function() {
- var this_obj = this;
- forEach (this.start_callbacks,
- function(callback)
- {
- callback(this_obj.properties);
- });
- };
-
- Tests.prototype.result = function(test)
- {
- // If the harness has already transitioned beyond the `HAVE_RESULTS`
- // phase, subsequent tests should not cause it to revert.
- if (this.phase <= this.phases.HAVE_RESULTS) {
- this.phase = this.phases.HAVE_RESULTS;
- }
- this.num_pending--;
- this.notify_result(test);
- };
-
- Tests.prototype.notify_result = function(test) {
- var this_obj = this;
- this.processing_callbacks = true;
- forEach(this.test_done_callbacks,
- function(callback)
- {
- callback(test, this_obj);
- });
- this.processing_callbacks = false;
- if (this_obj.all_done()) {
- this_obj.complete();
- }
- };
-
- Tests.prototype.complete = function() {
- if (this.phase === this.phases.COMPLETE) {
- return;
- }
- var this_obj = this;
- var all_complete = function() {
- this_obj.phase = this_obj.phases.COMPLETE;
- this_obj.notify_complete();
- };
- var incomplete = filter(this.tests,
- function(test) {
- return test.phase < test.phases.COMPLETE;
- });
-
- /**
- * To preserve legacy behavior, overall test completion must be
- * signaled synchronously.
- */
- if (incomplete.length === 0) {
- all_complete();
- return;
- }
-
- all_async(incomplete,
- function(test, testDone)
- {
- if (test.phase === test.phases.INITIAL) {
- test.phase = test.phases.COMPLETE;
- testDone();
- } else {
- add_test_done_callback(test, testDone);
- test.cleanup();
- }
- },
- all_complete);
- };
-
- Tests.prototype.set_assert = function(assert_name, args) {
- this.asserts_run.push(new AssertRecord(this.current_test, assert_name, args))
- }
-
- Tests.prototype.set_assert_status = function(status, stack) {
- let assert_record = this.asserts_run[this.asserts_run.length - 1];
- assert_record.status = status;
- assert_record.stack = stack;
- }
-
- /**
- * Update the harness status to reflect an unrecoverable harness error that
- * should cancel all further testing. Update all previously-defined tests
- * which have not yet started to indicate that they will not be executed.
- */
- Tests.prototype.abort = function() {
- this.status.status = this.status.ERROR;
- this.is_aborted = true;
-
- forEach(this.tests,
- function(test) {
- if (test.phase === test.phases.INITIAL) {
- test.phase = test.phases.COMPLETE;
- }
- });
- };
-
- /*
- * Determine if any tests share the same `name` property. Return an array
- * containing the names of any such duplicates.
- */
- Tests.prototype.find_duplicates = function() {
- var names = Object.create(null);
- var duplicates = [];
-
- forEach (this.tests,
- function(test)
- {
- if (test.name in names && duplicates.indexOf(test.name) === -1) {
- duplicates.push(test.name);
- }
- names[test.name] = true;
- });
-
- return duplicates;
- };
-
- function code_unit_str(char) {
- return 'U+' + char.charCodeAt(0).toString(16);
- }
-
- function sanitize_unpaired_surrogates(str) {
- return str.replace(
- /([\ud800-\udbff]+)(?![\udc00-\udfff])|(^|[^\ud800-\udbff])([\udc00-\udfff]+)/g,
- function(_, low, prefix, high) {
- var output = prefix || ""; // prefix may be undefined
- var string = low || high; // only one of these alternates can match
- for (var i = 0; i < string.length; i++) {
- output += code_unit_str(string[i]);
- }
- return output;
- });
- }
-
- function sanitize_all_unpaired_surrogates(tests) {
- forEach (tests,
- function (test)
- {
- var sanitized = sanitize_unpaired_surrogates(test.name);
-
- if (test.name !== sanitized) {
- test.name = sanitized;
- delete test._structured_clone;
- }
- });
- }
-
- Tests.prototype.notify_complete = function() {
- var this_obj = this;
- var duplicates;
-
- if (this.status.status === null) {
- duplicates = this.find_duplicates();
-
- // Some transports adhere to UTF-8's restriction on unpaired
- // surrogates. Sanitize the titles so that the results can be
- // consistently sent via all transports.
- sanitize_all_unpaired_surrogates(this.tests);
-
- // Test names are presumed to be unique within test files--this
- // allows consumers to use them for identification purposes.
- // Duplicated names violate this expectation and should therefore
- // be reported as an error.
- if (duplicates.length) {
- this.status.status = this.status.ERROR;
- this.status.message =
- duplicates.length + ' duplicate test name' +
- (duplicates.length > 1 ? 's' : '') + ': "' +
- duplicates.join('", "') + '"';
- } else {
- this.status.status = this.status.OK;
- }
- }
-
- forEach (this.all_done_callbacks,
- function(callback)
- {
- callback(this_obj.tests, this_obj.status, this_obj.asserts_run);
- });
- };
-
- /*
- * Constructs a RemoteContext that tracks tests from a specific worker.
- */
- Tests.prototype.create_remote_worker = function(worker) {
- var message_port;
-
- if (is_service_worker(worker)) {
- message_port = navigator.serviceWorker;
- worker.postMessage({type: "connect"});
- } else if (is_shared_worker(worker)) {
- message_port = worker.port;
- message_port.start();
- } else {
- message_port = worker;
- }
-
- return new RemoteContext(worker, message_port);
- };
-
- /*
- * Constructs a RemoteContext that tracks tests from a specific window.
- */
- Tests.prototype.create_remote_window = function(remote) {
- remote.postMessage({type: "getmessages"}, "*");
- return new RemoteContext(
- remote,
- window,
- function(msg) {
- return msg.source === remote;
- }
- );
- };
-
- Tests.prototype.fetch_tests_from_worker = function(worker) {
- if (this.phase >= this.phases.COMPLETE) {
- return;
- }
-
- var remoteContext = this.create_remote_worker(worker);
- this.pending_remotes.push(remoteContext);
- return remoteContext.done;
- };
-
- /**
- * Get test results from a worker and include them in the current test.
- *
- * @param {Worker|SharedWorker|ServiceWorker|MessagePort} port -
- * Either a worker object or a port connected to a worker which is
- * running tests..
- * @returns {Promise} - A promise that's resolved once all the remote tests are complete.
- */
- function fetch_tests_from_worker(port) {
- return tests.fetch_tests_from_worker(port);
- }
- expose(fetch_tests_from_worker, 'fetch_tests_from_worker');
-
- Tests.prototype.fetch_tests_from_window = function(remote) {
- if (this.phase >= this.phases.COMPLETE) {
- return;
- }
-
- this.pending_remotes.push(this.create_remote_window(remote));
- };
-
- /**
- * Aggregate tests from separate windows or iframes
- * into the current document as if they were all part of the same test file.
- *
- * The document of the second window (or iframe) should include
- * ``testharness.js``, but not ``testharnessreport.js``, and use
- * :js:func:`test`, :js:func:`async_test`, and :js:func:`promise_test` in
- * the usual manner.
- *
- * @param {Window} window - The window to fetch tests from.
- */
- function fetch_tests_from_window(window) {
- tests.fetch_tests_from_window(window);
- }
- expose(fetch_tests_from_window, 'fetch_tests_from_window');
-
- /**
- * Get test results from a shadow realm and include them in the current test.
- *
- * @param {ShadowRealm} realm - A shadow realm also running the test harness
- * @returns {Promise} - A promise that's resolved once all the remote tests are complete.
- */
- function fetch_tests_from_shadow_realm(realm) {
- var chan = new MessageChannel();
- function receiveMessage(msg_json) {
- chan.port1.postMessage(JSON.parse(msg_json));
- }
- var done = tests.fetch_tests_from_worker(chan.port2);
- realm.evaluate("begin_shadow_realm_tests")(receiveMessage);
- chan.port2.start();
- return done;
- }
- expose(fetch_tests_from_shadow_realm, 'fetch_tests_from_shadow_realm');
-
- /**
- * Begin running tests in this shadow realm test harness.
- *
- * To be called after all tests have been loaded; it is an error to call
- * this more than once or in a non-Shadow Realm environment
- *
- * @param {Function} postMessage - A function to send test updates to the
- * incubating realm-- accepts JSON-encoded messages in the format used by
- * RemoteContext
- */
- function begin_shadow_realm_tests(postMessage) {
- if (!(test_environment instanceof ShadowRealmTestEnvironment)) {
- throw new Error("beign_shadow_realm_tests called in non-Shadow Realm environment");
- }
-
- test_environment.begin(function (msg) {
- postMessage(JSON.stringify(msg));
- });
- }
- expose(begin_shadow_realm_tests, 'begin_shadow_realm_tests');
-
- /**
- * Timeout the tests.
- *
- * This only has an effect when ``explict_timeout`` has been set
- * in :js:func:`setup`. In other cases any call is a no-op.
- *
- */
- function timeout() {
- if (tests.timeout_length === null) {
- tests.timeout();
- }
- }
- expose(timeout, 'timeout');
-
- /**
- * Add a callback that's triggered when the first :js:class:`Test` is created.
- *
- * @param {Function} callback - Callback function. This is called
- * without arguments.
- */
- function add_start_callback(callback) {
- tests.start_callbacks.push(callback);
- }
-
- /**
- * Add a callback that's triggered when a test state changes.
- *
- * @param {Function} callback - Callback function, called with the
- * :js:class:`Test` as the only argument.
- */
- function add_test_state_callback(callback) {
- tests.test_state_callbacks.push(callback);
- }
-
- /**
- * Add a callback that's triggered when a test result is received.
- *
- * @param {Function} callback - Callback function, called with the
- * :js:class:`Test` as the only argument.
- */
- function add_result_callback(callback) {
- tests.test_done_callbacks.push(callback);
- }
-
- /**
- * Add a callback that's triggered when all tests are complete.
- *
- * @param {Function} callback - Callback function, called with an
- * array of :js:class:`Test` objects, a :js:class:`TestsStatus`
- * object and an array of :js:class:`AssertRecord` objects. If the
- * debug setting is ``false`` the final argument will be an empty
- * array.
- *
- * For performance reasons asserts are only tracked when the debug
- * setting is ``true``. In other cases the array of asserts will be
- * empty.
- */
- function add_completion_callback(callback) {
- tests.all_done_callbacks.push(callback);
- }
-
- 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');
-
- function remove(array, item) {
- var index = array.indexOf(item);
- if (index > -1) {
- array.splice(index, 1);
- }
- }
-
- function remove_start_callback(callback) {
- remove(tests.start_callbacks, callback);
- }
-
- function remove_test_state_callback(callback) {
- remove(tests.test_state_callbacks, callback);
- }
-
- function remove_result_callback(callback) {
- remove(tests.test_done_callbacks, callback);
- }
-
- function remove_completion_callback(callback) {
- remove(tests.all_done_callbacks, callback);
- }
-
- /*
- * Output listener
- */
-
- function Output() {
- this.output_document = document;
- this.output_node = null;
- this.enabled = settings.output;
- this.phase = this.INITIAL;
- }
-
- Output.prototype.INITIAL = 0;
- Output.prototype.STARTED = 1;
- Output.prototype.HAVE_RESULTS = 2;
- Output.prototype.COMPLETE = 3;
-
- Output.prototype.setup = function(properties) {
- if (this.phase > this.INITIAL) {
- return;
- }
-
- //If output is disabled in testharnessreport.js the test shouldn't be
- //able to override that
- this.enabled = this.enabled && (properties.hasOwnProperty("output") ?
- properties.output : settings.output);
- };
-
- Output.prototype.init = function(properties) {
- if (this.phase >= this.STARTED) {
- return;
- }
- if (properties.output_document) {
- this.output_document = properties.output_document;
- } else {
- this.output_document = document;
- }
- this.phase = this.STARTED;
- };
-
- Output.prototype.resolve_log = function() {
- var output_document;
- if (this.output_node) {
- return;
- }
- if (typeof this.output_document === "function") {
- output_document = this.output_document.apply(undefined);
- } else {
- output_document = this.output_document;
- }
- if (!output_document) {
- return;
- }
- var node = output_document.getElementById("log");
- if (!node) {
- if (output_document.readyState === "loading") {
- return;
- }
- node = output_document.createElementNS("http://www.w3.org/1999/xhtml", "div");
- node.id = "log";
- if (output_document.body) {
- output_document.body.appendChild(node);
- } else {
- var root = output_document.documentElement;
- var is_html = (root &&
- root.namespaceURI == "http://www.w3.org/1999/xhtml" &&
- root.localName == "html");
- var is_svg = (output_document.defaultView &&
- "SVGSVGElement" in output_document.defaultView &&
- root instanceof output_document.defaultView.SVGSVGElement);
- if (is_svg) {
- var foreignObject = output_document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
- foreignObject.setAttribute("width", "100%");
- foreignObject.setAttribute("height", "100%");
- root.appendChild(foreignObject);
- foreignObject.appendChild(node);
- } else if (is_html) {
- root.appendChild(output_document.createElementNS("http://www.w3.org/1999/xhtml", "body"))
- .appendChild(node);
- } else {
- root.appendChild(node);
- }
- }
- }
- this.output_document = output_document;
- this.output_node = node;
- };
-
- Output.prototype.show_status = function() {
- if (this.phase < this.STARTED) {
- this.init({});
- }
- if (!this.enabled || this.phase === this.COMPLETE) {
- return;
- }
- this.resolve_log();
- if (this.phase < this.HAVE_RESULTS) {
- this.phase = this.HAVE_RESULTS;
- }
- var done_count = tests.tests.length - tests.num_pending;
- if (this.output_node && !tests.hide_test_state) {
- 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, asserts_run) {
- if (this.phase >= this.COMPLETE) {
- return;
- }
- if (!this.enabled) {
- return;
- }
- if (!this.output_node) {
- this.resolve_log();
- }
- this.phase = this.COMPLETE;
-
- var log = this.output_node;
- if (!log) {
- return;
- }
- var output_document = this.output_document;
-
- while (log.lastChild) {
- log.removeChild(log.lastChild);
- }
-
- var stylesheet = output_document.createElementNS(xhtml_ns, "style");
- stylesheet.textContent = stylesheetContent;
- var heads = output_document.getElementsByTagName("head");
- if (heads.length) {
- heads[0].appendChild(stylesheet);
- }
-
- var status_number = {};
- forEach(tests,
- function(test) {
- var status = test.format_status();
- if (status_number.hasOwnProperty(status)) {
- status_number[status] += 1;
- } else {
- status_number[status] = 1;
- }
- });
-
- function status_class(status)
- {
- return status.replace(/\s/g, '').toLowerCase();
- }
-
- var summary_template = ["section", {"id":"summary"},
- ["h2", {}, "Summary"],
- function()
- {
- var status = harness_status.format_status();
- var rv = [["section", {},
- ["p", {},
- "Harness status: ",
- ["span", {"class":status_class(status)},
- status
- ],
- ],
- ["button",
- {"onclick": "let evt = new Event('__test_restart'); " +
- "let canceled = !window.dispatchEvent(evt);" +
- "if (!canceled) { location.reload() }"},
- "Rerun"]
- ]];
-
- if (harness_status.status === harness_status.ERROR) {
- rv[0].push(["pre", {}, harness_status.message]);
- if (harness_status.stack) {
- rv[0].push(["pre", {}, harness_status.stack]);
- }
- }
- return rv;
- },
- ["p", {}, "Found ${num_tests} tests"],
- function() {
- var rv = [["div", {}]];
- var i = 0;
- while (Test.prototype.status_formats.hasOwnProperty(i)) {
- if (status_number.hasOwnProperty(Test.prototype.status_formats[i])) {
- var status = Test.prototype.status_formats[i];
- rv[0].push(["div", {},
- ["label", {},
- ["input", {type:"checkbox", checked:"checked"}],
- status_number[status] + " ",
- ["span", {"class":status_class(status)}, status]]]);
- }
- i++;
- }
- return rv;
- },
- ];
-
- log.appendChild(render(summary_template, {num_tests:tests.length}, output_document));
-
- forEach(output_document.querySelectorAll("section#summary label"),
- function(element)
- {
- on_event(element, "click",
- function(e)
- {
- if (output_document.getElementById("results") === null) {
- e.preventDefault();
- return;
- }
- var result_class = element.querySelector("span[class]").getAttribute("class");
- var style_element = output_document.querySelector("style#hide-" + result_class);
- var input_element = element.querySelector("input");
- if (!style_element && !input_element.checked) {
- style_element = output_document.createElementNS(xhtml_ns, "style");
- style_element.id = "hide-" + result_class;
- style_element.textContent = "table#results > tbody > tr.overall-"+result_class+"{display:none}";
- output_document.body.appendChild(style_element);
- } else if (style_element && input_element.checked) {
- style_element.parentNode.removeChild(style_element);
- }
- });
- });
-
- // This use of innerHTML plus manual escaping is not recommended in
- // general, but is necessary here for performance. Using textContent
- // on each individual adds tens of seconds of execution time for
- // large test suites (tens of thousands of tests).
- function escape_html(s)
- {
- return s.replace(/\&/g, "&")
- .replace(/ {
- if (!asserts_run_by_test.has(assert.test)) {
- asserts_run_by_test.set(assert.test, []);
- }
- asserts_run_by_test.get(assert.test).push(assert);
- });
-
- function get_asserts_output(test) {
- var asserts = asserts_run_by_test.get(test);
- if (!asserts) {
- return "No asserts ran";
- }
- rv = "";
- rv += asserts.map(assert => {
- var output_fn = "" + escape_html(assert.assert_name) + "(";
- var prefix_len = output_fn.length;
- var output_args = assert.args;
- var output_len = output_args.reduce((prev, current) => prev+current, prefix_len);
- if (output_len[output_len.length - 1] > 50) {
- output_args = output_args.map((x, i) =>
- (i > 0 ? " ".repeat(prefix_len) : "" )+ x + (i < output_args.length - 1 ? ",\n" : ""));
- } else {
- output_args = output_args.map((x, i) => x + (i < output_args.length - 1 ? ", " : ""));
- }
- output_fn += escape_html(output_args.join(""));
- output_fn += ')';
- var output_location;
- if (assert.stack) {
- output_location = assert.stack.split("\n", 1)[0].replace(/@?\w+:\/\/[^ "\/]+(?::\d+)?/g, " ");
- }
- return "" +
- "" +
- Test.prototype.status_formats[assert.status] + " | " +
- "" +
- output_fn +
- (output_location ? "\n" + escape_html(output_location) : "") +
- " | ";
- }
- ).join("\n");
- rv += " ";
- return rv;
- }
-
- log.appendChild(document.createElementNS(xhtml_ns, "section"));
- var assertions = has_assertions();
- var html = "Details" +
- "Result | Test Name | " +
- (assertions ? "Assertion | " : "") +
- "Message | " +
- "";
- for (var i = 0; i < tests.length; i++) {
- var test = tests[i];
- html += '' +
- '' +
- test.format_status() +
- " | " +
- escape_html(test.name) +
- " | " +
- (assertions ? escape_html(get_assertion(test)) + " | " : "") +
- escape_html(test.message ? tests[i].message : " ") +
- (tests[i].stack ? "" +
- escape_html(tests[i].stack) +
- " ": "");
- if (!(test instanceof RemoteTest)) {
- html += "Asserts run" + get_asserts_output(test) + " "
- }
- html += " | ";
- }
- html += " ";
- try {
- log.lastChild.innerHTML = html;
- } catch (e) {
- log.appendChild(document.createElementNS(xhtml_ns, "p"))
- .textContent = "Setting innerHTML for the log threw an exception.";
- log.appendChild(document.createElementNS(xhtml_ns, "pre"))
- .textContent = html;
- }
- };
-
- /*
- * Template code
- *
- * A template is just a JavaScript structure. An element is represented as:
- *
- * [tag_name, {attr_name:attr_value}, child1, child2]
- *
- * the children can either be strings (which act like text nodes), other templates or
- * functions (see below)
- *
- * A text node is represented as
- *
- * ["{text}", value]
- *
- * String values have a simple substitution syntax; ${foo} represents a variable foo.
- *
- * It is possible to embed logic in templates by using a function in a place where a
- * node would usually go. The function must either return part of a template or null.
- *
- * In cases where a set of nodes are required as output rather than a single node
- * with children it is possible to just use a list
- * [node1, node2, node3]
- *
- * Usage:
- *
- * render(template, substitutions) - take a template and an object mapping
- * variable names to parameters and return either a DOM node or a list of DOM nodes
- *
- * substitute(template, substitutions) - take a template and variable mapping object,
- * make the variable substitutions and return the substituted template
- *
- */
-
- function is_single_node(template)
- {
- return typeof template[0] === "string";
- }
-
- function substitute(template, substitutions)
- {
- if (typeof template === "function") {
- var replacement = template(substitutions);
- if (!replacement) {
- return null;
- }
-
- return substitute(replacement, substitutions);
- }
-
- if (is_single_node(template)) {
- return substitute_single(template, substitutions);
- }
-
- return filter(map(template, function(x) {
- return substitute(x, substitutions);
- }), function(x) {return x !== null;});
- }
-
- function substitute_single(template, substitutions)
- {
- var substitution_re = /\$\{([^ }]*)\}/g;
-
- function do_substitution(input) {
- var components = input.split(substitution_re);
- var rv = [];
- for (var i = 0; i < components.length; i += 2) {
- rv.push(components[i]);
- if (components[i + 1]) {
- rv.push(String(substitutions[components[i + 1]]));
- }
- }
- return rv;
- }
-
- function substitute_attrs(attrs, rv)
- {
- rv[1] = {};
- for (var name in template[1]) {
- if (attrs.hasOwnProperty(name)) {
- var new_name = do_substitution(name).join("");
- var new_value = do_substitution(attrs[name]).join("");
- rv[1][new_name] = new_value;
- }
- }
- }
-
- function substitute_children(children, rv)
- {
- for (var i = 0; i < children.length; i++) {
- if (children[i] instanceof Object) {
- var replacement = substitute(children[i], substitutions);
- if (replacement !== null) {
- if (is_single_node(replacement)) {
- rv.push(replacement);
- } else {
- extend(rv, replacement);
- }
- }
- } else {
- extend(rv, do_substitution(String(children[i])));
- }
- }
- return rv;
- }
-
- var rv = [];
- rv.push(do_substitution(String(template[0])).join(""));
-
- if (template[0] === "{text}") {
- substitute_children(template.slice(1), rv);
- } else {
- substitute_attrs(template[1], rv);
- substitute_children(template.slice(2), rv);
- }
-
- return rv;
- }
-
- function make_dom_single(template, doc)
- {
- var output_document = doc || document;
- var element;
- if (template[0] === "{text}") {
- element = output_document.createTextNode("");
- for (var i = 1; i < template.length; i++) {
- element.data += template[i];
- }
- } else {
- element = output_document.createElementNS(xhtml_ns, template[0]);
- for (var name in template[1]) {
- if (template[1].hasOwnProperty(name)) {
- element.setAttribute(name, template[1][name]);
- }
- }
- for (var i = 2; i < template.length; i++) {
- if (template[i] instanceof Object) {
- var sub_element = make_dom(template[i]);
- element.appendChild(sub_element);
- } else {
- var text_node = output_document.createTextNode(template[i]);
- element.appendChild(text_node);
- }
- }
- }
-
- return element;
- }
-
- function make_dom(template, substitutions, output_document)
- {
- if (is_single_node(template)) {
- return make_dom_single(template, output_document);
- }
-
- return map(template, function(x) {
- return make_dom_single(x, output_document);
- });
- }
-
- function render(template, substitutions, output_document)
- {
- return make_dom(substitute(template, substitutions), output_document);
- }
-
- /*
- * Utility functions
- */
- function assert(expected_true, function_name, description, error, substitutions)
- {
- if (expected_true !== true) {
- var msg = make_message(function_name, description,
- error, substitutions);
- throw new AssertionError(msg);
- }
- }
-
- /**
- * @class
- * Exception type that represents a failing assert.
- *
- * @param {string} message - Error message.
- */
- function AssertionError(message)
- {
- if (typeof message == "string") {
- message = sanitize_unpaired_surrogates(message);
- }
- this.message = message;
- this.stack = get_stack();
- }
- expose(AssertionError, "AssertionError");
-
- AssertionError.prototype = Object.create(Error.prototype);
-
- const get_stack = function() {
- var stack = new Error().stack;
-
- // 'Error.stack' is not supported in all browsers/versions
- if (!stack) {
- return "(Stack trace unavailable)";
- }
-
- var lines = stack.split("\n");
-
- // Create a pattern to match stack frames originating within testharness.js. These include the
- // script URL, followed by the line/col (e.g., '/resources/testharness.js:120:21').
- // Escape the URL per http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
- // in case it contains RegExp characters.
- var script_url = get_script_url();
- var re_text = script_url ? script_url.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') : "\\btestharness.js";
- var re = new RegExp(re_text + ":\\d+:\\d+");
-
- // Some browsers include a preamble that specifies the type of the error object. Skip this by
- // advancing until we find the first stack frame originating from testharness.js.
- var i = 0;
- while (!re.test(lines[i]) && i < lines.length) {
- i++;
- }
-
- // Then skip the top frames originating from testharness.js to begin the stack at the test code.
- while (re.test(lines[i]) && i < lines.length) {
- i++;
- }
-
- // Paranoid check that we didn't skip all frames. If so, return the original stack unmodified.
- if (i >= lines.length) {
- return stack;
- }
-
- return lines.slice(i).join("\n");
- }
-
- function OptionalFeatureUnsupportedError(message)
- {
- AssertionError.call(this, message);
- }
- OptionalFeatureUnsupportedError.prototype = Object.create(AssertionError.prototype);
- expose(OptionalFeatureUnsupportedError, "OptionalFeatureUnsupportedError");
-
- function make_message(function_name, description, error, substitutions)
- {
- for (var p in substitutions) {
- if (substitutions.hasOwnProperty(p)) {
- substitutions[p] = format_value(substitutions[p]);
- }
- }
- var node_form = substitute(["{text}", "${function_name}: ${description}" + error],
- merge({function_name:function_name,
- description:(description?description + " ":"")},
- substitutions));
- return node_form.slice(1).join("");
- }
-
- function filter(array, callable, thisObj) {
- var rv = [];
- for (var i = 0; i < array.length; i++) {
- if (array.hasOwnProperty(i)) {
- var pass = callable.call(thisObj, array[i], i, array);
- if (pass) {
- rv.push(array[i]);
- }
- }
- }
- return rv;
- }
-
- function map(array, callable, thisObj)
- {
- var rv = [];
- rv.length = array.length;
- for (var i = 0; i < array.length; i++) {
- if (array.hasOwnProperty(i)) {
- rv[i] = callable.call(thisObj, array[i], i, array);
- }
- }
- return rv;
- }
-
- function extend(array, items)
- {
- Array.prototype.push.apply(array, items);
- }
-
- function forEach(array, callback, thisObj)
- {
- for (var i = 0; i < array.length; i++) {
- if (array.hasOwnProperty(i)) {
- callback.call(thisObj, array[i], i, array);
- }
- }
- }
-
- /**
- * Immediately invoke a "iteratee" function with a series of values in
- * parallel and invoke a final "done" function when all of the "iteratee"
- * invocations have signaled completion.
- *
- * If all callbacks complete synchronously (or if no callbacks are
- * specified), the ``done_callback`` will be invoked synchronously. It is the
- * responsibility of the caller to ensure asynchronicity in cases where
- * that is desired.
- *
- * @param {array} value Zero or more values to use in the invocation of
- * ``iter_callback``
- * @param {function} iter_callback A function that will be invoked
- * once for each of the values min
- * ``value``. Two arguments will
- * be available in each
- * invocation: the value from
- * ``value`` and a function that
- * must be invoked to signal
- * completion
- * @param {function} done_callback A function that will be invoked after
- * all operations initiated by the
- * ``iter_callback`` function have signaled
- * completion
- */
- function all_async(values, iter_callback, done_callback)
- {
- var remaining = values.length;
-
- if (remaining === 0) {
- done_callback();
- }
-
- forEach(values,
- function(element) {
- var invoked = false;
- var elDone = function() {
- if (invoked) {
- return;
- }
-
- invoked = true;
- remaining -= 1;
-
- if (remaining === 0) {
- done_callback();
- }
- };
-
- iter_callback(element, elDone);
- });
- }
-
- function merge(a,b)
- {
- var rv = {};
- var p;
- for (p in a) {
- rv[p] = a[p];
- }
- for (p in b) {
- rv[p] = b[p];
- }
- return rv;
- }
-
- function expose(object, name)
- {
- var components = name.split(".");
- var target = global_scope;
- for (var i = 0; i < components.length - 1; i++) {
- if (!(components[i] in target)) {
- target[components[i]] = {};
- }
- target = target[components[i]];
- }
- target[components[components.length - 1]] = object;
- }
-
- function is_same_origin(w) {
- try {
- 'random_prop' in w;
- return true;
- } catch (e) {
- return false;
- }
- }
-
- /** Returns the 'src' URL of the first
diff --git a/test/wpt/tests/LICENSE.md b/test/wpt/tests/LICENSE.md
new file mode 100644
index 00000000000..39c46d03ac2
--- /dev/null
+++ b/test/wpt/tests/LICENSE.md
@@ -0,0 +1,11 @@
+# The 3-Clause BSD License
+
+Copyright © web-platform-tests contributors
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/test/wpt/tests/README.md b/test/wpt/tests/README.md
new file mode 100644
index 00000000000..7e8e9948091
--- /dev/null
+++ b/test/wpt/tests/README.md
@@ -0,0 +1,124 @@
+The web-platform-tests Project
+==============================
+
+[![Taskcluster CI Status](https://community-tc.services.mozilla.com/api/github/v1/repository/web-platform-tests/wpt/master/badge.svg)](https://community-tc.services.mozilla.com/api/github/v1/repository/web-platform-tests/wpt/master/latest) [![documentation](https://github.com/web-platform-tests/wpt/workflows/documentation/badge.svg)](https://github.com/web-platform-tests/wpt/actions?query=workflow%3Adocumentation+branch%3Amaster) [![manifest](https://github.com/web-platform-tests/wpt/workflows/manifest/badge.svg)](https://github.com/web-platform-tests/wpt/actions?query=workflow%3Amanifest+branch%3Amaster) [![Python 3](https://pyup.io/repos/github/web-platform-tests/wpt/python-3-shield.svg)](https://pyup.io/repos/github/web-platform-tests/wpt/)
+
+The web-platform-tests Project is a cross-browser test suite for the
+Web-platform stack. Writing tests in a way that allows them to be run in all
+browsers gives browser projects confidence that they are shipping software that
+is compatible with other implementations, and that later implementations will
+be compatible with their implementations. This in turn gives Web
+authors/developers confidence that they can actually rely on the Web platform
+to deliver on the promise of working across browsers and devices without
+needing extra layers of abstraction to paper over the gaps left by
+specification editors and implementors.
+
+The most important sources of information and activity are:
+
+- [github.com/web-platform-tests/wpt](https://github.com/web-platform-tests/wpt):
+ the canonical location of the project's source code revision history and the
+ discussion forum for changes to the code
+- [web-platform-tests.org](https://web-platform-tests.org): the documentation
+ website; details how to set up the project, how to write tests, how to give
+ and receive peer review, how to serve as an administrator, and more
+- [wpt.live](https://wpt.live): a public deployment of the test suite,
+ allowing anyone to run the tests by visiting from an
+ Internet-enabled browser of their choice
+- [wpt.fyi](https://wpt.fyi): an archive of test results collected from an
+ array of web browsers on a regular basis
+- [Real-time chat room](https://app.element.io/#/room/#wpt:matrix.org): the
+ `wpt:matrix.org` matrix channel; includes participants located
+ around the world, but busiest during the European working day.
+- [Mailing list](https://lists.w3.org/Archives/Public/public-test-infra/): a
+ public and low-traffic discussion list
+- [RFCs](https://github.com/web-platform-tests/rfcs): a repo for requesting
+ comments on substantial changes that would impact other stakeholders or
+ users; people who work on WPT infra are encouraged to watch the repo.
+
+**If you'd like clarification about anything**, don't hesitate to ask in the
+chat room or on the mailing list.
+
+Setting Up the Repo
+===================
+
+Clone or otherwise get https://github.com/web-platform-tests/wpt.
+
+Note: because of the frequent creation and deletion of branches in this
+repo, it is recommended to "prune" stale branches when fetching updates,
+i.e. use `git pull --prune` (or `git fetch -p && git merge`).
+
+Running the Tests
+=================
+
+See the [documentation website](https://web-platform-tests.org/running-tests/)
+and in particular the
+[system setup for running tests locally](https://web-platform-tests.org/running-tests/from-local-system.html#system-setup).
+
+Command Line Tools
+==================
+
+The `wpt` command provides a frontend to a variety of tools for
+working with and running web-platform-tests. Some of the most useful
+commands are:
+
+* `wpt serve` - For starting the wpt http server
+* `wpt run` - For running tests in a browser
+* `wpt lint` - For running the lint against all tests
+* `wpt manifest` - For updating or generating a `MANIFEST.json` test manifest
+* `wpt install` - For installing the latest release of a browser or
+ webdriver server on the local machine.
+* `wpt serve-wave` - For starting the wpt http server and the WAVE test runner.
+For more details on how to use the WAVE test runner see the [documentation](./tools/wave/docs/usage/usage.md).
+
+Windows Notes
+=============================================
+
+On Windows `wpt` commands must be prefixed with `python` or the path
+to the python binary (if `python` is not in your `%PATH%`).
+
+```bash
+python wpt [command]
+```
+
+Alternatively, you may also use
+[Bash on Ubuntu on Windows](https://msdn.microsoft.com/en-us/commandline/wsl/about)
+in the Windows 10 Anniversary Update build, then access your windows
+partition from there to launch `wpt` commands.
+
+Please make sure git and your text editor do not automatically convert
+line endings, as it will cause lint errors. For git, please set
+`git config core.autocrlf false` in your working tree.
+
+Publication
+===========
+
+The master branch is automatically synced to [wpt.live](https://wpt.live/) and
+[w3c-test.org](https://w3c-test.org/).
+
+Contributing
+============
+
+Save the Web, Write Some Tests!
+
+Absolutely everyone is welcome to contribute to test development. No
+test is too small or too simple, especially if it corresponds to
+something for which you've noted an interoperability bug in a browser.
+
+The way to contribute is just as usual:
+
+* Fork this repository (and make sure you're still relatively in sync
+ with it if you forked a while ago).
+* Create a branch for your changes:
+ `git checkout -b topic`.
+* Make your changes.
+* Run `./wpt lint` as described above.
+* Commit locally and push that to your repo.
+* Create a pull request based on the above.
+
+Issues with web-platform-tests
+------------------------------
+
+If you spot an issue with a test and are not comfortable providing a
+pull request per above to fix it, please
+[file a new issue](https://github.com/web-platform-tests/wpt/issues/new).
+Thank you!
diff --git a/test/wpt/tests/common/security-features/resources/common.sub.js b/test/wpt/tests/common/security-features/resources/common.sub.js
index d0f88f17010..96ca280597b 100644
--- a/test/wpt/tests/common/security-features/resources/common.sub.js
+++ b/test/wpt/tests/common/security-features/resources/common.sub.js
@@ -485,9 +485,13 @@ function dedicatedWorkerUrlThatFetches(url) {
.catch((e) => postMessage(e.message));`;
}
-function workerUrlThatImports(url) {
+function workerUrlThatImports(url, additionalAttributes) {
+ let csp = "";
+ if (additionalAttributes && additionalAttributes.contentSecurityPolicy) {
+ csp=`&contentSecurityPolicy=${additionalAttributes.contentSecurityPolicy}`;
+ }
return `/common/security-features/subresource/static-import.py` +
- `?import_url=${encodeURIComponent(url)}`;
+ `?import_url=${encodeURIComponent(url)}${csp}`;
}
function workerDataUrlThatImports(url) {
@@ -907,8 +911,8 @@ const subresourceMap = {
},
"worker-import": {
path: "/common/security-features/subresource/worker.py",
- invoker: url =>
- requestViaDedicatedWorker(workerUrlThatImports(url), {type: "module"}),
+ invoker: (url, additionalAttributes) =>
+ requestViaDedicatedWorker(workerUrlThatImports(url, additionalAttributes), {type: "module"}),
},
"worker-import-data": {
path: "/common/security-features/subresource/worker.py",
@@ -925,8 +929,8 @@ const subresourceMap = {
},
"sharedworker-import": {
path: "/common/security-features/subresource/shared-worker.py",
- invoker: url =>
- requestViaSharedWorker(workerUrlThatImports(url), {type: "module"}),
+ invoker: (url, additionalAttributes) =>
+ requestViaSharedWorker(workerUrlThatImports(url, additionalAttributes), {type: "module"}),
},
"sharedworker-import-data": {
path: "/common/security-features/subresource/shared-worker.py",
@@ -1109,6 +1113,10 @@ function invokeRequest(subresource, sourceContextList) {
additionalAttributes[policyDelivery.key] = policyDelivery.value;
} else if (policyDelivery.deliveryType === "rel-noref") {
additionalAttributes["rel"] = "noreferrer";
+ } else if (policyDelivery.deliveryType === "http-rp") {
+ additionalAttributes[policyDelivery.key] = policyDelivery.value;
+ } else if (policyDelivery.deliveryType === "meta") {
+ additionalAttributes[policyDelivery.key] = policyDelivery.value;
}
}
diff --git a/test/wpt/tests/common/security-features/subresource/static-import.py b/test/wpt/tests/common/security-features/subresource/static-import.py
index 717d3de6b18..3c3a6f6871d 100644
--- a/test/wpt/tests/common/security-features/subresource/static-import.py
+++ b/test/wpt/tests/common/security-features/subresource/static-import.py
@@ -1,10 +1,47 @@
-import os, sys
+import os, sys, json
from urllib.parse import unquote
from wptserve.utils import isomorphic_decode
import importlib
subresource = importlib.import_module("common.security-features.subresource.subresource")
+def get_csp_value(value):
+ '''
+ Returns actual CSP header values (e.g. "worker-src 'self'") for the
+ given string used in PolicyDelivery's value (e.g. "worker-src-self").
+ '''
+
+ # script-src
+ # Test-related scripts like testharness.js and inline scripts containing
+ # test bodies.
+ # 'unsafe-inline' is added as a workaround here. This is probably not so
+ # bad, as it shouldn't intefere non-inline-script requests that we want to
+ # test.
+ if value == 'script-src-wildcard':
+ return "script-src * 'unsafe-inline'"
+ if value == 'script-src-self':
+ return "script-src 'self' 'unsafe-inline'"
+ # Workaround for "script-src 'none'" would be more complicated, because
+ # - "script-src 'none' 'unsafe-inline'" is handled somehow differently from
+ # "script-src 'none'", i.e.
+ # https://w3c.github.io/webappsec-csp/#match-url-to-source-list Step 3
+ # handles the latter but not the former.
+ # - We need nonce- or path-based additional values to allow same-origin
+ # test scripts like testharness.js.
+ # Therefore, we disable 'script-src-none' tests for now in
+ # `/content-security-policy/spec.src.json`.
+ if value == 'script-src-none':
+ return "script-src 'none'"
+
+ # worker-src
+ if value == 'worker-src-wildcard':
+ return 'worker-src *'
+ if value == 'worker-src-self':
+ return "worker-src 'self'"
+ if value == 'worker-src-none':
+ return "worker-src 'none'"
+ raise Exception('Invalid delivery_value: %s' % value)
+
def generate_payload(request):
import_url = unquote(isomorphic_decode(request.GET[b'import_url']))
return subresource.get_template(u"static-import.js.template") % {
@@ -12,8 +49,13 @@ def generate_payload(request):
}
def main(request, response):
- payload_generator = lambda _: generate_payload(request)
+ def payload_generator(_): return generate_payload(request)
+ maybe_additional_headers = {}
+ if b'contentSecurityPolicy' in request.GET:
+ csp = unquote(isomorphic_decode(request.GET[b'contentSecurityPolicy']))
+ maybe_additional_headers[b'Content-Security-Policy'] = get_csp_value(csp)
subresource.respond(request,
response,
payload_generator = payload_generator,
- content_type = b"application/javascript")
+ content_type = b"application/javascript",
+ maybe_additional_headers = maybe_additional_headers)
diff --git a/test/wpt/tests/fetch/api/credentials/authentication-redirection.any.js b/test/wpt/tests/fetch/api/credentials/authentication-redirection.any.js
index a0175e6d2a7..16656b5435a 100644
--- a/test/wpt/tests/fetch/api/credentials/authentication-redirection.any.js
+++ b/test/wpt/tests/fetch/api/credentials/authentication-redirection.any.js
@@ -16,7 +16,10 @@ promise_test(async test => {
}, "getAuthorizationHeaderValue - no redirection");
promise_test(async test => {
- const result = await getAuthorizationHeaderValue("/fetch/api/resources/redirect.py?location=" + encodeURIComponent("/fetch/api/resources/dump-authorization-header.py"));
+ result = await getAuthorizationHeaderValue("/fetch/api/resources/redirect.py?location=" + encodeURIComponent("/fetch/api/resources/dump-authorization-header.py"));
+ assert_equals(result, authorizationValue);
+
+ result = await getAuthorizationHeaderValue(get_host_info().HTTPS_REMOTE_ORIGIN + "/fetch/api/resources/redirect.py?allow_headers=Authorization&location=" + encodeURIComponent(get_host_info().HTTPS_REMOTE_ORIGIN + "/fetch/api/resources/dump-authorization-header.py"));
assert_equals(result, authorizationValue);
}, "getAuthorizationHeaderValue - same origin redirection");
diff --git a/test/wpt/tests/fetch/orb/resources/empty.json b/test/wpt/tests/fetch/orb/resources/empty.json
new file mode 100644
index 00000000000..0967ef424bc
--- /dev/null
+++ b/test/wpt/tests/fetch/orb/resources/empty.json
@@ -0,0 +1 @@
+{}
diff --git a/test/wpt/tests/fetch/orb/tentative/known-mime-type.sub.any.js b/test/wpt/tests/fetch/orb/tentative/known-mime-type.sub.any.js
index a7bb6630583..d0954c83555 100644
--- a/test/wpt/tests/fetch/orb/tentative/known-mime-type.sub.any.js
+++ b/test/wpt/tests/fetch/orb/tentative/known-mime-type.sub.any.js
@@ -29,7 +29,17 @@ promise_test(
TypeError,
fetchORB(`${path}/data.json`, null, contentType("application/json"))
),
- "ORB should block opaque application/json"
+ "ORB should block opaque application/json (non-empty)"
+);
+
+promise_test(
+ t =>
+ promise_rejects_js(
+ t,
+ TypeError,
+ fetchORB(`${path}/empty.json`, null, contentType("application/json"))
+ ),
+ "ORB should block opaque application/json (empty)"
);
promise_test(async () => {
diff --git a/test/wpt/tests/fetch/origin/assorted.window.js b/test/wpt/tests/fetch/origin/assorted.window.js
index 423790dfb1e..033d010f35a 100644
--- a/test/wpt/tests/fetch/origin/assorted.window.js
+++ b/test/wpt/tests/fetch/origin/assorted.window.js
@@ -10,7 +10,7 @@ promise_test(async function () {
// Cross-origin -> same-origin will result in setting the tainted origin flag for the second
// request.
let url = origins.HTTP_ORIGIN + redirectPath + "?stash=" + stash;
- url = origins.HTTP_REMOTE_ORIGIN + redirectPath + "?stash=" + stash + "&location=" + encodeURIComponent(url);
+ url = origins.HTTP_REMOTE_ORIGIN + redirectPath + "?stash=" + stash + "&location=" + encodeURIComponent(url) + "&dummyJS";
await fetch(url, { mode: "no-cors", method: "POST" });
@@ -123,7 +123,7 @@ function fetchReferrerPolicy(referrerPolicy, destination, fetchMode, expectedOri
let fetchUrl =
(destination === "same-origin" ? origins.HTTP_ORIGIN
: origins.HTTP_REMOTE_ORIGIN) +
- redirectPath + "?stash=" + stash;
+ redirectPath + "?stash=" + stash + "&dummyJS";
await fetch(fetchUrl, { mode: fetchMode, method: httpMethod , "referrerPolicy": referrerPolicy});
diff --git a/test/wpt/tests/fetch/origin/resources/redirect-and-stash.py b/test/wpt/tests/fetch/origin/resources/redirect-and-stash.py
index 9bf9e1f18c2..36c584c08cc 100644
--- a/test/wpt/tests/fetch/origin/resources/redirect-and-stash.py
+++ b/test/wpt/tests/fetch/origin/resources/redirect-and-stash.py
@@ -23,10 +23,16 @@ def main(request, response):
request.server.stash.put(key, origin_list)
if b"location" in request.GET:
+ location = request.GET.first(b"location")
+ if b"dummyJS" in request.GET:
+ location += b"&dummyJS"
response.status = 308
- response.headers.set(b"Location", request.GET.first(b"location"))
+ response.headers.set(b"Location", location)
return
response.headers.set(b"Content-Type", b"text/html")
response.headers.set(b"Access-Control-Allow-Origin", b"*")
- response.content = b"\n"
+ if b"dummyJS" in request.GET:
+ response.content = b"console.log('dummy JS')"
+ else:
+ response.content = b"\n"
diff --git a/test/wpt/tests/fetch/private-network-access/resources/shared-worker-blob-fetcher.html b/test/wpt/tests/fetch/private-network-access/resources/shared-worker-blob-fetcher.html
new file mode 100644
index 00000000000..a79869b2f96
--- /dev/null
+++ b/test/wpt/tests/fetch/private-network-access/resources/shared-worker-blob-fetcher.html
@@ -0,0 +1,50 @@
+
+
+SharedWorker Blob Fetcher
+
diff --git a/test/wpt/tests/fetch/private-network-access/resources/support.sub.js b/test/wpt/tests/fetch/private-network-access/resources/support.sub.js
index a104021d158..210184ec4b6 100644
--- a/test/wpt/tests/fetch/private-network-access/resources/support.sub.js
+++ b/test/wpt/tests/fetch/private-network-access/resources/support.sub.js
@@ -629,10 +629,10 @@ async function workerFetchTest(t, { source, target, expected }) {
iframe.contentWindow.postMessage({ url: sourceUrl.href }, "*");
- const { error, status, message } = await reply;
+ const { error, status, body } = await reply;
assert_equals(error, expected.error, "fetch error");
assert_equals(status, expected.status, "response status");
- assert_equals(message, expected.message, "response body");
+ assert_equals(body, expected.body, "response body");
}
async function workerBlobFetchTest(t, { source, target, expected }) {
@@ -646,10 +646,10 @@ async function workerBlobFetchTest(t, { source, target, expected }) {
iframe.contentWindow.postMessage({ url: targetUrl.href }, "*");
- const { error, status, message } = await reply;
+ const { error, status, body } = await reply;
assert_equals(error, expected.error, "fetch error");
assert_equals(status, expected.status, "response status");
- assert_equals(message, expected.message, "response body");
+ assert_equals(body, expected.body, "response body");
}
async function sharedWorkerFetchTest(t, { source, target, expected }) {
@@ -666,8 +666,26 @@ async function sharedWorkerFetchTest(t, { source, target, expected }) {
iframe.contentWindow.postMessage({ url: sourceUrl.href }, "*");
- const { error, status, message } = await reply;
+ const { error, status, body } = await reply;
assert_equals(error, expected.error, "fetch error");
assert_equals(status, expected.status, "response status");
- assert_equals(message, expected.message, "response body");
+ assert_equals(body, expected.body, "response body");
+}
+
+async function sharedWorkerBlobFetchTest(t, { source, target, expected }) {
+ const targetUrl = preflightUrl(target);
+
+ const fetcherUrl = resolveUrl(
+ 'resources/shared-worker-blob-fetcher.html',
+ sourceResolveOptions(source));
+
+ const reply = futureMessage();
+ const iframe = await appendIframe(t, document, fetcherUrl);
+
+ iframe.contentWindow.postMessage({ url: targetUrl.href }, "*");
+
+ const { error, status, body } = await reply;
+ assert_equals(error, expected.error, "fetch error");
+ assert_equals(status, expected.status, "response status");
+ assert_equals(body, expected.body, "response body");
}
diff --git a/test/wpt/tests/fetch/private-network-access/resources/worker-blob-fetcher.html b/test/wpt/tests/fetch/private-network-access/resources/worker-blob-fetcher.html
index 18a454b7fa3..5a50271e11b 100644
--- a/test/wpt/tests/fetch/private-network-access/resources/worker-blob-fetcher.html
+++ b/test/wpt/tests/fetch/private-network-access/resources/worker-blob-fetcher.html
@@ -1,6 +1,6 @@
-Worker Fetcher
+Worker Blob Fetcher
|