Debian Codegraph @

testing/web-platform/tests/resources/testharness.js

raw
1 /*global self*/
2 /*jshint latedef: nofunc*/
3
4 /* Documentation: https://web-platform-tests.org/writing-tests/testharness-api.html
5 * (../docs/_writing-tests/testharness-api.md) */
6
7 (function (global_scope)
8 {
9 // default timeout is 10 seconds, test can override if needed
10 var settings = {
11 output:true,
12 harness_timeout:{
13 "normal":10000,
14 "long":60000
15 },
16 test_timeout:null,
17 message_events: ["start", "test_state", "result", "completion"],
18 debug: false,
19 };
20
21 var xhtml_ns = "http://www.w3.org/1999/xhtml";
22
23 /*
24 * TestEnvironment is an abstraction for the environment in which the test
25 * harness is used. Each implementation of a test environment has to provide
26 * the following interface:
27 *
28 * interface TestEnvironment {
29 * // Invoked after the global 'tests' object has been created and it's
30 * // safe to call add_*_callback() to register event handlers.
31 * void on_tests_ready();
32 *
33 * // Invoked after setup() has been called to notify the test environment
34 * // of changes to the test harness properties.
35 * void on_new_harness_properties(object properties);
36 *
37 * // Should return a new unique default test name.
38 * DOMString next_default_test_name();
39 *
40 * // Should return the test harness timeout duration in milliseconds.
41 * float test_timeout();
42 * };
43 */
44
45 /*
46 * A test environment with a DOM. The global object is 'window'. By default
47 * test results are displayed in a table. Any parent windows receive
48 * callbacks or messages via postMessage() when test events occur. See
49 * apisample11.html and apisample12.html.
50 */
51 function WindowTestEnvironment() {
52 this.name_counter = 0;
53 this.window_cache = null;
54 this.output_handler = null;
55 this.all_loaded = false;
56 var this_obj = this;
57 this.message_events = [];
58 this.dispatched_messages = [];
59
60 this.message_functions = {
61 start: [add_start_callback, remove_start_callback,
62 function (properties) {
63 this_obj._dispatch("start_callback", [properties],
64 {type: "start", properties: properties});
65 }],
66
67 test_state: [add_test_state_callback, remove_test_state_callback,
68 function(test) {
69 this_obj._dispatch("test_state_callback", [test],
70 {type: "test_state",
71 test: test.structured_clone()});
72 }],
73 result: [add_result_callback, remove_result_callback,
74 function (test) {
75 this_obj.output_handler.show_status();
76 this_obj._dispatch("result_callback", [test],
77 {type: "result",
78 test: test.structured_clone()});
79 }],
80 completion: [add_completion_callback, remove_completion_callback,
81 function (tests, harness_status, asserts) {
82 var cloned_tests = map(tests, function(test) {
83 return test.structured_clone();
84 });
85 this_obj._dispatch("completion_callback", [tests, harness_status],
86 {type: "complete",
87 tests: cloned_tests,
88 status: harness_status.structured_clone(),
89 asserts: asserts.map(assert => assert.structured_clone())});
90 }]
91 };
92
93 on_event(window, 'load', function() {
94 setTimeout(() => {
95 this_obj.all_loaded = true;
96 if (tests.all_done()) {
97 tests.complete();
98 }
99 },0);
100 });
101
102 on_event(window, 'message', function(event) {
103 if (event.data && event.data.type === "getmessages" && event.source) {
104 // A window can post "getmessages" to receive a duplicate of every
105 // message posted by this environment so far. This allows subscribers
106 // from fetch_tests_from_window to 'catch up' to the current state of
107 // this environment.
108 for (var i = 0; i < this_obj.dispatched_messages.length; ++i)
109 {
110 event.source.postMessage(this_obj.dispatched_messages[i], "*");
111 }
112 }
113 });
114 }
115
116 WindowTestEnvironment.prototype._dispatch = function(selector, callback_args, message_arg) {
117 this.dispatched_messages.push(message_arg);
118 this._forEach_windows(
119 function(w, same_origin) {
120 if (same_origin) {
121 try {
122 var has_selector = selector in w;
123 } catch(e) {
124 // If document.domain was set at some point same_origin can be
125 // wrong and the above will fail.
126 has_selector = false;
127 }
128 if (has_selector) {
129 try {
130 w[selector].apply(undefined, callback_args);
131 } catch (e) {}
132 }
133 }
134 if (w !== self) {
135 w.postMessage(message_arg, "*");
136 }
137 });
138 };
139
140 WindowTestEnvironment.prototype._forEach_windows = function(callback) {
141 // Iterate over the windows [self ... top, opener]. The callback is passed
142 // two objects, the first one is the window object itself, the second one
143 // is a boolean indicating whether or not it's on the same origin as the
144 // current window.
145 var cache = this.window_cache;
146 if (!cache) {
147 cache = [[self, true]];
148 var w = self;
149 var i = 0;
150 var so;
151 while (w != w.parent) {
152 w = w.parent;
153 so = is_same_origin(w);
154 cache.push([w, so]);
155 i++;
156 }
157 w = window.opener;
158 if (w) {
159 cache.push([w, is_same_origin(w)]);
160 }
161 this.window_cache = cache;
162 }
163
164 forEach(cache,
165 function(a) {
166 callback.apply(null, a);
167 });
168 };
169
170 WindowTestEnvironment.prototype.on_tests_ready = function() {
171 var output = new Output();
172 this.output_handler = output;
173
174 var this_obj = this;
175
176 add_start_callback(function (properties) {
177 this_obj.output_handler.init(properties);
178 });
179
180 add_test_state_callback(function(test) {
181 this_obj.output_handler.show_status();
182 });
183
184 add_result_callback(function (test) {
185 this_obj.output_handler.show_status();
186 });
187
188 add_completion_callback(function (tests, harness_status, asserts_run) {
189 this_obj.output_handler.show_results(tests, harness_status, asserts_run);
190 });
191 this.setup_messages(settings.message_events);
192 };
193
194 WindowTestEnvironment.prototype.setup_messages = function(new_events) {
195 var this_obj = this;
196 forEach(settings.message_events, function(x) {
197 var current_dispatch = this_obj.message_events.indexOf(x) !== -1;
198 var new_dispatch = new_events.indexOf(x) !== -1;
199 if (!current_dispatch && new_dispatch) {
200 this_obj.message_functions[x][0](this_obj.message_functions[x][2]);
201 } else if (current_dispatch && !new_dispatch) {
202 this_obj.message_functions[x][1](this_obj.message_functions[x][2]);
203 }
204 });
205 this.message_events = new_events;
206 };
207
208 WindowTestEnvironment.prototype.next_default_test_name = function() {
209 var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
210 this.name_counter++;
211 return get_title() + suffix;
212 };
213
214 WindowTestEnvironment.prototype.on_new_harness_properties = function(properties) {
215 this.output_handler.setup(properties);
216 if (properties.hasOwnProperty("message_events")) {
217 this.setup_messages(properties.message_events);
218 }
219 };
220
221 WindowTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
222 on_event(window, 'load', callback);
223 };
224
225 WindowTestEnvironment.prototype.test_timeout = function() {
226 var metas = document.getElementsByTagName("meta");
227 for (var i = 0; i < metas.length; i++) {
228 if (metas[i].name === "timeout") {
229 if (metas[i].content === "long") {
230 return settings.harness_timeout.long;
231 }
232 break;
233 }
234 }
235 return settings.harness_timeout.normal;
236 };
237
238 /*
239 * Base TestEnvironment implementation for a generic web worker.
240 *
241 * Workers accumulate test results. One or more clients can connect and
242 * retrieve results from a worker at any time.
243 *
244 * WorkerTestEnvironment supports communicating with a client via a
245 * MessagePort. The mechanism for determining the appropriate MessagePort
246 * for communicating with a client depends on the type of worker and is
247 * implemented by the various specializations of WorkerTestEnvironment
248 * below.
249 *
250 * A client document using testharness can use fetch_tests_from_worker() to
251 * retrieve results from a worker. See apisample16.html.
252 */
253 function WorkerTestEnvironment() {
254 this.name_counter = 0;
255 this.all_loaded = true;
256 this.message_list = [];
257 this.message_ports = [];
258 }
259
260 WorkerTestEnvironment.prototype._dispatch = function(message) {
261 this.message_list.push(message);
262 for (var i = 0; i < this.message_ports.length; ++i)
263 {
264 this.message_ports[i].postMessage(message);
265 }
266 };
267
268 // The only requirement is that port has a postMessage() method. It doesn't
269 // have to be an instance of a MessagePort, and often isn't.
270 WorkerTestEnvironment.prototype._add_message_port = function(port) {
271 this.message_ports.push(port);
272 for (var i = 0; i < this.message_list.length; ++i)
273 {
274 port.postMessage(this.message_list[i]);
275 }
276 };
277
278 WorkerTestEnvironment.prototype.next_default_test_name = function() {
279 var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
280 this.name_counter++;
281 return get_title() + suffix;
282 };
283
284 WorkerTestEnvironment.prototype.on_new_harness_properties = function() {};
285
286 WorkerTestEnvironment.prototype.on_tests_ready = function() {
287 var this_obj = this;
288 add_start_callback(
289 function(properties) {
290 this_obj._dispatch({
291 type: "start",
292 properties: properties,
293 });
294 });
295 add_test_state_callback(
296 function(test) {
297 this_obj._dispatch({
298 type: "test_state",
299 test: test.structured_clone()
300 });
301 });
302 add_result_callback(
303 function(test) {
304 this_obj._dispatch({
305 type: "result",
306 test: test.structured_clone()
307 });
308 });
309 add_completion_callback(
310 function(tests, harness_status, asserts) {
311 this_obj._dispatch({
312 type: "complete",
313 tests: map(tests,
314 function(test) {
315 return test.structured_clone();
316 }),
317 status: harness_status.structured_clone(),
318 asserts: asserts.map(assert => assert.structured_clone()),
319 });
320 });
321 };
322
323 WorkerTestEnvironment.prototype.add_on_loaded_callback = function() {};
324
325 WorkerTestEnvironment.prototype.test_timeout = function() {
326 // Tests running in a worker don't have a default timeout. I.e. all
327 // worker tests behave as if settings.explicit_timeout is true.
328 return null;
329 };
330
331 /*
332 * Dedicated web workers.
333 * https://html.spec.whatwg.org/multipage/workers.html#dedicatedworkerglobalscope
334 *
335 * This class is used as the test_environment when testharness is running
336 * inside a dedicated worker.
337 */
338 function DedicatedWorkerTestEnvironment() {
339 WorkerTestEnvironment.call(this);
340 // self is an instance of DedicatedWorkerGlobalScope which exposes
341 // a postMessage() method for communicating via the message channel
342 // established when the worker is created.
343 this._add_message_port(self);
344 }
345 DedicatedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
346
347 DedicatedWorkerTestEnvironment.prototype.on_tests_ready = function() {
348 WorkerTestEnvironment.prototype.on_tests_ready.call(this);
349 // In the absence of an onload notification, we a require dedicated
350 // workers to explicitly signal when the tests are done.
351 tests.wait_for_finish = true;
352 };
353
354 /*
355 * Shared web workers.
356 * https://html.spec.whatwg.org/multipage/workers.html#sharedworkerglobalscope
357 *
358 * This class is used as the test_environment when testharness is running
359 * inside a shared web worker.
360 */
361 function SharedWorkerTestEnvironment() {
362 WorkerTestEnvironment.call(this);
363 var this_obj = this;
364 // Shared workers receive message ports via the 'onconnect' event for
365 // each connection.
366 self.addEventListener("connect",
367 function(message_event) {
368 this_obj._add_message_port(message_event.source);
369 }, false);
370 }
371 SharedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
372
373 SharedWorkerTestEnvironment.prototype.on_tests_ready = function() {
374 WorkerTestEnvironment.prototype.on_tests_ready.call(this);
375 // In the absence of an onload notification, we a require shared
376 // workers to explicitly signal when the tests are done.
377 tests.wait_for_finish = true;
378 };
379
380 /*
381 * Service workers.
382 * http://www.w3.org/TR/service-workers/
383 *
384 * This class is used as the test_environment when testharness is running
385 * inside a service worker.
386 */
387 function ServiceWorkerTestEnvironment() {
388 WorkerTestEnvironment.call(this);
389 this.all_loaded = false;
390 this.on_loaded_callback = null;
391 var this_obj = this;
392 self.addEventListener("message",
393 function(event) {
394 if (event.data && event.data.type && event.data.type === "connect") {
395 this_obj._add_message_port(event.source);
396 }
397 }, false);
398
399 // The oninstall event is received after the service worker script and
400 // all imported scripts have been fetched and executed. It's the
401 // equivalent of an onload event for a document. All tests should have
402 // been added by the time this event is received, thus it's not
403 // necessary to wait until the onactivate event. However, tests for
404 // installed service workers need another event which is equivalent to
405 // the onload event because oninstall is fired only on installation. The
406 // onmessage event is used for that purpose since tests using
407 // testharness.js should ask the result to its service worker by
408 // PostMessage. If the onmessage event is triggered on the service
409 // worker's context, that means the worker's script has been evaluated.
410 on_event(self, "install", on_all_loaded);
411 on_event(self, "message", on_all_loaded);
412 function on_all_loaded() {
413 if (this_obj.all_loaded)
414 return;
415 this_obj.all_loaded = true;
416 if (this_obj.on_loaded_callback) {
417 this_obj.on_loaded_callback();
418 }
419 }
420 }
421
422 ServiceWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
423
424 ServiceWorkerTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
425 if (this.all_loaded) {
426 callback();
427 } else {
428 this.on_loaded_callback = callback;
429 }
430 };
431
432 /*
433 * Shadow realms.
434 * https://github.com/tc39/proposal-shadowrealm
435 *
436 * This class is used as the test_environment when testharness is running
437 * inside a shadow realm.
438 */
439 function ShadowRealmTestEnvironment() {
440 WorkerTestEnvironment.call(this);
441 this.all_loaded = false;
442 this.on_loaded_callback = null;
443 }
444
445 ShadowRealmTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
446
447 /**
448 * Signal to the test environment that the tests are ready and the on-loaded
449 * callback should be run.
450 *
451 * Shadow realms are not *really* a DOM context: they have no `onload` or similar
452 * event for us to use to set up the test environment; so, instead, this method
453 * is manually triggered from the incubating realm
454 *
455 * @param {Function} message_destination - a function that receives JSON-serializable
456 * data to send to the incubating realm, in the same format as used by RemoteContext
457 */
458 ShadowRealmTestEnvironment.prototype.begin = function(message_destination) {
459 if (this.all_loaded) {
460 throw new Error("Tried to start a shadow realm test environment after it has already started");
461 }
462 var fakeMessagePort = {};
463 fakeMessagePort.postMessage = message_destination;
464 this._add_message_port(fakeMessagePort);
465 this.all_loaded = true;
466 if (this.on_loaded_callback) {
467 this.on_loaded_callback();
468 }
469 };
470
471 ShadowRealmTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
472 if (this.all_loaded) {
473 callback();
474 } else {
475 this.on_loaded_callback = callback;
476 }
477 };
478
479 /*
480 * JavaScript shells.
481 *
482 * This class is used as the test_environment when testharness is running
483 * inside a JavaScript shell.
484 */
485 function ShellTestEnvironment() {
486 this.name_counter = 0;
487 this.all_loaded = false;
488 this.on_loaded_callback = null;
489 Promise.resolve().then(function() {
490 this.all_loaded = true;
491 if (this.on_loaded_callback) {
492 this.on_loaded_callback();
493 }
494 }.bind(this));
495 this.message_list = [];
496 this.message_ports = [];
497 }
498
499 ShellTestEnvironment.prototype.next_default_test_name = function() {
500 var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
501 this.name_counter++;
502 return get_title() + suffix;
503 };
504
505 ShellTestEnvironment.prototype.on_new_harness_properties = function() {};
506
507 ShellTestEnvironment.prototype.on_tests_ready = function() {};
508
509 ShellTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
510 if (this.all_loaded) {
511 callback();
512 } else {
513 this.on_loaded_callback = callback;
514 }
515 };
516
517 ShellTestEnvironment.prototype.test_timeout = function() {
518 // Tests running in a shell don't have a default timeout, so behave as
519 // if settings.explicit_timeout is true.
520 return null;
521 };
522
523 function create_test_environment() {
524 if ('document' in global_scope) {
525 return new WindowTestEnvironment();
526 }
527 if ('DedicatedWorkerGlobalScope' in global_scope &&
528 global_scope instanceof DedicatedWorkerGlobalScope) {
529 return new DedicatedWorkerTestEnvironment();
530 }
531 if ('SharedWorkerGlobalScope' in global_scope &&
532 global_scope instanceof SharedWorkerGlobalScope) {
533 return new SharedWorkerTestEnvironment();
534 }
535 if ('ServiceWorkerGlobalScope' in global_scope &&
536 global_scope instanceof ServiceWorkerGlobalScope) {
537 return new ServiceWorkerTestEnvironment();
538 }
539 if ('WorkerGlobalScope' in global_scope &&
540 global_scope instanceof WorkerGlobalScope) {
541 return new DedicatedWorkerTestEnvironment();
542 }
543 /* Shadow realm global objects are _ordinary_ objects (i.e. their prototype is
544 * Object) so we don't have a nice `instanceof` test to use; instead, we
545 * check if the there is a GLOBAL.isShadowRealm() property
546 * on the global object. that was set by the test harness when it
547 * created the ShadowRealm.
548 */
549 if (global_scope.GLOBAL && global_scope.GLOBAL.isShadowRealm()) {
550 return new ShadowRealmTestEnvironment();
551 }
552
553 return new ShellTestEnvironment();
554 }
555
556 var test_environment = create_test_environment();
557
558 function is_shared_worker(worker) {
559 return 'SharedWorker' in global_scope && worker instanceof SharedWorker;
560 }
561
562 function is_service_worker(worker) {
563 // The worker object may be from another execution context,
564 // so do not use instanceof here.
565 return 'ServiceWorker' in global_scope &&
566 Object.prototype.toString.call(worker) === '[object ServiceWorker]';
567 }
568
569 var seen_func_name = Object.create(null);
570
571 function get_test_name(func, name)
572 {
573 if (name) {
574 return name;
575 }
576
577 if (func) {
578 var func_code = func.toString();
579
580 // Try and match with brackets, but fallback to matching without
581 var arrow = func_code.match(/^\(\)\s*=>\s*(?:{(.*)}\s*|(.*))$/);
582
583 // Check for JS line separators
584 if (arrow !== null && !/[\u000A\u000D\u2028\u2029]/.test(func_code)) {
585 var trimmed = (arrow[1] !== undefined ? arrow[1] : arrow[2]).trim();
586 // drop trailing ; if there's no earlier ones
587 trimmed = trimmed.replace(/^([^;]*)(;\s*)+$/, "$1");
588
589 if (trimmed) {
590 let name = trimmed;
591 if (seen_func_name[trimmed]) {
592 // This subtest name already exists, so add a suffix.
593 name += " " + seen_func_name[trimmed];
594 } else {
595 seen_func_name[trimmed] = 0;
596 }
597 seen_func_name[trimmed] += 1;
598 return name;
599 }
600 }
601 }
602
603 return test_environment.next_default_test_name();
604 }
605
606 /**
607 * @callback TestFunction
608 * @param {Test} test - The test currnetly being run.
609 * @param {Any[]} args - Additional args to pass to function.
610 *
611 */
612
613 /**
614 * Create a synchronous test
615 *
616 * @param {TestFunction} func - Test function. This is executed
617 * immediately. If it returns without error, the test status is
618 * set to ``PASS``. If it throws an :js:class:`AssertionError`, or
619 * any other exception, the test status is set to ``FAIL``
620 * (typically from an `assert` function).
621 * @param {String} name - Test name. This must be unique in a
622 * given file and must be invariant between runs.
623 */
624 function test(func, name, properties)
625 {
626 if (tests.promise_setup_called) {
627 tests.status.status = tests.status.ERROR;
628 tests.status.message = '`test` invoked after `promise_setup`';
629 tests.complete();
630 }
631 var test_name = get_test_name(func, name);
632 var test_obj = new Test(test_name, properties);
633 var value = test_obj.step(func, test_obj, test_obj);
634
635 if (value !== undefined) {
636 var msg = 'Test named "' + test_name +
637 '" passed a function to `test` that returned a value.';
638
639 try {
640 if (value && typeof value.then === 'function') {
641 msg += ' Consider using `promise_test` instead when ' +
642 'using Promises or async/await.';
643 }
644 } catch (err) {}
645
646 tests.status.status = tests.status.ERROR;
647 tests.status.message = msg;
648 }
649
650 if (test_obj.phase === test_obj.phases.STARTED) {
651 test_obj.done();
652 }
653 }
654
655 /**
656 * Create an asynchronous test
657 *
658 * @param {TestFunction|string} funcOrName - Initial step function
659 * to call immediately with the test name as an argument (if any),
660 * or name of the test.
661 * @param {String} name - Test name (if a test function was
662 * provided). This must be unique in a given file and must be
663 * invariant between runs.
664 * @returns {Test} An object representing the ongoing test.
665 */
666 function async_test(func, name, properties)
667 {
668 if (tests.promise_setup_called) {
669 tests.status.status = tests.status.ERROR;
670 tests.status.message = '`async_test` invoked after `promise_setup`';
671 tests.complete();
672 }
673 if (typeof func !== "function") {
674 properties = name;
675 name = func;
676 func = null;
677 }
678 var test_name = get_test_name(func, name);
679 var test_obj = new Test(test_name, properties);
680 if (func) {
681 var value = test_obj.step(func, test_obj, test_obj);
682
683 // Test authors sometimes return values to async_test, expecting us
684 // to handle the value somehow. Make doing so a harness error to be
685 // clear this is invalid, and point authors to promise_test if it
686 // may be appropriate.
687 //
688 // Note that we only perform this check on the initial function
689 // passed to async_test, not on any later steps - we haven't seen a
690 // consistent problem with those (and it's harder to check).
691 if (value !== undefined) {
692 var msg = 'Test named "' + test_name +
693 '" passed a function to `async_test` that returned a value.';
694
695 try {
696 if (value && typeof value.then === 'function') {
697 msg += ' Consider using `promise_test` instead when ' +
698 'using Promises or async/await.';
699 }
700 } catch (err) {}
701
702 tests.set_status(tests.status.ERROR, msg);
703 tests.complete();
704 }
705 }
706 return test_obj;
707 }
708
709 /**
710 * Create a promise test.
711 *
712 * Promise tests are tests which are represented by a promise
713 * object. If the promise is fulfilled the test passes, if it's
714 * rejected the test fails, otherwise the test passes.
715 *
716 * @param {TestFunction} func - Test function. This must return a
717 * promise. The test is automatically marked as complete once the
718 * promise settles.
719 * @param {String} name - Test name. This must be unique in a
720 * given file and must be invariant between runs.
721 */
722 function promise_test(func, name, properties) {
723 if (typeof func !== "function") {
724 properties = name;
725 name = func;
726 func = null;
727 }
728 var test_name = get_test_name(func, name);
729 var test = new Test(test_name, properties);
730 test._is_promise_test = true;
731
732 // If there is no promise tests queue make one.
733 if (!tests.promise_tests) {
734 tests.promise_tests = Promise.resolve();
735 }
736 tests.promise_tests = tests.promise_tests.then(function() {
737 return new Promise(function(resolve) {
738 var promise = test.step(func, test, test);
739
740 test.step(function() {
741 assert(!!promise, "promise_test", null,
742 "test body must return a 'thenable' object (received ${value})",
743 {value:promise});
744 assert(typeof promise.then === "function", "promise_test", null,
745 "test body must return a 'thenable' object (received an object with no `then` method)",
746 null);
747 });
748
749 // Test authors may use the `step` method within a
750 // `promise_test` even though this reflects a mixture of
751 // asynchronous control flow paradigms. The "done" callback
752 // should be registered prior to the resolution of the
753 // user-provided Promise to avoid timeouts in cases where the
754 // Promise does not settle but a `step` function has thrown an
755 // error.
756 add_test_done_callback(test, resolve);
757
758 Promise.resolve(promise)
759 .catch(test.step_func(
760 function(value) {
761 if (value instanceof AssertionError) {
762 throw value;
763 }
764 assert(false, "promise_test", null,
765 "Unhandled rejection with value: ${value}", {value:value});
766 }))
767 .then(function() {
768 test.done();
769 });
770 });
771 });
772 }
773
774 /**
775 * Make a copy of a Promise in the current realm.
776 *
777 * @param {Promise} promise the given promise that may be from a different
778 * realm
779 * @returns {Promise}
780 *
781 * An arbitrary promise provided by the caller may have originated
782 * in another frame that have since navigated away, rendering the
783 * frame's document inactive. Such a promise cannot be used with
784 * `await` or Promise.resolve(), as microtasks associated with it
785 * may be prevented from being run. See `issue
786 * 5319<https://github.com/whatwg/html/issues/5319>`_ for a
787 * particular case.
788 *
789 * In functions we define here, there is an expectation from the caller
790 * that the promise is from the current realm, that can always be used with
791 * `await`, etc. We therefore create a new promise in this realm that
792 * inherit the value and status from the given promise.
793 */
794
795 function bring_promise_to_current_realm(promise) {
796 return new Promise(promise.then.bind(promise));
797 }
798
799 /**
800 * Assert that a Promise is rejected with the right ECMAScript exception.
801 *
802 * @param {Test} test - the `Test` to use for the assertion.
803 * @param {Function} constructor - The expected exception constructor.
804 * @param {Promise} promise - The promise that's expected to
805 * reject with the given exception.
806 * @param {string} [description] Error message to add to assert in case of
807 * failure.
808 */
809 function promise_rejects_js(test, constructor, promise, description) {
810 return bring_promise_to_current_realm(promise)
811 .then(test.unreached_func("Should have rejected: " + description))
812 .catch(function(e) {
813 assert_throws_js_impl(constructor, function() { throw e; },
814 description, "promise_rejects_js");
815 });
816 }
817
818 /**
819 * Assert that a Promise is rejected with the right DOMException.
820 *
821 * For the remaining arguments, there are two ways of calling
822 * promise_rejects_dom:
823 *
824 * 1) If the DOMException is expected to come from the current global, the
825 * third argument should be the promise expected to reject, and a fourth,
826 * optional, argument is the assertion description.
827 *
828 * 2) If the DOMException is expected to come from some other global, the
829 * third argument should be the DOMException constructor from that global,
830 * the fourth argument the promise expected to reject, and the fifth,
831 * optional, argument the assertion description.
832 *
833 * @param {Test} test - the `Test` to use for the assertion.
834 * @param {number|string} type - See documentation for
835 * `assert_throws_dom <#assert_throws_dom>`_.
836 * @param {Function} promiseOrConstructor - Either the constructor
837 * for the expected exception (if the exception comes from another
838 * global), or the promise that's expected to reject (if the
839 * exception comes from the current global).
840 * @param {Function|string} descriptionOrPromise - Either the
841 * promise that's expected to reject (if the exception comes from
842 * another global), or the optional description of the condition
843 * being tested (if the exception comes from the current global).
844 * @param {string} [description] - Description of the condition
845 * being tested (if the exception comes from another global).
846 *
847 */
848 function promise_rejects_dom(test, type, promiseOrConstructor, descriptionOrPromise, maybeDescription) {
849 let constructor, promise, description;
850 if (typeof promiseOrConstructor === "function" &&
851 promiseOrConstructor.name === "DOMException") {
852 constructor = promiseOrConstructor;
853 promise = descriptionOrPromise;
854 description = maybeDescription;
855 } else {
856 constructor = self.DOMException;
857 promise = promiseOrConstructor;
858 description = descriptionOrPromise;
859 assert(maybeDescription === undefined,
860 "Too many args passed to no-constructor version of promise_rejects_dom, or accidentally explicitly passed undefined");
861 }
862 return bring_promise_to_current_realm(promise)
863 .then(test.unreached_func("Should have rejected: " + description))
864 .catch(function(e) {
865 assert_throws_dom_impl(type, function() { throw e; }, description,
866 "promise_rejects_dom", constructor);
867 });
868 }
869
870 /**
871 * Assert that a Promise is rejected with the provided value.
872 *
873 * @param {Test} test - the `Test` to use for the assertion.
874 * @param {Any} exception - The expected value of the rejected promise.
875 * @param {Promise} promise - The promise that's expected to
876 * reject.
877 * @param {string} [description] Error message to add to assert in case of
878 * failure.
879 */
880 function promise_rejects_exactly(test, exception, promise, description) {
881 return bring_promise_to_current_realm(promise)
882 .then(test.unreached_func("Should have rejected: " + description))
883 .catch(function(e) {
884 assert_throws_exactly_impl(exception, function() { throw e; },
885 description, "promise_rejects_exactly");
886 });
887 }
888
889 /**
890 * Allow DOM events to be handled using Promises.
891 *
892 * This can make it a lot easier to test a very specific series of events,
893 * including ensuring that unexpected events are not fired at any point.
894 *
895 * `EventWatcher` will assert if an event occurs while there is no `wait_for`
896 * created Promise waiting to be fulfilled, or if the event is of a different type
897 * to the type currently expected. This ensures that only the events that are
898 * expected occur, in the correct order, and with the correct timing.
899 *
900 * @constructor
901 * @param {Test} test - The `Test` to use for the assertion.
902 * @param {EventTarget} watchedNode - The target expected to receive the events.
903 * @param {string[]} eventTypes - List of events to watch for.
904 * @param {Promise} timeoutPromise - Promise that will cause the
905 * test to be set to `TIMEOUT` once fulfilled.
906 *
907 */
908 function EventWatcher(test, watchedNode, eventTypes, timeoutPromise)
909 {
910 if (typeof eventTypes === 'string') {
911 eventTypes = [eventTypes];
912 }
913
914 var waitingFor = null;
915
916 // This is null unless we are recording all events, in which case it
917 // will be an Array object.
918 var recordedEvents = null;
919
920 var eventHandler = test.step_func(function(evt) {
921 assert_true(!!waitingFor,
922 'Not expecting event, but got ' + evt.type + ' event');
923 assert_equals(evt.type, waitingFor.types[0],
924 'Expected ' + waitingFor.types[0] + ' event, but got ' +
925 evt.type + ' event instead');
926
927 if (Array.isArray(recordedEvents)) {
928 recordedEvents.push(evt);
929 }
930
931 if (waitingFor.types.length > 1) {
932 // Pop first event from array
933 waitingFor.types.shift();
934 return;
935 }
936 // We need to null out waitingFor before calling the resolve function
937 // since the Promise's resolve handlers may call wait_for() which will
938 // need to set waitingFor.
939 var resolveFunc = waitingFor.resolve;
940 waitingFor = null;
941 // Likewise, we should reset the state of recordedEvents.
942 var result = recordedEvents || evt;
943 recordedEvents = null;
944 resolveFunc(result);
945 });
946
947 for (var i = 0; i < eventTypes.length; i++) {
948 watchedNode.addEventListener(eventTypes[i], eventHandler, false);
949 }
950
951 /**
952 * Returns a Promise that will resolve after the specified event or
953 * series of events has occurred.
954 *
955 * @param {Object} options An optional options object. If the 'record' property
956 * on this object has the value 'all', when the Promise
957 * returned by this function is resolved, *all* Event
958 * objects that were waited for will be returned as an
959 * array.
960 *
961 * @example
962 * const watcher = new EventWatcher(t, div, [ 'animationstart',
963 * 'animationiteration',
964 * 'animationend' ]);
965 * return watcher.wait_for([ 'animationstart', 'animationend' ],
966 * { record: 'all' }).then(evts => {
967 * assert_equals(evts[0].elapsedTime, 0.0);
968 * assert_equals(evts[1].elapsedTime, 2.0);
969 * });
970 */
971 this.wait_for = function(types, options) {
972 if (waitingFor) {
973 return Promise.reject('Already waiting for an event or events');
974 }
975 if (typeof types === 'string') {
976 types = [types];
977 }
978 if (options && options.record && options.record === 'all') {
979 recordedEvents = [];
980 }
981 return new Promise(function(resolve, reject) {
982 var timeout = test.step_func(function() {
983 // If the timeout fires after the events have been received
984 // or during a subsequent call to wait_for, ignore it.
985 if (!waitingFor || waitingFor.resolve !== resolve)
986 return;
987
988 // This should always fail, otherwise we should have
989 // resolved the promise.
990 assert_true(waitingFor.types.length === 0,
991 'Timed out waiting for ' + waitingFor.types.join(', '));
992 var result = recordedEvents;
993 recordedEvents = null;
994 var resolveFunc = waitingFor.resolve;
995 waitingFor = null;
996 resolveFunc(result);
997 });
998
999 if (timeoutPromise) {
1000 timeoutPromise().then(timeout);
1001 }
1002
1003 waitingFor = {
1004 types: types,
1005 resolve: resolve,
1006 reject: reject
1007 };
1008 });
1009 };
1010
1011 /**
1012 * Stop listening for events
1013 */
1014 this.stop_watching = function() {
1015 for (var i = 0; i < eventTypes.length; i++) {
1016 watchedNode.removeEventListener(eventTypes[i], eventHandler, false);
1017 }
1018 };
1019
1020 test._add_cleanup(this.stop_watching);
1021
1022 return this;
1023 }
1024 expose(EventWatcher, 'EventWatcher');
1025
1026 /**
1027 * @typedef {Object} SettingsObject
1028 * @property {bool} single_test - Use the single-page-test
1029 * mode. In this mode the Document represents a single
1030 * `async_test`. Asserts may be used directly without requiring
1031 * `Test.step` or similar wrappers, and any exceptions set the
1032 * status of the test rather than the status of the harness.
1033 * @property {bool} allow_uncaught_exception - don't treat an
1034 * uncaught exception as an error; needed when e.g. testing the
1035 * `window.onerror` handler.
1036 * @property {boolean} explicit_done - Wait for a call to `done()`
1037 * before declaring all tests complete (this is always true for
1038 * single-page tests).
1039 * @property hide_test_state - hide the test state output while
1040 * the test is running; This is helpful when the output of the test state
1041 * may interfere the test results.
1042 * @property {bool} explicit_timeout - disable file timeout; only
1043 * stop waiting for results when the `timeout()` function is
1044 * called This should typically only be set for manual tests, or
1045 * by a test runner that providees its own timeout mechanism.
1046 * @property {number} timeout_multiplier - Multiplier to apply to
1047 * per-test timeouts. This should only be set by a test runner.
1048 * @property {Document} output_document - The document to which
1049 * results should be logged. By default this is the current
1050 * document but could be an ancestor document in some cases e.g. a
1051 * SVG test loaded in an HTML wrapper
1052 *
1053 */
1054
1055 /**
1056 * Configure the harness
1057 *
1058 * @param {Function|SettingsObject} funcOrProperties - Either a
1059 * setup function to run, or a set of properties. If this is a
1060 * function that function is run synchronously. Any exception in
1061 * the function will set the overall harness status to `ERROR`.
1062 * @param {SettingsObject} maybeProperties - An object containing
1063 * the settings to use, if the first argument is a function.
1064 *
1065 */
1066 function setup(func_or_properties, maybe_properties)
1067 {
1068 var func = null;
1069 var properties = {};
1070 if (arguments.length === 2) {
1071 func = func_or_properties;
1072 properties = maybe_properties;
1073 } else if (func_or_properties instanceof Function) {
1074 func = func_or_properties;
1075 } else {
1076 properties = func_or_properties;
1077 }
1078 tests.setup(func, properties);
1079 test_environment.on_new_harness_properties(properties);
1080 }
1081
1082 /**
1083 * Configure the harness, waiting for a promise to resolve
1084 * before running any `promise_test` tests.
1085 *
1086 * @param {Function} func - Function returning a promise that's
1087 * run synchronously. Promise tests are not run until after this
1088 * function has resolved.
1089 * @param {SettingsObject} [properties] - An object containing
1090 * the harness settings to use.
1091 *
1092 */
1093 function promise_setup(func, properties={})
1094 {
1095 if (typeof func !== "function") {
1096 tests.set_status(tests.status.ERROR,
1097 "`promise_setup` invoked without a function");
1098 tests.complete();
1099 return;
1100 }
1101 tests.promise_setup_called = true;
1102
1103 if (!tests.promise_tests) {
1104 tests.promise_tests = Promise.resolve();
1105 }
1106
1107 tests.promise_tests = tests.promise_tests
1108 .then(function()
1109 {
1110 var result;
1111
1112 tests.setup(null, properties);
1113 result = func();
1114 test_environment.on_new_harness_properties(properties);
1115
1116 if (!result || typeof result.then !== "function") {
1117 throw "Non-thenable returned by function passed to `promise_setup`";
1118 }
1119 return result;
1120 })
1121 .catch(function(e)
1122 {
1123 tests.set_status(tests.status.ERROR,
1124 String(e),
1125 e && e.stack);
1126 tests.complete();
1127 });
1128 }
1129
1130 /**
1131 * Mark test loading as complete.
1132 *
1133 * Typically this function is called implicitly on page load; it's
1134 * only necessary for users to call this when either the
1135 * ``explicit_done`` or ``single_page`` properties have been set
1136 * via the :js:func:`setup` function.
1137 *
1138 * For single page tests this marks the test as complete and sets its status.
1139 * For other tests, this marks test loading as complete, but doesn't affect ongoing tests.
1140 */
1141 function done() {
1142 if (tests.tests.length === 0) {
1143 // `done` is invoked after handling uncaught exceptions, so if the
1144 // harness status is already set, the corresponding message is more
1145 // descriptive than the generic message defined here.
1146 if (tests.status.status === null) {
1147 tests.status.status = tests.status.ERROR;
1148 tests.status.message = "done() was called without first defining any tests";
1149 }
1150
1151 tests.complete();
1152 return;
1153 }
1154 if (tests.file_is_test) {
1155 // file is test files never have asynchronous cleanup logic,
1156 // meaning the fully-synchronous `done` function can be used here.
1157 tests.tests[0].done();
1158 }
1159 tests.end_wait();
1160 }
1161
1162 /**
1163 * @deprecated generate a list of tests from a function and list of arguments
1164 *
1165 * This is deprecated because it runs all the tests outside of the test functions
1166 * and as a result any test throwing an exception will result in no tests being
1167 * run. In almost all cases, you should simply call test within the loop you would
1168 * use to generate the parameter list array.
1169 *
1170 * @param {Function} func - The function that will be called for each generated tests.
1171 * @param {Any[][]} args - An array of arrays. Each nested array
1172 * has the structure `[testName, ...testArgs]`. For each of these nested arrays
1173 * array, a test is generated with name `testName` and test function equivalent to
1174 * `func(..testArgs)`.
1175 */
1176 function generate_tests(func, args, properties) {
1177 forEach(args, function(x, i)
1178 {
1179 var name = x[0];
1180 test(function()
1181 {
1182 func.apply(this, x.slice(1));
1183 },
1184 name,
1185 Array.isArray(properties) ? properties[i] : properties);
1186 });
1187 }
1188
1189 /**
1190 * @deprecated
1191 *
1192 * Register a function as a DOM event listener to the
1193 * given object for the event bubbling phase.
1194 *
1195 * @param {EventTarget} object - Event target
1196 * @param {string} event - Event name
1197 * @param {Function} callback - Event handler.
1198 */
1199 function on_event(object, event, callback)
1200 {
1201 object.addEventListener(event, callback, false);
1202 }
1203
1204 // Internal helper function to provide timeout-like functionality in
1205 // environments where there is no setTimeout(). (No timeout ID or
1206 // clearTimeout().)
1207 function fake_set_timeout(callback, delay) {
1208 var p = Promise.resolve();
1209 var start = Date.now();
1210 var end = start + delay;
1211 function check() {
1212 if ((end - Date.now()) > 0) {
1213 p.then(check);
1214 } else {
1215 callback();
1216 }
1217 }
1218 p.then(check);
1219 }
1220
1221 /**
1222 * Global version of :js:func:`Test.step_timeout` for use in single page tests.
1223 *
1224 * @param {Function} func - Function to run after the timeout
1225 * @param {number} timeout - Time in ms to wait before running the
1226 * test step. The actual wait time is ``timeout`` x
1227 * ``timeout_multiplier``.
1228 */
1229 function step_timeout(func, timeout) {
1230 var outer_this = this;
1231 var args = Array.prototype.slice.call(arguments, 2);
1232 var local_set_timeout = typeof global_scope.setTimeout === "undefined" ? fake_set_timeout : setTimeout;
1233 return local_set_timeout(function() {
1234 func.apply(outer_this, args);
1235 }, timeout * tests.timeout_multiplier);
1236 }
1237
1238 expose(test, 'test');
1239 expose(async_test, 'async_test');
1240 expose(promise_test, 'promise_test');
1241 expose(promise_rejects_js, 'promise_rejects_js');
1242 expose(promise_rejects_dom, 'promise_rejects_dom');
1243 expose(promise_rejects_exactly, 'promise_rejects_exactly');
1244 expose(generate_tests, 'generate_tests');
1245 expose(setup, 'setup');
1246 expose(promise_setup, 'promise_setup');
1247 expose(done, 'done');
1248 expose(on_event, 'on_event');
1249 expose(step_timeout, 'step_timeout');
1250
1251 /*
1252 * Return a string truncated to the given length, with ... added at the end
1253 * if it was longer.
1254 */
1255 function truncate(s, len)
1256 {
1257 if (s.length > len) {
1258 return s.substring(0, len - 3) + "...";
1259 }
1260 return s;
1261 }
1262
1263 /*
1264 * Return true if object is probably a Node object.
1265 */
1266 function is_node(object)
1267 {
1268 // I use duck-typing instead of instanceof, because
1269 // instanceof doesn't work if the node is from another window (like an
1270 // iframe's contentWindow):
1271 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=12295
1272 try {
1273 var has_node_properties = ("nodeType" in object &&
1274 "nodeName" in object &&
1275 "nodeValue" in object &&
1276 "childNodes" in object);
1277 } catch (e) {
1278 // We're probably cross-origin, which means we aren't a node
1279 return false;
1280 }
1281
1282 if (has_node_properties) {
1283 try {
1284 object.nodeType;
1285 } catch (e) {
1286 // The object is probably Node.prototype or another prototype
1287 // object that inherits from it, and not a Node instance.
1288 return false;
1289 }
1290 return true;
1291 }
1292 return false;
1293 }
1294
1295 var replacements = {
1296 "0": "0",
1297 "1": "x01",
1298 "2": "x02",
1299 "3": "x03",
1300 "4": "x04",
1301 "5": "x05",
1302 "6": "x06",
1303 "7": "x07",
1304 "8": "b",
1305 "9": "t",
1306 "10": "n",
1307 "11": "v",
1308 "12": "f",
1309 "13": "r",
1310 "14": "x0e",
1311 "15": "x0f",
1312 "16": "x10",
1313 "17": "x11",
1314 "18": "x12",
1315 "19": "x13",
1316 "20": "x14",
1317 "21": "x15",
1318 "22": "x16",
1319 "23": "x17",
1320 "24": "x18",
1321 "25": "x19",
1322 "26": "x1a",
1323 "27": "x1b",
1324 "28": "x1c",
1325 "29": "x1d",
1326 "30": "x1e",
1327 "31": "x1f",
1328 "0xfffd": "ufffd",
1329 "0xfffe": "ufffe",
1330 "0xffff": "uffff",
1331 };
1332
1333 const formatEscapeMap = {
1334 "\\": "\\\\",
1335 '"': '\\"'
1336 };
1337 for (const p in replacements) {
1338 formatEscapeMap[String.fromCharCode(p)] = "\\" + replacements[p];
1339 }
1340 const formatEscapePattern = new RegExp(`[${Object.keys(formatEscapeMap).map(k => k === "\\" ? "\\\\" : k).join("")}]`, "g");
1341
1342 /**
1343 * Convert a value to a nice, human-readable string
1344 *
1345 * When many JavaScript Object values are coerced to a String, the
1346 * resulting value will be ``"[object Object]"``. This obscures
1347 * helpful information, making the coerced value unsuitable for
1348 * use in assertion messages, test names, and debugging
1349 * statements. `format_value` produces more distinctive string
1350 * representations of many kinds of objects, including arrays and
1351 * the more important DOM Node types. It also translates String
1352 * values containing control characters to include human-readable
1353 * representations.
1354 *
1355 * @example
1356 * // "Document node with 2 children"
1357 * format_value(document);
1358 * @example
1359 * // "\"foo\\uffffbar\""
1360 * format_value("foo\uffffbar");
1361 * @example
1362 * // "[-0, Infinity]"
1363 * format_value([-0, Infinity]);
1364 * @param {Any} val - The value to convert to a string.
1365 * @returns {string} - A string representation of ``val``, optimised for human readability.
1366 */
1367 function format_value(val, seen)
1368 {
1369 if (!seen) {
1370 seen = [];
1371 }
1372 if (typeof val === "object" && val !== null) {
1373 if (seen.indexOf(val) >= 0) {
1374 return "[...]";
1375 }
1376 seen.push(val);
1377 }
1378 if (Array.isArray(val)) {
1379 let output = "[";
1380 if (val.beginEllipsis !== undefined) {
1381 output += "…, ";
1382 }
1383 output += val.map(function(x) {return format_value(x, seen);}).join(", ");
1384 if (val.endEllipsis !== undefined) {
1385 output += ", …";
1386 }
1387 return output + "]";
1388 }
1389
1390 switch (typeof val) {
1391 case "string":
1392 return '"' + val.replace(formatEscapePattern, match => formatEscapeMap[match]) + '"';
1393 case "boolean":
1394 case "undefined":
1395 return String(val);
1396 case "number":
1397 // In JavaScript, -0 === 0 and String(-0) == "0", so we have to
1398 // special-case.
1399 if (val === -0 && 1/val === -Infinity) {
1400 return "-0";
1401 }
1402 return String(val);
1403 case "bigint":
1404 return String(val) + 'n';
1405 case "object":
1406 if (val === null) {
1407 return "null";
1408 }
1409
1410 // Special-case Node objects, since those come up a lot in my tests. I
1411 // ignore namespaces.
1412 if (is_node(val)) {
1413 switch (val.nodeType) {
1414 case Node.ELEMENT_NODE:
1415 var ret = "<" + val.localName;
1416 for (var i = 0; i < val.attributes.length; i++) {
1417 ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"';
1418 }
1419 ret += ">" + val.innerHTML + "</" + val.localName + ">";
1420 return "Element node " + truncate(ret, 60);
1421 case Node.TEXT_NODE:
1422 return 'Text node "' + truncate(val.data, 60) + '"';
1423 case Node.PROCESSING_INSTRUCTION_NODE:
1424 return "ProcessingInstruction node with target " + format_value(truncate(val.target, 60)) + " and data " + format_value(truncate(val.data, 60));
1425 case Node.COMMENT_NODE:
1426 return "Comment node <!--" + truncate(val.data, 60) + "-->";
1427 case Node.DOCUMENT_NODE:
1428 return "Document node with " + val.childNodes.length + (val.childNodes.length === 1 ? " child" : " children");
1429 case Node.DOCUMENT_TYPE_NODE:
1430 return "DocumentType node";
1431 case Node.DOCUMENT_FRAGMENT_NODE:
1432 return "DocumentFragment node with " + val.childNodes.length + (val.childNodes.length === 1 ? " child" : " children");
1433 default:
1434 return "Node object of unknown type";
1435 }
1436 }
1437
1438 /* falls through */
1439 default:
1440 try {
1441 return typeof val + ' "' + truncate(String(val), 1000) + '"';
1442 } catch(e) {
1443 return ("[stringifying object threw " + String(e) +
1444 " with type " + String(typeof e) + "]");
1445 }
1446 }
1447 }
1448 expose(format_value, "format_value");
1449
1450 /*
1451 * Assertions
1452 */
1453
1454 function expose_assert(f, name) {
1455 function assert_wrapper(...args) {
1456 let status = Test.statuses.TIMEOUT;
1457 let stack = null;
1458 let new_assert_index = null;
1459 try {
1460 if (settings.debug) {
1461 console.debug("ASSERT", name, tests.current_test && tests.current_test.name, args);
1462 }
1463 if (tests.output) {
1464 tests.set_assert(name, args);
1465 // Remember the newly pushed assert's index, because `apply`
1466 // below might push new asserts.
1467 new_assert_index = tests.asserts_run.length - 1;
1468 }
1469 const rv = f.apply(undefined, args);
1470 status = Test.statuses.PASS;
1471 return rv;
1472 } catch(e) {
1473 status = Test.statuses.FAIL;
1474 stack = e.stack ? e.stack : null;
1475 throw e;
1476 } finally {
1477 if (tests.output && !stack) {
1478 stack = get_stack();
1479 }
1480 if (tests.output) {
1481 tests.set_assert_status(new_assert_index, status, stack);
1482 }
1483 }
1484 }
1485 expose(assert_wrapper, name);
1486 }
1487
1488 /**
1489 * Assert that ``actual`` is strictly true
1490 *
1491 * @param {Any} actual - Value that is asserted to be true
1492 * @param {string} [description] - Description of the condition being tested
1493 */
1494 function assert_true(actual, description)
1495 {
1496 assert(actual === true, "assert_true", description,
1497 "expected true got ${actual}", {actual:actual});
1498 }
1499 expose_assert(assert_true, "assert_true");
1500
1501 /**
1502 * Assert that ``actual`` is strictly false
1503 *
1504 * @param {Any} actual - Value that is asserted to be false
1505 * @param {string} [description] - Description of the condition being tested
1506 */
1507 function assert_false(actual, description)
1508 {
1509 assert(actual === false, "assert_false", description,
1510 "expected false got ${actual}", {actual:actual});
1511 }
1512 expose_assert(assert_false, "assert_false");
1513
1514 function same_value(x, y) {
1515 if (y !== y) {
1516 //NaN case
1517 return x !== x;
1518 }
1519 if (x === 0 && y === 0) {
1520 //Distinguish +0 and -0
1521 return 1/x === 1/y;
1522 }
1523 return x === y;
1524 }
1525
1526 /**
1527 * Assert that ``actual`` is the same value as ``expected``.
1528 *
1529 * For objects this compares by object identity; for primitives
1530 * this distinguishes between 0 and -0, and has correct handling
1531 * of NaN.
1532 *
1533 * @param {Any} actual - Test value.
1534 * @param {Any} expected - Expected value.
1535 * @param {string} [description] - Description of the condition being tested.
1536 */
1537 function assert_equals(actual, expected, description)
1538 {
1539 /*
1540 * Test if two primitives are equal or two objects
1541 * are the same object
1542 */
1543 if (typeof actual != typeof expected) {
1544 assert(false, "assert_equals", description,
1545 "expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}",
1546 {expected:expected, actual:actual});
1547 return;
1548 }
1549 assert(same_value(actual, expected), "assert_equals", description,
1550 "expected ${expected} but got ${actual}",
1551 {expected:expected, actual:actual});
1552 }
1553 expose_assert(assert_equals, "assert_equals");
1554
1555 /**
1556 * Assert that ``actual`` is not the same value as ``expected``.
1557 *
1558 * Comparison is as for :js:func:`assert_equals`.
1559 *
1560 * @param {Any} actual - Test value.
1561 * @param {Any} expected - The value ``actual`` is expected to be different to.
1562 * @param {string} [description] - Description of the condition being tested.
1563 */
1564 function assert_not_equals(actual, expected, description)
1565 {
1566 assert(!same_value(actual, expected), "assert_not_equals", description,
1567 "got disallowed value ${actual}",
1568 {actual:actual});
1569 }
1570 expose_assert(assert_not_equals, "assert_not_equals");
1571
1572 /**
1573 * Assert that ``expected`` is an array and ``actual`` is one of the members.
1574 * This is implemented using ``indexOf``, so doesn't handle NaN or ±0 correctly.
1575 *
1576 * @param {Any} actual - Test value.
1577 * @param {Array} expected - An array that ``actual`` is expected to
1578 * be a member of.
1579 * @param {string} [description] - Description of the condition being tested.
1580 */
1581 function assert_in_array(actual, expected, description)
1582 {
1583 assert(expected.indexOf(actual) != -1, "assert_in_array", description,
1584 "value ${actual} not in array ${expected}",
1585 {actual:actual, expected:expected});
1586 }
1587 expose_assert(assert_in_array, "assert_in_array");
1588
1589 // This function was deprecated in July of 2015.
1590 // See https://github.com/web-platform-tests/wpt/issues/2033
1591 /**
1592 * @deprecated
1593 * Recursively compare two objects for equality.
1594 *
1595 * See `Issue 2033
1596 * <https://github.com/web-platform-tests/wpt/issues/2033>`_ for
1597 * more information.
1598 *
1599 * @param {Object} actual - Test value.
1600 * @param {Object} expected - Expected value.
1601 * @param {string} [description] - Description of the condition being tested.
1602 */
1603 function assert_object_equals(actual, expected, description)
1604 {
1605 assert(typeof actual === "object" && actual !== null, "assert_object_equals", description,
1606 "value is ${actual}, expected object",
1607 {actual: actual});
1608 //This needs to be improved a great deal
1609 function check_equal(actual, expected, stack)
1610 {
1611 stack.push(actual);
1612
1613 var p;
1614 for (p in actual) {
1615 assert(expected.hasOwnProperty(p), "assert_object_equals", description,
1616 "unexpected property ${p}", {p:p});
1617
1618 if (typeof actual[p] === "object" && actual[p] !== null) {
1619 if (stack.indexOf(actual[p]) === -1) {
1620 check_equal(actual[p], expected[p], stack);
1621 }
1622 } else {
1623 assert(same_value(actual[p], expected[p]), "assert_object_equals", description,
1624 "property ${p} expected ${expected} got ${actual}",
1625 {p:p, expected:expected[p], actual:actual[p]});
1626 }
1627 }
1628 for (p in expected) {
1629 assert(actual.hasOwnProperty(p),
1630 "assert_object_equals", description,
1631 "expected property ${p} missing", {p:p});
1632 }
1633 stack.pop();
1634 }
1635 check_equal(actual, expected, []);
1636 }
1637 expose_assert(assert_object_equals, "assert_object_equals");
1638
1639 /**
1640 * Assert that ``actual`` and ``expected`` are both arrays, and that the array properties of
1641 * ``actual`` and ``expected`` are all the same value (as for :js:func:`assert_equals`).
1642 *
1643 * @param {Array} actual - Test array.
1644 * @param {Array} expected - Array that is expected to contain the same values as ``actual``.
1645 * @param {string} [description] - Description of the condition being tested.
1646 */
1647 function assert_array_equals(actual, expected, description)
1648 {
1649 const max_array_length = 20;
1650 function shorten_array(arr, offset = 0) {
1651 // Make ", …" only show up when it would likely reduce the length, not accounting for
1652 // fonts.
1653 if (arr.length < max_array_length + 2) {
1654 return arr;
1655 }
1656 // By default we want half the elements after the offset and half before
1657 // But if that takes us past the end of the array, we have more before, and
1658 // if it takes us before the start we have more after.
1659 const length_after_offset = Math.floor(max_array_length / 2);
1660 let upper_bound = Math.min(length_after_offset + offset, arr.length);
1661 const lower_bound = Math.max(upper_bound - max_array_length, 0);
1662
1663 if (lower_bound === 0) {
1664 upper_bound = max_array_length;
1665 }
1666
1667 const output = arr.slice(lower_bound, upper_bound);
1668 if (lower_bound > 0) {
1669 output.beginEllipsis = true;
1670 }
1671 if (upper_bound < arr.length) {
1672 output.endEllipsis = true;
1673 }
1674 return output;
1675 }
1676
1677 assert(typeof actual === "object" && actual !== null && "length" in actual,
1678 "assert_array_equals", description,
1679 "value is ${actual}, expected array",
1680 {actual:actual});
1681 assert(actual.length === expected.length,
1682 "assert_array_equals", description,
1683 "lengths differ, expected array ${expected} length ${expectedLength}, got ${actual} length ${actualLength}",
1684 {expected:shorten_array(expected, expected.length - 1), expectedLength:expected.length,
1685 actual:shorten_array(actual, actual.length - 1), actualLength:actual.length
1686 });
1687
1688 for (var i = 0; i < actual.length; i++) {
1689 assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),
1690 "assert_array_equals", description,
1691 "expected property ${i} to be ${expected} but was ${actual} (expected array ${arrayExpected} got ${arrayActual})",
1692 {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing",
1693 actual:actual.hasOwnProperty(i) ? "present" : "missing",
1694 arrayExpected:shorten_array(expected, i), arrayActual:shorten_array(actual, i)});
1695 assert(same_value(expected[i], actual[i]),
1696 "assert_array_equals", description,
1697 "expected property ${i} to be ${expected} but got ${actual} (expected array ${arrayExpected} got ${arrayActual})",
1698 {i:i, expected:expected[i], actual:actual[i],
1699 arrayExpected:shorten_array(expected, i), arrayActual:shorten_array(actual, i)});
1700 }
1701 }
1702 expose_assert(assert_array_equals, "assert_array_equals");
1703
1704 /**
1705 * Assert that each array property in ``actual`` is a number within
1706 * ± `epsilon` of the corresponding property in `expected`.
1707 *
1708 * @param {Array} actual - Array of test values.
1709 * @param {Array} expected - Array of values expected to be close to the values in ``actual``.
1710 * @param {number} epsilon - Magnitude of allowed difference
1711 * between each value in ``actual`` and ``expected``.
1712 * @param {string} [description] - Description of the condition being tested.
1713 */
1714 function assert_array_approx_equals(actual, expected, epsilon, description)
1715 {
1716 /*
1717 * Test if two primitive arrays are equal within +/- epsilon
1718 */
1719 assert(actual.length === expected.length,
1720 "assert_array_approx_equals", description,
1721 "lengths differ, expected ${expected} got ${actual}",
1722 {expected:expected.length, actual:actual.length});
1723
1724 for (var i = 0; i < actual.length; i++) {
1725 assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),
1726 "assert_array_approx_equals", description,
1727 "property ${i}, property expected to be ${expected} but was ${actual}",
1728 {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing",
1729 actual:actual.hasOwnProperty(i) ? "present" : "missing"});
1730 assert(typeof actual[i] === "number",
1731 "assert_array_approx_equals", description,
1732 "property ${i}, expected a number but got a ${type_actual}",
1733 {i:i, type_actual:typeof actual[i]});
1734 assert(Math.abs(actual[i] - expected[i]) <= epsilon,
1735 "assert_array_approx_equals", description,
1736 "property ${i}, expected ${expected} +/- ${epsilon}, expected ${expected} but got ${actual}",
1737 {i:i, expected:expected[i], actual:actual[i], epsilon:epsilon});
1738 }
1739 }
1740 expose_assert(assert_array_approx_equals, "assert_array_approx_equals");
1741
1742 /**
1743 * Assert that ``actual`` is within ± ``epsilon`` of ``expected``.
1744 *
1745 * @param {number} actual - Test value.
1746 * @param {number} expected - Value number is expected to be close to.
1747 * @param {number} epsilon - Magnitude of allowed difference between ``actual`` and ``expected``.
1748 * @param {string} [description] - Description of the condition being tested.
1749 */
1750 function assert_approx_equals(actual, expected, epsilon, description)
1751 {
1752 /*
1753 * Test if two primitive numbers are equal within +/- epsilon
1754 */
1755 assert(typeof actual === "number",
1756 "assert_approx_equals", description,
1757 "expected a number but got a ${type_actual}",
1758 {type_actual:typeof actual});
1759
1760 // The epsilon math below does not place nice with NaN and Infinity
1761 // But in this case Infinity = Infinity and NaN = NaN
1762 if (isFinite(actual) || isFinite(expected)) {
1763 assert(Math.abs(actual - expected) <= epsilon,
1764 "assert_approx_equals", description,
1765 "expected ${expected} +/- ${epsilon} but got ${actual}",
1766 {expected:expected, actual:actual, epsilon:epsilon});
1767 } else {
1768 assert_equals(actual, expected);
1769 }
1770 }
1771 expose_assert(assert_approx_equals, "assert_approx_equals");
1772
1773 /**
1774 * Assert that ``actual`` is a number less than ``expected``.
1775 *
1776 * @param {number|bigint} actual - Test value.
1777 * @param {number|bigint} expected - Value that ``actual`` must be less than.
1778 * @param {string} [description] - Description of the condition being tested.
1779 */
1780 function assert_less_than(actual, expected, description)
1781 {
1782 /*
1783 * Test if a primitive number (or bigint) is less than another
1784 */
1785 assert(typeof actual === "number" || typeof actual === "bigint",
1786 "assert_less_than", description,
1787 "expected a number but got a ${type_actual}",
1788 {type_actual:typeof actual});
1789
1790 assert(typeof actual === typeof expected,
1791 "assert_less_than", description,
1792 "expected a ${type_expected} but got a ${type_actual}",
1793 {type_expected:typeof expected, type_actual:typeof actual});
1794
1795 assert(actual < expected,
1796 "assert_less_than", description,
1797 "expected a number less than ${expected} but got ${actual}",
1798 {expected:expected, actual:actual});
1799 }
1800 expose_assert(assert_less_than, "assert_less_than");
1801
1802 /**
1803 * Assert that ``actual`` is a number greater than ``expected``.
1804 *
1805 * @param {number|bigint} actual - Test value.
1806 * @param {number|bigint} expected - Value that ``actual`` must be greater than.
1807 * @param {string} [description] - Description of the condition being tested.
1808 */
1809 function assert_greater_than(actual, expected, description)
1810 {
1811 /*
1812 * Test if a primitive number (or bigint) is greater than another
1813 */
1814 assert(typeof actual === "number" || typeof actual === "bigint",
1815 "assert_greater_than", description,
1816 "expected a number but got a ${type_actual}",
1817 {type_actual:typeof actual});
1818
1819 assert(typeof actual === typeof expected,
1820 "assert_greater_than", description,
1821 "expected a ${type_expected} but got a ${type_actual}",
1822 {type_expected:typeof expected, type_actual:typeof actual});
1823
1824 assert(actual > expected,
1825 "assert_greater_than", description,
1826 "expected a number greater than ${expected} but got ${actual}",
1827 {expected:expected, actual:actual});
1828 }
1829 expose_assert(assert_greater_than, "assert_greater_than");
1830
1831 /**
1832 * Assert that ``actual`` is a number greater than ``lower`` and less
1833 * than ``upper`` but not equal to either.
1834 *
1835 * @param {number|bigint} actual - Test value.
1836 * @param {number|bigint} lower - Value that ``actual`` must be greater than.
1837 * @param {number|bigint} upper - Value that ``actual`` must be less than.
1838 * @param {string} [description] - Description of the condition being tested.
1839 */
1840 function assert_between_exclusive(actual, lower, upper, description)
1841 {
1842 /*
1843 * Test if a primitive number (or bigint) is between two others
1844 */
1845 assert(typeof lower === typeof upper,
1846 "assert_between_exclusive", description,
1847 "expected lower (${type_lower}) and upper (${type_upper}) types to match (test error)",
1848 {type_lower:typeof lower, type_upper:typeof upper});
1849
1850 assert(typeof actual === "number" || typeof actual === "bigint",
1851 "assert_between_exclusive", description,
1852 "expected a number but got a ${type_actual}",
1853 {type_actual:typeof actual});
1854
1855 assert(typeof actual === typeof lower,
1856 "assert_between_exclusive", description,
1857 "expected a ${type_lower} but got a ${type_actual}",
1858 {type_lower:typeof lower, type_actual:typeof actual});
1859
1860 assert(actual > lower && actual < upper,
1861 "assert_between_exclusive", description,
1862 "expected a number greater than ${lower} " +
1863 "and less than ${upper} but got ${actual}",
1864 {lower:lower, upper:upper, actual:actual});
1865 }
1866 expose_assert(assert_between_exclusive, "assert_between_exclusive");
1867
1868 /**
1869 * Assert that ``actual`` is a number less than or equal to ``expected``.
1870 *
1871 * @param {number|bigint} actual - Test value.
1872 * @param {number|bigint} expected - Value that ``actual`` must be less
1873 * than or equal to.
1874 * @param {string} [description] - Description of the condition being tested.
1875 */
1876 function assert_less_than_equal(actual, expected, description)
1877 {
1878 /*
1879 * Test if a primitive number (or bigint) is less than or equal to another
1880 */
1881 assert(typeof actual === "number" || typeof actual === "bigint",
1882 "assert_less_than_equal", description,
1883 "expected a number but got a ${type_actual}",
1884 {type_actual:typeof actual});
1885
1886 assert(typeof actual === typeof expected,
1887 "assert_less_than_equal", description,
1888 "expected a ${type_expected} but got a ${type_actual}",
1889 {type_expected:typeof expected, type_actual:typeof actual});
1890
1891 assert(actual <= expected,
1892 "assert_less_than_equal", description,
1893 "expected a number less than or equal to ${expected} but got ${actual}",
1894 {expected:expected, actual:actual});
1895 }
1896 expose_assert(assert_less_than_equal, "assert_less_than_equal");
1897
1898 /**
1899 * Assert that ``actual`` is a number greater than or equal to ``expected``.
1900 *
1901 * @param {number|bigint} actual - Test value.
1902 * @param {number|bigint} expected - Value that ``actual`` must be greater
1903 * than or equal to.
1904 * @param {string} [description] - Description of the condition being tested.
1905 */
1906 function assert_greater_than_equal(actual, expected, description)
1907 {
1908 /*
1909 * Test if a primitive number (or bigint) is greater than or equal to another
1910 */
1911 assert(typeof actual === "number" || typeof actual === "bigint",
1912 "assert_greater_than_equal", description,
1913 "expected a number but got a ${type_actual}",
1914 {type_actual:typeof actual});
1915
1916 assert(typeof actual === typeof expected,
1917 "assert_greater_than_equal", description,
1918 "expected a ${type_expected} but got a ${type_actual}",
1919 {type_expected:typeof expected, type_actual:typeof actual});
1920
1921 assert(actual >= expected,
1922 "assert_greater_than_equal", description,
1923 "expected a number greater than or equal to ${expected} but got ${actual}",
1924 {expected:expected, actual:actual});
1925 }
1926 expose_assert(assert_greater_than_equal, "assert_greater_than_equal");
1927
1928 /**
1929 * Assert that ``actual`` is a number greater than or equal to ``lower`` and less
1930 * than or equal to ``upper``.
1931 *
1932 * @param {number|bigint} actual - Test value.
1933 * @param {number|bigint} lower - Value that ``actual`` must be greater than or equal to.
1934 * @param {number|bigint} upper - Value that ``actual`` must be less than or equal to.
1935 * @param {string} [description] - Description of the condition being tested.
1936 */
1937 function assert_between_inclusive(actual, lower, upper, description)
1938 {
1939 /*
1940 * Test if a primitive number (or bigint) is between to two others or equal to either of them
1941 */
1942 assert(typeof lower === typeof upper,
1943 "assert_between_inclusive", description,
1944 "expected lower (${type_lower}) and upper (${type_upper}) types to match (test error)",
1945 {type_lower:typeof lower, type_upper:typeof upper});
1946
1947 assert(typeof actual === "number" || typeof actual === "bigint",
1948 "assert_between_inclusive", description,
1949 "expected a number but got a ${type_actual}",
1950 {type_actual:typeof actual});
1951
1952 assert(typeof actual === typeof lower,
1953 "assert_between_inclusive", description,
1954 "expected a ${type_lower} but got a ${type_actual}",
1955 {type_lower:typeof lower, type_actual:typeof actual});
1956
1957 assert(actual >= lower && actual <= upper,
1958 "assert_between_inclusive", description,
1959 "expected a number greater than or equal to ${lower} " +
1960 "and less than or equal to ${upper} but got ${actual}",
1961 {lower:lower, upper:upper, actual:actual});
1962 }
1963 expose_assert(assert_between_inclusive, "assert_between_inclusive");
1964
1965 /**
1966 * Assert that ``actual`` matches the RegExp ``expected``.
1967 *
1968 * @param {String} actual - Test string.
1969 * @param {RegExp} expected - RegExp ``actual`` must match.
1970 * @param {string} [description] - Description of the condition being tested.
1971 */
1972 function assert_regexp_match(actual, expected, description) {
1973 /*
1974 * Test if a string (actual) matches a regexp (expected)
1975 */
1976 assert(expected.test(actual),
1977 "assert_regexp_match", description,
1978 "expected ${expected} but got ${actual}",
1979 {expected:expected, actual:actual});
1980 }
1981 expose_assert(assert_regexp_match, "assert_regexp_match");
1982
1983 /**
1984 * Assert that the class string of ``object`` as returned in
1985 * ``Object.prototype.toString`` is equal to ``class_name``.
1986 *
1987 * @param {Object} object - Object to stringify.
1988 * @param {string} class_string - Expected class string for ``object``.
1989 * @param {string} [description] - Description of the condition being tested.
1990 */
1991 function assert_class_string(object, class_string, description) {
1992 var actual = {}.toString.call(object);
1993 var expected = "[object " + class_string + "]";
1994 assert(same_value(actual, expected), "assert_class_string", description,
1995 "expected ${expected} but got ${actual}",
1996 {expected:expected, actual:actual});
1997 }
1998 expose_assert(assert_class_string, "assert_class_string");
1999
2000 /**
2001 * Assert that ``object`` has an own property with name ``property_name``.
2002 *
2003 * @param {Object} object - Object that should have the given property.
2004 * @param {string} property_name - Expected property name.
2005 * @param {string} [description] - Description of the condition being tested.
2006 */
2007 function assert_own_property(object, property_name, description) {
2008 assert(object.hasOwnProperty(property_name),
2009 "assert_own_property", description,
2010 "expected property ${p} missing", {p:property_name});
2011 }
2012 expose_assert(assert_own_property, "assert_own_property");
2013
2014 /**
2015 * Assert that ``object`` does not have an own property with name ``property_name``.
2016 *
2017 * @param {Object} object - Object that should not have the given property.
2018 * @param {string} property_name - Property name to test.
2019 * @param {string} [description] - Description of the condition being tested.
2020 */
2021 function assert_not_own_property(object, property_name, description) {
2022 assert(!object.hasOwnProperty(property_name),
2023 "assert_not_own_property", description,
2024 "unexpected property ${p} is found on object", {p:property_name});
2025 }
2026 expose_assert(assert_not_own_property, "assert_not_own_property");
2027
2028 function _assert_inherits(name) {
2029 return function (object, property_name, description)
2030 {
2031 assert((typeof object === "object" && object !== null) ||
2032 typeof object === "function" ||
2033 // Or has [[IsHTMLDDA]] slot
2034 String(object) === "[object HTMLAllCollection]",
2035 name, description,
2036 "provided value is not an object");
2037
2038 assert("hasOwnProperty" in object,
2039 name, description,
2040 "provided value is an object but has no hasOwnProperty method");
2041
2042 assert(!object.hasOwnProperty(property_name),
2043 name, description,
2044 "property ${p} found on object expected in prototype chain",
2045 {p:property_name});
2046
2047 assert(property_name in object,
2048 name, description,
2049 "property ${p} not found in prototype chain",
2050 {p:property_name});
2051 };
2052 }
2053
2054 /**
2055 * Assert that ``object`` does not have an own property with name
2056 * ``property_name``, but inherits one through the prototype chain.
2057 *
2058 * @param {Object} object - Object that should have the given property in its prototype chain.
2059 * @param {string} property_name - Expected property name.
2060 * @param {string} [description] - Description of the condition being tested.
2061 */
2062 function assert_inherits(object, property_name, description) {
2063 return _assert_inherits("assert_inherits")(object, property_name, description);
2064 }
2065 expose_assert(assert_inherits, "assert_inherits");
2066
2067 /**
2068 * Alias for :js:func:`insert_inherits`.
2069 *
2070 * @param {Object} object - Object that should have the given property in its prototype chain.
2071 * @param {string} property_name - Expected property name.
2072 * @param {string} [description] - Description of the condition being tested.
2073 */
2074 function assert_idl_attribute(object, property_name, description) {
2075 return _assert_inherits("assert_idl_attribute")(object, property_name, description);
2076 }
2077 expose_assert(assert_idl_attribute, "assert_idl_attribute");
2078
2079
2080 /**
2081 * Assert that ``object`` has a property named ``property_name`` and that the property is not writable or has no setter.
2082 *
2083 * @param {Object} object - Object that should have the given (not necessarily own) property.
2084 * @param {string} property_name - Expected property name.
2085 * @param {string} [description] - Description of the condition being tested.
2086 */
2087 function assert_readonly(object, property_name, description)
2088 {
2089 assert(property_name in object,
2090 "assert_readonly", description,
2091 "property ${p} not found",
2092 {p:property_name});
2093
2094 let desc;
2095 while (object && (desc = Object.getOwnPropertyDescriptor(object, property_name)) === undefined) {
2096 object = Object.getPrototypeOf(object);
2097 }
2098
2099 assert(desc !== undefined,
2100 "assert_readonly", description,
2101 "could not find a descriptor for property ${p}",
2102 {p:property_name});
2103
2104 if (desc.hasOwnProperty("value")) {
2105 // We're a data property descriptor
2106 assert(desc.writable === false, "assert_readonly", description,
2107 "descriptor [[Writable]] expected false got ${actual}", {actual:desc.writable});
2108 } else if (desc.hasOwnProperty("get") || desc.hasOwnProperty("set")) {
2109 // We're an accessor property descriptor
2110 assert(desc.set === undefined, "assert_readonly", description,
2111 "property ${p} is an accessor property with a [[Set]] attribute, cannot test readonly-ness",
2112 {p:property_name});
2113 } else {
2114 // We're a generic property descriptor
2115 // This shouldn't happen, because Object.getOwnPropertyDescriptor
2116 // forwards the return value of [[GetOwnProperty]] (P), which must
2117 // be a fully populated Property Descriptor or Undefined.
2118 assert(false, "assert_readonly", description,
2119 "Object.getOwnPropertyDescriptor must return a fully populated property descriptor");
2120 }
2121 }
2122 expose_assert(assert_readonly, "assert_readonly");
2123
2124 /**
2125 * Assert a JS Error with the expected constructor is thrown.
2126 *
2127 * @param {object} constructor The expected exception constructor.
2128 * @param {Function} func Function which should throw.
2129 * @param {string} [description] Error description for the case that the error is not thrown.
2130 */
2131 function assert_throws_js(constructor, func, description)
2132 {
2133 assert_throws_js_impl(constructor, func, description,
2134 "assert_throws_js");
2135 }
2136 expose_assert(assert_throws_js, "assert_throws_js");
2137
2138 /**
2139 * Like assert_throws_js but allows specifying the assertion type
2140 * (assert_throws_js or promise_rejects_js, in practice).
2141 */
2142 function assert_throws_js_impl(constructor, func, description,
2143 assertion_type)
2144 {
2145 try {
2146 func.call(this);
2147 assert(false, assertion_type, description,
2148 "${func} did not throw", {func:func});
2149 } catch (e) {
2150 if (e instanceof AssertionError) {
2151 throw e;
2152 }
2153
2154 // Basic sanity-checks on the thrown exception.
2155 assert(typeof e === "object",
2156 assertion_type, description,
2157 "${func} threw ${e} with type ${type}, not an object",
2158 {func:func, e:e, type:typeof e});
2159
2160 assert(e !== null,
2161 assertion_type, description,
2162 "${func} threw null, not an object",
2163 {func:func});
2164
2165 // Basic sanity-check on the passed-in constructor
2166 assert(typeof constructor === "function",
2167 assertion_type, description,
2168 "${constructor} is not a constructor",
2169 {constructor:constructor});
2170 var obj = constructor;
2171 while (obj) {
2172 if (typeof obj === "function" &&
2173 obj.name === "Error") {
2174 break;
2175 }
2176 obj = Object.getPrototypeOf(obj);
2177 }
2178 assert(obj != null,
2179 assertion_type, description,
2180 "${constructor} is not an Error subtype",
2181 {constructor:constructor});
2182
2183 // And checking that our exception is reasonable
2184 assert(e.constructor === constructor &&
2185 e.name === constructor.name,
2186 assertion_type, description,
2187 "${func} threw ${actual} (${actual_name}) expected instance of ${expected} (${expected_name})",
2188 {func:func, actual:e, actual_name:e.name,
2189 expected:constructor,
2190 expected_name:constructor.name});
2191 }
2192 }
2193
2194 // TODO: Figure out how to document the overloads better.
2195 // sphinx-js doesn't seem to handle @variation correctly,
2196 // and only expects a single JSDoc entry per function.
2197 /**
2198 * Assert a DOMException with the expected type is thrown.
2199 *
2200 * There are two ways of calling assert_throws_dom:
2201 *
2202 * 1) If the DOMException is expected to come from the current global, the
2203 * second argument should be the function expected to throw and a third,
2204 * optional, argument is the assertion description.
2205 *
2206 * 2) If the DOMException is expected to come from some other global, the
2207 * second argument should be the DOMException constructor from that global,
2208 * the third argument the function expected to throw, and the fourth, optional,
2209 * argument the assertion description.
2210 *
2211 * @param {number|string} type - The expected exception name or
2212 * code. See the `table of names and codes
2213 * <https://webidl.spec.whatwg.org/#dfn-error-names-table>`_. If a
2214 * number is passed it should be one of the numeric code values in
2215 * that table (e.g. 3, 4, etc). If a string is passed it can
2216 * either be an exception name (e.g. "HierarchyRequestError",
2217 * "WrongDocumentError") or the name of the corresponding error
2218 * code (e.g. "``HIERARCHY_REQUEST_ERR``", "``WRONG_DOCUMENT_ERR``").
2219 * @param {Function} descriptionOrFunc - The function expected to
2220 * throw (if the exception comes from another global), or the
2221 * optional description of the condition being tested (if the
2222 * exception comes from the current global).
2223 * @param {string} [description] - Description of the condition
2224 * being tested (if the exception comes from another global).
2225 *
2226 */
2227 function assert_throws_dom(type, funcOrConstructor, descriptionOrFunc, maybeDescription)
2228 {
2229 let constructor, func, description;
2230 if (funcOrConstructor.name === "DOMException") {
2231 constructor = funcOrConstructor;
2232 func = descriptionOrFunc;
2233 description = maybeDescription;
2234 } else {
2235 constructor = self.DOMException;
2236 func = funcOrConstructor;
2237 description = descriptionOrFunc;
2238 assert(maybeDescription === undefined,
2239 "Too many args passed to no-constructor version of assert_throws_dom, or accidentally explicitly passed undefined");
2240 }
2241 assert_throws_dom_impl(type, func, description, "assert_throws_dom", constructor);
2242 }
2243 expose_assert(assert_throws_dom, "assert_throws_dom");
2244
2245 /**
2246 * Similar to assert_throws_dom but allows specifying the assertion type
2247 * (assert_throws_dom or promise_rejects_dom, in practice). The
2248 * "constructor" argument must be the DOMException constructor from the
2249 * global we expect the exception to come from.
2250 */
2251 function assert_throws_dom_impl(type, func, description, assertion_type, constructor)
2252 {
2253 try {
2254 func.call(this);
2255 assert(false, assertion_type, description,
2256 "${func} did not throw", {func:func});
2257 } catch (e) {
2258 if (e instanceof AssertionError) {
2259 throw e;
2260 }
2261
2262 // Basic sanity-checks on the thrown exception.
2263 assert(typeof e === "object",
2264 assertion_type, description,
2265 "${func} threw ${e} with type ${type}, not an object",
2266 {func:func, e:e, type:typeof e});
2267
2268 assert(e !== null,
2269 assertion_type, description,
2270 "${func} threw null, not an object",
2271 {func:func});
2272
2273 // Sanity-check our type
2274 assert(typeof type === "number" ||
2275 typeof type === "string",
2276 assertion_type, description,
2277 "${type} is not a number or string",
2278 {type:type});
2279
2280 var codename_name_map = {
2281 INDEX_SIZE_ERR: 'IndexSizeError',
2282 HIERARCHY_REQUEST_ERR: 'HierarchyRequestError',
2283 WRONG_DOCUMENT_ERR: 'WrongDocumentError',
2284 INVALID_CHARACTER_ERR: 'InvalidCharacterError',
2285 NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',
2286 NOT_FOUND_ERR: 'NotFoundError',
2287 NOT_SUPPORTED_ERR: 'NotSupportedError',
2288 INUSE_ATTRIBUTE_ERR: 'InUseAttributeError',
2289 INVALID_STATE_ERR: 'InvalidStateError',
2290 SYNTAX_ERR: 'SyntaxError',
2291 INVALID_MODIFICATION_ERR: 'InvalidModificationError',
2292 NAMESPACE_ERR: 'NamespaceError',
2293 INVALID_ACCESS_ERR: 'InvalidAccessError',
2294 TYPE_MISMATCH_ERR: 'TypeMismatchError',
2295 SECURITY_ERR: 'SecurityError',
2296 NETWORK_ERR: 'NetworkError',
2297 ABORT_ERR: 'AbortError',
2298 URL_MISMATCH_ERR: 'URLMismatchError',
2299 QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
2300 TIMEOUT_ERR: 'TimeoutError',
2301 INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError',
2302 DATA_CLONE_ERR: 'DataCloneError'
2303 };
2304
2305 var name_code_map = {
2306 IndexSizeError: 1,
2307 HierarchyRequestError: 3,
2308 WrongDocumentError: 4,
2309 InvalidCharacterError: 5,
2310 NoModificationAllowedError: 7,
2311 NotFoundError: 8,
2312 NotSupportedError: 9,
2313 InUseAttributeError: 10,
2314 InvalidStateError: 11,
2315 SyntaxError: 12,
2316 InvalidModificationError: 13,
2317 NamespaceError: 14,
2318 InvalidAccessError: 15,
2319 TypeMismatchError: 17,
2320 SecurityError: 18,
2321 NetworkError: 19,
2322 AbortError: 20,
2323 URLMismatchError: 21,
2324 QuotaExceededError: 22,
2325 TimeoutError: 23,
2326 InvalidNodeTypeError: 24,
2327 DataCloneError: 25,
2328
2329 EncodingError: 0,
2330 NotReadableError: 0,
2331 UnknownError: 0,
2332 ConstraintError: 0,
2333 DataError: 0,
2334 TransactionInactiveError: 0,
2335 ReadOnlyError: 0,
2336 VersionError: 0,
2337 OperationError: 0,
2338 NotAllowedError: 0,
2339 OptOutError: 0
2340 };
2341
2342 var code_name_map = {};
2343 for (var key in name_code_map) {
2344 if (name_code_map[key] > 0) {
2345 code_name_map[name_code_map[key]] = key;
2346 }
2347 }
2348
2349 var required_props = {};
2350 var name;
2351
2352 if (typeof type === "number") {
2353 if (type === 0) {
2354 throw new AssertionError('Test bug: ambiguous DOMException code 0 passed to assert_throws_dom()');
2355 } else if (!(type in code_name_map)) {
2356 throw new AssertionError('Test bug: unrecognized DOMException code "' + type + '" passed to assert_throws_dom()');
2357 }
2358 name = code_name_map[type];
2359 required_props.code = type;
2360 } else if (typeof type === "string") {
2361 name = type in codename_name_map ? codename_name_map[type] : type;
2362 if (!(name in name_code_map)) {
2363 throw new AssertionError('Test bug: unrecognized DOMException code name or name "' + type + '" passed to assert_throws_dom()');
2364 }
2365
2366 required_props.code = name_code_map[name];
2367 }
2368
2369 if (required_props.code === 0 ||
2370 ("name" in e &&
2371 e.name !== e.name.toUpperCase() &&
2372 e.name !== "DOMException")) {
2373 // New style exception: also test the name property.
2374 required_props.name = name;
2375 }
2376
2377 for (var prop in required_props) {
2378 assert(prop in e && e[prop] == required_props[prop],
2379 assertion_type, description,
2380 "${func} threw ${e} that is not a DOMException " + type + ": property ${prop} is equal to ${actual}, expected ${expected}",
2381 {func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]});
2382 }
2383
2384 // Check that the exception is from the right global. This check is last
2385 // so more specific, and more informative, checks on the properties can
2386 // happen in case a totally incorrect exception is thrown.
2387 assert(e.constructor === constructor,
2388 assertion_type, description,
2389 "${func} threw an exception from the wrong global",
2390 {func});
2391
2392 }
2393 }
2394
2395 /**
2396 * Assert the provided value is thrown.
2397 *
2398 * @param {value} exception The expected exception.
2399 * @param {Function} func Function which should throw.
2400 * @param {string} [description] Error description for the case that the error is not thrown.
2401 */
2402 function assert_throws_exactly(exception, func, description)
2403 {
2404 assert_throws_exactly_impl(exception, func, description,
2405 "assert_throws_exactly");
2406 }
2407 expose_assert(assert_throws_exactly, "assert_throws_exactly");
2408
2409 /**
2410 * Like assert_throws_exactly but allows specifying the assertion type
2411 * (assert_throws_exactly or promise_rejects_exactly, in practice).
2412 */
2413 function assert_throws_exactly_impl(exception, func, description,
2414 assertion_type)
2415 {
2416 try {
2417 func.call(this);
2418 assert(false, assertion_type, description,
2419 "${func} did not throw", {func:func});
2420 } catch (e) {
2421 if (e instanceof AssertionError) {
2422 throw e;
2423 }
2424
2425 assert(same_value(e, exception), assertion_type, description,
2426 "${func} threw ${e} but we expected it to throw ${exception}",
2427 {func:func, e:e, exception:exception});
2428 }
2429 }
2430
2431 /**
2432 * Asserts if called. Used to ensure that a specific codepath is
2433 * not taken e.g. that an error event isn't fired.
2434 *
2435 * @param {string} [description] - Description of the condition being tested.
2436 */
2437 function assert_unreached(description) {
2438 assert(false, "assert_unreached", description,
2439 "Reached unreachable code");
2440 }
2441 expose_assert(assert_unreached, "assert_unreached");
2442
2443 /**
2444 * @callback AssertFunc
2445 * @param {Any} actual
2446 * @param {Any} expected
2447 * @param {Any[]} args
2448 */
2449
2450 /**
2451 * Asserts that ``actual`` matches at least one value of ``expected``
2452 * according to a comparison defined by ``assert_func``.
2453 *
2454 * Note that tests with multiple allowed pass conditions are bad
2455 * practice unless the spec specifically allows multiple
2456 * behaviours. Test authors should not use this method simply to
2457 * hide UA bugs.
2458 *
2459 * @param {AssertFunc} assert_func - Function to compare actual
2460 * and expected. It must throw when the comparison fails and
2461 * return when the comparison passes.
2462 * @param {Any} actual - Test value.
2463 * @param {Array} expected_array - Array of possible expected values.
2464 * @param {Any[]} args - Additional arguments to pass to ``assert_func``.
2465 */
2466 function assert_any(assert_func, actual, expected_array, ...args)
2467 {
2468 var errors = [];
2469 var passed = false;
2470 forEach(expected_array,
2471 function(expected)
2472 {
2473 try {
2474 assert_func.apply(this, [actual, expected].concat(args));
2475 passed = true;
2476 } catch (e) {
2477 errors.push(e.message);
2478 }
2479 });
2480 if (!passed) {
2481 throw new AssertionError(errors.join("\n\n"));
2482 }
2483 }
2484 // FIXME: assert_any cannot use expose_assert, because assert_wrapper does
2485 // not support nested assert calls (e.g. to assert_func). We need to
2486 // support bypassing assert_wrapper for the inner asserts here.
2487 expose(assert_any, "assert_any");
2488
2489 /**
2490 * Assert that a feature is implemented, based on a 'truthy' condition.
2491 *
2492 * This function should be used to early-exit from tests in which there is
2493 * no point continuing without support for a non-optional spec or spec
2494 * feature. For example:
2495 *
2496 * assert_implements(window.Foo, 'Foo is not supported');
2497 *
2498 * @param {object} condition The truthy value to test
2499 * @param {string} [description] Error description for the case that the condition is not truthy.
2500 */
2501 function assert_implements(condition, description) {
2502 assert(!!condition, "assert_implements", description);
2503 }
2504 expose_assert(assert_implements, "assert_implements");
2505
2506 /**
2507 * Assert that an optional feature is implemented, based on a 'truthy' condition.
2508 *
2509 * This function should be used to early-exit from tests in which there is
2510 * no point continuing without support for an explicitly optional spec or
2511 * spec feature. For example:
2512 *
2513 * assert_implements_optional(video.canPlayType("video/webm"),
2514 * "webm video playback not supported");
2515 *
2516 * @param {object} condition The truthy value to test
2517 * @param {string} [description] Error description for the case that the condition is not truthy.
2518 */
2519 function assert_implements_optional(condition, description) {
2520 if (!condition) {
2521 throw new OptionalFeatureUnsupportedError(description);
2522 }
2523 }
2524 expose_assert(assert_implements_optional, "assert_implements_optional");
2525
2526 /**
2527 * @class
2528 *
2529 * A single subtest. A Test is not constructed directly but via the
2530 * :js:func:`test`, :js:func:`async_test` or :js:func:`promise_test` functions.
2531 *
2532 * @param {string} name - This must be unique in a given file and must be
2533 * invariant between runs.
2534 *
2535 */
2536 function Test(name, properties)
2537 {
2538 if (tests.file_is_test && tests.tests.length) {
2539 throw new Error("Tried to create a test with file_is_test");
2540 }
2541 /** The test name. */
2542 this.name = name;
2543
2544 this.phase = (tests.is_aborted || tests.phase === tests.phases.COMPLETE) ?
2545 this.phases.COMPLETE : this.phases.INITIAL;
2546
2547 /** The test status code.*/
2548 this.status = this.NOTRUN;
2549 this.timeout_id = null;
2550 this.index = null;
2551
2552 this.properties = properties || {};
2553 this.timeout_length = settings.test_timeout;
2554 if (this.timeout_length !== null) {
2555 this.timeout_length *= tests.timeout_multiplier;
2556 }
2557
2558 /** A message indicating the reason for test failure. */
2559 this.message = null;
2560 /** Stack trace in case of failure. */
2561 this.stack = null;
2562
2563 this.steps = [];
2564 this._is_promise_test = false;
2565
2566 this.cleanup_callbacks = [];
2567 this._user_defined_cleanup_count = 0;
2568 this._done_callbacks = [];
2569
2570 if (typeof AbortController === "function") {
2571 this._abortController = new AbortController();
2572 }
2573
2574 // Tests declared following harness completion are likely an indication
2575 // of a programming error, but they cannot be reported
2576 // deterministically.
2577 if (tests.phase === tests.phases.COMPLETE) {
2578 return;
2579 }
2580
2581 tests.push(this);
2582 }
2583
2584 /**
2585 * Enum of possible test statuses.
2586 *
2587 * :values:
2588 * - ``PASS``
2589 * - ``FAIL``
2590 * - ``TIMEOUT``
2591 * - ``NOTRUN``
2592 * - ``PRECONDITION_FAILED``
2593 */
2594 Test.statuses = {
2595 PASS:0,
2596 FAIL:1,
2597 TIMEOUT:2,
2598 NOTRUN:3,
2599 PRECONDITION_FAILED:4
2600 };
2601
2602 Test.prototype = merge({}, Test.statuses);
2603
2604 Test.prototype.phases = {
2605 INITIAL:0,
2606 STARTED:1,
2607 HAS_RESULT:2,
2608 CLEANING:3,
2609 COMPLETE:4
2610 };
2611
2612 Test.prototype.status_formats = {
2613 0: "Pass",
2614 1: "Fail",
2615 2: "Timeout",
2616 3: "Not Run",
2617 4: "Optional Feature Unsupported",
2618 };
2619
2620 Test.prototype.format_status = function() {
2621 return this.status_formats[this.status];
2622 };
2623
2624 Test.prototype.structured_clone = function()
2625 {
2626 if (!this._structured_clone) {
2627 var msg = this.message;
2628 msg = msg ? String(msg) : msg;
2629 this._structured_clone = merge({
2630 name:String(this.name),
2631 properties:merge({}, this.properties),
2632 phases:merge({}, this.phases)
2633 }, Test.statuses);
2634 }
2635 this._structured_clone.status = this.status;
2636 this._structured_clone.message = this.message;
2637 this._structured_clone.stack = this.stack;
2638 this._structured_clone.index = this.index;
2639 this._structured_clone.phase = this.phase;
2640 return this._structured_clone;
2641 };
2642
2643 /**
2644 * Run a single step of an ongoing test.
2645 *
2646 * @param {string} func - Callback function to run as a step. If
2647 * this throws an :js:func:`AssertionError`, or any other
2648 * exception, the :js:class:`Test` status is set to ``FAIL``.
2649 * @param {Object} [this_obj] - The object to use as the this
2650 * value when calling ``func``. Defaults to the :js:class:`Test` object.
2651 */
2652 Test.prototype.step = function(func, this_obj)
2653 {
2654 if (this.phase > this.phases.STARTED) {
2655 return;
2656 }
2657
2658 if (settings.debug && this.phase !== this.phases.STARTED) {
2659 console.log("TEST START", this.name);
2660 }
2661 this.phase = this.phases.STARTED;
2662 //If we don't get a result before the harness times out that will be a test timeout
2663 this.set_status(this.TIMEOUT, "Test timed out");
2664
2665 tests.started = true;
2666 tests.current_test = this;
2667 tests.notify_test_state(this);
2668
2669 if (this.timeout_id === null) {
2670 this.set_timeout();
2671 }
2672
2673 this.steps.push(func);
2674
2675 if (arguments.length === 1) {
2676 this_obj = this;
2677 }
2678
2679 if (settings.debug) {
2680 console.debug("TEST STEP", this.name);
2681 }
2682
2683 try {
2684 return func.apply(this_obj, Array.prototype.slice.call(arguments, 2));
2685 } catch (e) {
2686 if (this.phase >= this.phases.HAS_RESULT) {
2687 return;
2688 }
2689 var status = e instanceof OptionalFeatureUnsupportedError ? this.PRECONDITION_FAILED : this.FAIL;
2690 var message = String((typeof e === "object" && e !== null) ? e.message : e);
2691 var stack = e.stack ? e.stack : null;
2692
2693 this.set_status(status, message, stack);
2694 this.phase = this.phases.HAS_RESULT;
2695 this.done();
2696 } finally {
2697 this.current_test = null;
2698 }
2699 };
2700
2701 /**
2702 * Wrap a function so that it runs as a step of the current test.
2703 *
2704 * This allows creating a callback function that will run as a
2705 * test step.
2706 *
2707 * @example
2708 * let t = async_test("Example");
2709 * onload = t.step_func(e => {
2710 * assert_equals(e.name, "load");
2711 * // Mark the test as complete.
2712 * t.done();
2713 * })
2714 *
2715 * @param {string} func - Function to run as a step. If this
2716 * throws an :js:func:`AssertionError`, or any other exception,
2717 * the :js:class:`Test` status is set to ``FAIL``.
2718 * @param {Object} [this_obj] - The object to use as the this
2719 * value when calling ``func``. Defaults to the :js:class:`Test` object.
2720 */
2721 Test.prototype.step_func = function(func, this_obj)
2722 {
2723 var test_this = this;
2724
2725 if (arguments.length === 1) {
2726 this_obj = test_this;
2727 }
2728
2729 return function()
2730 {
2731 return test_this.step.apply(test_this, [func, this_obj].concat(
2732 Array.prototype.slice.call(arguments)));
2733 };
2734 };
2735
2736 /**
2737 * Wrap a function so that it runs as a step of the current test,
2738 * and automatically marks the test as complete if the function
2739 * returns without error.
2740 *
2741 * @param {string} func - Function to run as a step. If this
2742 * throws an :js:func:`AssertionError`, or any other exception,
2743 * the :js:class:`Test` status is set to ``FAIL``. If it returns
2744 * without error the status is set to ``PASS``.
2745 * @param {Object} [this_obj] - The object to use as the this
2746 * value when calling `func`. Defaults to the :js:class:`Test` object.
2747 */
2748 Test.prototype.step_func_done = function(func, this_obj)
2749 {
2750 var test_this = this;
2751
2752 if (arguments.length === 1) {
2753 this_obj = test_this;
2754 }
2755
2756 return function()
2757 {
2758 if (func) {
2759 test_this.step.apply(test_this, [func, this_obj].concat(
2760 Array.prototype.slice.call(arguments)));
2761 }
2762 test_this.done();
2763 };
2764 };
2765
2766 /**
2767 * Return a function that automatically sets the current test to
2768 * ``FAIL`` if it's called.
2769 *
2770 * @param {string} [description] - Error message to add to assert
2771 * in case of failure.
2772 *
2773 */
2774 Test.prototype.unreached_func = function(description)
2775 {
2776 return this.step_func(function() {
2777 assert_unreached(description);
2778 });
2779 };
2780
2781 /**
2782 * Run a function as a step of the test after a given timeout.
2783 *
2784 * This multiplies the timeout by the global timeout multiplier to
2785 * account for the expected execution speed of the current test
2786 * environment. For example ``test.step_timeout(f, 2000)`` with a
2787 * timeout multiplier of 2 will wait for 4000ms before calling ``f``.
2788 *
2789 * In general it's encouraged to use :js:func:`Test.step_wait` or
2790 * :js:func:`step_wait_func` in preference to this function where possible,
2791 * as they provide better test performance.
2792 *
2793 * @param {Function} func - Function to run as a test
2794 * step.
2795 * @param {number} timeout - Time in ms to wait before running the
2796 * test step. The actual wait time is ``timeout`` x
2797 * ``timeout_multiplier``.
2798 *
2799 */
2800 Test.prototype.step_timeout = function(func, timeout) {
2801 var test_this = this;
2802 var args = Array.prototype.slice.call(arguments, 2);
2803 var local_set_timeout = typeof global_scope.setTimeout === "undefined" ? fake_set_timeout : setTimeout;
2804 return local_set_timeout(this.step_func(function() {
2805 return func.apply(test_this, args);
2806 }), timeout * tests.timeout_multiplier);
2807 };
2808
2809 /**
2810 * Poll for a function to return true, and call a callback
2811 * function once it does, or assert if a timeout is
2812 * reached. This is preferred over a simple step_timeout
2813 * whenever possible since it allows the timeout to be longer
2814 * to reduce intermittents without compromising test execution
2815 * speed when the condition is quickly met.
2816 *
2817 * @param {Function} cond A function taking no arguments and
2818 * returning a boolean or a Promise. The callback is
2819 * called when this function returns true, or the
2820 * returned Promise is resolved with true.
2821 * @param {Function} func A function taking no arguments to call once
2822 * the condition is met.
2823 * @param {string} [description] Error message to add to assert in case of
2824 * failure.
2825 * @param {number} timeout Timeout in ms. This is multiplied by the global
2826 * timeout_multiplier
2827 * @param {number} interval Polling interval in ms
2828 *
2829 */
2830 Test.prototype.step_wait_func = function(cond, func, description,
2831 timeout=3000, interval=100) {
2832 var timeout_full = timeout * tests.timeout_multiplier;
2833 var remaining = Math.ceil(timeout_full / interval);
2834 var test_this = this;
2835 var local_set_timeout = typeof global_scope.setTimeout === 'undefined' ? fake_set_timeout : setTimeout;
2836
2837 const step = test_this.step_func((result) => {
2838 if (result) {
2839 func();
2840 } else {
2841 if (remaining === 0) {
2842 assert(false, "step_wait_func", description,
2843 "Timed out waiting on condition");
2844 }
2845 remaining--;
2846 local_set_timeout(wait_for_inner, interval);
2847 }
2848 });
2849
2850 var wait_for_inner = test_this.step_func(() => {
2851 Promise.resolve(cond()).then(
2852 step,
2853 test_this.unreached_func("step_wait_func"));
2854 });
2855
2856 wait_for_inner();
2857 };
2858
2859 /**
2860 * Poll for a function to return true, and invoke a callback
2861 * followed by this.done() once it does, or assert if a timeout
2862 * is reached. This is preferred over a simple step_timeout
2863 * whenever possible since it allows the timeout to be longer
2864 * to reduce intermittents without compromising test execution speed
2865 * when the condition is quickly met.
2866 *
2867 * @example
2868 * async_test(t => {
2869 * const popup = window.open("resources/coop-coep.py?coop=same-origin&coep=&navigate=about:blank");
2870 * t.add_cleanup(() => popup.close());
2871 * assert_equals(window, popup.opener);
2872 *
2873 * popup.onload = t.step_func(() => {
2874 * assert_true(popup.location.href.endsWith("&navigate=about:blank"));
2875 * // Use step_wait_func_done as about:blank cannot message back.
2876 * t.step_wait_func_done(() => popup.location.href === "about:blank");
2877 * });
2878 * }, "Navigating a popup to about:blank");
2879 *
2880 * @param {Function} cond A function taking no arguments and
2881 * returning a boolean or a Promise. The callback is
2882 * called when this function returns true, or the
2883 * returned Promise is resolved with true.
2884 * @param {Function} func A function taking no arguments to call once
2885 * the condition is met.
2886 * @param {string} [description] Error message to add to assert in case of
2887 * failure.
2888 * @param {number} timeout Timeout in ms. This is multiplied by the global
2889 * timeout_multiplier
2890 * @param {number} interval Polling interval in ms
2891 *
2892 */
2893 Test.prototype.step_wait_func_done = function(cond, func, description,
2894 timeout=3000, interval=100) {
2895 this.step_wait_func(cond, () => {
2896 if (func) {
2897 func();
2898 }
2899 this.done();
2900 }, description, timeout, interval);
2901 };
2902
2903 /**
2904 * Poll for a function to return true, and resolve a promise
2905 * once it does, or assert if a timeout is reached. This is
2906 * preferred over a simple step_timeout whenever possible
2907 * since it allows the timeout to be longer to reduce
2908 * intermittents without compromising test execution speed
2909 * when the condition is quickly met.
2910 *
2911 * @example
2912 * promise_test(async t => {
2913 * // …
2914 * await t.step_wait(() => frame.contentDocument === null, "Frame navigated to a cross-origin document");
2915 * // …
2916 * }, "");
2917 *
2918 * @param {Function} cond A function taking no arguments and
2919 * returning a boolean or a Promise.
2920 * @param {string} [description] Error message to add to assert in case of
2921 * failure.
2922 * @param {number} timeout Timeout in ms. This is multiplied by the global
2923 * timeout_multiplier
2924 * @param {number} interval Polling interval in ms
2925 * @returns {Promise} Promise resolved once cond is met.
2926 *
2927 */
2928 Test.prototype.step_wait = function(cond, description, timeout=3000, interval=100) {
2929 return new Promise(resolve => {
2930 this.step_wait_func(cond, resolve, description, timeout, interval);
2931 });
2932 };
2933
2934 /*
2935 * Private method for registering cleanup functions. `testharness.js`
2936 * internals should use this method instead of the public `add_cleanup`
2937 * method in order to hide implementation details from the harness status
2938 * message in the case errors.
2939 */
2940 Test.prototype._add_cleanup = function(callback) {
2941 this.cleanup_callbacks.push(callback);
2942 };
2943
2944 /**
2945 * Schedule a function to be run after the test result is known, regardless
2946 * of passing or failing state.
2947 *
2948 * The behavior of this function will not
2949 * influence the result of the test, but if an exception is thrown, the
2950 * test harness will report an error.
2951 *
2952 * @param {Function} callback - The cleanup function to run. This
2953 * is called with no arguments.
2954 */
2955 Test.prototype.add_cleanup = function(callback) {
2956 this._user_defined_cleanup_count += 1;
2957 this._add_cleanup(callback);
2958 };
2959
2960 Test.prototype.set_timeout = function()
2961 {
2962 if (this.timeout_length !== null) {
2963 var this_obj = this;
2964 this.timeout_id = setTimeout(function()
2965 {
2966 this_obj.timeout();
2967 }, this.timeout_length);
2968 }
2969 };
2970
2971 Test.prototype.set_status = function(status, message, stack)
2972 {
2973 this.status = status;
2974 this.message = message;
2975 this.stack = stack ? stack : null;
2976 };
2977
2978 /**
2979 * Manually set the test status to ``TIMEOUT``.
2980 */
2981 Test.prototype.timeout = function()
2982 {
2983 this.timeout_id = null;
2984 this.set_status(this.TIMEOUT, "Test timed out");
2985 this.phase = this.phases.HAS_RESULT;
2986 this.done();
2987 };
2988
2989 /**
2990 * Manually set the test status to ``TIMEOUT``.
2991 *
2992 * Alias for `Test.timeout <#Test.timeout>`_.
2993 */
2994 Test.prototype.force_timeout = function() {
2995 return this.timeout();
2996 };
2997
2998 /**
2999 * Mark the test as complete.
3000 *
3001 * This sets the test status to ``PASS`` if no other status was
3002 * already recorded. Any subsequent attempts to run additional
3003 * test steps will be ignored.
3004 *
3005 * After setting the test status any test cleanup functions will
3006 * be run.
3007 */
3008 Test.prototype.done = function()
3009 {
3010 if (this.phase >= this.phases.CLEANING) {
3011 return;
3012 }
3013
3014 if (this.phase <= this.phases.STARTED) {
3015 this.set_status(this.PASS, null);
3016 }
3017
3018 if (global_scope.clearTimeout) {
3019 clearTimeout(this.timeout_id);
3020 }
3021
3022 if (settings.debug) {
3023 console.log("TEST DONE",
3024 this.status,
3025 this.name);
3026 }
3027
3028 this.cleanup();
3029 };
3030
3031 function add_test_done_callback(test, callback)
3032 {
3033 if (test.phase === test.phases.COMPLETE) {
3034 callback();
3035 return;
3036 }
3037
3038 test._done_callbacks.push(callback);
3039 }
3040
3041 /*
3042 * Invoke all specified cleanup functions. If one or more produce an error,
3043 * the context is in an unpredictable state, so all further testing should
3044 * be cancelled.
3045 */
3046 Test.prototype.cleanup = function() {
3047 var errors = [];
3048 var bad_value_count = 0;
3049 function on_error(e) {
3050 errors.push(e);
3051 // Abort tests immediately so that tests declared within subsequent
3052 // cleanup functions are not run.
3053 tests.abort();
3054 }
3055 var this_obj = this;
3056 var results = [];
3057
3058 this.phase = this.phases.CLEANING;
3059
3060 if (this._abortController) {
3061 this._abortController.abort("Test cleanup");
3062 }
3063
3064 forEach(this.cleanup_callbacks,
3065 function(cleanup_callback) {
3066 var result;
3067
3068 try {
3069 result = cleanup_callback();
3070 } catch (e) {
3071 on_error(e);
3072 return;
3073 }
3074
3075 if (!is_valid_cleanup_result(this_obj, result)) {
3076 bad_value_count += 1;
3077 // Abort tests immediately so that tests declared
3078 // within subsequent cleanup functions are not run.
3079 tests.abort();
3080 }
3081
3082 results.push(result);
3083 });
3084
3085 if (!this._is_promise_test) {
3086 cleanup_done(this_obj, errors, bad_value_count);
3087 } else {
3088 all_async(results,
3089 function(result, done) {
3090 if (result && typeof result.then === "function") {
3091 result
3092 .then(null, on_error)
3093 .then(done);
3094 } else {
3095 done();
3096 }
3097 },
3098 function() {
3099 cleanup_done(this_obj, errors, bad_value_count);
3100 });
3101 }
3102 };
3103
3104 /*
3105 * Determine if the return value of a cleanup function is valid for a given
3106 * test. Any test may return the value `undefined`. Tests created with
3107 * `promise_test` may alternatively return "thenable" object values.
3108 */
3109 function is_valid_cleanup_result(test, result) {
3110 if (result === undefined) {
3111 return true;
3112 }
3113
3114 if (test._is_promise_test) {
3115 return result && typeof result.then === "function";
3116 }
3117
3118 return false;
3119 }
3120
3121 function cleanup_done(test, errors, bad_value_count) {
3122 if (errors.length || bad_value_count) {
3123 var total = test._user_defined_cleanup_count;
3124
3125 tests.status.status = tests.status.ERROR;
3126 tests.status.stack = null;
3127 tests.status.message = "Test named '" + test.name +
3128 "' specified " + total +
3129 " 'cleanup' function" + (total > 1 ? "s" : "");
3130
3131 if (errors.length) {
3132 tests.status.message += ", and " + errors.length + " failed";
3133 tests.status.stack = ((typeof errors[0] === "object" &&
3134 errors[0].hasOwnProperty("stack")) ?
3135 errors[0].stack : null);
3136 }
3137
3138 if (bad_value_count) {
3139 var type = test._is_promise_test ?
3140 "non-thenable" : "non-undefined";
3141 tests.status.message += ", and " + bad_value_count +
3142 " returned a " + type + " value";
3143 }
3144
3145 tests.status.message += ".";
3146 }
3147
3148 test.phase = test.phases.COMPLETE;
3149 tests.result(test);
3150 forEach(test._done_callbacks,
3151 function(callback) {
3152 callback();
3153 });
3154 test._done_callbacks.length = 0;
3155 }
3156
3157 /**
3158 * Gives an AbortSignal that will be aborted when the test finishes.
3159 */
3160 Test.prototype.get_signal = function() {
3161 if (!this._abortController) {
3162 throw new Error("AbortController is not supported in this browser");
3163 }
3164 return this._abortController.signal;
3165 };
3166
3167 /**
3168 * A RemoteTest object mirrors a Test object on a remote worker. The
3169 * associated RemoteWorker updates the RemoteTest object in response to
3170 * received events. In turn, the RemoteTest object replicates these events
3171 * on the local document. This allows listeners (test result reporting
3172 * etc..) to transparently handle local and remote events.
3173 */
3174 function RemoteTest(clone) {
3175 var this_obj = this;
3176 Object.keys(clone).forEach(
3177 function(key) {
3178 this_obj[key] = clone[key];
3179 });
3180 this.index = null;
3181 this.phase = this.phases.INITIAL;
3182 this.update_state_from(clone);
3183 this._done_callbacks = [];
3184 tests.push(this);
3185 }
3186
3187 RemoteTest.prototype.structured_clone = function() {
3188 var clone = {};
3189 Object.keys(this).forEach(
3190 (function(key) {
3191 var value = this[key];
3192 // `RemoteTest` instances are responsible for managing
3193 // their own "done" callback functions, so those functions
3194 // are not relevant in other execution contexts. Because of
3195 // this (and because Function values cannot be serialized
3196 // for cross-realm transmittance), the property should not
3197 // be considered when cloning instances.
3198 if (key === '_done_callbacks' ) {
3199 return;
3200 }
3201
3202 if (typeof value === "object" && value !== null) {
3203 clone[key] = merge({}, value);
3204 } else {
3205 clone[key] = value;
3206 }
3207 }).bind(this));
3208 clone.phases = merge({}, this.phases);
3209 return clone;
3210 };
3211
3212 /**
3213 * `RemoteTest` instances are objects which represent tests running in
3214 * another realm. They do not define "cleanup" functions (if necessary,
3215 * such functions are defined on the associated `Test` instance within the
3216 * external realm). However, `RemoteTests` may have "done" callbacks (e.g.
3217 * as attached by the `Tests` instance responsible for tracking the overall
3218 * test status in the parent realm). The `cleanup` method delegates to
3219 * `done` in order to ensure that such callbacks are invoked following the
3220 * completion of the `RemoteTest`.
3221 */
3222 RemoteTest.prototype.cleanup = function() {
3223 this.done();
3224 };
3225 RemoteTest.prototype.phases = Test.prototype.phases;
3226 RemoteTest.prototype.update_state_from = function(clone) {
3227 this.status = clone.status;
3228 this.message = clone.message;
3229 this.stack = clone.stack;
3230 if (this.phase === this.phases.INITIAL) {
3231 this.phase = this.phases.STARTED;
3232 }
3233 };
3234 RemoteTest.prototype.done = function() {
3235 this.phase = this.phases.COMPLETE;
3236
3237 forEach(this._done_callbacks,
3238 function(callback) {
3239 callback();
3240 });
3241 };
3242
3243 RemoteTest.prototype.format_status = function() {
3244 return Test.prototype.status_formats[this.status];
3245 };
3246
3247 /*
3248 * A RemoteContext listens for test events from a remote test context, such
3249 * as another window or a worker. These events are then used to construct
3250 * and maintain RemoteTest objects that mirror the tests running in the
3251 * remote context.
3252 *
3253 * An optional third parameter can be used as a predicate to filter incoming
3254 * MessageEvents.
3255 */
3256 function RemoteContext(remote, message_target, message_filter) {
3257 this.running = true;
3258 this.started = false;
3259 this.tests = new Array();
3260 this.early_exception = null;
3261
3262 var this_obj = this;
3263 // If remote context is cross origin assigning to onerror is not
3264 // possible, so silently catch those errors.
3265 try {
3266 remote.onerror = function(error) { this_obj.remote_error(error); };
3267 } catch (e) {
3268 // Ignore.
3269 }
3270
3271 // Keeping a reference to the remote object and the message handler until
3272 // remote_done() is seen prevents the remote object and its message channel
3273 // from going away before all the messages are dispatched.
3274 this.remote = remote;
3275 this.message_target = message_target;
3276 this.message_handler = function(message) {
3277 var passesFilter = !message_filter || message_filter(message);
3278 // The reference to the `running` property in the following
3279 // condition is unnecessary because that value is only set to
3280 // `false` after the `message_handler` function has been
3281 // unsubscribed.
3282 // TODO: Simplify the condition by removing the reference.
3283 if (this_obj.running && message.data && passesFilter &&
3284 (message.data.type in this_obj.message_handlers)) {
3285 this_obj.message_handlers[message.data.type].call(this_obj, message.data);
3286 }
3287 };
3288
3289 if (self.Promise) {
3290 this.done = new Promise(function(resolve) {
3291 this_obj.doneResolve = resolve;
3292 });
3293 }
3294
3295 this.message_target.addEventListener("message", this.message_handler);
3296 }
3297
3298 RemoteContext.prototype.remote_error = function(error) {
3299 if (error.preventDefault) {
3300 error.preventDefault();
3301 }
3302
3303 // Defer interpretation of errors until the testing protocol has
3304 // started and the remote test's `allow_uncaught_exception` property
3305 // is available.
3306 if (!this.started) {
3307 this.early_exception = error;
3308 } else if (!this.allow_uncaught_exception) {
3309 this.report_uncaught(error);
3310 }
3311 };
3312
3313 RemoteContext.prototype.report_uncaught = function(error) {
3314 var message = error.message || String(error);
3315 var filename = (error.filename ? " " + error.filename: "");
3316 // FIXME: Display remote error states separately from main document
3317 // error state.
3318 tests.set_status(tests.status.ERROR,
3319 "Error in remote" + filename + ": " + message,
3320 error.stack);
3321 };
3322
3323 RemoteContext.prototype.start = function(data) {
3324 this.started = true;
3325 this.allow_uncaught_exception = data.properties.allow_uncaught_exception;
3326
3327 if (this.early_exception && !this.allow_uncaught_exception) {
3328 this.report_uncaught(this.early_exception);
3329 }
3330 };
3331
3332 RemoteContext.prototype.test_state = function(data) {
3333 var remote_test = this.tests[data.test.index];
3334 if (!remote_test) {
3335 remote_test = new RemoteTest(data.test);
3336 this.tests[data.test.index] = remote_test;
3337 }
3338 remote_test.update_state_from(data.test);
3339 tests.notify_test_state(remote_test);
3340 };
3341
3342 RemoteContext.prototype.test_done = function(data) {
3343 var remote_test = this.tests[data.test.index];
3344 remote_test.update_state_from(data.test);
3345 remote_test.done();
3346 tests.result(remote_test);
3347 };
3348
3349 RemoteContext.prototype.remote_done = function(data) {
3350 if (tests.status.status === null &&
3351 data.status.status !== data.status.OK) {
3352 tests.set_status(data.status.status, data.status.message, data.status.stack);
3353 }
3354
3355 for (let assert of data.asserts) {
3356 var record = new AssertRecord();
3357 record.assert_name = assert.assert_name;
3358 record.args = assert.args;
3359 record.test = assert.test != null ? this.tests[assert.test.index] : null;
3360 record.status = assert.status;
3361 record.stack = assert.stack;
3362 tests.asserts_run.push(record);
3363 }
3364
3365 this.message_target.removeEventListener("message", this.message_handler);
3366 this.running = false;
3367
3368 // If remote context is cross origin assigning to onerror is not
3369 // possible, so silently catch those errors.
3370 try {
3371 this.remote.onerror = null;
3372 } catch (e) {
3373 // Ignore.
3374 }
3375
3376 this.remote = null;
3377 this.message_target = null;
3378 if (this.doneResolve) {
3379 this.doneResolve();
3380 }
3381
3382 if (tests.all_done()) {
3383 tests.complete();
3384 }
3385 };
3386
3387 RemoteContext.prototype.message_handlers = {
3388 start: RemoteContext.prototype.start,
3389 test_state: RemoteContext.prototype.test_state,
3390 result: RemoteContext.prototype.test_done,
3391 complete: RemoteContext.prototype.remote_done
3392 };
3393
3394 /**
3395 * @class
3396 * Status of the overall harness
3397 */
3398 function TestsStatus()
3399 {
3400 /** The status code */
3401 this.status = null;
3402 /** Message in case of failure */
3403 this.message = null;
3404 /** Stack trace in case of an exception. */
3405 this.stack = null;
3406 }
3407
3408 /**
3409 * Enum of possible harness statuses.
3410 *
3411 * :values:
3412 * - ``OK``
3413 * - ``ERROR``
3414 * - ``TIMEOUT``
3415 * - ``PRECONDITION_FAILED``
3416 */
3417 TestsStatus.statuses = {
3418 OK:0,
3419 ERROR:1,
3420 TIMEOUT:2,
3421 PRECONDITION_FAILED:3
3422 };
3423
3424 TestsStatus.prototype = merge({}, TestsStatus.statuses);
3425
3426 TestsStatus.prototype.formats = {
3427 0: "OK",
3428 1: "Error",
3429 2: "Timeout",
3430 3: "Optional Feature Unsupported"
3431 };
3432
3433 TestsStatus.prototype.structured_clone = function()
3434 {
3435 if (!this._structured_clone) {
3436 var msg = this.message;
3437 msg = msg ? String(msg) : msg;
3438 this._structured_clone = merge({
3439 status:this.status,
3440 message:msg,
3441 stack:this.stack
3442 }, TestsStatus.statuses);
3443 }
3444 return this._structured_clone;
3445 };
3446
3447 TestsStatus.prototype.format_status = function() {
3448 return this.formats[this.status];
3449 };
3450
3451 /**
3452 * @class
3453 * Record of an assert that ran.
3454 *
3455 * @param {Test} test - The test which ran the assert.
3456 * @param {string} assert_name - The function name of the assert.
3457 * @param {Any} args - The arguments passed to the assert function.
3458 */
3459 function AssertRecord(test, assert_name, args = []) {
3460 /** Name of the assert that ran */
3461 this.assert_name = assert_name;
3462 /** Test that ran the assert */
3463 this.test = test;
3464 // Avoid keeping complex objects alive
3465 /** Stringification of the arguments that were passed to the assert function */
3466 this.args = args.map(x => format_value(x).replace(/\n/g, " "));
3467 /** Status of the assert */
3468 this.status = null;
3469 }
3470
3471 AssertRecord.prototype.structured_clone = function() {
3472 return {
3473 assert_name: this.assert_name,
3474 test: this.test ? this.test.structured_clone() : null,
3475 args: this.args,
3476 status: this.status,
3477 };
3478 };
3479
3480 function Tests()
3481 {
3482 this.tests = [];
3483 this.num_pending = 0;
3484
3485 this.phases = {
3486 INITIAL:0,
3487 SETUP:1,
3488 HAVE_TESTS:2,
3489 HAVE_RESULTS:3,
3490 COMPLETE:4
3491 };
3492 this.phase = this.phases.INITIAL;
3493
3494 this.properties = {};
3495
3496 this.wait_for_finish = false;
3497 this.processing_callbacks = false;
3498
3499 this.allow_uncaught_exception = false;
3500
3501 this.file_is_test = false;
3502 // This value is lazily initialized in order to avoid introducing a
3503 // dependency on ECMAScript 2015 Promises to all tests.
3504 this.promise_tests = null;
3505 this.promise_setup_called = false;
3506
3507 this.timeout_multiplier = 1;
3508 this.timeout_length = test_environment.test_timeout();
3509 this.timeout_id = null;
3510
3511 this.start_callbacks = [];
3512 this.test_state_callbacks = [];
3513 this.test_done_callbacks = [];
3514 this.all_done_callbacks = [];
3515
3516 this.hide_test_state = false;
3517 this.remotes = [];
3518
3519 this.current_test = null;
3520 this.asserts_run = [];
3521
3522 // Track whether output is enabled, and thus whether or not we should
3523 // track asserts.
3524 //
3525 // On workers we don't get properties set from testharnessreport.js, so
3526 // we don't know whether or not to track asserts. To avoid the
3527 // resulting performance hit, we assume we are not meant to. This means
3528 // that assert tracking does not function on workers.
3529 this.output = settings.output && 'document' in global_scope;
3530
3531 this.status = new TestsStatus();
3532
3533 var this_obj = this;
3534
3535 test_environment.add_on_loaded_callback(function() {
3536 if (this_obj.all_done()) {
3537 this_obj.complete();
3538 }
3539 });
3540
3541 this.set_timeout();
3542 }
3543
3544 Tests.prototype.setup = function(func, properties)
3545 {
3546 if (this.phase >= this.phases.HAVE_RESULTS) {
3547 return;
3548 }
3549
3550 if (this.phase < this.phases.SETUP) {
3551 this.phase = this.phases.SETUP;
3552 }
3553
3554 this.properties = properties;
3555
3556 for (var p in properties) {
3557 if (properties.hasOwnProperty(p)) {
3558 var value = properties[p];
3559 if (p === "allow_uncaught_exception") {
3560 this.allow_uncaught_exception = value;
3561 } else if (p === "explicit_done" && value) {
3562 this.wait_for_finish = true;
3563 } else if (p === "explicit_timeout" && value) {
3564 this.timeout_length = null;
3565 if (this.timeout_id)
3566 {
3567 clearTimeout(this.timeout_id);
3568 }
3569 } else if (p === "single_test" && value) {
3570 this.set_file_is_test();
3571 } else if (p === "timeout_multiplier") {
3572 this.timeout_multiplier = value;
3573 if (this.timeout_length) {
3574 this.timeout_length *= this.timeout_multiplier;
3575 }
3576 } else if (p === "hide_test_state") {
3577 this.hide_test_state = value;
3578 } else if (p === "output") {
3579 this.output = value;
3580 } else if (p === "debug") {
3581 settings.debug = value;
3582 }
3583 }
3584 }
3585
3586 if (func) {
3587 try {
3588 func();
3589 } catch (e) {
3590 this.status.status = e instanceof OptionalFeatureUnsupportedError ? this.status.PRECONDITION_FAILED : this.status.ERROR;
3591 this.status.message = String(e);
3592 this.status.stack = e.stack ? e.stack : null;
3593 this.complete();
3594 }
3595 }
3596 this.set_timeout();
3597 };
3598
3599 Tests.prototype.set_file_is_test = function() {
3600 if (this.tests.length > 0) {
3601 throw new Error("Tried to set file as test after creating a test");
3602 }
3603 this.wait_for_finish = true;
3604 this.file_is_test = true;
3605 // Create the test, which will add it to the list of tests
3606 tests.current_test = async_test();
3607 };
3608
3609 Tests.prototype.set_status = function(status, message, stack)
3610 {
3611 this.status.status = status;
3612 this.status.message = message;
3613 this.status.stack = stack ? stack : null;
3614 };
3615
3616 Tests.prototype.set_timeout = function() {
3617 if (global_scope.clearTimeout) {
3618 var this_obj = this;
3619 clearTimeout(this.timeout_id);
3620 if (this.timeout_length !== null) {
3621 this.timeout_id = setTimeout(function() {
3622 this_obj.timeout();
3623 }, this.timeout_length);
3624 }
3625 }
3626 };
3627
3628 Tests.prototype.timeout = function() {
3629 var test_in_cleanup = null;
3630
3631 if (this.status.status === null) {
3632 forEach(this.tests,
3633 function(test) {
3634 // No more than one test is expected to be in the
3635 // "CLEANUP" phase at any time
3636 if (test.phase === test.phases.CLEANING) {
3637 test_in_cleanup = test;
3638 }
3639
3640 test.phase = test.phases.COMPLETE;
3641 });
3642
3643 // Timeouts that occur while a test is in the "cleanup" phase
3644 // indicate that some global state was not properly reverted. This
3645 // invalidates the overall test execution, so the timeout should be
3646 // reported as an error and cancel the execution of any remaining
3647 // tests.
3648 if (test_in_cleanup) {
3649 this.status.status = this.status.ERROR;
3650 this.status.message = "Timeout while running cleanup for " +
3651 "test named \"" + test_in_cleanup.name + "\".";
3652 tests.status.stack = null;
3653 } else {
3654 this.status.status = this.status.TIMEOUT;
3655 }
3656 }
3657
3658 this.complete();
3659 };
3660
3661 Tests.prototype.end_wait = function()
3662 {
3663 this.wait_for_finish = false;
3664 if (this.all_done()) {
3665 this.complete();
3666 }
3667 };
3668
3669 Tests.prototype.push = function(test)
3670 {
3671 if (this.phase === this.phases.COMPLETE) {
3672 return;
3673 }
3674 if (this.phase < this.phases.HAVE_TESTS) {
3675 this.start();
3676 }
3677 this.num_pending++;
3678 test.index = this.tests.push(test) - 1;
3679 this.notify_test_state(test);
3680 };
3681
3682 Tests.prototype.notify_test_state = function(test) {
3683 var this_obj = this;
3684 forEach(this.test_state_callbacks,
3685 function(callback) {
3686 callback(test, this_obj);
3687 });
3688 };
3689
3690 Tests.prototype.all_done = function() {
3691 return (this.tests.length > 0 || this.remotes.length > 0) &&
3692 test_environment.all_loaded &&
3693 (this.num_pending === 0 || this.is_aborted) && !this.wait_for_finish &&
3694 !this.processing_callbacks &&
3695 !this.remotes.some(function(w) { return w.running; });
3696 };
3697
3698 Tests.prototype.start = function() {
3699 this.phase = this.phases.HAVE_TESTS;
3700 this.notify_start();
3701 };
3702
3703 Tests.prototype.notify_start = function() {
3704 var this_obj = this;
3705 forEach (this.start_callbacks,
3706 function(callback)
3707 {
3708 callback(this_obj.properties);
3709 });
3710 };
3711
3712 Tests.prototype.result = function(test)
3713 {
3714 // If the harness has already transitioned beyond the `HAVE_RESULTS`
3715 // phase, subsequent tests should not cause it to revert.
3716 if (this.phase <= this.phases.HAVE_RESULTS) {
3717 this.phase = this.phases.HAVE_RESULTS;
3718 }
3719 this.num_pending--;
3720 this.notify_result(test);
3721 };
3722
3723 Tests.prototype.notify_result = function(test) {
3724 var this_obj = this;
3725 this.processing_callbacks = true;
3726 forEach(this.test_done_callbacks,
3727 function(callback)
3728 {
3729 callback(test, this_obj);
3730 });
3731 this.processing_callbacks = false;
3732 if (this_obj.all_done()) {
3733 this_obj.complete();
3734 }
3735 };
3736
3737 Tests.prototype.complete = function() {
3738 if (this.phase === this.phases.COMPLETE) {
3739 return;
3740 }
3741 var this_obj = this;
3742 var all_complete = function() {
3743 this_obj.phase = this_obj.phases.COMPLETE;
3744 this_obj.notify_complete();
3745 };
3746 var incomplete = filter(this.tests,
3747 function(test) {
3748 return test.phase < test.phases.COMPLETE;
3749 });
3750
3751 /**
3752 * To preserve legacy behavior, overall test completion must be
3753 * signaled synchronously.
3754 */
3755 if (incomplete.length === 0) {
3756 all_complete();
3757 return;
3758 }
3759
3760 all_async(incomplete,
3761 function(test, testDone)
3762 {
3763 if (test.phase === test.phases.INITIAL) {
3764 test.phase = test.phases.HAS_RESULT;
3765 test.done();
3766 testDone();
3767 } else {
3768 add_test_done_callback(test, testDone);
3769 test.cleanup();
3770 }
3771 },
3772 all_complete);
3773 };
3774
3775 Tests.prototype.set_assert = function(assert_name, args) {
3776 this.asserts_run.push(new AssertRecord(this.current_test, assert_name, args));
3777 };
3778
3779 Tests.prototype.set_assert_status = function(index, status, stack) {
3780 let assert_record = this.asserts_run[index];
3781 assert_record.status = status;
3782 assert_record.stack = stack;
3783 };
3784
3785 /**
3786 * Update the harness status to reflect an unrecoverable harness error that
3787 * should cancel all further testing. Update all previously-defined tests
3788 * which have not yet started to indicate that they will not be executed.
3789 */
3790 Tests.prototype.abort = function() {
3791 this.status.status = this.status.ERROR;
3792 this.is_aborted = true;
3793
3794 forEach(this.tests,
3795 function(test) {
3796 if (test.phase === test.phases.INITIAL) {
3797 test.phase = test.phases.COMPLETE;
3798 }
3799 });
3800 };
3801
3802 /*
3803 * Determine if any tests share the same `name` property. Return an array
3804 * containing the names of any such duplicates.
3805 */
3806 Tests.prototype.find_duplicates = function() {
3807 var names = Object.create(null);
3808 var duplicates = [];
3809
3810 forEach (this.tests,
3811 function(test)
3812 {
3813 if (test.name in names && duplicates.indexOf(test.name) === -1) {
3814 duplicates.push(test.name);
3815 }
3816 names[test.name] = true;
3817 });
3818
3819 return duplicates;
3820 };
3821
3822 function code_unit_str(char) {
3823 return 'U+' + char.charCodeAt(0).toString(16);
3824 }
3825
3826 function sanitize_unpaired_surrogates(str) {
3827 return str.replace(
3828 /([\ud800-\udbff]+)(?![\udc00-\udfff])|(^|[^\ud800-\udbff])([\udc00-\udfff]+)/g,
3829 function(_, low, prefix, high) {
3830 var output = prefix || ""; // prefix may be undefined
3831 var string = low || high; // only one of these alternates can match
3832 for (var i = 0; i < string.length; i++) {
3833 output += code_unit_str(string[i]);
3834 }
3835 return output;
3836 });
3837 }
3838
3839 function sanitize_all_unpaired_surrogates(tests) {
3840 forEach (tests,
3841 function (test)
3842 {
3843 var sanitized = sanitize_unpaired_surrogates(test.name);
3844
3845 if (test.name !== sanitized) {
3846 test.name = sanitized;
3847 delete test._structured_clone;
3848 }
3849 });
3850 }
3851
3852 Tests.prototype.notify_complete = function() {
3853 var this_obj = this;
3854 var duplicates;
3855
3856 if (this.status.status === null) {
3857 duplicates = this.find_duplicates();
3858
3859 // Some transports adhere to UTF-8's restriction on unpaired
3860 // surrogates. Sanitize the titles so that the results can be
3861 // consistently sent via all transports.
3862 sanitize_all_unpaired_surrogates(this.tests);
3863
3864 // Test names are presumed to be unique within test files--this
3865 // allows consumers to use them for identification purposes.
3866 // Duplicated names violate this expectation and should therefore
3867 // be reported as an error.
3868 if (duplicates.length) {
3869 this.status.status = this.status.ERROR;
3870 this.status.message =
3871 duplicates.length + ' duplicate test name' +
3872 (duplicates.length > 1 ? 's' : '') + ': "' +
3873 duplicates.join('", "') + '"';
3874 } else {
3875 this.status.status = this.status.OK;
3876 }
3877 }
3878
3879 forEach (this.all_done_callbacks,
3880 function(callback)
3881 {
3882 callback(this_obj.tests, this_obj.status, this_obj.asserts_run);
3883 });
3884 };
3885
3886 /*
3887 * Constructs a RemoteContext that tracks tests from a specific worker.
3888 */
3889 Tests.prototype.create_remote_worker = function(worker) {
3890 var message_port;
3891
3892 if (is_service_worker(worker)) {
3893 message_port = navigator.serviceWorker;
3894 worker.postMessage({type: "connect"});
3895 } else if (is_shared_worker(worker)) {
3896 message_port = worker.port;
3897 message_port.start();
3898 } else {
3899 message_port = worker;
3900 }
3901
3902 return new RemoteContext(worker, message_port);
3903 };
3904
3905 /*
3906 * Constructs a RemoteContext that tracks tests from a specific window.
3907 */
3908 Tests.prototype.create_remote_window = function(remote) {
3909 remote.postMessage({type: "getmessages"}, "*");
3910 return new RemoteContext(
3911 remote,
3912 window,
3913 function(msg) {
3914 return msg.source === remote;
3915 }
3916 );
3917 };
3918
3919 Tests.prototype.fetch_tests_from_worker = function(worker) {
3920 if (this.phase >= this.phases.COMPLETE) {
3921 return;
3922 }
3923
3924 var remoteContext = this.create_remote_worker(worker);
3925 this.remotes.push(remoteContext);
3926 return remoteContext.done;
3927 };
3928
3929 /**
3930 * Get test results from a worker and include them in the current test.
3931 *
3932 * @param {Worker|SharedWorker|ServiceWorker|MessagePort} port -
3933 * Either a worker object or a port connected to a worker which is
3934 * running tests..
3935 * @returns {Promise} - A promise that's resolved once all the remote tests are complete.
3936 */
3937 function fetch_tests_from_worker(port) {
3938 return tests.fetch_tests_from_worker(port);
3939 }
3940 expose(fetch_tests_from_worker, 'fetch_tests_from_worker');
3941
3942 Tests.prototype.fetch_tests_from_window = function(remote) {
3943 if (this.phase >= this.phases.COMPLETE) {
3944 return;
3945 }
3946
3947 var remoteContext = this.create_remote_window(remote);
3948 this.remotes.push(remoteContext);
3949 return remoteContext.done;
3950 };
3951
3952 /**
3953 * Aggregate tests from separate windows or iframes
3954 * into the current document as if they were all part of the same test file.
3955 *
3956 * The document of the second window (or iframe) should include
3957 * ``testharness.js``, but not ``testharnessreport.js``, and use
3958 * :js:func:`test`, :js:func:`async_test`, and :js:func:`promise_test` in
3959 * the usual manner.
3960 *
3961 * @param {Window} window - The window to fetch tests from.
3962 */
3963 function fetch_tests_from_window(window) {
3964 return tests.fetch_tests_from_window(window);
3965 }
3966 expose(fetch_tests_from_window, 'fetch_tests_from_window');
3967
3968 /**
3969 * Get test results from a shadow realm and include them in the current test.
3970 *
3971 * @param {ShadowRealm} realm - A shadow realm also running the test harness
3972 * @returns {Promise} - A promise that's resolved once all the remote tests are complete.
3973 */
3974 function fetch_tests_from_shadow_realm(realm) {
3975 var chan = new MessageChannel();
3976 function receiveMessage(msg_json) {
3977 chan.port1.postMessage(JSON.parse(msg_json));
3978 }
3979 var done = tests.fetch_tests_from_worker(chan.port2);
3980 realm.evaluate("begin_shadow_realm_tests")(receiveMessage);
3981 chan.port2.start();
3982 return done;
3983 }
3984 expose(fetch_tests_from_shadow_realm, 'fetch_tests_from_shadow_realm');
3985
3986 /**
3987 * Begin running tests in this shadow realm test harness.
3988 *
3989 * To be called after all tests have been loaded; it is an error to call
3990 * this more than once or in a non-Shadow Realm environment
3991 *
3992 * @param {Function} postMessage - A function to send test updates to the
3993 * incubating realm-- accepts JSON-encoded messages in the format used by
3994 * RemoteContext
3995 */
3996 function begin_shadow_realm_tests(postMessage) {
3997 if (!(test_environment instanceof ShadowRealmTestEnvironment)) {
3998 throw new Error("begin_shadow_realm_tests called in non-Shadow Realm environment");
3999 }
4000
4001 test_environment.begin(function (msg) {
4002 postMessage(JSON.stringify(msg));
4003 });
4004 }
4005 expose(begin_shadow_realm_tests, 'begin_shadow_realm_tests');
4006
4007 /**
4008 * Timeout the tests.
4009 *
4010 * This only has an effect when ``explicit_timeout`` has been set
4011 * in :js:func:`setup`. In other cases any call is a no-op.
4012 *
4013 */
4014 function timeout() {
4015 if (tests.timeout_length === null) {
4016 tests.timeout();
4017 }
4018 }
4019 expose(timeout, 'timeout');
4020
4021 /**
4022 * Add a callback that's triggered when the first :js:class:`Test` is created.
4023 *
4024 * @param {Function} callback - Callback function. This is called
4025 * without arguments.
4026 */
4027 function add_start_callback(callback) {
4028 tests.start_callbacks.push(callback);
4029 }
4030
4031 /**
4032 * Add a callback that's triggered when a test state changes.
4033 *
4034 * @param {Function} callback - Callback function, called with the
4035 * :js:class:`Test` as the only argument.
4036 */
4037 function add_test_state_callback(callback) {
4038 tests.test_state_callbacks.push(callback);
4039 }
4040
4041 /**
4042 * Add a callback that's triggered when a test result is received.
4043 *
4044 * @param {Function} callback - Callback function, called with the
4045 * :js:class:`Test` as the only argument.
4046 */
4047 function add_result_callback(callback) {
4048 tests.test_done_callbacks.push(callback);
4049 }
4050
4051 /**
4052 * Add a callback that's triggered when all tests are complete.
4053 *
4054 * @param {Function} callback - Callback function, called with an
4055 * array of :js:class:`Test` objects, a :js:class:`TestsStatus`
4056 * object and an array of :js:class:`AssertRecord` objects. If the
4057 * debug setting is ``false`` the final argument will be an empty
4058 * array.
4059 *
4060 * For performance reasons asserts are only tracked when the debug
4061 * setting is ``true``. In other cases the array of asserts will be
4062 * empty.
4063 */
4064 function add_completion_callback(callback) {
4065 tests.all_done_callbacks.push(callback);
4066 }
4067
4068 expose(add_start_callback, 'add_start_callback');
4069 expose(add_test_state_callback, 'add_test_state_callback');
4070 expose(add_result_callback, 'add_result_callback');
4071 expose(add_completion_callback, 'add_completion_callback');
4072
4073 function remove(array, item) {
4074 var index = array.indexOf(item);
4075 if (index > -1) {
4076 array.splice(index, 1);
4077 }
4078 }
4079
4080 function remove_start_callback(callback) {
4081 remove(tests.start_callbacks, callback);
4082 }
4083
4084 function remove_test_state_callback(callback) {
4085 remove(tests.test_state_callbacks, callback);
4086 }
4087
4088 function remove_result_callback(callback) {
4089 remove(tests.test_done_callbacks, callback);
4090 }
4091
4092 function remove_completion_callback(callback) {
4093 remove(tests.all_done_callbacks, callback);
4094 }
4095
4096 /*
4097 * Output listener
4098 */
4099
4100 function Output() {
4101 this.output_document = document;
4102 this.output_node = null;
4103 this.enabled = settings.output;
4104 this.phase = this.INITIAL;
4105 }
4106
4107 Output.prototype.INITIAL = 0;
4108 Output.prototype.STARTED = 1;
4109 Output.prototype.HAVE_RESULTS = 2;
4110 Output.prototype.COMPLETE = 3;
4111
4112 Output.prototype.setup = function(properties) {
4113 if (this.phase > this.INITIAL) {
4114 return;
4115 }
4116
4117 //If output is disabled in testharnessreport.js the test shouldn't be
4118 //able to override that
4119 this.enabled = this.enabled && (properties.hasOwnProperty("output") ?
4120 properties.output : settings.output);
4121 };
4122
4123 Output.prototype.init = function(properties) {
4124 if (this.phase >= this.STARTED) {
4125 return;
4126 }
4127 if (properties.output_document) {
4128 this.output_document = properties.output_document;
4129 } else {
4130 this.output_document = document;
4131 }
4132 this.phase = this.STARTED;
4133 };
4134
4135 Output.prototype.resolve_log = function() {
4136 var output_document;
4137 if (this.output_node) {
4138 return;
4139 }
4140 if (typeof this.output_document === "function") {
4141 output_document = this.output_document.apply(undefined);
4142 } else {
4143 output_document = this.output_document;
4144 }
4145 if (!output_document) {
4146 return;
4147 }
4148 var node = output_document.getElementById("log");
4149 if (!node) {
4150 if (output_document.readyState === "loading") {
4151 return;
4152 }
4153 node = output_document.createElementNS("http://www.w3.org/1999/xhtml", "div");
4154 node.id = "log";
4155 if (output_document.body) {
4156 output_document.body.appendChild(node);
4157 } else {
4158 var root = output_document.documentElement;
4159 var is_html = (root &&
4160 root.namespaceURI === "http://www.w3.org/1999/xhtml" &&
4161 root.localName === "html");
4162 var is_svg = (output_document.defaultView &&
4163 "SVGSVGElement" in output_document.defaultView &&
4164 root instanceof output_document.defaultView.SVGSVGElement);
4165 if (is_svg) {
4166 var foreignObject = output_document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
4167 foreignObject.setAttribute("width", "100%");
4168 foreignObject.setAttribute("height", "100%");
4169 root.appendChild(foreignObject);
4170 foreignObject.appendChild(node);
4171 } else if (is_html) {
4172 root.appendChild(output_document.createElementNS("http://www.w3.org/1999/xhtml", "body"))
4173 .appendChild(node);
4174 } else {
4175 root.appendChild(node);
4176 }
4177 }
4178 }
4179 this.output_document = output_document;
4180 this.output_node = node;
4181 };
4182
4183 Output.prototype.show_status = function() {
4184 if (this.phase < this.STARTED) {
4185 this.init({});
4186 }
4187 if (!this.enabled || this.phase === this.COMPLETE) {
4188 return;
4189 }
4190 this.resolve_log();
4191 if (this.phase < this.HAVE_RESULTS) {
4192 this.phase = this.HAVE_RESULTS;
4193 }
4194 var done_count = tests.tests.length - tests.num_pending;
4195 if (this.output_node && !tests.hide_test_state) {
4196 if (done_count < 100 ||
4197 (done_count < 1000 && done_count % 100 === 0) ||
4198 done_count % 1000 === 0) {
4199 this.output_node.textContent = "Running, " +
4200 done_count + " complete, " +
4201 tests.num_pending + " remain";
4202 }
4203 }
4204 };
4205
4206 Output.prototype.show_results = function (tests, harness_status, asserts_run) {
4207 if (this.phase >= this.COMPLETE) {
4208 return;
4209 }
4210 if (!this.enabled) {
4211 return;
4212 }
4213 if (!this.output_node) {
4214 this.resolve_log();
4215 }
4216 this.phase = this.COMPLETE;
4217
4218 var log = this.output_node;
4219 if (!log) {
4220 return;
4221 }
4222 var output_document = this.output_document;
4223
4224 while (log.lastChild) {
4225 log.removeChild(log.lastChild);
4226 }
4227
4228 var stylesheet = output_document.createElementNS(xhtml_ns, "style");
4229 stylesheet.textContent = stylesheetContent;
4230 var heads = output_document.getElementsByTagName("head");
4231 if (heads.length) {
4232 heads[0].appendChild(stylesheet);
4233 }
4234
4235 var status_number = {};
4236 forEach(tests,
4237 function(test) {
4238 var status = test.format_status();
4239 if (status_number.hasOwnProperty(status)) {
4240 status_number[status] += 1;
4241 } else {
4242 status_number[status] = 1;
4243 }
4244 });
4245
4246 function status_class(status)
4247 {
4248 return status.replace(/\s/g, '').toLowerCase();
4249 }
4250
4251 var summary_template = ["section", {"id":"summary"},
4252 ["h2", {}, "Summary"],
4253 function()
4254 {
4255 var status = harness_status.format_status();
4256 var rv = [["section", {},
4257 ["p", {},
4258 "Harness status: ",
4259 ["span", {"class":status_class(status)},
4260 status
4261 ],
4262 ],
4263 ["button", {"id":"rerun"}, "Rerun"]
4264 ]];
4265
4266 if (harness_status.status === harness_status.ERROR) {
4267 rv[0].push(["pre", {}, harness_status.message]);
4268 if (harness_status.stack) {
4269 rv[0].push(["pre", {}, harness_status.stack]);
4270 }
4271 }
4272 return rv;
4273 },
4274 ["p", {}, "Found ${num_tests} tests"],
4275 function() {
4276 var rv = [["div", {}]];
4277 var i = 0;
4278 while (Test.prototype.status_formats.hasOwnProperty(i)) {
4279 if (status_number.hasOwnProperty(Test.prototype.status_formats[i])) {
4280 var status = Test.prototype.status_formats[i];
4281 rv[0].push(["div", {},
4282 ["label", {},
4283 ["input", {type:"checkbox", checked:"checked"}],
4284 status_number[status] + " ",
4285 ["span", {"class":status_class(status)}, status]]]);
4286 }
4287 i++;
4288 }
4289 return rv;
4290 },
4291 ];
4292
4293 log.appendChild(render(summary_template, {num_tests:tests.length}, output_document));
4294
4295 output_document.getElementById("rerun").addEventListener("click",
4296 function() {
4297 let evt = new Event('__test_restart');
4298 let canceled = !window.dispatchEvent(evt);
4299 if (!canceled) { location.reload(); }
4300 });
4301
4302 forEach(output_document.querySelectorAll("section#summary label"),
4303 function(element)
4304 {
4305 on_event(element, "click",
4306 function(e)
4307 {
4308 if (output_document.getElementById("results") === null) {
4309 e.preventDefault();
4310 return;
4311 }
4312 var result_class = element.querySelector("span[class]").getAttribute("class");
4313 var style_element = output_document.querySelector("style#hide-" + result_class);
4314 var input_element = element.querySelector("input");
4315 if (!style_element && !input_element.checked) {
4316 style_element = output_document.createElementNS(xhtml_ns, "style");
4317 style_element.id = "hide-" + result_class;
4318 style_element.textContent = "table#results > tbody > tr.overall-"+result_class+"{display:none}";
4319 output_document.body.appendChild(style_element);
4320 } else if (style_element && input_element.checked) {
4321 style_element.parentNode.removeChild(style_element);
4322 }
4323 });
4324 });
4325
4326 function has_assertions()
4327 {
4328 for (var i = 0; i < tests.length; i++) {
4329 if (tests[i].properties.hasOwnProperty("assert")) {
4330 return true;
4331 }
4332 }
4333 return false;
4334 }
4335
4336 function get_assertion(test)
4337 {
4338 if (test.properties.hasOwnProperty("assert")) {
4339 if (Array.isArray(test.properties.assert)) {
4340 return test.properties.assert.join(' ');
4341 }
4342 return test.properties.assert;
4343 }
4344 return '';
4345 }
4346
4347 var asserts_run_by_test = new Map();
4348 asserts_run.forEach(assert => {
4349 if (!asserts_run_by_test.has(assert.test)) {
4350 asserts_run_by_test.set(assert.test, []);
4351 }
4352 asserts_run_by_test.get(assert.test).push(assert);
4353 });
4354
4355 function get_asserts_output(test) {
4356 const asserts_output = render(
4357 ["details", {},
4358 ["summary", {}, "Asserts run"],
4359 ["table", {}, ""] ]);
4360
4361 var asserts = asserts_run_by_test.get(test);
4362 if (!asserts) {
4363 asserts_output.querySelector("summary").insertAdjacentText("afterend", "No asserts ran");
4364 return asserts_output;
4365 }
4366
4367 const table = asserts_output.querySelector("table");
4368 for (const assert of asserts) {
4369 const status_class_name = status_class(Test.prototype.status_formats[assert.status]);
4370 var output_fn = "(" + assert.args.join(", ") + ")";
4371 if (assert.stack) {
4372 output_fn += "\n";
4373 output_fn += assert.stack.split("\n", 1)[0].replace(/@?\w+:\/\/[^ "\/]+(?::\d+)?/g, " ");
4374 }
4375 table.appendChild(render(
4376 ["tr", {"class":"overall-" + status_class_name},
4377 ["td", {"class":status_class_name}, Test.prototype.status_formats[assert.status]],
4378 ["td", {}, ["pre", {}, ["strong", {}, assert.assert_name], output_fn]] ]));
4379 }
4380 return asserts_output;
4381 }
4382
4383 var assertions = has_assertions();
4384 const section = render(
4385 ["section", {},
4386 ["h2", {}, "Details"],
4387 ["table", {"id":"results", "class":(assertions ? "assertions" : "")},
4388 ["thead", {},
4389 ["tr", {},
4390 ["th", {}, "Result"],
4391 ["th", {}, "Test Name"],
4392 (assertions ? ["th", {}, "Assertion"] : ""),
4393 ["th", {}, "Message" ]]],
4394 ["tbody", {}]]]);
4395
4396 const tbody = section.querySelector("tbody");
4397 for (const test of tests) {
4398 const status = test.format_status();
4399 const status_class_name = status_class(status);
4400 tbody.appendChild(render(
4401 ["tr", {"class":"overall-" + status_class_name},
4402 ["td", {"class":status_class_name}, status],
4403 ["td", {}, test.name],
4404 (assertions ? ["td", {}, get_assertion(test)] : ""),
4405 ["td", {},
4406 test.message ?? "",
4407 ["pre", {}, test.stack ?? ""]]]));
4408 if (!(test instanceof RemoteTest)) {
4409 tbody.lastChild.lastChild.appendChild(get_asserts_output(test));
4410 }
4411 }
4412 log.appendChild(section);
4413 };
4414
4415 /*
4416 * Template code
4417 *
4418 * A template is just a JavaScript structure. An element is represented as:
4419 *
4420 * [tag_name, {attr_name:attr_value}, child1, child2]
4421 *
4422 * the children can either be strings (which act like text nodes), other templates or
4423 * functions (see below)
4424 *
4425 * A text node is represented as
4426 *
4427 * ["{text}", value]
4428 *
4429 * String values have a simple substitution syntax; ${foo} represents a variable foo.
4430 *
4431 * It is possible to embed logic in templates by using a function in a place where a
4432 * node would usually go. The function must either return part of a template or null.
4433 *
4434 * In cases where a set of nodes are required as output rather than a single node
4435 * with children it is possible to just use a list
4436 * [node1, node2, node3]
4437 *
4438 * Usage:
4439 *
4440 * render(template, substitutions) - take a template and an object mapping
4441 * variable names to parameters and return either a DOM node or a list of DOM nodes
4442 *
4443 * substitute(template, substitutions) - take a template and variable mapping object,
4444 * make the variable substitutions and return the substituted template
4445 *
4446 */
4447
4448 function is_single_node(template)
4449 {
4450 return typeof template[0] === "string";
4451 }
4452
4453 function substitute(template, substitutions)
4454 {
4455 if (typeof template === "function") {
4456 var replacement = template(substitutions);
4457 if (!replacement) {
4458 return null;
4459 }
4460
4461 return substitute(replacement, substitutions);
4462 }
4463
4464 if (is_single_node(template)) {
4465 return substitute_single(template, substitutions);
4466 }
4467
4468 return filter(map(template, function(x) {
4469 return substitute(x, substitutions);
4470 }), function(x) {return x !== null;});
4471 }
4472
4473 function substitute_single(template, substitutions)
4474 {
4475 var substitution_re = /\$\{([^ }]*)\}/g;
4476
4477 function do_substitution(input)
4478 {
4479 var components = input.split(substitution_re);
4480 var rv = [];
4481 if (components.length === 1) {
4482 rv = components;
4483 } else if (substitutions) {
4484 for (var i = 0; i < components.length; i += 2) {
4485 if (components[i]) {
4486 rv.push(components[i]);
4487 }
4488 if (substitutions[components[i + 1]]) {
4489 rv.push(String(substitutions[components[i + 1]]));
4490 }
4491 }
4492 }
4493 return rv;
4494 }
4495
4496 function substitute_attrs(attrs, rv)
4497 {
4498 rv[1] = {};
4499 for (var name in template[1]) {
4500 if (attrs.hasOwnProperty(name)) {
4501 var new_name = do_substitution(name).join("");
4502 var new_value = do_substitution(attrs[name]).join("");
4503 rv[1][new_name] = new_value;
4504 }
4505 }
4506 }
4507
4508 function substitute_children(children, rv)
4509 {
4510 for (var i = 0; i < children.length; i++) {
4511 if (children[i] instanceof Object) {
4512 var replacement = substitute(children[i], substitutions);
4513 if (replacement !== null) {
4514 if (is_single_node(replacement)) {
4515 rv.push(replacement);
4516 } else {
4517 extend(rv, replacement);
4518 }
4519 }
4520 } else {
4521 extend(rv, do_substitution(String(children[i])));
4522 }
4523 }
4524 return rv;
4525 }
4526
4527 var rv = [];
4528 rv.push(do_substitution(String(template[0])).join(""));
4529
4530 if (template[0] === "{text}") {
4531 substitute_children(template.slice(1), rv);
4532 } else {
4533 substitute_attrs(template[1], rv);
4534 substitute_children(template.slice(2), rv);
4535 }
4536
4537 return rv;
4538 }
4539
4540 function make_dom_single(template, doc)
4541 {
4542 var output_document = doc || document;
4543 var element;
4544 if (template[0] === "{text}") {
4545 element = output_document.createTextNode("");
4546 for (var i = 1; i < template.length; i++) {
4547 element.data += template[i];
4548 }
4549 } else {
4550 element = output_document.createElementNS(xhtml_ns, template[0]);
4551 for (var name in template[1]) {
4552 if (template[1].hasOwnProperty(name)) {
4553 element.setAttribute(name, template[1][name]);
4554 }
4555 }
4556 for (var i = 2; i < template.length; i++) {
4557 if (template[i] instanceof Object) {
4558 var sub_element = make_dom(template[i]);
4559 element.appendChild(sub_element);
4560 } else {
4561 var text_node = output_document.createTextNode(template[i]);
4562 element.appendChild(text_node);
4563 }
4564 }
4565 }
4566
4567 return element;
4568 }
4569
4570 function make_dom(template, substitutions, output_document)
4571 {
4572 if (is_single_node(template)) {
4573 return make_dom_single(template, output_document);
4574 }
4575
4576 return map(template, function(x) {
4577 return make_dom_single(x, output_document);
4578 });
4579 }
4580
4581 function render(template, substitutions, output_document)
4582 {
4583 return make_dom(substitute(template, substitutions), output_document);
4584 }
4585
4586 /*
4587 * Utility functions
4588 */
4589 function assert(expected_true, function_name, description, error, substitutions)
4590 {
4591 if (expected_true !== true) {
4592 var msg = make_message(function_name, description,
4593 error, substitutions);
4594 throw new AssertionError(msg);
4595 }
4596 }
4597
4598 /**
4599 * @class
4600 * Exception type that represents a failing assert.
4601 *
4602 * @param {string} message - Error message.
4603 */
4604 function AssertionError(message)
4605 {
4606 if (typeof message === "string") {
4607 message = sanitize_unpaired_surrogates(message);
4608 }
4609 this.message = message;
4610 this.stack = get_stack();
4611 }
4612 expose(AssertionError, "AssertionError");
4613
4614 AssertionError.prototype = Object.create(Error.prototype);
4615
4616 const get_stack = function() {
4617 var stack = new Error().stack;
4618
4619 // 'Error.stack' is not supported in all browsers/versions
4620 if (!stack) {
4621 return "(Stack trace unavailable)";
4622 }
4623
4624 var lines = stack.split("\n");
4625
4626 // Create a pattern to match stack frames originating within testharness.js. These include the
4627 // script URL, followed by the line/col (e.g., '/resources/testharness.js:120:21').
4628 // Escape the URL per http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
4629 // in case it contains RegExp characters.
4630 var script_url = get_script_url();
4631 var re_text = script_url ? script_url.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') : "\\btestharness.js";
4632 var re = new RegExp(re_text + ":\\d+:\\d+");
4633
4634 // Some browsers include a preamble that specifies the type of the error object. Skip this by
4635 // advancing until we find the first stack frame originating from testharness.js.
4636 var i = 0;
4637 while (!re.test(lines[i]) && i < lines.length) {
4638 i++;
4639 }
4640
4641 // Then skip the top frames originating from testharness.js to begin the stack at the test code.
4642 while (re.test(lines[i]) && i < lines.length) {
4643 i++;
4644 }
4645
4646 // Paranoid check that we didn't skip all frames. If so, return the original stack unmodified.
4647 if (i >= lines.length) {
4648 return stack;
4649 }
4650
4651 return lines.slice(i).join("\n");
4652 };
4653
4654 function OptionalFeatureUnsupportedError(message)
4655 {
4656 AssertionError.call(this, message);
4657 }
4658 OptionalFeatureUnsupportedError.prototype = Object.create(AssertionError.prototype);
4659 expose(OptionalFeatureUnsupportedError, "OptionalFeatureUnsupportedError");
4660
4661 function make_message(function_name, description, error, substitutions)
4662 {
4663 for (var p in substitutions) {
4664 if (substitutions.hasOwnProperty(p)) {
4665 substitutions[p] = format_value(substitutions[p]);
4666 }
4667 }
4668 var node_form = substitute(["{text}", "${function_name}: ${description}" + error],
4669 merge({function_name:function_name,
4670 description:(description?description + " ":"")},
4671 substitutions));
4672 return node_form.slice(1).join("");
4673 }
4674
4675 function filter(array, callable, thisObj) {
4676 var rv = [];
4677 for (var i = 0; i < array.length; i++) {
4678 if (array.hasOwnProperty(i)) {
4679 var pass = callable.call(thisObj, array[i], i, array);
4680 if (pass) {
4681 rv.push(array[i]);
4682 }
4683 }
4684 }
4685 return rv;
4686 }
4687
4688 function map(array, callable, thisObj)
4689 {
4690 var rv = [];
4691 rv.length = array.length;
4692 for (var i = 0; i < array.length; i++) {
4693 if (array.hasOwnProperty(i)) {
4694 rv[i] = callable.call(thisObj, array[i], i, array);
4695 }
4696 }
4697 return rv;
4698 }
4699
4700 function extend(array, items)
4701 {
4702 Array.prototype.push.apply(array, items);
4703 }
4704
4705 function forEach(array, callback, thisObj)
4706 {
4707 for (var i = 0; i < array.length; i++) {
4708 if (array.hasOwnProperty(i)) {
4709 callback.call(thisObj, array[i], i, array);
4710 }
4711 }
4712 }
4713
4714 /**
4715 * Immediately invoke a "iteratee" function with a series of values in
4716 * parallel and invoke a final "done" function when all of the "iteratee"
4717 * invocations have signaled completion.
4718 *
4719 * If all callbacks complete synchronously (or if no callbacks are
4720 * specified), the ``done_callback`` will be invoked synchronously. It is the
4721 * responsibility of the caller to ensure asynchronicity in cases where
4722 * that is desired.
4723 *
4724 * @param {array} value Zero or more values to use in the invocation of
4725 * ``iter_callback``
4726 * @param {function} iter_callback A function that will be invoked
4727 * once for each of the values min
4728 * ``value``. Two arguments will
4729 * be available in each
4730 * invocation: the value from
4731 * ``value`` and a function that
4732 * must be invoked to signal
4733 * completion
4734 * @param {function} done_callback A function that will be invoked after
4735 * all operations initiated by the
4736 * ``iter_callback`` function have signaled
4737 * completion
4738 */
4739 function all_async(values, iter_callback, done_callback)
4740 {
4741 var remaining = values.length;
4742
4743 if (remaining === 0) {
4744 done_callback();
4745 }
4746
4747 forEach(values,
4748 function(element) {
4749 var invoked = false;
4750 var elDone = function() {
4751 if (invoked) {
4752 return;
4753 }
4754
4755 invoked = true;
4756 remaining -= 1;
4757
4758 if (remaining === 0) {
4759 done_callback();
4760 }
4761 };
4762
4763 iter_callback(element, elDone);
4764 });
4765 }
4766
4767 function merge(a,b)
4768 {
4769 var rv = {};
4770 var p;
4771 for (p in a) {
4772 rv[p] = a[p];
4773 }
4774 for (p in b) {
4775 rv[p] = b[p];
4776 }
4777 return rv;
4778 }
4779
4780 function expose(object, name)
4781 {
4782 var components = name.split(".");
4783 var target = global_scope;
4784 for (var i = 0; i < components.length - 1; i++) {
4785 if (!(components[i] in target)) {
4786 target[components[i]] = {};
4787 }
4788 target = target[components[i]];
4789 }
4790 target[components[components.length - 1]] = object;
4791 }
4792
4793 function is_same_origin(w) {
4794 try {
4795 'random_prop' in w;
4796 return true;
4797 } catch (e) {
4798 return false;
4799 }
4800 }
4801
4802 /** Returns the 'src' URL of the first <script> tag in the page to include the file 'testharness.js'. */
4803 function get_script_url()
4804 {
4805 if (!('document' in global_scope)) {
4806 return undefined;
4807 }
4808
4809 var scripts = document.getElementsByTagName("script");
4810 for (var i = 0; i < scripts.length; i++) {
4811 var src;
4812 if (scripts[i].src) {
4813 src = scripts[i].src;
4814 } else if (scripts[i].href) {
4815 //SVG case
4816 src = scripts[i].href.baseVal;
4817 }
4818
4819 var matches = src && src.match(/^(.*\/|)testharness\.js$/);
4820 if (matches) {
4821 return src;
4822 }
4823 }
4824 return undefined;
4825 }
4826
4827 /** Returns the <title> or filename or "Untitled" */
4828 function get_title()
4829 {
4830 if ('document' in global_scope) {
4831 //Don't use document.title to work around an Opera/Presto bug in XHTML documents
4832 var title = document.getElementsByTagName("title")[0];
4833 if (title && title.firstChild && title.firstChild.data) {
4834 return title.firstChild.data;
4835 }
4836 }
4837 if ('META_TITLE' in global_scope && META_TITLE) {
4838 return META_TITLE;
4839 }
4840 if ('location' in global_scope && 'pathname' in location) {
4841 var filename = location.pathname.substring(location.pathname.lastIndexOf('/') + 1);
4842 return filename.substring(0, filename.indexOf('.'));
4843 }
4844 return "Untitled";
4845 }
4846
4847 /** Fetches a JSON resource and parses it */
4848 async function fetch_json(resource) {
4849 const response = await fetch(resource);
4850 return await response.json();
4851 }
4852 if (!global_scope.GLOBAL || !global_scope.GLOBAL.isShadowRealm()) {
4853 expose(fetch_json, 'fetch_json');
4854 }
4855
4856 /**
4857 * Setup globals
4858 */
4859
4860 var tests = new Tests();
4861
4862 if (global_scope.addEventListener) {
4863 var error_handler = function(error, message, stack) {
4864 var optional_unsupported = error instanceof OptionalFeatureUnsupportedError;
4865 if (tests.file_is_test) {
4866 var test = tests.tests[0];
4867 if (test.phase >= test.phases.HAS_RESULT) {
4868 return;
4869 }
4870 var status = optional_unsupported ? test.PRECONDITION_FAILED : test.FAIL;
4871 test.set_status(status, message, stack);
4872 test.phase = test.phases.HAS_RESULT;
4873 } else if (!tests.allow_uncaught_exception) {
4874 var status = optional_unsupported ? tests.status.PRECONDITION_FAILED : tests.status.ERROR;
4875 tests.status.status = status;
4876 tests.status.message = message;
4877 tests.status.stack = stack;
4878 }
4879
4880 // Do not transition to the "complete" phase if the test has been
4881 // configured to allow uncaught exceptions. This gives the test an
4882 // opportunity to define subtests based on the exception reporting
4883 // behavior.
4884 if (!tests.allow_uncaught_exception) {
4885 done();
4886 }
4887 };
4888
4889 addEventListener("error", function(e) {
4890 var message = e.message;
4891 var stack;
4892 if (e.error && e.error.stack) {
4893 stack = e.error.stack;
4894 } else {
4895 stack = e.filename + ":" + e.lineno + ":" + e.colno;
4896 }
4897 error_handler(e.error, message, stack);
4898 }, false);
4899
4900 addEventListener("unhandledrejection", function(e) {
4901 var message;
4902 if (e.reason && e.reason.message) {
4903 message = "Unhandled rejection: " + e.reason.message;
4904 } else {
4905 message = "Unhandled rejection";
4906 }
4907 var stack;
4908 if (e.reason && e.reason.stack) {
4909 stack = e.reason.stack;
4910 }
4911 error_handler(e.reason, message, stack);
4912 }, false);
4913 }
4914
4915 test_environment.on_tests_ready();
4916
4917 /**
4918 * Stylesheet
4919 */
4920 var stylesheetContent = "\
4921 html {\
4922 font-family:DejaVu Sans, Bitstream Vera Sans, Arial, Sans;\
4923 }\
4924 \
4925 #log .warning,\
4926 #log .warning a {\
4927 color: black;\
4928 background: yellow;\
4929 }\
4930 \
4931 #log .error,\
4932 #log .error a {\
4933 color: white;\
4934 background: red;\
4935 }\
4936 \
4937 section#summary {\
4938 margin-bottom:1em;\
4939 }\
4940 \
4941 table#results {\
4942 border-collapse:collapse;\
4943 table-layout:fixed;\
4944 width:100%;\
4945 }\
4946 \
4947 table#results > thead > tr > th:first-child,\
4948 table#results > tbody > tr > td:first-child {\
4949 width:8em;\
4950 }\
4951 \
4952 table#results > thead > tr > th:last-child,\
4953 table#results > thead > tr > td:last-child {\
4954 width:50%;\
4955 }\
4956 \
4957 table#results.assertions > thead > tr > th:last-child,\
4958 table#results.assertions > tbody > tr > td:last-child {\
4959 width:35%;\
4960 }\
4961 \
4962 table#results > thead > > tr > th {\
4963 padding:0;\
4964 padding-bottom:0.5em;\
4965 border-bottom:medium solid black;\
4966 }\
4967 \
4968 table#results > tbody > tr> td {\
4969 padding:1em;\
4970 padding-bottom:0.5em;\
4971 border-bottom:thin solid black;\
4972 }\
4973 \
4974 .pass {\
4975 color:green;\
4976 }\
4977 \
4978 .fail {\
4979 color:red;\
4980 }\
4981 \
4982 tr.timeout {\
4983 color:red;\
4984 }\
4985 \
4986 tr.notrun {\
4987 color:blue;\
4988 }\
4989 \
4990 tr.optionalunsupported {\
4991 color:blue;\
4992 }\
4993 \
4994 .ok {\
4995 color:green;\
4996 }\
4997 \
4998 .error {\
4999 color:red;\
5000 }\
5001 \
5002 .pass, .fail, .timeout, .notrun, .optionalunsupported .ok, .timeout, .error {\
5003 font-variant:small-caps;\
5004 }\
5005 \
5006 table#results span {\
5007 display:block;\
5008 }\
5009 \
5010 table#results span.expected {\
5011 font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace;\
5012 white-space:pre;\
5013 }\
5014 \
5015 table#results span.actual {\
5016 font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace;\
5017 white-space:pre;\
5018 }\
5019 ";
5020
5021 })(self);
5022 // vim: set expandtab shiftwidth=4 tabstop=4: