Move helper files for iOS touch gestures into LayoutTests/resources
[WebKit-https.git] / LayoutTests / resources / testharness.js
1 /*global self*/
2 /*jshint latedef: nofunc*/
3 /*
4 Distributed under both the W3C Test Suite License [1] and the W3C
5 3-clause BSD License [2]. To contribute to a W3C Test Suite, see the
6 policies and contribution forms [3].
7
8 [1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license
9 [2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license
10 [3] http://www.w3.org/2004/10/27-testcases
11 */
12
13 /* Documentation is in docs/api.md */
14
15 (function ()
16 {
17     var debug = false;
18     // default timeout is 10 seconds, test can override if needed
19     var settings = {
20         output:true,
21         harness_timeout:{
22             "normal":10000,
23             "long":60000
24         },
25         test_timeout:null,
26         message_events: ["start", "test_state", "result", "completion"]
27     };
28
29     var xhtml_ns = "http://www.w3.org/1999/xhtml";
30
31     /*
32      * TestEnvironment is an abstraction for the environment in which the test
33      * harness is used. Each implementation of a test environment has to provide
34      * the following interface:
35      *
36      * interface TestEnvironment {
37      *   // Invoked after the global 'tests' object has been created and it's
38      *   // safe to call add_*_callback() to register event handlers.
39      *   void on_tests_ready();
40      *
41      *   // Invoked after setup() has been called to notify the test environment
42      *   // of changes to the test harness properties.
43      *   void on_new_harness_properties(object properties);
44      *
45      *   // Should return a new unique default test name.
46      *   DOMString next_default_test_name();
47      *
48      *   // Should return the test harness timeout duration in milliseconds.
49      *   float test_timeout();
50      *
51      *   // Should return the global scope object.
52      *   object global_scope();
53      * };
54      */
55
56     /*
57      * A test environment with a DOM. The global object is 'window'. By default
58      * test results are displayed in a table. Any parent windows receive
59      * callbacks or messages via postMessage() when test events occur. See
60      * apisample11.html and apisample12.html.
61      */
62     function WindowTestEnvironment() {
63         this.name_counter = 0;
64         this.window_cache = null;
65         this.output_handler = null;
66         this.all_loaded = false;
67         var this_obj = this;
68         this.message_events = [];
69
70         this.message_functions = {
71             start: [add_start_callback, remove_start_callback,
72                     function (properties) {
73                         this_obj._dispatch("start_callback", [properties],
74                                            {type: "start", properties: properties});
75                     }],
76
77             test_state: [add_test_state_callback, remove_test_state_callback,
78                          function(test) {
79                              this_obj._dispatch("test_state_callback", [test],
80                                                 {type: "test_state",
81                                                  test: test.structured_clone()});
82                          }],
83             result: [add_result_callback, remove_result_callback,
84                      function (test) {
85                          this_obj.output_handler.show_status();
86                          this_obj._dispatch("result_callback", [test],
87                                             {type: "result",
88                                              test: test.structured_clone()});
89                      }],
90             completion: [add_completion_callback, remove_completion_callback,
91                          function (tests, harness_status) {
92                              var cloned_tests = map(tests, function(test) {
93                                  return test.structured_clone();
94                              });
95                              this_obj._dispatch("completion_callback", [tests, harness_status],
96                                                 {type: "complete",
97                                                  tests: cloned_tests,
98                                                  status: harness_status.structured_clone()});
99                          }]
100         }
101
102         on_event(window, 'load', function() {
103             this_obj.all_loaded = true;
104         });
105     }
106
107     WindowTestEnvironment.prototype._dispatch = function(selector, callback_args, message_arg) {
108         this._forEach_windows(
109                 function(w, same_origin) {
110                     if (same_origin) {
111                         try {
112                             var has_selector = selector in w;
113                         } catch(e) {
114                             // If document.domain was set at some point same_origin can be
115                             // wrong and the above will fail.
116                             has_selector = false;
117                         }
118                         if (has_selector) {
119                             try {
120                                 w[selector].apply(undefined, callback_args);
121                             } catch (e) {
122                                 if (debug) {
123                                     throw e;
124                                 }
125                             }
126                         }
127                     }
128                     if (supports_post_message(w) && w !== self) {
129                         w.postMessage(message_arg, "*");
130                     }
131                 });
132     };
133
134     WindowTestEnvironment.prototype._forEach_windows = function(callback) {
135         // Iterate of the the windows [self ... top, opener]. The callback is passed
136         // two objects, the first one is the windows object itself, the second one
137         // is a boolean indicating whether or not its on the same origin as the
138         // current window.
139         var cache = this.window_cache;
140         if (!cache) {
141             cache = [[self, true]];
142             var w = self;
143             var i = 0;
144             var so;
145             var origins = location.ancestorOrigins;
146             while (w != w.parent) {
147                 w = w.parent;
148                 // In WebKit, calls to parent windows' properties that aren't on the same
149                 // origin cause an error message to be displayed in the error console but
150                 // don't throw an exception. This is a deviation from the current HTML5
151                 // spec. See: https://bugs.webkit.org/show_bug.cgi?id=43504
152                 // The problem with WebKit's behavior is that it pollutes the error console
153                 // with error messages that can't be caught.
154                 //
155                 // This issue can be mitigated by relying on the (for now) proprietary
156                 // `location.ancestorOrigins` property which returns an ordered list of
157                 // the origins of enclosing windows. See:
158                 // http://trac.webkit.org/changeset/113945.
159                 if (origins) {
160                     so = (location.origin == origins[i]);
161                 } else {
162                     so = is_same_origin(w);
163                 }
164                 cache.push([w, so]);
165                 i++;
166             }
167             w = window.opener;
168             if (w) {
169                 // window.opener isn't included in the `location.ancestorOrigins` prop.
170                 // We'll just have to deal with a simple check and an error msg on WebKit
171                 // browsers in this case.
172                 cache.push([w, is_same_origin(w)]);
173             }
174             this.window_cache = cache;
175         }
176
177         forEach(cache,
178                 function(a) {
179                     callback.apply(null, a);
180                 });
181     };
182
183     WindowTestEnvironment.prototype.on_tests_ready = function() {
184         var output = new Output();
185         this.output_handler = output;
186
187         var this_obj = this;
188
189         add_start_callback(function (properties) {
190             this_obj.output_handler.init(properties);
191         });
192
193         add_test_state_callback(function(test) {
194             this_obj.output_handler.show_status();
195         });
196
197         add_result_callback(function (test) {
198             this_obj.output_handler.show_status();
199         });
200
201         add_completion_callback(function (tests, harness_status) {
202             this_obj.output_handler.show_results(tests, harness_status);
203         });
204         this.setup_messages(settings.message_events);
205     };
206
207     WindowTestEnvironment.prototype.setup_messages = function(new_events) {
208         var this_obj = this;
209         forEach(settings.message_events, function(x) {
210             var current_dispatch = this_obj.message_events.indexOf(x) !== -1;
211             var new_dispatch = new_events.indexOf(x) !== -1;
212             if (!current_dispatch && new_dispatch) {
213                 this_obj.message_functions[x][0](this_obj.message_functions[x][2]);
214             } else if (current_dispatch && !new_dispatch) {
215                 this_obj.message_functions[x][1](this_obj.message_functions[x][2]);
216             }
217         });
218         this.message_events = new_events;
219     }
220
221     WindowTestEnvironment.prototype.next_default_test_name = function() {
222         //Don't use document.title to work around an Opera bug in XHTML documents
223         var title = document.getElementsByTagName("title")[0];
224         var prefix = (title && title.firstChild && title.firstChild.data) || "Untitled";
225         var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
226         this.name_counter++;
227         return prefix + suffix;
228     };
229
230     WindowTestEnvironment.prototype.on_new_harness_properties = function(properties) {
231         this.output_handler.setup(properties);
232         if (properties.hasOwnProperty("message_events")) {
233             this.setup_messages(properties.message_events);
234         }
235     };
236
237     WindowTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
238         on_event(window, 'load', callback);
239     };
240
241     WindowTestEnvironment.prototype.test_timeout = function() {
242         var metas = document.getElementsByTagName("meta");
243         for (var i = 0; i < metas.length; i++) {
244             if (metas[i].name == "timeout") {
245                 if (metas[i].content == "long") {
246                     return settings.harness_timeout.long;
247                 }
248                 break;
249             }
250         }
251         return settings.harness_timeout.normal;
252     };
253
254     WindowTestEnvironment.prototype.global_scope = function() {
255         return window;
256     };
257
258     /*
259      * Base TestEnvironment implementation for a generic web worker.
260      *
261      * Workers accumulate test results. One or more clients can connect and
262      * retrieve results from a worker at any time.
263      *
264      * WorkerTestEnvironment supports communicating with a client via a
265      * MessagePort.  The mechanism for determining the appropriate MessagePort
266      * for communicating with a client depends on the type of worker and is
267      * implemented by the various specializations of WorkerTestEnvironment
268      * below.
269      *
270      * A client document using testharness can use fetch_tests_from_worker() to
271      * retrieve results from a worker. See apisample16.html.
272      */
273     function WorkerTestEnvironment() {
274         this.name_counter = 0;
275         this.all_loaded = true;
276         this.message_list = [];
277         this.message_ports = [];
278     }
279
280     WorkerTestEnvironment.prototype._dispatch = function(message) {
281         this.message_list.push(message);
282         for (var i = 0; i < this.message_ports.length; ++i)
283         {
284             this.message_ports[i].postMessage(message);
285         }
286     };
287
288     // The only requirement is that port has a postMessage() method. It doesn't
289     // have to be an instance of a MessagePort, and often isn't.
290     WorkerTestEnvironment.prototype._add_message_port = function(port) {
291         this.message_ports.push(port);
292         for (var i = 0; i < this.message_list.length; ++i)
293         {
294             port.postMessage(this.message_list[i]);
295         }
296     };
297
298     WorkerTestEnvironment.prototype.next_default_test_name = function() {
299         var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
300         this.name_counter++;
301         return "Untitled" + suffix;
302     };
303
304     WorkerTestEnvironment.prototype.on_new_harness_properties = function() {};
305
306     WorkerTestEnvironment.prototype.on_tests_ready = function() {
307         var this_obj = this;
308         add_start_callback(
309                 function(properties) {
310                     this_obj._dispatch({
311                         type: "start",
312                         properties: properties,
313                     });
314                 });
315         add_test_state_callback(
316                 function(test) {
317                     this_obj._dispatch({
318                         type: "test_state",
319                         test: test.structured_clone()
320                     });
321                 });
322         add_result_callback(
323                 function(test) {
324                     this_obj._dispatch({
325                         type: "result",
326                         test: test.structured_clone()
327                     });
328                 });
329         add_completion_callback(
330                 function(tests, harness_status) {
331                     this_obj._dispatch({
332                         type: "complete",
333                         tests: map(tests,
334                             function(test) {
335                                 return test.structured_clone();
336                             }),
337                         status: harness_status.structured_clone()
338                     });
339                 });
340     };
341
342     WorkerTestEnvironment.prototype.add_on_loaded_callback = function() {};
343
344     WorkerTestEnvironment.prototype.test_timeout = function() {
345         // Tests running in a worker don't have a default timeout. I.e. all
346         // worker tests behave as if settings.explicit_timeout is true.
347         return null;
348     };
349
350     WorkerTestEnvironment.prototype.global_scope = function() {
351         return self;
352     };
353
354     /*
355      * Dedicated web workers.
356      * https://html.spec.whatwg.org/multipage/workers.html#dedicatedworkerglobalscope
357      *
358      * This class is used as the test_environment when testharness is running
359      * inside a dedicated worker.
360      */
361     function DedicatedWorkerTestEnvironment() {
362         WorkerTestEnvironment.call(this);
363         // self is an instance of DedicatedWorkerGlobalScope which exposes
364         // a postMessage() method for communicating via the message channel
365         // established when the worker is created.
366         this._add_message_port(self);
367     }
368     DedicatedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
369
370     DedicatedWorkerTestEnvironment.prototype.on_tests_ready = function() {
371         WorkerTestEnvironment.prototype.on_tests_ready.call(this);
372         // In the absence of an onload notification, we a require dedicated
373         // workers to explicitly signal when the tests are done.
374         tests.wait_for_finish = true;
375     };
376
377     /*
378      * Shared web workers.
379      * https://html.spec.whatwg.org/multipage/workers.html#sharedworkerglobalscope
380      *
381      * This class is used as the test_environment when testharness is running
382      * inside a shared web worker.
383      */
384     function SharedWorkerTestEnvironment() {
385         WorkerTestEnvironment.call(this);
386         var this_obj = this;
387         // Shared workers receive message ports via the 'onconnect' event for
388         // each connection.
389         self.addEventListener("connect",
390                 function(message_event) {
391                     this_obj._add_message_port(message_event.source);
392                 }, false);
393     }
394     SharedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
395
396     SharedWorkerTestEnvironment.prototype.on_tests_ready = function() {
397         WorkerTestEnvironment.prototype.on_tests_ready.call(this);
398         // In the absence of an onload notification, we a require shared
399         // workers to explicitly signal when the tests are done.
400         tests.wait_for_finish = true;
401     };
402
403     /*
404      * Service workers.
405      * http://www.w3.org/TR/service-workers/
406      *
407      * This class is used as the test_environment when testharness is running
408      * inside a service worker.
409      */
410     function ServiceWorkerTestEnvironment() {
411         WorkerTestEnvironment.call(this);
412         this.all_loaded = false;
413         this.on_loaded_callback = null;
414         var this_obj = this;
415         self.addEventListener("message",
416                 function(event) {
417                     if (event.data.type && event.data.type === "connect") {
418                         if (event.ports && event.ports[0]) {
419                             // If a MessageChannel was passed, then use it to
420                             // send results back to the main window.  This
421                             // allows the tests to work even if the browser
422                             // does not fully support MessageEvent.source in
423                             // ServiceWorkers yet.
424                             this_obj._add_message_port(event.ports[0]);
425                             event.ports[0].start();
426                         } else {
427                             // If there is no MessageChannel, then attempt to
428                             // use the MessageEvent.source to send results
429                             // back to the main window.
430                             this_obj._add_message_port(event.source);
431                         }
432                     }
433                 }, false);
434
435         // The oninstall event is received after the service worker script and
436         // all imported scripts have been fetched and executed. It's the
437         // equivalent of an onload event for a document. All tests should have
438         // been added by the time this event is received, thus it's not
439         // necessary to wait until the onactivate event.
440         on_event(self, "install",
441                 function(event) {
442                     this_obj.all_loaded = true;
443                     if (this_obj.on_loaded_callback) {
444                         this_obj.on_loaded_callback();
445                     }
446                 });
447     }
448     ServiceWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
449
450     ServiceWorkerTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
451         if (this.all_loaded) {
452             callback();
453         } else {
454             this.on_loaded_callback = callback;
455         }
456     };
457
458     function create_test_environment() {
459         if ('document' in self) {
460             return new WindowTestEnvironment();
461         }
462         if ('DedicatedWorkerGlobalScope' in self &&
463             self instanceof DedicatedWorkerGlobalScope) {
464             return new DedicatedWorkerTestEnvironment();
465         }
466         if ('SharedWorkerGlobalScope' in self &&
467             self instanceof SharedWorkerGlobalScope) {
468             return new SharedWorkerTestEnvironment();
469         }
470         if ('ServiceWorkerGlobalScope' in self &&
471             self instanceof ServiceWorkerGlobalScope) {
472             return new ServiceWorkerTestEnvironment();
473         }
474         if ('WorkerGlobalScope' in self &&
475             self instanceof WorkerGlobalScope) {
476             return new DedicatedWorkerTestEnvironment();
477         }
478
479         throw new Error("Unsupported test environment");
480     }
481
482     var test_environment = create_test_environment();
483
484     function is_shared_worker(worker) {
485         return 'SharedWorker' in self && worker instanceof SharedWorker;
486     }
487
488     function is_service_worker(worker) {
489         return 'ServiceWorker' in self && worker instanceof ServiceWorker;
490     }
491
492     /*
493      * API functions
494      */
495
496     function test(func, name, properties)
497     {
498         var test_name = name ? name : test_environment.next_default_test_name();
499         properties = properties ? properties : {};
500         var test_obj = new Test(test_name, properties);
501         test_obj.step(func, test_obj, test_obj);
502         if (test_obj.phase === test_obj.phases.STARTED) {
503             test_obj.done();
504         }
505     }
506
507     function async_test(func, name, properties)
508     {
509         if (typeof func !== "function") {
510             properties = name;
511             name = func;
512             func = null;
513         }
514         var test_name = name ? name : test_environment.next_default_test_name();
515         properties = properties ? properties : {};
516         var test_obj = new Test(test_name, properties);
517         if (func) {
518             test_obj.step(func, test_obj, test_obj);
519         }
520         return test_obj;
521     }
522
523     function promise_test(func, name, properties) {
524         var test = async_test(name, properties);
525         // If there is no promise tests queue make one.
526         if (!tests.promise_tests) {
527             tests.promise_tests = Promise.resolve();
528         }
529         tests.promise_tests = tests.promise_tests.then(function() {
530             var donePromise = new Promise(function(resolve) {
531                 test.add_cleanup(resolve);
532             });
533             var promise = test.step(func, test, test);
534             test.step(function() {
535                 assert_not_equals(promise, undefined);
536             });
537             Promise.resolve(promise).then(
538                     function() {
539                         test.done();
540                     })
541                 .catch(test.step_func(
542                     function(value) {
543                         if (value instanceof AssertionError) {
544                             throw value;
545                         }
546                         assert(false, "promise_test", null,
547                                "Unhandled rejection with value: ${value}", {value:value});
548                     }));
549             return donePromise;
550         });
551     }
552
553     function promise_rejects(test, expected, promise, description) {
554         return promise.then(test.unreached_func("Should have rejected: " + description)).catch(function(e) {
555             assert_throws(expected, function() { throw e }, description);
556         });
557     }
558
559     /**
560      * This constructor helper allows DOM events to be handled using Promises,
561      * which can make it a lot easier to test a very specific series of events,
562      * including ensuring that unexpected events are not fired at any point.
563      */
564     function EventWatcher(test, watchedNode, eventTypes)
565     {
566         if (typeof eventTypes == 'string') {
567             eventTypes = [eventTypes];
568         }
569
570         var waitingFor = null;
571
572         var eventHandler = test.step_func(function(evt) {
573             assert_true(!!waitingFor,
574                         'Not expecting event, but got ' + evt.type + ' event');
575             assert_equals(evt.type, waitingFor.types[0],
576                           'Expected ' + waitingFor.types[0] + ' event, but got ' +
577                           evt.type + ' event instead');
578             if (waitingFor.types.length > 1) {
579                 // Pop first event from array
580                 waitingFor.types.shift();
581                 return;
582             }
583             // We need to null out waitingFor before calling the resolve function
584             // since the Promise's resolve handlers may call wait_for() which will
585             // need to set waitingFor.
586             var resolveFunc = waitingFor.resolve;
587             waitingFor = null;
588             resolveFunc(evt);
589         });
590
591         for (var i = 0; i < eventTypes.length; i++) {
592             watchedNode.addEventListener(eventTypes[i], eventHandler, false);
593         }
594
595         /**
596          * Returns a Promise that will resolve after the specified event or
597          * series of events has occured.
598          */
599         this.wait_for = function(types) {
600             if (waitingFor) {
601                 return Promise.reject('Already waiting for an event or events');
602             }
603             if (typeof types == 'string') {
604                 types = [types];
605             }
606             return new Promise(function(resolve, reject) {
607                 waitingFor = {
608                     types: types,
609                     resolve: resolve,
610                     reject: reject
611                 };
612             });
613         };
614
615         function stop_watching() {
616             for (var i = 0; i < eventTypes.length; i++) {
617                 watchedNode.removeEventListener(eventTypes[i], eventHandler, false);
618             }
619         };
620
621         test.add_cleanup(stop_watching);
622
623         return this;
624     }
625     expose(EventWatcher, 'EventWatcher');
626
627     function setup(func_or_properties, maybe_properties)
628     {
629         var func = null;
630         var properties = {};
631         if (arguments.length === 2) {
632             func = func_or_properties;
633             properties = maybe_properties;
634         } else if (func_or_properties instanceof Function) {
635             func = func_or_properties;
636         } else {
637             properties = func_or_properties;
638         }
639         tests.setup(func, properties);
640         test_environment.on_new_harness_properties(properties);
641     }
642
643     function done() {
644         if (tests.tests.length === 0) {
645             tests.set_file_is_test();
646         }
647         if (tests.file_is_test) {
648             tests.tests[0].done();
649         }
650         tests.end_wait();
651     }
652
653     function generate_tests(func, args, properties) {
654         forEach(args, function(x, i)
655                 {
656                     var name = x[0];
657                     test(function()
658                          {
659                              func.apply(this, x.slice(1));
660                          },
661                          name,
662                          Array.isArray(properties) ? properties[i] : properties);
663                 });
664     }
665
666     function on_event(object, event, callback)
667     {
668         object.addEventListener(event, callback, false);
669     }
670
671     function step_timeout(f, t) {
672         var outer_this = this;
673         var args = Array.prototype.slice.call(arguments, 2);
674         return setTimeout(function() {
675             f.apply(outer_this, args);
676         }, t * tests.timeout_multiplier);
677     }
678
679     expose(test, 'test');
680     expose(async_test, 'async_test');
681     expose(promise_test, 'promise_test');
682     expose(promise_rejects, 'promise_rejects');
683     expose(generate_tests, 'generate_tests');
684     expose(setup, 'setup');
685     expose(done, 'done');
686     expose(on_event, 'on_event');
687     expose(step_timeout, 'step_timeout');
688
689     /*
690      * Return a string truncated to the given length, with ... added at the end
691      * if it was longer.
692      */
693     function truncate(s, len)
694     {
695         if (s.length > len) {
696             return s.substring(0, len - 3) + "...";
697         }
698         return s;
699     }
700
701     /*
702      * Return true if object is probably a Node object.
703      */
704     function is_node(object)
705     {
706         // I use duck-typing instead of instanceof, because
707         // instanceof doesn't work if the node is from another window (like an
708         // iframe's contentWindow):
709         // http://www.w3.org/Bugs/Public/show_bug.cgi?id=12295
710         try {
711             var has_node_properties = ("nodeType" in object &&
712                                        "nodeName" in object &&
713                                        "nodeValue" in object &&
714                                        "childNodes" in object);
715         } catch (e) {
716             // We're probably cross-origin, which means we aren't a node
717             return false;
718         }
719
720         if (has_node_properties) {
721             try {
722                 object.nodeType;
723             } catch (e) {
724                 // The object is probably Node.prototype or another prototype
725                 // object that inherits from it, and not a Node instance.
726                 return false;
727             }
728             return true;
729         }
730         return false;
731     }
732
733     var replacements = {
734         "0": "0",
735         "1": "x01",
736         "2": "x02",
737         "3": "x03",
738         "4": "x04",
739         "5": "x05",
740         "6": "x06",
741         "7": "x07",
742         "8": "b",
743         "9": "t",
744         "10": "n",
745         "11": "v",
746         "12": "f",
747         "13": "r",
748         "14": "x0e",
749         "15": "x0f",
750         "16": "x10",
751         "17": "x11",
752         "18": "x12",
753         "19": "x13",
754         "20": "x14",
755         "21": "x15",
756         "22": "x16",
757         "23": "x17",
758         "24": "x18",
759         "25": "x19",
760         "26": "x1a",
761         "27": "x1b",
762         "28": "x1c",
763         "29": "x1d",
764         "30": "x1e",
765         "31": "x1f",
766         "0xfffd": "ufffd",
767         "0xfffe": "ufffe",
768         "0xffff": "uffff",
769     };
770
771     /*
772      * Convert a value to a nice, human-readable string
773      */
774     function format_value(val, seen)
775     {
776         if (!seen) {
777             seen = [];
778         }
779         if (typeof val === "object" && val !== null) {
780             if (seen.indexOf(val) >= 0) {
781                 return "[...]";
782             }
783             seen.push(val);
784         }
785         if (Array.isArray(val)) {
786             return "[" + val.map(function(x) {return format_value(x, seen);}).join(", ") + "]";
787         }
788
789         switch (typeof val) {
790         case "string":
791             val = val.replace("\\", "\\\\");
792             for (var p in replacements) {
793                 var replace = "\\" + replacements[p];
794                 val = val.replace(RegExp(String.fromCharCode(p), "g"), replace);
795             }
796             return '"' + val.replace(/"/g, '\\"') + '"';
797         case "boolean":
798         case "undefined":
799             return String(val);
800         case "number":
801             // In JavaScript, -0 === 0 and String(-0) == "0", so we have to
802             // special-case.
803             if (val === -0 && 1/val === -Infinity) {
804                 return "-0";
805             }
806             return String(val);
807         case "object":
808             if (val === null) {
809                 return "null";
810             }
811
812             // Special-case Node objects, since those come up a lot in my tests.  I
813             // ignore namespaces.
814             if (is_node(val)) {
815                 switch (val.nodeType) {
816                 case Node.ELEMENT_NODE:
817                     var ret = "<" + val.localName;
818                     for (var i = 0; i < val.attributes.length; i++) {
819                         ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"';
820                     }
821                     ret += ">" + val.innerHTML + "</" + val.localName + ">";
822                     return "Element node " + truncate(ret, 60);
823                 case Node.TEXT_NODE:
824                     return 'Text node "' + truncate(val.data, 60) + '"';
825                 case Node.PROCESSING_INSTRUCTION_NODE:
826                     return "ProcessingInstruction node with target " + format_value(truncate(val.target, 60)) + " and data " + format_value(truncate(val.data, 60));
827                 case Node.COMMENT_NODE:
828                     return "Comment node <!--" + truncate(val.data, 60) + "-->";
829                 case Node.DOCUMENT_NODE:
830                     return "Document node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
831                 case Node.DOCUMENT_TYPE_NODE:
832                     return "DocumentType node";
833                 case Node.DOCUMENT_FRAGMENT_NODE:
834                     return "DocumentFragment node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
835                 default:
836                     return "Node object of unknown type";
837                 }
838             }
839
840         /* falls through */
841         default:
842             try {
843                 return typeof val + ' "' + truncate(String(val), 1000) + '"';
844             } catch(e) {
845                 return ("[stringifying object threw " + String(e) +
846                         " with type " + String(typeof e) + "]");
847             }
848         }
849     }
850     expose(format_value, "format_value");
851
852     /*
853      * Assertions
854      */
855
856     function assert_true(actual, description)
857     {
858         assert(actual === true, "assert_true", description,
859                                 "expected true got ${actual}", {actual:actual});
860     }
861     expose(assert_true, "assert_true");
862
863     function assert_false(actual, description)
864     {
865         assert(actual === false, "assert_false", description,
866                                  "expected false got ${actual}", {actual:actual});
867     }
868     expose(assert_false, "assert_false");
869
870     function same_value(x, y) {
871         if (y !== y) {
872             //NaN case
873             return x !== x;
874         }
875         if (x === 0 && y === 0) {
876             //Distinguish +0 and -0
877             return 1/x === 1/y;
878         }
879         return x === y;
880     }
881
882     function assert_equals(actual, expected, description)
883     {
884          /*
885           * Test if two primitives are equal or two objects
886           * are the same object
887           */
888         if (typeof actual != typeof expected) {
889             assert(false, "assert_equals", description,
890                           "expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}",
891                           {expected:expected, actual:actual});
892             return;
893         }
894         assert(same_value(actual, expected), "assert_equals", description,
895                                              "expected ${expected} but got ${actual}",
896                                              {expected:expected, actual:actual});
897     }
898     expose(assert_equals, "assert_equals");
899
900     function assert_not_equals(actual, expected, description)
901     {
902          /*
903           * Test if two primitives are unequal or two objects
904           * are different objects
905           */
906         assert(!same_value(actual, expected), "assert_not_equals", description,
907                                               "got disallowed value ${actual}",
908                                               {actual:actual});
909     }
910     expose(assert_not_equals, "assert_not_equals");
911
912     function assert_in_array(actual, expected, description)
913     {
914         assert(expected.indexOf(actual) != -1, "assert_in_array", description,
915                                                "value ${actual} not in array ${expected}",
916                                                {actual:actual, expected:expected});
917     }
918     expose(assert_in_array, "assert_in_array");
919
920     function assert_object_equals(actual, expected, description)
921     {
922          //This needs to be improved a great deal
923          function check_equal(actual, expected, stack)
924          {
925              stack.push(actual);
926
927              var p;
928              for (p in actual) {
929                  assert(expected.hasOwnProperty(p), "assert_object_equals", description,
930                                                     "unexpected property ${p}", {p:p});
931
932                  if (typeof actual[p] === "object" && actual[p] !== null) {
933                      if (stack.indexOf(actual[p]) === -1) {
934                          check_equal(actual[p], expected[p], stack);
935                      }
936                  } else {
937                      assert(same_value(actual[p], expected[p]), "assert_object_equals", description,
938                                                        "property ${p} expected ${expected} got ${actual}",
939                                                        {p:p, expected:expected, actual:actual});
940                  }
941              }
942              for (p in expected) {
943                  assert(actual.hasOwnProperty(p),
944                         "assert_object_equals", description,
945                         "expected property ${p} missing", {p:p});
946              }
947              stack.pop();
948          }
949          check_equal(actual, expected, []);
950     }
951     expose(assert_object_equals, "assert_object_equals");
952
953     function assert_array_equals(actual, expected, description)
954     {
955         assert(actual.length === expected.length,
956                "assert_array_equals", description,
957                "lengths differ, expected ${expected} got ${actual}",
958                {expected:expected.length, actual:actual.length});
959
960         for (var i = 0; i < actual.length; i++) {
961             assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),
962                    "assert_array_equals", description,
963                    "property ${i}, property expected to be ${expected} but was ${actual}",
964                    {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing",
965                    actual:actual.hasOwnProperty(i) ? "present" : "missing"});
966             assert(same_value(expected[i], actual[i]),
967                    "assert_array_equals", description,
968                    "property ${i}, expected ${expected} but got ${actual}",
969                    {i:i, expected:expected[i], actual:actual[i]});
970         }
971     }
972     expose(assert_array_equals, "assert_array_equals");
973
974     function assert_approx_equals(actual, expected, epsilon, description)
975     {
976         /*
977          * Test if two primitive numbers are equal withing +/- epsilon
978          */
979         assert(typeof actual === "number",
980                "assert_approx_equals", description,
981                "expected a number but got a ${type_actual}",
982                {type_actual:typeof actual});
983
984         assert(Math.abs(actual - expected) <= epsilon,
985                "assert_approx_equals", description,
986                "expected ${expected} +/- ${epsilon} but got ${actual}",
987                {expected:expected, actual:actual, epsilon:epsilon});
988     }
989     expose(assert_approx_equals, "assert_approx_equals");
990
991     function assert_less_than(actual, expected, description)
992     {
993         /*
994          * Test if a primitive number is less than another
995          */
996         assert(typeof actual === "number",
997                "assert_less_than", description,
998                "expected a number but got a ${type_actual}",
999                {type_actual:typeof actual});
1000
1001         assert(actual < expected,
1002                "assert_less_than", description,
1003                "expected a number less than ${expected} but got ${actual}",
1004                {expected:expected, actual:actual});
1005     }
1006     expose(assert_less_than, "assert_less_than");
1007
1008     function assert_greater_than(actual, expected, description)
1009     {
1010         /*
1011          * Test if a primitive number is greater than another
1012          */
1013         assert(typeof actual === "number",
1014                "assert_greater_than", description,
1015                "expected a number but got a ${type_actual}",
1016                {type_actual:typeof actual});
1017
1018         assert(actual > expected,
1019                "assert_greater_than", description,
1020                "expected a number greater than ${expected} but got ${actual}",
1021                {expected:expected, actual:actual});
1022     }
1023     expose(assert_greater_than, "assert_greater_than");
1024
1025     function assert_between_exclusive(actual, lower, upper, description)
1026     {
1027         /*
1028          * Test if a primitive number is between two others
1029          */
1030         assert(typeof actual === "number",
1031                "assert_between_exclusive", description,
1032                "expected a number but got a ${type_actual}",
1033                {type_actual:typeof actual});
1034
1035         assert(actual > lower && actual < upper,
1036                "assert_between_exclusive", description,
1037                "expected a number greater than ${lower} " +
1038                "and less than ${upper} but got ${actual}",
1039                {lower:lower, upper:upper, actual:actual});
1040     }
1041     expose(assert_between_exclusive, "assert_between_exclusive");
1042
1043     function assert_less_than_equal(actual, expected, description)
1044     {
1045         /*
1046          * Test if a primitive number is less than or equal to another
1047          */
1048         assert(typeof actual === "number",
1049                "assert_less_than_equal", description,
1050                "expected a number but got a ${type_actual}",
1051                {type_actual:typeof actual});
1052
1053         assert(actual <= expected,
1054                "assert_less_than_equal", description,
1055                "expected a number less than or equal to ${expected} but got ${actual}",
1056                {expected:expected, actual:actual});
1057     }
1058     expose(assert_less_than_equal, "assert_less_than_equal");
1059
1060     function assert_greater_than_equal(actual, expected, description)
1061     {
1062         /*
1063          * Test if a primitive number is greater than or equal to another
1064          */
1065         assert(typeof actual === "number",
1066                "assert_greater_than_equal", description,
1067                "expected a number but got a ${type_actual}",
1068                {type_actual:typeof actual});
1069
1070         assert(actual >= expected,
1071                "assert_greater_than_equal", description,
1072                "expected a number greater than or equal to ${expected} but got ${actual}",
1073                {expected:expected, actual:actual});
1074     }
1075     expose(assert_greater_than_equal, "assert_greater_than_equal");
1076
1077     function assert_between_inclusive(actual, lower, upper, description)
1078     {
1079         /*
1080          * Test if a primitive number is between to two others or equal to either of them
1081          */
1082         assert(typeof actual === "number",
1083                "assert_between_inclusive", description,
1084                "expected a number but got a ${type_actual}",
1085                {type_actual:typeof actual});
1086
1087         assert(actual >= lower && actual <= upper,
1088                "assert_between_inclusive", description,
1089                "expected a number greater than or equal to ${lower} " +
1090                "and less than or equal to ${upper} but got ${actual}",
1091                {lower:lower, upper:upper, actual:actual});
1092     }
1093     expose(assert_between_inclusive, "assert_between_inclusive");
1094
1095     function assert_regexp_match(actual, expected, description) {
1096         /*
1097          * Test if a string (actual) matches a regexp (expected)
1098          */
1099         assert(expected.test(actual),
1100                "assert_regexp_match", description,
1101                "expected ${expected} but got ${actual}",
1102                {expected:expected, actual:actual});
1103     }
1104     expose(assert_regexp_match, "assert_regexp_match");
1105
1106     function assert_class_string(object, class_string, description) {
1107         assert_equals({}.toString.call(object), "[object " + class_string + "]",
1108                       description);
1109     }
1110     expose(assert_class_string, "assert_class_string");
1111
1112
1113     function _assert_own_property(name) {
1114         return function(object, property_name, description)
1115         {
1116             assert(object.hasOwnProperty(property_name),
1117                    name, description,
1118                    "expected property ${p} missing", {p:property_name});
1119         };
1120     }
1121     expose(_assert_own_property("assert_exists"), "assert_exists");
1122     expose(_assert_own_property("assert_own_property"), "assert_own_property");
1123
1124     function assert_not_exists(object, property_name, description)
1125     {
1126         assert(!object.hasOwnProperty(property_name),
1127                "assert_not_exists", description,
1128                "unexpected property ${p} found", {p:property_name});
1129     }
1130     expose(assert_not_exists, "assert_not_exists");
1131
1132     function _assert_inherits(name) {
1133         return function (object, property_name, description)
1134         {
1135             assert(typeof object === "object" || typeof object === "function",
1136                    name, description,
1137                    "provided value is not an object");
1138
1139             assert("hasOwnProperty" in object,
1140                    name, description,
1141                    "provided value is an object but has no hasOwnProperty method");
1142
1143             assert(!object.hasOwnProperty(property_name),
1144                    name, description,
1145                    "property ${p} found on object expected in prototype chain",
1146                    {p:property_name});
1147
1148             assert(property_name in object,
1149                    name, description,
1150                    "property ${p} not found in prototype chain",
1151                    {p:property_name});
1152         };
1153     }
1154     expose(_assert_inherits("assert_inherits"), "assert_inherits");
1155     expose(_assert_inherits("assert_idl_attribute"), "assert_idl_attribute");
1156
1157     function assert_readonly(object, property_name, description)
1158     {
1159          var initial_value = object[property_name];
1160          try {
1161              //Note that this can have side effects in the case where
1162              //the property has PutForwards
1163              object[property_name] = initial_value + "a"; //XXX use some other value here?
1164              assert(same_value(object[property_name], initial_value),
1165                     "assert_readonly", description,
1166                     "changing property ${p} succeeded",
1167                     {p:property_name});
1168          } finally {
1169              object[property_name] = initial_value;
1170          }
1171     }
1172     expose(assert_readonly, "assert_readonly");
1173
1174     function assert_throws(code, func, description)
1175     {
1176         try {
1177             func.call(this);
1178             assert(false, "assert_throws", description,
1179                    "${func} did not throw", {func:func});
1180         } catch (e) {
1181             if (e instanceof AssertionError) {
1182                 throw e;
1183             }
1184             if (code === null) {
1185                 return;
1186             }
1187             if (typeof code === "object") {
1188                 assert(typeof e == "object" && "name" in e && e.name == code.name,
1189                        "assert_throws", description,
1190                        "${func} threw ${actual} (${actual_name}) expected ${expected} (${expected_name})",
1191                                     {func:func, actual:e, actual_name:e.name,
1192                                      expected:code,
1193                                      expected_name:code.name});
1194                 return;
1195             }
1196
1197             var code_name_map = {
1198                 INDEX_SIZE_ERR: 'IndexSizeError',
1199                 HIERARCHY_REQUEST_ERR: 'HierarchyRequestError',
1200                 WRONG_DOCUMENT_ERR: 'WrongDocumentError',
1201                 INVALID_CHARACTER_ERR: 'InvalidCharacterError',
1202                 NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',
1203                 NOT_FOUND_ERR: 'NotFoundError',
1204                 NOT_SUPPORTED_ERR: 'NotSupportedError',
1205                 INUSE_ATTRIBUTE_ERR: 'InUseAttributeError',
1206                 INVALID_STATE_ERR: 'InvalidStateError',
1207                 SYNTAX_ERR: 'SyntaxError',
1208                 INVALID_MODIFICATION_ERR: 'InvalidModificationError',
1209                 NAMESPACE_ERR: 'NamespaceError',
1210                 INVALID_ACCESS_ERR: 'InvalidAccessError',
1211                 TYPE_MISMATCH_ERR: 'TypeMismatchError',
1212                 SECURITY_ERR: 'SecurityError',
1213                 NETWORK_ERR: 'NetworkError',
1214                 ABORT_ERR: 'AbortError',
1215                 URL_MISMATCH_ERR: 'URLMismatchError',
1216                 QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
1217                 TIMEOUT_ERR: 'TimeoutError',
1218                 INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError',
1219                 DATA_CLONE_ERR: 'DataCloneError'
1220             };
1221
1222             var name = code in code_name_map ? code_name_map[code] : code;
1223
1224             var name_code_map = {
1225                 IndexSizeError: 1,
1226                 HierarchyRequestError: 3,
1227                 WrongDocumentError: 4,
1228                 InvalidCharacterError: 5,
1229                 NoModificationAllowedError: 7,
1230                 NotFoundError: 8,
1231                 NotSupportedError: 9,
1232                 InUseAttributeError: 10,
1233                 InvalidStateError: 11,
1234                 SyntaxError: 12,
1235                 InvalidModificationError: 13,
1236                 NamespaceError: 14,
1237                 InvalidAccessError: 15,
1238                 TypeMismatchError: 17,
1239                 SecurityError: 18,
1240                 NetworkError: 19,
1241                 AbortError: 20,
1242                 URLMismatchError: 21,
1243                 QuotaExceededError: 22,
1244                 TimeoutError: 23,
1245                 InvalidNodeTypeError: 24,
1246                 DataCloneError: 25,
1247
1248                 EncodingError: 0,
1249                 NotReadableError: 0,
1250                 UnknownError: 0,
1251                 ConstraintError: 0,
1252                 DataError: 0,
1253                 TransactionInactiveError: 0,
1254                 ReadOnlyError: 0,
1255                 VersionError: 0,
1256                 OperationError: 0,
1257                 NotAllowedError: 0
1258             };
1259
1260             if (!(name in name_code_map)) {
1261                 throw new AssertionError('Test bug: unrecognized DOMException code "' + code + '" passed to assert_throws()');
1262             }
1263
1264             var required_props = { code: name_code_map[name] };
1265
1266             if (required_props.code === 0 ||
1267                (typeof e == "object" &&
1268                 "name" in e &&
1269                 e.name !== e.name.toUpperCase() &&
1270                 e.name !== "DOMException")) {
1271                 // New style exception: also test the name property.
1272                 required_props.name = name;
1273             }
1274
1275             //We'd like to test that e instanceof the appropriate interface,
1276             //but we can't, because we don't know what window it was created
1277             //in.  It might be an instanceof the appropriate interface on some
1278             //unknown other window.  TODO: Work around this somehow?
1279
1280             assert(typeof e == "object",
1281                    "assert_throws", description,
1282                    "${func} threw ${e} with type ${type}, not an object",
1283                    {func:func, e:e, type:typeof e});
1284
1285             for (var prop in required_props) {
1286                 assert(typeof e == "object" && prop in e && e[prop] == required_props[prop],
1287                        "assert_throws", description,
1288                        "${func} threw ${e} that is not a DOMException " + code + ": property ${prop} is equal to ${actual}, expected ${expected}",
1289                        {func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]});
1290             }
1291         }
1292     }
1293     expose(assert_throws, "assert_throws");
1294
1295     function assert_unreached(description) {
1296          assert(false, "assert_unreached", description,
1297                 "Reached unreachable code");
1298     }
1299     expose(assert_unreached, "assert_unreached");
1300
1301     function assert_any(assert_func, actual, expected_array)
1302     {
1303         var args = [].slice.call(arguments, 3);
1304         var errors = [];
1305         var passed = false;
1306         forEach(expected_array,
1307                 function(expected)
1308                 {
1309                     try {
1310                         assert_func.apply(this, [actual, expected].concat(args));
1311                         passed = true;
1312                     } catch (e) {
1313                         errors.push(e.message);
1314                     }
1315                 });
1316         if (!passed) {
1317             throw new AssertionError(errors.join("\n\n"));
1318         }
1319     }
1320     expose(assert_any, "assert_any");
1321
1322     function Test(name, properties)
1323     {
1324         if (tests.file_is_test && tests.tests.length) {
1325             throw new Error("Tried to create a test with file_is_test");
1326         }
1327         this.name = name;
1328
1329         this.phase = this.phases.INITIAL;
1330
1331         this.status = this.NOTRUN;
1332         this.timeout_id = null;
1333         this.index = null;
1334
1335         this.properties = properties;
1336         var timeout = properties.timeout ? properties.timeout : settings.test_timeout;
1337         if (timeout !== null) {
1338             this.timeout_length = timeout * tests.timeout_multiplier;
1339         } else {
1340             this.timeout_length = null;
1341         }
1342
1343         this.message = null;
1344         this.stack = null;
1345
1346         this.steps = [];
1347
1348         this.cleanup_callbacks = [];
1349
1350         tests.push(this);
1351     }
1352
1353     Test.statuses = {
1354         PASS:0,
1355         FAIL:1,
1356         TIMEOUT:2,
1357         NOTRUN:3
1358     };
1359
1360     Test.prototype = merge({}, Test.statuses);
1361
1362     Test.prototype.phases = {
1363         INITIAL:0,
1364         STARTED:1,
1365         HAS_RESULT:2,
1366         COMPLETE:3
1367     };
1368
1369     Test.prototype.structured_clone = function()
1370     {
1371         if (!this._structured_clone) {
1372             var msg = this.message;
1373             msg = msg ? String(msg) : msg;
1374             this._structured_clone = merge({
1375                 name:String(this.name),
1376                 properties:merge({}, this.properties),
1377             }, Test.statuses);
1378         }
1379         this._structured_clone.status = this.status;
1380         this._structured_clone.message = this.message;
1381         this._structured_clone.stack = this.stack;
1382         this._structured_clone.index = this.index;
1383         return this._structured_clone;
1384     };
1385
1386     Test.prototype.step = function(func, this_obj)
1387     {
1388         if (this.phase > this.phases.STARTED) {
1389             return;
1390         }
1391         this.phase = this.phases.STARTED;
1392         //If we don't get a result before the harness times out that will be a test timout
1393         this.set_status(this.TIMEOUT, "Test timed out");
1394
1395         tests.started = true;
1396         tests.notify_test_state(this);
1397
1398         if (this.timeout_id === null) {
1399             this.set_timeout();
1400         }
1401
1402         this.steps.push(func);
1403
1404         if (arguments.length === 1) {
1405             this_obj = this;
1406         }
1407
1408         try {
1409             return func.apply(this_obj, Array.prototype.slice.call(arguments, 2));
1410         } catch (e) {
1411             if (this.phase >= this.phases.HAS_RESULT) {
1412                 return;
1413             }
1414             var message = String((typeof e === "object" && e !== null) ? e.message : e);
1415             var stack = e.stack ? e.stack : null;
1416
1417             this.set_status(this.FAIL, message, stack);
1418             this.phase = this.phases.HAS_RESULT;
1419             this.done();
1420         }
1421     };
1422
1423     Test.prototype.step_func = function(func, this_obj)
1424     {
1425         var test_this = this;
1426
1427         if (arguments.length === 1) {
1428             this_obj = test_this;
1429         }
1430
1431         return function()
1432         {
1433             return test_this.step.apply(test_this, [func, this_obj].concat(
1434                 Array.prototype.slice.call(arguments)));
1435         };
1436     };
1437
1438     Test.prototype.step_func_done = function(func, this_obj)
1439     {
1440         var test_this = this;
1441
1442         if (arguments.length === 1) {
1443             this_obj = test_this;
1444         }
1445
1446         return function()
1447         {
1448             if (func) {
1449                 test_this.step.apply(test_this, [func, this_obj].concat(
1450                     Array.prototype.slice.call(arguments)));
1451             }
1452             test_this.done();
1453         };
1454     };
1455
1456     Test.prototype.unreached_func = function(description)
1457     {
1458         return this.step_func(function() {
1459             assert_unreached(description);
1460         });
1461     };
1462
1463     Test.prototype.step_timeout = function(f, timeout) {
1464         var test_this = this;
1465         var args = Array.prototype.slice.call(arguments, 2);
1466         return setTimeout(this.step_func(function() {
1467             return f.apply(test_this, args);
1468         }), timeout * tests.timeout_multiplier);
1469     }
1470
1471     Test.prototype.add_cleanup = function(callback) {
1472         this.cleanup_callbacks.push(callback);
1473     };
1474
1475     Test.prototype.force_timeout = function() {
1476         this.set_status(this.TIMEOUT);
1477         this.phase = this.phases.HAS_RESULT;
1478     };
1479
1480     Test.prototype.set_timeout = function()
1481     {
1482         if (this.timeout_length !== null) {
1483             var this_obj = this;
1484             this.timeout_id = setTimeout(function()
1485                                          {
1486                                              this_obj.timeout();
1487                                          }, this.timeout_length);
1488         }
1489     };
1490
1491     Test.prototype.set_status = function(status, message, stack)
1492     {
1493         this.status = status;
1494         this.message = message;
1495         this.stack = stack ? stack : null;
1496     };
1497
1498     Test.prototype.timeout = function()
1499     {
1500         this.timeout_id = null;
1501         this.set_status(this.TIMEOUT, "Test timed out");
1502         this.phase = this.phases.HAS_RESULT;
1503         this.done();
1504     };
1505
1506     Test.prototype.done = function()
1507     {
1508         if (this.phase == this.phases.COMPLETE) {
1509             return;
1510         }
1511
1512         if (this.phase <= this.phases.STARTED) {
1513             this.set_status(this.PASS, null);
1514         }
1515
1516         this.phase = this.phases.COMPLETE;
1517
1518         clearTimeout(this.timeout_id);
1519         tests.result(this);
1520         this.cleanup();
1521     };
1522
1523     Test.prototype.cleanup = function() {
1524         forEach(this.cleanup_callbacks,
1525                 function(cleanup_callback) {
1526                     cleanup_callback();
1527                 });
1528     };
1529
1530     /*
1531      * A RemoteTest object mirrors a Test object on a remote worker. The
1532      * associated RemoteWorker updates the RemoteTest object in response to
1533      * received events. In turn, the RemoteTest object replicates these events
1534      * on the local document. This allows listeners (test result reporting
1535      * etc..) to transparently handle local and remote events.
1536      */
1537     function RemoteTest(clone) {
1538         var this_obj = this;
1539         Object.keys(clone).forEach(
1540                 function(key) {
1541                     this_obj[key] = clone[key];
1542                 });
1543         this.index = null;
1544         this.phase = this.phases.INITIAL;
1545         this.update_state_from(clone);
1546         tests.push(this);
1547     }
1548
1549     RemoteTest.prototype.structured_clone = function() {
1550         var clone = {};
1551         Object.keys(this).forEach(
1552                 (function(key) {
1553                     if (typeof(this[key]) === "object") {
1554                         clone[key] = merge({}, this[key]);
1555                     } else {
1556                         clone[key] = this[key];
1557                     }
1558                 }).bind(this));
1559         clone.phases = merge({}, this.phases);
1560         return clone;
1561     };
1562
1563     RemoteTest.prototype.cleanup = function() {};
1564     RemoteTest.prototype.phases = Test.prototype.phases;
1565     RemoteTest.prototype.update_state_from = function(clone) {
1566         this.status = clone.status;
1567         this.message = clone.message;
1568         this.stack = clone.stack;
1569         if (this.phase === this.phases.INITIAL) {
1570             this.phase = this.phases.STARTED;
1571         }
1572     };
1573     RemoteTest.prototype.done = function() {
1574         this.phase = this.phases.COMPLETE;
1575     }
1576
1577     /*
1578      * A RemoteWorker listens for test events from a worker. These events are
1579      * then used to construct and maintain RemoteTest objects that mirror the
1580      * tests running on the remote worker.
1581      */
1582     function RemoteWorker(worker) {
1583         this.running = true;
1584         this.tests = new Array();
1585
1586         var this_obj = this;
1587         worker.onerror = function(error) { this_obj.worker_error(error); };
1588
1589         var message_port;
1590
1591         if (is_service_worker(worker)) {
1592             if (window.MessageChannel) {
1593                 // The ServiceWorker's implicit MessagePort is currently not
1594                 // reliably accessible from the ServiceWorkerGlobalScope due to
1595                 // Blink setting MessageEvent.source to null for messages sent
1596                 // via ServiceWorker.postMessage(). Until that's resolved,
1597                 // create an explicit MessageChannel and pass one end to the
1598                 // worker.
1599                 var message_channel = new MessageChannel();
1600                 message_port = message_channel.port1;
1601                 message_port.start();
1602                 worker.postMessage({type: "connect"}, [message_channel.port2]);
1603             } else {
1604                 // If MessageChannel is not available, then try the
1605                 // ServiceWorker.postMessage() approach using MessageEvent.source
1606                 // on the other end.
1607                 message_port = navigator.serviceWorker;
1608                 worker.postMessage({type: "connect"});
1609             }
1610         } else if (is_shared_worker(worker)) {
1611             message_port = worker.port;
1612         } else {
1613             message_port = worker;
1614         }
1615
1616         // Keeping a reference to the worker until worker_done() is seen
1617         // prevents the Worker object and its MessageChannel from going away
1618         // before all the messages are dispatched.
1619         this.worker = worker;
1620
1621         message_port.onmessage =
1622             function(message) {
1623                 if (this_obj.running && (message.data.type in this_obj.message_handlers)) {
1624                     this_obj.message_handlers[message.data.type].call(this_obj, message.data);
1625                 }
1626             };
1627     }
1628
1629     RemoteWorker.prototype.worker_error = function(error) {
1630         var message = error.message || String(error);
1631         var filename = (error.filename ? " " + error.filename: "");
1632         // FIXME: Display worker error states separately from main document
1633         // error state.
1634         this.worker_done({
1635             status: {
1636                 status: tests.status.ERROR,
1637                 message: "Error in worker" + filename + ": " + message,
1638                 stack: error.stack
1639             }
1640         });
1641         error.preventDefault();
1642     };
1643
1644     RemoteWorker.prototype.test_state = function(data) {
1645         var remote_test = this.tests[data.test.index];
1646         if (!remote_test) {
1647             remote_test = new RemoteTest(data.test);
1648             this.tests[data.test.index] = remote_test;
1649         }
1650         remote_test.update_state_from(data.test);
1651         tests.notify_test_state(remote_test);
1652     };
1653
1654     RemoteWorker.prototype.test_done = function(data) {
1655         var remote_test = this.tests[data.test.index];
1656         remote_test.update_state_from(data.test);
1657         remote_test.done();
1658         tests.result(remote_test);
1659     };
1660
1661     RemoteWorker.prototype.worker_done = function(data) {
1662         if (tests.status.status === null &&
1663             data.status.status !== data.status.OK) {
1664             tests.status.status = data.status.status;
1665             tests.status.message = data.status.message;
1666             tests.status.stack = data.status.stack;
1667         }
1668         this.running = false;
1669         this.worker = null;
1670         if (tests.all_done()) {
1671             tests.complete();
1672         }
1673     };
1674
1675     RemoteWorker.prototype.message_handlers = {
1676         test_state: RemoteWorker.prototype.test_state,
1677         result: RemoteWorker.prototype.test_done,
1678         complete: RemoteWorker.prototype.worker_done
1679     };
1680
1681     /*
1682      * Harness
1683      */
1684
1685     function TestsStatus()
1686     {
1687         this.status = null;
1688         this.message = null;
1689         this.stack = null;
1690     }
1691
1692     TestsStatus.statuses = {
1693         OK:0,
1694         ERROR:1,
1695         TIMEOUT:2
1696     };
1697
1698     TestsStatus.prototype = merge({}, TestsStatus.statuses);
1699
1700     TestsStatus.prototype.structured_clone = function()
1701     {
1702         if (!this._structured_clone) {
1703             var msg = this.message;
1704             msg = msg ? String(msg) : msg;
1705             this._structured_clone = merge({
1706                 status:this.status,
1707                 message:msg,
1708                 stack:this.stack
1709             }, TestsStatus.statuses);
1710         }
1711         return this._structured_clone;
1712     };
1713
1714     function Tests()
1715     {
1716         this.tests = [];
1717         this.num_pending = 0;
1718
1719         this.phases = {
1720             INITIAL:0,
1721             SETUP:1,
1722             HAVE_TESTS:2,
1723             HAVE_RESULTS:3,
1724             COMPLETE:4
1725         };
1726         this.phase = this.phases.INITIAL;
1727
1728         this.properties = {};
1729
1730         this.wait_for_finish = false;
1731         this.processing_callbacks = false;
1732
1733         this.allow_uncaught_exception = false;
1734
1735         this.file_is_test = false;
1736
1737         this.timeout_multiplier = 1;
1738         this.timeout_length = test_environment.test_timeout();
1739         this.timeout_id = null;
1740
1741         this.start_callbacks = [];
1742         this.test_state_callbacks = [];
1743         this.test_done_callbacks = [];
1744         this.all_done_callbacks = [];
1745
1746         this.pending_workers = [];
1747
1748         this.status = new TestsStatus();
1749
1750         var this_obj = this;
1751
1752         test_environment.add_on_loaded_callback(function() {
1753             if (this_obj.all_done()) {
1754                 this_obj.complete();
1755             }
1756         });
1757
1758         this.set_timeout();
1759     }
1760
1761     Tests.prototype.setup = function(func, properties)
1762     {
1763         if (this.phase >= this.phases.HAVE_RESULTS) {
1764             return;
1765         }
1766
1767         if (this.phase < this.phases.SETUP) {
1768             this.phase = this.phases.SETUP;
1769         }
1770
1771         this.properties = properties;
1772
1773         for (var p in properties) {
1774             if (properties.hasOwnProperty(p)) {
1775                 var value = properties[p];
1776                 if (p == "allow_uncaught_exception") {
1777                     this.allow_uncaught_exception = value;
1778                 } else if (p == "explicit_done" && value) {
1779                     this.wait_for_finish = true;
1780                 } else if (p == "explicit_timeout" && value) {
1781                     this.timeout_length = null;
1782                     if (this.timeout_id)
1783                     {
1784                         clearTimeout(this.timeout_id);
1785                     }
1786                 } else if (p == "timeout_multiplier") {
1787                     this.timeout_multiplier = value;
1788                 }
1789             }
1790         }
1791
1792         if (func) {
1793             try {
1794                 func();
1795             } catch (e) {
1796                 this.status.status = this.status.ERROR;
1797                 this.status.message = String(e);
1798                 this.status.stack = e.stack ? e.stack : null;
1799             }
1800         }
1801         this.set_timeout();
1802     };
1803
1804     Tests.prototype.set_file_is_test = function() {
1805         if (this.tests.length > 0) {
1806             throw new Error("Tried to set file as test after creating a test");
1807         }
1808         this.wait_for_finish = true;
1809         this.file_is_test = true;
1810         // Create the test, which will add it to the list of tests
1811         async_test();
1812     };
1813
1814     Tests.prototype.set_timeout = function() {
1815         var this_obj = this;
1816         clearTimeout(this.timeout_id);
1817         if (this.timeout_length !== null) {
1818             this.timeout_id = setTimeout(function() {
1819                                              this_obj.timeout();
1820                                          }, this.timeout_length);
1821         }
1822     };
1823
1824     Tests.prototype.timeout = function() {
1825         if (this.status.status === null) {
1826             this.status.status = this.status.TIMEOUT;
1827         }
1828         this.complete();
1829     };
1830
1831     Tests.prototype.end_wait = function()
1832     {
1833         this.wait_for_finish = false;
1834         if (this.all_done()) {
1835             this.complete();
1836         }
1837     };
1838
1839     Tests.prototype.push = function(test)
1840     {
1841         if (this.phase < this.phases.HAVE_TESTS) {
1842             this.start();
1843         }
1844         this.num_pending++;
1845         test.index = this.tests.push(test);
1846         this.notify_test_state(test);
1847     };
1848
1849     Tests.prototype.notify_test_state = function(test) {
1850         var this_obj = this;
1851         forEach(this.test_state_callbacks,
1852                 function(callback) {
1853                     callback(test, this_obj);
1854                 });
1855     };
1856
1857     Tests.prototype.all_done = function() {
1858         return (this.tests.length > 0 && test_environment.all_loaded &&
1859                 this.num_pending === 0 && !this.wait_for_finish &&
1860                 !this.processing_callbacks &&
1861                 !this.pending_workers.some(function(w) { return w.running; }));
1862     };
1863
1864     Tests.prototype.start = function() {
1865         this.phase = this.phases.HAVE_TESTS;
1866         this.notify_start();
1867     };
1868
1869     Tests.prototype.notify_start = function() {
1870         var this_obj = this;
1871         forEach (this.start_callbacks,
1872                  function(callback)
1873                  {
1874                      callback(this_obj.properties);
1875                  });
1876     };
1877
1878     Tests.prototype.result = function(test)
1879     {
1880         if (this.phase > this.phases.HAVE_RESULTS) {
1881             return;
1882         }
1883         this.phase = this.phases.HAVE_RESULTS;
1884         this.num_pending--;
1885         this.notify_result(test);
1886     };
1887
1888     Tests.prototype.notify_result = function(test) {
1889         var this_obj = this;
1890         this.processing_callbacks = true;
1891         forEach(this.test_done_callbacks,
1892                 function(callback)
1893                 {
1894                     callback(test, this_obj);
1895                 });
1896         this.processing_callbacks = false;
1897         if (this_obj.all_done()) {
1898             this_obj.complete();
1899         }
1900     };
1901
1902     Tests.prototype.complete = function() {
1903         if (this.phase === this.phases.COMPLETE) {
1904             return;
1905         }
1906         this.phase = this.phases.COMPLETE;
1907         var this_obj = this;
1908         this.tests.forEach(
1909             function(x)
1910             {
1911                 if (x.phase < x.phases.COMPLETE) {
1912                     this_obj.notify_result(x);
1913                     x.cleanup();
1914                     x.phase = x.phases.COMPLETE;
1915                 }
1916             }
1917         );
1918         this.notify_complete();
1919     };
1920
1921     Tests.prototype.notify_complete = function() {
1922         var this_obj = this;
1923         if (this.status.status === null) {
1924             this.status.status = this.status.OK;
1925         }
1926
1927         forEach (this.all_done_callbacks,
1928                  function(callback)
1929                  {
1930                      callback(this_obj.tests, this_obj.status);
1931                  });
1932     };
1933
1934     Tests.prototype.fetch_tests_from_worker = function(worker) {
1935         if (this.phase >= this.phases.COMPLETE) {
1936             return;
1937         }
1938
1939         this.pending_workers.push(new RemoteWorker(worker));
1940     };
1941
1942     function fetch_tests_from_worker(port) {
1943         tests.fetch_tests_from_worker(port);
1944     }
1945     expose(fetch_tests_from_worker, 'fetch_tests_from_worker');
1946
1947     function timeout() {
1948         if (tests.timeout_length === null) {
1949             tests.timeout();
1950         }
1951     }
1952     expose(timeout, 'timeout');
1953
1954     function add_start_callback(callback) {
1955         tests.start_callbacks.push(callback);
1956     }
1957
1958     function add_test_state_callback(callback) {
1959         tests.test_state_callbacks.push(callback);
1960     }
1961
1962     function add_result_callback(callback) {
1963         tests.test_done_callbacks.push(callback);
1964     }
1965
1966     function add_completion_callback(callback) {
1967         tests.all_done_callbacks.push(callback);
1968     }
1969
1970     expose(add_start_callback, 'add_start_callback');
1971     expose(add_test_state_callback, 'add_test_state_callback');
1972     expose(add_result_callback, 'add_result_callback');
1973     expose(add_completion_callback, 'add_completion_callback');
1974
1975     function remove(array, item) {
1976         var index = array.indexOf(item);
1977         if (index > -1) {
1978             array.splice(index, 1);
1979         }
1980     }
1981
1982     function remove_start_callback(callback) {
1983         remove(tests.start_callbacks, callback);
1984     }
1985
1986     function remove_test_state_callback(callback) {
1987         remove(tests.test_state_callbacks, callback);
1988     }
1989
1990     function remove_result_callback(callback) {
1991         remove(tests.test_done_callbacks, callback);
1992     }
1993
1994     function remove_completion_callback(callback) {
1995        remove(tests.all_done_callbacks, callback);
1996     }
1997
1998     /*
1999      * Output listener
2000     */
2001
2002     function Output() {
2003         this.output_document = document;
2004         this.output_node = null;
2005         this.enabled = settings.output;
2006         this.phase = this.INITIAL;
2007     }
2008
2009     Output.prototype.INITIAL = 0;
2010     Output.prototype.STARTED = 1;
2011     Output.prototype.HAVE_RESULTS = 2;
2012     Output.prototype.COMPLETE = 3;
2013
2014     Output.prototype.setup = function(properties) {
2015         if (this.phase > this.INITIAL) {
2016             return;
2017         }
2018
2019         //If output is disabled in testharnessreport.js the test shouldn't be
2020         //able to override that
2021         this.enabled = this.enabled && (properties.hasOwnProperty("output") ?
2022                                         properties.output : settings.output);
2023     };
2024
2025     Output.prototype.init = function(properties) {
2026         if (this.phase >= this.STARTED) {
2027             return;
2028         }
2029         if (properties.output_document) {
2030             this.output_document = properties.output_document;
2031         } else {
2032             this.output_document = document;
2033         }
2034         this.phase = this.STARTED;
2035     };
2036
2037     Output.prototype.resolve_log = function() {
2038         var output_document;
2039         if (typeof this.output_document === "function") {
2040             output_document = this.output_document.apply(undefined);
2041         } else {
2042             output_document = this.output_document;
2043         }
2044         if (!output_document) {
2045             return;
2046         }
2047         var node = output_document.getElementById("log");
2048         if (!node) {
2049             if (!document.body || document.readyState == "loading") {
2050                 return;
2051             }
2052             node = output_document.createElement("div");
2053             node.id = "log";
2054             output_document.body.appendChild(node);
2055         }
2056         this.output_document = output_document;
2057         this.output_node = node;
2058     };
2059
2060     Output.prototype.show_status = function() {
2061         if (this.phase < this.STARTED) {
2062             this.init();
2063         }
2064         if (!this.enabled) {
2065             return;
2066         }
2067         if (this.phase < this.HAVE_RESULTS) {
2068             this.resolve_log();
2069             this.phase = this.HAVE_RESULTS;
2070         }
2071         var done_count = tests.tests.length - tests.num_pending;
2072         if (this.output_node) {
2073             if (done_count < 100 ||
2074                 (done_count < 1000 && done_count % 100 === 0) ||
2075                 done_count % 1000 === 0) {
2076                 this.output_node.textContent = "Running, " +
2077                     done_count + " complete, " +
2078                     tests.num_pending + " remain";
2079             }
2080         }
2081     };
2082
2083     Output.prototype.show_results = function (tests, harness_status) {
2084         if (this.phase >= this.COMPLETE) {
2085             return;
2086         }
2087         if (!this.enabled) {
2088             return;
2089         }
2090         if (!this.output_node) {
2091             this.resolve_log();
2092         }
2093         this.phase = this.COMPLETE;
2094
2095         var log = this.output_node;
2096         if (!log) {
2097             return;
2098         }
2099         var output_document = this.output_document;
2100
2101         while (log.lastChild) {
2102             log.removeChild(log.lastChild);
2103         }
2104
2105         var harness_url = get_harness_url();
2106         if (harness_url !== null) {
2107             var stylesheet = output_document.createElementNS(xhtml_ns, "link");
2108             stylesheet.setAttribute("rel", "stylesheet");
2109             stylesheet.setAttribute("href", harness_url + "testharness.css");
2110             var heads = output_document.getElementsByTagName("head");
2111             if (heads.length) {
2112                 heads[0].appendChild(stylesheet);
2113             }
2114         }
2115
2116         var status_text_harness = {};
2117         status_text_harness[harness_status.OK] = "OK";
2118         status_text_harness[harness_status.ERROR] = "Error";
2119         status_text_harness[harness_status.TIMEOUT] = "Timeout";
2120
2121         var status_text = {};
2122         status_text[Test.prototype.PASS] = "Pass";
2123         status_text[Test.prototype.FAIL] = "Fail";
2124         status_text[Test.prototype.TIMEOUT] = "Timeout";
2125         status_text[Test.prototype.NOTRUN] = "Not Run";
2126
2127         var status_number = {};
2128         forEach(tests,
2129                 function(test) {
2130                     var status = status_text[test.status];
2131                     if (status_number.hasOwnProperty(status)) {
2132                         status_number[status] += 1;
2133                     } else {
2134                         status_number[status] = 1;
2135                     }
2136                 });
2137
2138         function status_class(status)
2139         {
2140             return status.replace(/\s/g, '').toLowerCase();
2141         }
2142
2143         var summary_template = ["section", {"id":"summary"},
2144                                 ["h2", {}, "Summary"],
2145                                 function()
2146                                 {
2147
2148                                     var status = status_text_harness[harness_status.status];
2149                                     var rv = [["section", {},
2150                                                ["p", {},
2151                                                 "Harness status: ",
2152                                                 ["span", {"class":status_class(status)},
2153                                                  status
2154                                                 ],
2155                                                ]
2156                                               ]];
2157
2158                                     if (harness_status.status === harness_status.ERROR) {
2159                                         rv[0].push(["pre", {}, harness_status.message]);
2160                                         if (harness_status.stack) {
2161                                             rv[0].push(["pre", {}, harness_status.stack]);
2162                                         }
2163                                     }
2164                                     return rv;
2165                                 },
2166                                 ["p", {}, "Found ${num_tests} tests"],
2167                                 function() {
2168                                     var rv = [["div", {}]];
2169                                     var i = 0;
2170                                     while (status_text.hasOwnProperty(i)) {
2171                                         if (status_number.hasOwnProperty(status_text[i])) {
2172                                             var status = status_text[i];
2173                                             rv[0].push(["div", {"class":status_class(status)},
2174                                                         ["label", {},
2175                                                          ["input", {type:"checkbox", checked:"checked"}],
2176                                                          status_number[status] + " " + status]]);
2177                                         }
2178                                         i++;
2179                                     }
2180                                     return rv;
2181                                 },
2182                                ];
2183
2184         log.appendChild(render(summary_template, {num_tests:tests.length}, output_document));
2185
2186         forEach(output_document.querySelectorAll("section#summary label"),
2187                 function(element)
2188                 {
2189                     on_event(element, "click",
2190                              function(e)
2191                              {
2192                                  if (output_document.getElementById("results") === null) {
2193                                      e.preventDefault();
2194                                      return;
2195                                  }
2196                                  var result_class = element.parentNode.getAttribute("class");
2197                                  var style_element = output_document.querySelector("style#hide-" + result_class);
2198                                  var input_element = element.querySelector("input");
2199                                  if (!style_element && !input_element.checked) {
2200                                      style_element = output_document.createElementNS(xhtml_ns, "style");
2201                                      style_element.id = "hide-" + result_class;
2202                                      style_element.textContent = "table#results > tbody > tr."+result_class+"{display:none}";
2203                                      output_document.body.appendChild(style_element);
2204                                  } else if (style_element && input_element.checked) {
2205                                      style_element.parentNode.removeChild(style_element);
2206                                  }
2207                              });
2208                 });
2209
2210         // This use of innerHTML plus manual escaping is not recommended in
2211         // general, but is necessary here for performance.  Using textContent
2212         // on each individual <td> adds tens of seconds of execution time for
2213         // large test suites (tens of thousands of tests).
2214         function escape_html(s)
2215         {
2216             return s.replace(/\&/g, "&amp;")
2217                 .replace(/</g, "&lt;")
2218                 .replace(/"/g, "&quot;")
2219                 .replace(/'/g, "&#39;");
2220         }
2221
2222         function has_assertions()
2223         {
2224             for (var i = 0; i < tests.length; i++) {
2225                 if (tests[i].properties.hasOwnProperty("assert")) {
2226                     return true;
2227                 }
2228             }
2229             return false;
2230         }
2231
2232         function get_assertion(test)
2233         {
2234             if (test.properties.hasOwnProperty("assert")) {
2235                 if (Array.isArray(test.properties.assert)) {
2236                     return test.properties.assert.join(' ');
2237                 }
2238                 return test.properties.assert;
2239             }
2240             return '';
2241         }
2242
2243         log.appendChild(document.createElementNS(xhtml_ns, "section"));
2244         var assertions = has_assertions();
2245         var html = "<h2>Details</h2><table id='results' " + (assertions ? "class='assertions'" : "" ) + ">" +
2246             "<thead><tr><th>Result</th><th>Test Name</th>" +
2247             (assertions ? "<th>Assertion</th>" : "") +
2248             "<th>Message</th></tr></thead>" +
2249             "<tbody>";
2250         for (var i = 0; i < tests.length; i++) {
2251             html += '<tr class="' +
2252                 escape_html(status_class(status_text[tests[i].status])) +
2253                 '"><td>' +
2254                 escape_html(status_text[tests[i].status]) +
2255                 "</td><td>" +
2256                 escape_html(tests[i].name) +
2257                 "</td><td>" +
2258                 (assertions ? escape_html(get_assertion(tests[i])) + "</td><td>" : "") +
2259                 escape_html(tests[i].message ? tests[i].message : " ") +
2260                 (tests[i].stack ? "<pre>" +
2261                  escape_html(tests[i].stack) +
2262                  "</pre>": "") +
2263                 "</td></tr>";
2264         }
2265         html += "</tbody></table>";
2266         try {
2267             log.lastChild.innerHTML = html;
2268         } catch (e) {
2269             log.appendChild(document.createElementNS(xhtml_ns, "p"))
2270                .textContent = "Setting innerHTML for the log threw an exception.";
2271             log.appendChild(document.createElementNS(xhtml_ns, "pre"))
2272                .textContent = html;
2273         }
2274     };
2275
2276     /*
2277      * Template code
2278      *
2279      * A template is just a javascript structure. An element is represented as:
2280      *
2281      * [tag_name, {attr_name:attr_value}, child1, child2]
2282      *
2283      * the children can either be strings (which act like text nodes), other templates or
2284      * functions (see below)
2285      *
2286      * A text node is represented as
2287      *
2288      * ["{text}", value]
2289      *
2290      * String values have a simple substitution syntax; ${foo} represents a variable foo.
2291      *
2292      * It is possible to embed logic in templates by using a function in a place where a
2293      * node would usually go. The function must either return part of a template or null.
2294      *
2295      * In cases where a set of nodes are required as output rather than a single node
2296      * with children it is possible to just use a list
2297      * [node1, node2, node3]
2298      *
2299      * Usage:
2300      *
2301      * render(template, substitutions) - take a template and an object mapping
2302      * variable names to parameters and return either a DOM node or a list of DOM nodes
2303      *
2304      * substitute(template, substitutions) - take a template and variable mapping object,
2305      * make the variable substitutions and return the substituted template
2306      *
2307      */
2308
2309     function is_single_node(template)
2310     {
2311         return typeof template[0] === "string";
2312     }
2313
2314     function substitute(template, substitutions)
2315     {
2316         if (typeof template === "function") {
2317             var replacement = template(substitutions);
2318             if (!replacement) {
2319                 return null;
2320             }
2321
2322             return substitute(replacement, substitutions);
2323         }
2324
2325         if (is_single_node(template)) {
2326             return substitute_single(template, substitutions);
2327         }
2328
2329         return filter(map(template, function(x) {
2330                               return substitute(x, substitutions);
2331                           }), function(x) {return x !== null;});
2332     }
2333
2334     function substitute_single(template, substitutions)
2335     {
2336         var substitution_re = /\$\{([^ }]*)\}/g;
2337
2338         function do_substitution(input) {
2339             var components = input.split(substitution_re);
2340             var rv = [];
2341             for (var i = 0; i < components.length; i += 2) {
2342                 rv.push(components[i]);
2343                 if (components[i + 1]) {
2344                     rv.push(String(substitutions[components[i + 1]]));
2345                 }
2346             }
2347             return rv;
2348         }
2349
2350         function substitute_attrs(attrs, rv)
2351         {
2352             rv[1] = {};
2353             for (var name in template[1]) {
2354                 if (attrs.hasOwnProperty(name)) {
2355                     var new_name = do_substitution(name).join("");
2356                     var new_value = do_substitution(attrs[name]).join("");
2357                     rv[1][new_name] = new_value;
2358                 }
2359             }
2360         }
2361
2362         function substitute_children(children, rv)
2363         {
2364             for (var i = 0; i < children.length; i++) {
2365                 if (children[i] instanceof Object) {
2366                     var replacement = substitute(children[i], substitutions);
2367                     if (replacement !== null) {
2368                         if (is_single_node(replacement)) {
2369                             rv.push(replacement);
2370                         } else {
2371                             extend(rv, replacement);
2372                         }
2373                     }
2374                 } else {
2375                     extend(rv, do_substitution(String(children[i])));
2376                 }
2377             }
2378             return rv;
2379         }
2380
2381         var rv = [];
2382         rv.push(do_substitution(String(template[0])).join(""));
2383
2384         if (template[0] === "{text}") {
2385             substitute_children(template.slice(1), rv);
2386         } else {
2387             substitute_attrs(template[1], rv);
2388             substitute_children(template.slice(2), rv);
2389         }
2390
2391         return rv;
2392     }
2393
2394     function make_dom_single(template, doc)
2395     {
2396         var output_document = doc || document;
2397         var element;
2398         if (template[0] === "{text}") {
2399             element = output_document.createTextNode("");
2400             for (var i = 1; i < template.length; i++) {
2401                 element.data += template[i];
2402             }
2403         } else {
2404             element = output_document.createElementNS(xhtml_ns, template[0]);
2405             for (var name in template[1]) {
2406                 if (template[1].hasOwnProperty(name)) {
2407                     element.setAttribute(name, template[1][name]);
2408                 }
2409             }
2410             for (var i = 2; i < template.length; i++) {
2411                 if (template[i] instanceof Object) {
2412                     var sub_element = make_dom(template[i]);
2413                     element.appendChild(sub_element);
2414                 } else {
2415                     var text_node = output_document.createTextNode(template[i]);
2416                     element.appendChild(text_node);
2417                 }
2418             }
2419         }
2420
2421         return element;
2422     }
2423
2424     function make_dom(template, substitutions, output_document)
2425     {
2426         if (is_single_node(template)) {
2427             return make_dom_single(template, output_document);
2428         }
2429
2430         return map(template, function(x) {
2431                        return make_dom_single(x, output_document);
2432                    });
2433     }
2434
2435     function render(template, substitutions, output_document)
2436     {
2437         return make_dom(substitute(template, substitutions), output_document);
2438     }
2439
2440     /*
2441      * Utility funcions
2442      */
2443     function assert(expected_true, function_name, description, error, substitutions)
2444     {
2445         if (tests.tests.length === 0) {
2446             tests.set_file_is_test();
2447         }
2448         if (expected_true !== true) {
2449             var msg = make_message(function_name, description,
2450                                    error, substitutions);
2451             throw new AssertionError(msg);
2452         }
2453     }
2454
2455     function AssertionError(message)
2456     {
2457         this.message = message;
2458         this.stack = this.get_stack();
2459     }
2460
2461     AssertionError.prototype = Object.create(Error.prototype);
2462
2463     AssertionError.prototype.get_stack = function() {
2464         var stack = new Error().stack;
2465         // IE11 does not initialize 'Error.stack' until the object is thrown.
2466         if (!stack) {
2467             try {
2468                 throw new Error();
2469             } catch (e) {
2470                 stack = e.stack;
2471             }
2472         }
2473
2474         // 'Error.stack' is not supported in all browsers/versions
2475         if (!stack) {
2476             return "(Stack trace unavailable)";
2477         }
2478
2479         var lines = stack.split("\n");
2480
2481         // Create a pattern to match stack frames originating within testharness.js.  These include the
2482         // script URL, followed by the line/col (e.g., '/resources/testharness.js:120:21').
2483         // Escape the URL per http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
2484         // in case it contains RegExp characters.
2485         var script_url = get_script_url();
2486         var re_text = script_url ? script_url.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') : "\\btestharness.js";
2487         var re = new RegExp(re_text + ":\\d+:\\d+");
2488
2489         // Some browsers include a preamble that specifies the type of the error object.  Skip this by
2490         // advancing until we find the first stack frame originating from testharness.js.
2491         var i = 0;
2492         while (!re.test(lines[i]) && i < lines.length) {
2493             i++;
2494         }
2495
2496         // Then skip the top frames originating from testharness.js to begin the stack at the test code.
2497         while (re.test(lines[i]) && i < lines.length) {
2498             i++;
2499         }
2500
2501         // Paranoid check that we didn't skip all frames.  If so, return the original stack unmodified.
2502         if (i >= lines.length) {
2503             return stack;
2504         }
2505
2506         return lines.slice(i).join("\n");
2507     }
2508
2509     function make_message(function_name, description, error, substitutions)
2510     {
2511         for (var p in substitutions) {
2512             if (substitutions.hasOwnProperty(p)) {
2513                 substitutions[p] = format_value(substitutions[p]);
2514             }
2515         }
2516         var node_form = substitute(["{text}", "${function_name}: ${description}" + error],
2517                                    merge({function_name:function_name,
2518                                           description:(description?description + " ":"")},
2519                                           substitutions));
2520         return node_form.slice(1).join("");
2521     }
2522
2523     function filter(array, callable, thisObj) {
2524         var rv = [];
2525         for (var i = 0; i < array.length; i++) {
2526             if (array.hasOwnProperty(i)) {
2527                 var pass = callable.call(thisObj, array[i], i, array);
2528                 if (pass) {
2529                     rv.push(array[i]);
2530                 }
2531             }
2532         }
2533         return rv;
2534     }
2535
2536     function map(array, callable, thisObj)
2537     {
2538         var rv = [];
2539         rv.length = array.length;
2540         for (var i = 0; i < array.length; i++) {
2541             if (array.hasOwnProperty(i)) {
2542                 rv[i] = callable.call(thisObj, array[i], i, array);
2543             }
2544         }
2545         return rv;
2546     }
2547
2548     function extend(array, items)
2549     {
2550         Array.prototype.push.apply(array, items);
2551     }
2552
2553     function forEach(array, callback, thisObj)
2554     {
2555         for (var i = 0; i < array.length; i++) {
2556             if (array.hasOwnProperty(i)) {
2557                 callback.call(thisObj, array[i], i, array);
2558             }
2559         }
2560     }
2561
2562     function merge(a,b)
2563     {
2564         var rv = {};
2565         var p;
2566         for (p in a) {
2567             rv[p] = a[p];
2568         }
2569         for (p in b) {
2570             rv[p] = b[p];
2571         }
2572         return rv;
2573     }
2574
2575     function expose(object, name)
2576     {
2577         var components = name.split(".");
2578         var target = test_environment.global_scope();
2579         for (var i = 0; i < components.length - 1; i++) {
2580             if (!(components[i] in target)) {
2581                 target[components[i]] = {};
2582             }
2583             target = target[components[i]];
2584         }
2585         target[components[components.length - 1]] = object;
2586     }
2587
2588     function is_same_origin(w) {
2589         try {
2590             'random_prop' in w;
2591             return true;
2592         } catch (e) {
2593             return false;
2594         }
2595     }
2596
2597     /** Returns the 'src' URL of the first <script> tag in the page to include the file 'testharness.js'. */
2598     function get_script_url()
2599     {
2600         if (!('document' in self)) {
2601             return undefined;
2602         }
2603
2604         var scripts = document.getElementsByTagName("script");
2605         for (var i = 0; i < scripts.length; i++) {
2606             var src;
2607             if (scripts[i].src) {
2608                 src = scripts[i].src;
2609             } else if (scripts[i].href) {
2610                 //SVG case
2611                 src = scripts[i].href.baseVal;
2612             }
2613
2614             var matches = src && src.match(/^(.*\/|)testharness\.js$/);
2615             if (matches) {
2616                 return src;
2617             }
2618         }
2619         return undefined;
2620     }
2621
2622     /** Returns the URL path at which the files for testharness.js are assumed to reside (e.g., '/resources/').
2623         The path is derived from inspecting the 'src' of the <script> tag that included 'testharness.js'. */
2624     function get_harness_url()
2625     {
2626         var script_url = get_script_url();
2627
2628         // Exclude the 'testharness.js' file from the returned path, but '+ 1' to include the trailing slash.
2629         return script_url ? script_url.slice(0, script_url.lastIndexOf('/') + 1) : undefined;
2630     }
2631
2632     function supports_post_message(w)
2633     {
2634         var supports;
2635         var type;
2636         // Given IE implements postMessage across nested iframes but not across
2637         // windows or tabs, you can't infer cross-origin communication from the presence
2638         // of postMessage on the current window object only.
2639         //
2640         // Touching the postMessage prop on a window can throw if the window is
2641         // not from the same origin AND post message is not supported in that
2642         // browser. So just doing an existence test here won't do, you also need
2643         // to wrap it in a try..cacth block.
2644         try {
2645             type = typeof w.postMessage;
2646             if (type === "function") {
2647                 supports = true;
2648             }
2649
2650             // IE8 supports postMessage, but implements it as a host object which
2651             // returns "object" as its `typeof`.
2652             else if (type === "object") {
2653                 supports = true;
2654             }
2655
2656             // This is the case where postMessage isn't supported AND accessing a
2657             // window property across origins does NOT throw (e.g. old Safari browser).
2658             else {
2659                 supports = false;
2660             }
2661         } catch (e) {
2662             // This is the case where postMessage isn't supported AND accessing a
2663             // window property across origins throws (e.g. old Firefox browser).
2664             supports = false;
2665         }
2666         return supports;
2667     }
2668
2669     /**
2670      * Setup globals
2671      */
2672
2673     var tests = new Tests();
2674
2675     var error_handler = function(e) {
2676         if (tests.file_is_test) {
2677             var test = tests.tests[0];
2678             if (test.phase >= test.phases.HAS_RESULT) {
2679                 return;
2680             }
2681             test.set_status(test.FAIL, e.message, e.stack);
2682             test.phase = test.phases.HAS_RESULT;
2683             test.done();
2684             done();
2685         } else if (!tests.allow_uncaught_exception) {
2686             tests.status.status = tests.status.ERROR;
2687             tests.status.message = e.message;
2688             tests.status.stack = e.stack;
2689         }
2690     };
2691
2692     addEventListener("error", error_handler, false);
2693     addEventListener("unhandledrejection", function(e){ error_handler(e.reason); }, false);
2694
2695     test_environment.on_tests_ready();
2696
2697 })();
2698 // vim: set expandtab shiftwidth=4 tabstop=4: