2 Distributed under both the W3C Test Suite License [1] and the W3C
3 3-clause BSD License [2]. To contribute to a W3C Test Suite, see the
4 policies and contribution forms [3].
6 [1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license
7 [2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license
8 [3] http://www.w3.org/2004/10/27-testcases
14 * This file provides a framework for writing testcases. It is intended to
15 * provide a convenient API for making common assertions, and to work both
16 * for testing synchronous and asynchronous DOM features in a way that
17 * promotes clear, robust, tests.
21 * To use this file, import the script and the testharnessreport script into
23 * <script src="/resources/testharness.js"></script>
24 * <script src="/resources/testharnessreport.js"></script>
26 * Within each file one may define one or more tests. Each test is atomic
27 * in the sense that a single test has a single result (pass/fail/timeout).
28 * Within each test one may have a number of asserts. The test fails at the
29 * first failing assert, and the remainder of the test is (typically) not run.
31 * If the file containing the tests is a HTML file with an element of id "log"
32 * this will be populated with a table containing the test results after all
35 * NOTE: By default tests must be created before the load event fires. For ways
36 * to create tests after the load event, see "Determining when all tests
37 * are complete", below
39 * == Synchronous Tests ==
41 * To create a synchronous test use the test() function:
43 * test(test_function, name, properties)
45 * test_function is a function that contains the code to test. For example a
46 * trivial passing test would be:
48 * test(function() {assert_true(true)}, "assert_true with true")
50 * The function passed in is run in the test() call.
52 * properties is an object that overrides default test properties. The
53 * recognised properties are:
54 * timeout - the test timeout in ms
57 * test(test_function, "Sample test", {timeout:1000})
59 * would run test_function with a timeout of 1s.
61 * Additionally, test-specific metadata can be passed in the properties. These
62 * are used when the individual test has different metadata from that stored
64 * The recognized metadata properties are:
66 * help - The url of the part of the specification being tested
68 * assert - A human readable description of what the test is attempting
71 * author - Name and contact information for the author of the test in the
72 * format: "Name <email_addr>" or "Name http://contact/url"
74 * == Asynchronous Tests ==
76 * Testing asynchronous features is somewhat more complex since the result of
77 * a test may depend on one or more events or other callbacks. The API provided
78 * for testing these features is indended to be rather low-level but hopefully
79 * applicable to many situations.
81 * To create a test, one starts by getting a Test object using async_test:
83 * async_test(name, properties)
86 * var t = async_test("Simple async test")
88 * Assertions can be added to the test by calling the step method of the test
89 * object with a function containing the test assertions:
91 * t.step(function() {assert_true(true)});
93 * When all the steps are complete, the done() method must be called:
97 * As a convenience, async_test can also takes a function as first argument.
98 * This function is called with the test object as both its `this` object and
99 * first argument. The above example can be rewritten as:
101 * async_test(function(t) {
102 * object.some_event = function() {
103 * t.step(function (){assert_true(true); t.done();});
105 * }, "Simple async test");
107 * which avoids cluttering the global scope with references to async
110 * The properties argument is identical to that for test().
112 * In many cases it is convenient to run a step in response to an event or a
113 * callback. A convenient method of doing this is through the step_func method
114 * which returns a function that, when called runs a test step. For example
116 * object.some_event = t.step_func(function(e) {assert_true(e.a)});
118 * == Making assertions ==
120 * Functions for making assertions start assert_
121 * The best way to get a list is to look in this file for functions names
122 * matching that pattern. The general signature is
124 * assert_something(actual, expected, description)
126 * although not all assertions precisely match this pattern e.g. assert_true
127 * only takes actual and description as arguments.
129 * The description parameter is used to present more useful error messages when
132 * NOTE: All asserts must be located in a test() or a step of an async_test().
133 * asserts outside these places won't be detected correctly by the harness
134 * and may cause a file to stop testing.
138 * Sometimes tests require non-trivial setup that may fail. For this purpose
139 * there is a setup() function, that may be called with one or two arguments.
140 * The two argument version is:
142 * setup(func, properties)
144 * The one argument versions may omit either argument.
145 * func is a function to be run synchronously. setup() becomes a no-op once
146 * any tests have returned results. Properties are global properties of the test
147 * harness. Currently recognised properties are:
149 * timeout - The time in ms after which the harness should stop waiting for
150 * tests to complete (this is different to the per-test timeout
151 * because async tests do not start their timer until .step is called)
153 * explicit_done - Wait for an explicit call to done() before declaring all
154 * tests complete (see below)
156 * output_document - The document to which results should be logged. By default
157 * this is the current document but could be an ancestor
158 * document in some cases e.g. a SVG test loaded in an HTML
161 * explicit_timeout - disable file timeout; only stop waiting for results
162 * when the timeout() function is called (typically for
163 * use when integrating with some existing test framework
164 * that has its own timeout mechanism).
166 * == Determining when all tests are complete ==
168 * By default the test harness will assume there are no more results to come
170 * 1) There are no Test objects that have been created but not completed
171 * 2) The load event on the document has fired
173 * This behaviour can be overridden by setting the explicit_done property to
174 * true in a call to setup(). If explicit_done is true, the test harness will
175 * not assume it is done until the global done() function is called. Once done()
176 * is called, the two conditions above apply like normal.
178 * == Generating tests ==
180 * NOTE: this functionality may be removed
182 * There are scenarios in which is is desirable to create a large number of
183 * (synchronous) tests that are internally similar but vary in the parameters
184 * used. To make this easier, the generate_tests function allows a single
185 * function to be called with each set of parameters in a list:
187 * generate_tests(test_function, parameter_lists, properties)
191 * generate_tests(assert_equals, [
192 * ["Sum one and one", 1+1, 2],
193 * ["Sum one and zero", 1+0, 1]
198 * test(function() {assert_equals(1+1, 2)}, "Sum one and one")
199 * test(function() {assert_equals(1+0, 1)}, "Sum one and zero")
201 * Note that the first item in each parameter list corresponds to the name of
204 * The properties argument is identical to that for test(). This may be a
205 * single object (used for all generated tests) or an array.
209 * The framework provides callbacks corresponding to 3 events:
211 * start - happens when the first Test is created
212 * result - happens when a test result is recieved
213 * complete - happens when all results are recieved
215 * The page defining the tests may add callbacks for these events by calling
216 * the following methods:
218 * add_start_callback(callback) - callback called with no arguments
219 * add_result_callback(callback) - callback called with a test argument
220 * add_completion_callback(callback) - callback called with an array of tests
221 * and an status object
223 * tests have the following properties:
224 * status: A status code. This can be compared to the PASS, FAIL, TIMEOUT and
225 * NOTRUN properties on the test object
226 * message: A message indicating the reason for failure. In the future this
227 * will always be a string
229 * The status object gives the overall status of the harness. It has the
230 * following properties:
231 * status: Can be compared to the OK, ERROR and TIMEOUT properties
232 * message: An error message set when the status is ERROR
236 * In order to collect the results of multiple pages containing tests, the test
237 * harness will, when loaded in a nested browsing context, attempt to call
238 * certain functions in each ancestor and opener browsing context:
240 * start - start_callback
241 * result - result_callback
242 * complete - completion_callback
244 * These are given the same arguments as the corresponding internal callbacks
247 * == External API through cross-document messaging ==
249 * Where supported, the test harness will also send messages using
250 * cross-document messaging to each ancestor and opener browsing context. Since
251 * it uses the wildcard keyword (*), cross-origin communication is enabled and
252 * script on different origins can collect the results.
254 * This API follows similar conventions as those described above only slightly
255 * modified to accommodate message event API. Each message is sent by the harness
256 * is passed a single vanilla object, available as the `data` property of the
257 * event object. These objects are structures as follows:
259 * start - { type: "start" }
260 * result - { type: "result", test: Test }
261 * complete - { type: "complete", tests: [Test, ...], status: TestsStatus }
263 * == List of assertions ==
265 * assert_true(actual, description)
266 * asserts that /actual/ is strictly true
268 * assert_false(actual, description)
269 * asserts that /actual/ is strictly false
271 * assert_equals(actual, expected, description)
272 * asserts that /actual/ is the same value as /expected/
274 * assert_not_equals(actual, expected, description)
275 * asserts that /actual/ is a different value to /expected/. Yes, this means
276 * that "expected" is a misnomer
278 * assert_in_array(actual, expected, description)
279 * asserts that /expected/ is an Array, and /actual/ is equal to one of the
280 * members -- expected.indexOf(actual) != -1
282 * assert_array_equals(actual, expected, description)
283 * asserts that /actual/ and /expected/ have the same length and the value of
284 * each indexed property in /actual/ is the strictly equal to the corresponding
285 * property value in /expected/
287 * assert_approx_equals(actual, expected, epsilon, description)
288 * asserts that /actual/ is a number within +/- /epsilon/ of /expected/
290 * assert_less_than(actual, expected, description)
291 * asserts that /actual/ is a number less than /expected/
293 * assert_greater_than(actual, expected, description)
294 * asserts that /actual/ is a number greater than /expected/
296 * assert_less_than_equal(actual, expected, description)
297 * asserts that /actual/ is a number less than or equal to /expected/
299 * assert_greater_than_equal(actual, expected, description)
300 * asserts that /actual/ is a number greater than or equal to /expected/
302 * assert_regexp_match(actual, expected, description)
303 * asserts that /actual/ matches the regexp /expected/
305 * assert_class_string(object, class_name, description)
306 * asserts that the class string of /object/ as returned in
307 * Object.prototype.toString is equal to /class_name/.
309 * assert_own_property(object, property_name, description)
310 * assert that object has own property property_name
312 * assert_inherits(object, property_name, description)
313 * assert that object does not have an own property named property_name
314 * but that property_name is present in the prototype chain for object
316 * assert_idl_attribute(object, attribute_name, description)
317 * assert that an object that is an instance of some interface has the
318 * attribute attribute_name following the conditions specified by WebIDL
320 * assert_readonly(object, property_name, description)
321 * assert that property property_name on object is readonly
323 * assert_throws(code, func, description)
324 * code - the expected exception:
325 * o string: the thrown exception must be a DOMException with the given
326 * name, e.g., "TimeoutError" (for compatibility with existing
327 * tests, a constant is also supported, e.g., "TIMEOUT_ERR")
328 * o object: the thrown exception must have a property called "name" that
330 * o null: allow any exception (in general, one of the options above
332 * func - a function that should throw
334 * assert_unreached(description)
335 * asserts if called. Used to ensure that some codepath is *not* taken e.g.
336 * an event does not fire.
338 * assert_any(assert_func, actual, expected_array, extra_arg_1, ... extra_arg_N)
339 * asserts that one assert_func(actual, expected_array_N, extra_arg1, ..., extra_arg_N)
340 * is true for some expected_array_N in expected_array. This only works for assert_func
341 * with signature assert_func(actual, expected, args_1, ..., args_N). Note that tests
342 * with multiple allowed pass conditions are bad practice unless the spec specifically
343 * allows multiple behaviours. Test authors should not use this method simply to hide
346 * assert_exists(object, property_name, description)
348 * asserts that object has an own property property_name
350 * assert_not_exists(object, property_name, description)
352 * assert that object does not have own property property_name
358 // default timeout is 5 seconds, test can override if needed
365 var xhtml_ns = "http://www.w3.org/1999/xhtml";
367 // script_prefix is used by Output.prototype.show_results() to figure out
368 // where to get testharness.css from. It's enclosed in an extra closure to
369 // not pollute the library's namespace with variables like "src".
370 var script_prefix = null;
373 var scripts = document.getElementsByTagName("script");
374 for (var i = 0; i < scripts.length; i++)
378 var src = scripts[i].src;
380 else if (scripts[i].href)
383 var src = scripts[i].href.baseVal;
385 if (src && src.slice(src.length - "testharness.js".length) === "testharness.js")
387 script_prefix = src.slice(0, src.length - "testharness.js".length);
397 var name_counter = 0;
398 function next_default_name()
400 //Don't use document.title to work around an Opera bug in XHTML documents
401 var prefix = document.getElementsByTagName("title").length > 0 ?
402 document.getElementsByTagName("title")[0].textContent :
404 var suffix = name_counter > 0 ? " " + name_counter : "";
406 return prefix + suffix;
409 function test(func, name, properties)
411 var test_name = name ? name : next_default_name();
412 properties = properties ? properties : {};
413 var test_obj = new Test(test_name, properties);
415 if (test_obj.status === test_obj.NOTRUN) {
420 function async_test(func, name, properties)
422 if (typeof func !== "function") {
427 var test_name = name ? name : next_default_name();
428 properties = properties ? properties : {};
429 var test_obj = new Test(test_name, properties);
431 test_obj.step(func, test_obj, test_obj);
436 function setup(func_or_properties, maybe_properties)
440 if (arguments.length === 2) {
441 func = func_or_properties;
442 properties = maybe_properties;
443 } else if (func_or_properties instanceof Function){
444 func = func_or_properties;
446 properties = func_or_properties;
448 tests.setup(func, properties);
449 output.setup(properties);
456 function generate_tests(func, args, properties) {
457 forEach(args, function(x, i)
462 func.apply(this, x.slice(1));
465 Array.isArray(properties) ? properties[i] : properties);
469 function on_event(object, event, callback)
471 object.addEventListener(event, callback, false);
474 expose(test, 'test');
475 expose(async_test, 'async_test');
476 expose(generate_tests, 'generate_tests');
477 expose(setup, 'setup');
478 expose(done, 'done');
479 expose(on_event, 'on_event');
482 * Return a string truncated to the given length, with ... added at the end
485 function truncate(s, len)
487 if (s.length > len) {
488 return s.substring(0, len - 3) + "...";
494 * Convert a value to a nice, human-readable string
496 function format_value(val, seen)
501 if (typeof val === "object" && val !== null)
503 if (seen.indexOf(val) >= 0)
509 if (Array.isArray(val))
511 return "[" + val.map(function(x) {return format_value(x, seen)}).join(", ") + "]";
517 val = val.replace("\\", "\\\\");
518 for (var i = 0; i < 32; i++)
522 case 0: replace += "0"; break;
523 case 1: replace += "x01"; break;
524 case 2: replace += "x02"; break;
525 case 3: replace += "x03"; break;
526 case 4: replace += "x04"; break;
527 case 5: replace += "x05"; break;
528 case 6: replace += "x06"; break;
529 case 7: replace += "x07"; break;
530 case 8: replace += "b"; break;
531 case 9: replace += "t"; break;
532 case 10: replace += "n"; break;
533 case 11: replace += "v"; break;
534 case 12: replace += "f"; break;
535 case 13: replace += "r"; break;
536 case 14: replace += "x0e"; break;
537 case 15: replace += "x0f"; break;
538 case 16: replace += "x10"; break;
539 case 17: replace += "x11"; break;
540 case 18: replace += "x12"; break;
541 case 19: replace += "x13"; break;
542 case 20: replace += "x14"; break;
543 case 21: replace += "x15"; break;
544 case 22: replace += "x16"; break;
545 case 23: replace += "x17"; break;
546 case 24: replace += "x18"; break;
547 case 25: replace += "x19"; break;
548 case 26: replace += "x1a"; break;
549 case 27: replace += "x1b"; break;
550 case 28: replace += "x1c"; break;
551 case 29: replace += "x1d"; break;
552 case 30: replace += "x1e"; break;
553 case 31: replace += "x1f"; break;
555 val = val.replace(RegExp(String.fromCharCode(i), "g"), replace);
557 return '"' + val.replace(/"/g, '\\"') + '"';
562 // In JavaScript, -0 === 0 and String(-0) == "0", so we have to
564 if (val === -0 && 1/val === -Infinity)
575 // Special-case Node objects, since those come up a lot in my tests. I
576 // ignore namespaces. I use duck-typing instead of instanceof, because
577 // instanceof doesn't work if the node is from another window (like an
578 // iframe's contentWindow):
579 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=12295
580 if ("nodeType" in val
582 && "nodeValue" in val
583 && "childNodes" in val)
585 switch (val.nodeType)
587 case Node.ELEMENT_NODE:
588 var ret = "<" + val.tagName.toLowerCase();
589 for (var i = 0; i < val.attributes.length; i++)
591 ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"';
593 ret += ">" + val.innerHTML + "</" + val.tagName.toLowerCase() + ">";
594 return "Element node " + truncate(ret, 60);
596 return 'Text node "' + truncate(val.data, 60) + '"';
597 case Node.PROCESSING_INSTRUCTION_NODE:
598 return "ProcessingInstruction node with target " + format_value(truncate(val.target, 60)) + " and data " + format_value(truncate(val.data, 60));
599 case Node.COMMENT_NODE:
600 return "Comment node <!--" + truncate(val.data, 60) + "-->";
601 case Node.DOCUMENT_NODE:
602 return "Document node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
603 case Node.DOCUMENT_TYPE_NODE:
604 return "DocumentType node";
605 case Node.DOCUMENT_FRAGMENT_NODE:
606 return "DocumentFragment node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
608 return "Node object of unknown type";
612 // Fall through to default
614 return typeof val + ' "' + truncate(String(val), 60) + '"';
617 expose(format_value, "format_value");
623 function assert_true(actual, description)
625 assert(actual === true, "assert_true", description,
626 "expected true got ${actual}", {actual:actual});
628 expose(assert_true, "assert_true");
630 function assert_false(actual, description)
632 assert(actual === false, "assert_false", description,
633 "expected false got ${actual}", {actual:actual});
635 expose(assert_false, "assert_false");
637 function same_value(x, y) {
643 else if (x === 0 && y === 0) {
644 //Distinguish +0 and -0
654 function assert_equals(actual, expected, description)
657 * Test if two primitives are equal or two objects
658 * are the same object
660 if (typeof actual != typeof expected)
662 assert(false, "assert_equals", description,
663 "expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}",
664 {expected:expected, actual:actual});
667 assert(same_value(actual, expected), "assert_equals", description,
668 "expected ${expected} but got ${actual}",
669 {expected:expected, actual:actual});
671 expose(assert_equals, "assert_equals");
673 function assert_not_equals(actual, expected, description)
676 * Test if two primitives are unequal or two objects
677 * are different objects
679 assert(!same_value(actual, expected), "assert_not_equals", description,
680 "got disallowed value ${actual}",
683 expose(assert_not_equals, "assert_not_equals");
685 function assert_in_array(actual, expected, description)
687 assert(expected.indexOf(actual) != -1, "assert_in_array", description,
688 "value ${actual} not in array ${expected}",
689 {actual:actual, expected:expected});
691 expose(assert_in_array, "assert_in_array");
693 function assert_object_equals(actual, expected, description)
695 //This needs to be improved a great deal
696 function check_equal(actual, expected, stack)
703 assert(expected.hasOwnProperty(p), "assert_object_equals", description,
704 "unexpected property ${p}", {p:p});
706 if (typeof actual[p] === "object" && actual[p] !== null)
708 if (stack.indexOf(actual[p]) === -1)
710 check_equal(actual[p], expected[p], stack);
715 assert(same_value(actual[p], expected[p]), "assert_object_equals", description,
716 "property ${p} expected ${expected} got ${actual}",
717 {p:p, expected:expected, actual:actual});
722 assert(actual.hasOwnProperty(p),
723 "assert_object_equals", description,
724 "expected property ${p} missing", {p:p});
728 check_equal(actual, expected, []);
730 expose(assert_object_equals, "assert_object_equals");
732 function assert_array_equals(actual, expected, description)
734 assert(actual.length === expected.length,
735 "assert_array_equals", description,
736 "lengths differ, expected ${expected} got ${actual}",
737 {expected:expected.length, actual:actual.length});
739 for (var i=0; i < actual.length; i++)
741 assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),
742 "assert_array_equals", description,
743 "property ${i}, property expected to be $expected but was $actual",
744 {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing",
745 actual:actual.hasOwnProperty(i) ? "present" : "missing"});
746 assert(same_value(expected[i], actual[i]),
747 "assert_array_equals", description,
748 "property ${i}, expected ${expected} but got ${actual}",
749 {i:i, expected:expected[i], actual:actual[i]});
752 expose(assert_array_equals, "assert_array_equals");
754 function assert_approx_equals(actual, expected, epsilon, description)
757 * Test if two primitive numbers are equal withing +/- epsilon
759 assert(typeof actual === "number",
760 "assert_approx_equals", description,
761 "expected a number but got a ${type_actual}",
762 {type_actual:typeof actual});
764 assert(Math.abs(actual - expected) <= epsilon,
765 "assert_approx_equals", description,
766 "expected ${expected} +/- ${epsilon} but got ${actual}",
767 {expected:expected, actual:actual, epsilon:epsilon});
769 expose(assert_approx_equals, "assert_approx_equals");
771 function assert_less_than(actual, expected, description)
774 * Test if a primitive number is less than another
776 assert(typeof actual === "number",
777 "assert_less_than", description,
778 "expected a number but got a ${type_actual}",
779 {type_actual:typeof actual});
781 assert(actual < expected,
782 "assert_less_than", description,
783 "expected a number less than ${expected} but got ${actual}",
784 {expected:expected, actual:actual});
786 expose(assert_less_than, "assert_less_than");
788 function assert_greater_than(actual, expected, description)
791 * Test if a primitive number is greater than another
793 assert(typeof actual === "number",
794 "assert_greater_than", description,
795 "expected a number but got a ${type_actual}",
796 {type_actual:typeof actual});
798 assert(actual > expected,
799 "assert_greater_than", description,
800 "expected a number greater than ${expected} but got ${actual}",
801 {expected:expected, actual:actual});
803 expose(assert_greater_than, "assert_greater_than");
805 function assert_less_than_equal(actual, expected, description)
808 * Test if a primitive number is less than or equal to another
810 assert(typeof actual === "number",
811 "assert_less_than_equal", description,
812 "expected a number but got a ${type_actual}",
813 {type_actual:typeof actual});
815 assert(actual <= expected,
816 "assert_less_than", description,
817 "expected a number less than or equal to ${expected} but got ${actual}",
818 {expected:expected, actual:actual});
820 expose(assert_less_than_equal, "assert_less_than_equal");
822 function assert_greater_than_equal(actual, expected, description)
825 * Test if a primitive number is greater than or equal to another
827 assert(typeof actual === "number",
828 "assert_greater_than_equal", description,
829 "expected a number but got a ${type_actual}",
830 {type_actual:typeof actual});
832 assert(actual >= expected,
833 "assert_greater_than_equal", description,
834 "expected a number greater than or equal to ${expected} but got ${actual}",
835 {expected:expected, actual:actual});
837 expose(assert_greater_than_equal, "assert_greater_than_equal");
839 function assert_regexp_match(actual, expected, description) {
841 * Test if a string (actual) matches a regexp (expected)
843 assert(expected.test(actual),
844 "assert_regexp_match", description,
845 "expected ${expected} but got ${actual}",
846 {expected:expected, actual:actual});
848 expose(assert_regexp_match, "assert_regexp_match");
850 function assert_class_string(object, class_string, description) {
851 assert_equals({}.toString.call(object), "[object " + class_string + "]",
854 expose(assert_class_string, "assert_class_string");
857 function _assert_own_property(name) {
858 return function(object, property_name, description)
860 assert(object.hasOwnProperty(property_name),
862 "expected property ${p} missing", {p:property_name});
865 expose(_assert_own_property("assert_exists"), "assert_exists");
866 expose(_assert_own_property("assert_own_property"), "assert_own_property");
868 function assert_not_exists(object, property_name, description)
870 assert(!object.hasOwnProperty(property_name),
871 "assert_not_exists", description,
872 "unexpected property ${p} found", {p:property_name});
874 expose(assert_not_exists, "assert_not_exists");
876 function _assert_inherits(name) {
877 return function (object, property_name, description)
879 assert(typeof object === "object",
881 "provided value is not an object");
883 assert("hasOwnProperty" in object,
885 "provided value is an object but has no hasOwnProperty method");
887 assert(!object.hasOwnProperty(property_name),
889 "property ${p} found on object expected in prototype chain",
892 assert(property_name in object,
894 "property ${p} not found in prototype chain",
898 expose(_assert_inherits("assert_inherits"), "assert_inherits");
899 expose(_assert_inherits("assert_idl_attribute"), "assert_idl_attribute");
901 function assert_readonly(object, property_name, description)
903 var initial_value = object[property_name];
905 //Note that this can have side effects in the case where
906 //the property has PutForwards
907 object[property_name] = initial_value + "a"; //XXX use some other value here?
908 assert(same_value(object[property_name], initial_value),
909 "assert_readonly", description,
910 "changing property ${p} succeeded",
915 object[property_name] = initial_value;
918 expose(assert_readonly, "assert_readonly");
920 function assert_throws(code, func, description)
925 assert(false, "assert_throws", description,
926 "${func} did not throw", {func:func});
930 if (e instanceof AssertionError) {
937 if (typeof code === "object")
939 assert(typeof e == "object" && "name" in e && e.name == code.name,
940 "assert_throws", description,
941 "${func} threw ${actual} (${actual_name}) expected ${expected} (${expected_name})",
942 {func:func, actual:e, actual_name:e.name,
944 expected_name:code.name});
948 var code_name_map = {
949 INDEX_SIZE_ERR: 'IndexSizeError',
950 HIERARCHY_REQUEST_ERR: 'HierarchyRequestError',
951 WRONG_DOCUMENT_ERR: 'WrongDocumentError',
952 INVALID_CHARACTER_ERR: 'InvalidCharacterError',
953 NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',
954 NOT_FOUND_ERR: 'NotFoundError',
955 NOT_SUPPORTED_ERR: 'NotSupportedError',
956 INVALID_STATE_ERR: 'InvalidStateError',
957 SYNTAX_ERR: 'SyntaxError',
958 INVALID_MODIFICATION_ERR: 'InvalidModificationError',
959 NAMESPACE_ERR: 'NamespaceError',
960 INVALID_ACCESS_ERR: 'InvalidAccessError',
961 TYPE_MISMATCH_ERR: 'TypeMismatchError',
962 SECURITY_ERR: 'SecurityError',
963 NETWORK_ERR: 'NetworkError',
964 ABORT_ERR: 'AbortError',
965 URL_MISMATCH_ERR: 'URLMismatchError',
966 QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
967 TIMEOUT_ERR: 'TimeoutError',
968 INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError',
969 DATA_CLONE_ERR: 'DataCloneError'
972 var name = code in code_name_map ? code_name_map[code] : code;
974 var name_code_map = {
976 HierarchyRequestError: 3,
977 WrongDocumentError: 4,
978 InvalidCharacterError: 5,
979 NoModificationAllowedError: 7,
981 NotSupportedError: 9,
982 InvalidStateError: 11,
984 InvalidModificationError: 13,
986 InvalidAccessError: 15,
987 TypeMismatchError: 17,
991 URLMismatchError: 21,
992 QuotaExceededError: 22,
994 InvalidNodeTypeError: 24,
1000 TransactionInactiveError: 0,
1005 if (!(name in name_code_map))
1007 throw new AssertionError('Test bug: unrecognized DOMException code "' + code + '" passed to assert_throws()');
1010 var required_props = { code: name_code_map[name] };
1012 if (required_props.code === 0
1013 || ("name" in e && e.name !== e.name.toUpperCase() && e.name !== "DOMException"))
1015 // New style exception: also test the name property.
1016 required_props.name = name;
1019 //We'd like to test that e instanceof the appropriate interface,
1020 //but we can't, because we don't know what window it was created
1021 //in. It might be an instanceof the appropriate interface on some
1022 //unknown other window. TODO: Work around this somehow?
1024 assert(typeof e == "object",
1025 "assert_throws", description,
1026 "${func} threw ${e} with type ${type}, not an object",
1027 {func:func, e:e, type:typeof e});
1029 for (var prop in required_props)
1031 assert(typeof e == "object" && prop in e && e[prop] == required_props[prop],
1032 "assert_throws", description,
1033 "${func} threw ${e} that is not a DOMException " + code + ": property ${prop} is equal to ${actual}, expected ${expected}",
1034 {func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]});
1038 expose(assert_throws, "assert_throws");
1040 function assert_unreached(description) {
1041 assert(false, "assert_unreached", description,
1042 "Reached unreachable code");
1044 expose(assert_unreached, "assert_unreached");
1046 function assert_any(assert_func, actual, expected_array)
1048 var args = [].slice.call(arguments, 3)
1051 forEach(expected_array,
1055 assert_func.apply(this, [actual, expected].concat(args))
1058 errors.push(e.message);
1062 throw new AssertionError(errors.join("\n\n"));
1065 expose(assert_any, "assert_any");
1067 function Test(name, properties)
1070 this.status = this.NOTRUN;
1071 this.timeout_id = null;
1072 this.is_done = false;
1074 this.properties = properties;
1075 this.timeout_length = properties.timeout ? properties.timeout : settings.test_timeout;
1077 this.message = null;
1079 var this_obj = this;
1092 Test.prototype = merge({}, Test.statuses);
1094 Test.prototype.structured_clone = function()
1096 if(!this._structured_clone)
1098 var msg = this.message;
1099 msg = msg ? String(msg) : msg;
1100 this._structured_clone = merge({
1101 name:String(this.name),
1106 return this._structured_clone;
1109 Test.prototype.step = function(func, this_obj)
1111 //In case the test has already failed
1112 if (this.status !== this.NOTRUN)
1117 tests.started = true;
1119 if (this.timeout_id === null) {
1123 this.steps.push(func);
1125 if (arguments.length === 1)
1132 return func.apply(this_obj, Array.prototype.slice.call(arguments, 2));
1136 //This can happen if something called synchronously invoked another
1138 if (this.status !== this.NOTRUN)
1142 this.status = this.FAIL;
1143 this.message = (typeof e === "object" && e !== null) ? e.message : e;
1144 if (typeof e.stack != "undefined" && typeof e.message == "string") {
1145 //Try to make it more informative for some exceptions, at least
1146 //in Gecko and WebKit. This results in a stack dump instead of
1147 //just errors like "Cannot read property 'parentNode' of null"
1148 //or "root is null". Makes it a lot longer, of course.
1149 this.message += "(stack: " + e.stack + ")";
1152 if (debug && e.constructor !== AssertionError) {
1158 Test.prototype.step_func = function(func, this_obj)
1160 var test_this = this;
1162 if (arguments.length === 1)
1164 this_obj = test_this;
1169 test_this.step.apply(test_this, [func, this_obj].concat(
1170 Array.prototype.slice.call(arguments)));
1174 Test.prototype.step_func_done = function(func, this_obj)
1176 var test_this = this;
1178 if (arguments.length === 1)
1180 this_obj = test_this;
1185 test_this.step.apply(test_this, [func, this_obj].concat(
1186 Array.prototype.slice.call(arguments)));
1191 Test.prototype.set_timeout = function()
1193 var this_obj = this;
1194 this.timeout_id = setTimeout(function()
1197 }, this.timeout_length);
1200 Test.prototype.timeout = function()
1202 this.status = this.TIMEOUT;
1203 this.timeout_id = null;
1204 this.message = "Test timed out";
1208 Test.prototype.done = function()
1213 clearTimeout(this.timeout_id);
1214 if (this.status === this.NOTRUN)
1216 this.status = this.PASS;
1218 this.is_done = true;
1227 function TestsStatus()
1230 this.message = null;
1233 TestsStatus.statuses = {
1239 TestsStatus.prototype = merge({}, TestsStatus.statuses);
1241 TestsStatus.prototype.structured_clone = function()
1243 if(!this._structured_clone)
1245 var msg = this.message;
1246 msg = msg ? String(msg) : msg;
1247 this._structured_clone = merge({
1250 }, TestsStatus.statuses);
1252 return this._structured_clone;
1258 this.num_pending = 0;
1267 this.phase = this.phases.INITIAL;
1269 this.properties = {};
1271 //All tests can't be done until the load event fires
1272 this.all_loaded = false;
1273 this.wait_for_finish = false;
1274 this.processing_callbacks = false;
1276 this.timeout_length = settings.timeout;
1277 this.timeout_id = null;
1279 this.start_callbacks = [];
1280 this.test_done_callbacks = [];
1281 this.all_done_callbacks = [];
1283 this.status = new TestsStatus();
1285 var this_obj = this;
1287 on_event(window, "load",
1290 this_obj.all_loaded = true;
1291 if (this_obj.all_done())
1293 this_obj.complete();
1300 Tests.prototype.setup = function(func, properties)
1302 if (this.phase >= this.phases.HAVE_RESULTS)
1306 if (this.phase < this.phases.SETUP)
1308 this.phase = this.phases.SETUP;
1311 for (var p in properties)
1313 if (properties.hasOwnProperty(p))
1315 this.properties[p] = properties[p];
1319 if (properties.timeout)
1321 this.timeout_length = properties.timeout;
1323 if (properties.explicit_done)
1325 this.wait_for_finish = true;
1327 if (properties.explicit_timeout) {
1328 this.timeout_length = null;
1338 this.status.status = this.status.ERROR;
1339 this.status.message = e;
1345 Tests.prototype.set_timeout = function()
1347 var this_obj = this;
1348 clearTimeout(this.timeout_id);
1349 if (this.timeout_length !== null)
1351 this.timeout_id = setTimeout(function() {
1353 }, this.timeout_length);
1357 Tests.prototype.timeout = function() {
1358 this.status.status = this.status.TIMEOUT;
1362 Tests.prototype.end_wait = function()
1364 this.wait_for_finish = false;
1365 if (this.all_done()) {
1370 Tests.prototype.push = function(test)
1372 if (this.phase < this.phases.HAVE_TESTS) {
1376 this.tests.push(test);
1379 Tests.prototype.all_done = function() {
1380 return (this.all_loaded && this.num_pending === 0 &&
1381 !this.wait_for_finish && !this.processing_callbacks);
1384 Tests.prototype.start = function() {
1385 this.phase = this.phases.HAVE_TESTS;
1386 this.notify_start();
1389 Tests.prototype.notify_start = function() {
1390 var this_obj = this;
1391 forEach (this.start_callbacks,
1394 callback(this_obj.properties);
1397 function(w, is_same_origin)
1399 if(is_same_origin && w.start_callback)
1403 w.start_callback(this_obj.properties);
1413 if (supports_post_message(w) && w !== self)
1417 properties: this_obj.properties
1423 Tests.prototype.result = function(test)
1425 if (this.phase > this.phases.HAVE_RESULTS)
1429 this.phase = this.phases.HAVE_RESULTS;
1431 this.notify_result(test);
1434 Tests.prototype.notify_result = function(test) {
1435 var this_obj = this;
1436 this.processing_callbacks = true;
1437 forEach(this.test_done_callbacks,
1440 callback(test, this_obj);
1444 function(w, is_same_origin)
1446 if(is_same_origin && w.result_callback)
1450 w.result_callback(test);
1459 if (supports_post_message(w) && w !== self)
1463 test: test.structured_clone()
1467 this.processing_callbacks = false;
1468 if (this_obj.all_done())
1470 this_obj.complete();
1474 Tests.prototype.complete = function() {
1475 if (this.phase === this.phases.COMPLETE) {
1478 this.phase = this.phases.COMPLETE;
1479 var this_obj = this;
1483 if(x.status === x.NOTRUN)
1485 this_obj.notify_result(x);
1489 this.notify_complete();
1492 Tests.prototype.notify_complete = function()
1494 clearTimeout(this.timeout_id);
1495 var this_obj = this;
1496 var tests = map(this_obj.tests,
1499 return test.structured_clone();
1501 if (this.status.status === null)
1503 this.status.status = this.status.OK;
1506 forEach (this.all_done_callbacks,
1509 callback(this_obj.tests, this_obj.status);
1513 function(w, is_same_origin)
1515 if(is_same_origin && w.completion_callback)
1519 w.completion_callback(this_obj.tests, this_obj.status);
1529 if (supports_post_message(w) && w !== self)
1534 status: this_obj.status.structured_clone()
1540 var tests = new Tests();
1542 function timeout() {
1543 if (tests.timeout_length === null)
1548 expose(timeout, 'timeout');
1550 function add_start_callback(callback) {
1551 tests.start_callbacks.push(callback);
1554 function add_result_callback(callback)
1556 tests.test_done_callbacks.push(callback);
1559 function add_completion_callback(callback)
1561 tests.all_done_callbacks.push(callback);
1564 expose(add_start_callback, 'add_start_callback');
1565 expose(add_result_callback, 'add_result_callback');
1566 expose(add_completion_callback, 'add_completion_callback');
1573 this.output_document = document;
1574 this.output_node = null;
1575 this.done_count = 0;
1576 this.enabled = settings.output;
1577 this.phase = this.INITIAL;
1580 Output.prototype.INITIAL = 0;
1581 Output.prototype.STARTED = 1;
1582 Output.prototype.HAVE_RESULTS = 2;
1583 Output.prototype.COMPLETE = 3;
1585 Output.prototype.setup = function(properties) {
1586 if (this.phase > this.INITIAL) {
1590 //If output is disabled in testharnessreport.js the test shouldn't be
1591 //able to override that
1592 this.enabled = this.enabled && (properties.hasOwnProperty("output") ?
1593 properties.output : settings.output);
1596 Output.prototype.init = function(properties)
1598 if (this.phase >= this.STARTED) {
1601 if (properties.output_document) {
1602 this.output_document = properties.output_document;
1604 this.output_document = document;
1606 this.phase = this.STARTED;
1609 Output.prototype.resolve_log = function()
1611 var output_document;
1612 if (typeof this.output_document === "function")
1614 output_document = this.output_document.apply(undefined);
1617 output_document = this.output_document;
1619 if (!output_document)
1623 var node = output_document.getElementById("log");
1626 this.output_document = output_document;
1627 this.output_node = node;
1631 Output.prototype.show_status = function(test)
1633 if (this.phase < this.STARTED)
1641 if (this.phase < this.HAVE_RESULTS)
1644 this.phase = this.HAVE_RESULTS;
1647 if (this.output_node)
1649 if (this.done_count < 100
1650 || (this.done_count < 1000 && this.done_count % 100 == 0)
1651 || this.done_count % 1000 == 0) {
1652 this.output_node.textContent = "Running, "
1653 + this.done_count + " complete, "
1654 + tests.num_pending + " remain";
1659 Output.prototype.show_results = function (tests, harness_status)
1661 if (this.phase >= this.COMPLETE) {
1668 if (!this.output_node) {
1671 this.phase = this.COMPLETE;
1673 var log = this.output_node;
1678 var output_document = this.output_document;
1680 while (log.lastChild)
1682 log.removeChild(log.lastChild);
1685 if (script_prefix != null) {
1686 var stylesheet = output_document.createElementNS(xhtml_ns, "link");
1687 stylesheet.setAttribute("rel", "stylesheet");
1688 stylesheet.setAttribute("href", script_prefix + "testharness.css");
1689 var heads = output_document.getElementsByTagName("head");
1691 heads[0].appendChild(stylesheet);
1695 var status_text = {};
1696 status_text[Test.prototype.PASS] = "Pass";
1697 status_text[Test.prototype.FAIL] = "Fail";
1698 status_text[Test.prototype.TIMEOUT] = "Timeout";
1699 status_text[Test.prototype.NOTRUN] = "Not Run";
1701 var status_number = {};
1702 forEach(tests, function(test) {
1703 var status = status_text[test.status];
1704 if (status_number.hasOwnProperty(status))
1706 status_number[status] += 1;
1708 status_number[status] = 1;
1712 function status_class(status)
1714 return status.replace(/\s/g, '').toLowerCase();
1717 var summary_template = ["section", {"id":"summary"},
1718 ["h2", {}, "Summary"],
1719 ["p", {}, "Found ${num_tests} tests"],
1721 var rv = [["div", {}]];
1723 while (status_text.hasOwnProperty(i)) {
1724 if (status_number.hasOwnProperty(status_text[i])) {
1725 var status = status_text[i];
1726 rv[0].push(["div", {"class":status_class(status)},
1728 ["input", {type:"checkbox", checked:"checked"}],
1729 status_number[status] + " " + status]]);
1736 log.appendChild(render(summary_template, {num_tests:tests.length}, output_document));
1738 forEach(output_document.querySelectorAll("section#summary label"),
1741 on_event(element, "click",
1744 if (output_document.getElementById("results") === null)
1749 var result_class = element.parentNode.getAttribute("class");
1750 var style_element = output_document.querySelector("style#hide-" + result_class);
1751 var input_element = element.querySelector("input");
1752 if (!style_element && !input_element.checked) {
1753 style_element = output_document.createElementNS(xhtml_ns, "style");
1754 style_element.id = "hide-" + result_class;
1755 style_element.textContent = "table#results > tbody > tr."+result_class+"{display:none}";
1756 output_document.body.appendChild(style_element);
1757 } else if (style_element && input_element.checked) {
1758 style_element.parentNode.removeChild(style_element);
1763 // This use of innerHTML plus manual escaping is not recommended in
1764 // general, but is necessary here for performance. Using textContent
1765 // on each individual <td> adds tens of seconds of execution time for
1766 // large test suites (tens of thousands of tests).
1767 function escape_html(s)
1769 return s.replace(/\&/g, "&")
1770 .replace(/</g, "<")
1771 .replace(/"/g, """)
1772 .replace(/'/g, "'");
1775 function has_assertions()
1777 for (var i = 0; i < tests.length; i++) {
1778 if (tests[i].properties.hasOwnProperty("assert")) {
1785 function get_assertion(test)
1787 if (test.properties.hasOwnProperty("assert")) {
1788 if (Array.isArray(test.properties.assert)) {
1789 return test.properties.assert.join(' ');
1791 return test.properties.assert;
1796 log.appendChild(document.createElementNS(xhtml_ns, "section"));
1797 var assertions = has_assertions();
1798 var html = "<h2>Details</h2><table id='results' " + (assertions ? "class='assertions'" : "" ) + ">"
1799 + "<thead><tr><th>Result</th><th>Test Name</th>"
1800 + (assertions ? "<th>Assertion</th>" : "")
1801 + "<th>Message</th></tr></thead>"
1803 for (var i = 0; i < tests.length; i++) {
1804 html += '<tr class="'
1805 + escape_html(status_class(status_text[tests[i].status]))
1807 + escape_html(status_text[tests[i].status])
1809 + escape_html(tests[i].name)
1811 + (assertions ? escape_html(get_assertion(tests[i])) + "</td><td>" : "")
1812 + escape_html(tests[i].message ? tests[i].message : " ")
1815 html += "</tbody></table>";
1817 log.lastChild.innerHTML = html;
1819 log.appendChild(document.createElementNS(xhtml_ns, "p"))
1820 .textContent = "Setting innerHTML for the log threw an exception.";
1821 log.appendChild(document.createElementNS(xhtml_ns, "pre"))
1822 .textContent = html;
1826 var output = new Output();
1827 add_start_callback(function (properties) {output.init(properties);});
1828 add_result_callback(function (test) {output.show_status(tests);});
1829 add_completion_callback(function (tests, harness_status) {output.show_results(tests, harness_status);});
1834 * A template is just a javascript structure. An element is represented as:
1836 * [tag_name, {attr_name:attr_value}, child1, child2]
1838 * the children can either be strings (which act like text nodes), other templates or
1839 * functions (see below)
1841 * A text node is represented as
1845 * String values have a simple substitution syntax; ${foo} represents a variable foo.
1847 * It is possible to embed logic in templates by using a function in a place where a
1848 * node would usually go. The function must either return part of a template or null.
1850 * In cases where a set of nodes are required as output rather than a single node
1851 * with children it is possible to just use a list
1852 * [node1, node2, node3]
1856 * render(template, substitutions) - take a template and an object mapping
1857 * variable names to parameters and return either a DOM node or a list of DOM nodes
1859 * substitute(template, substitutions) - take a template and variable mapping object,
1860 * make the variable substitutions and return the substituted template
1864 function is_single_node(template)
1866 return typeof template[0] === "string";
1869 function substitute(template, substitutions)
1871 if (typeof template === "function") {
1872 var replacement = template(substitutions);
1875 var rv = substitute(replacement, substitutions);
1883 else if (is_single_node(template))
1885 return substitute_single(template, substitutions);
1889 return filter(map(template, function(x) {
1890 return substitute(x, substitutions);
1891 }), function(x) {return x !== null;});
1895 function substitute_single(template, substitutions)
1897 var substitution_re = /\${([^ }]*)}/g;
1899 function do_substitution(input) {
1900 var components = input.split(substitution_re);
1902 for (var i=0; i<components.length; i+=2)
1904 rv.push(components[i]);
1905 if (components[i+1])
1907 rv.push(String(substitutions[components[i+1]]));
1914 rv.push(do_substitution(String(template[0])).join(""));
1916 if (template[0] === "{text}") {
1917 substitute_children(template.slice(1), rv);
1919 substitute_attrs(template[1], rv);
1920 substitute_children(template.slice(2), rv);
1923 function substitute_attrs(attrs, rv)
1926 for (var name in template[1])
1928 if (attrs.hasOwnProperty(name))
1930 var new_name = do_substitution(name).join("");
1931 var new_value = do_substitution(attrs[name]).join("");
1932 rv[1][new_name] = new_value;
1937 function substitute_children(children, rv)
1939 for (var i=0; i<children.length; i++)
1941 if (children[i] instanceof Object) {
1942 var replacement = substitute(children[i], substitutions);
1943 if (replacement !== null)
1945 if (is_single_node(replacement))
1947 rv.push(replacement);
1951 extend(rv, replacement);
1957 extend(rv, do_substitution(String(children[i])));
1966 function make_dom_single(template, doc)
1968 var output_document = doc || document;
1969 if (template[0] === "{text}")
1971 var element = output_document.createTextNode("");
1972 for (var i=1; i<template.length; i++)
1974 element.data += template[i];
1979 var element = output_document.createElementNS(xhtml_ns, template[0]);
1980 for (var name in template[1]) {
1981 if (template[1].hasOwnProperty(name))
1983 element.setAttribute(name, template[1][name]);
1986 for (var i=2; i<template.length; i++)
1988 if (template[i] instanceof Object)
1990 var sub_element = make_dom(template[i]);
1991 element.appendChild(sub_element);
1995 var text_node = output_document.createTextNode(template[i]);
1996 element.appendChild(text_node);
2006 function make_dom(template, substitutions, output_document)
2008 if (is_single_node(template))
2010 return make_dom_single(template, output_document);
2014 return map(template, function(x) {
2015 return make_dom_single(x, output_document);
2020 function render(template, substitutions, output_document)
2022 return make_dom(substitute(template, substitutions), output_document);
2028 function assert(expected_true, function_name, description, error, substitutions)
2030 if (expected_true !== true)
2032 throw new AssertionError(make_message(function_name, description,
2033 error, substitutions));
2037 function AssertionError(message)
2039 this.message = message;
2042 function make_message(function_name, description, error, substitutions)
2044 for (var p in substitutions) {
2045 if (substitutions.hasOwnProperty(p)) {
2046 substitutions[p] = format_value(substitutions[p]);
2049 var node_form = substitute(["{text}", "${function_name}: ${description}" + error],
2050 merge({function_name:function_name,
2051 description:(description?description + " ":"")},
2053 return node_form.slice(1).join("");
2056 function filter(array, callable, thisObj) {
2058 for (var i=0; i<array.length; i++)
2060 if (array.hasOwnProperty(i))
2062 var pass = callable.call(thisObj, array[i], i, array);
2071 function map(array, callable, thisObj)
2074 rv.length = array.length;
2075 for (var i=0; i<array.length; i++)
2077 if (array.hasOwnProperty(i))
2079 rv[i] = callable.call(thisObj, array[i], i, array);
2085 function extend(array, items)
2087 Array.prototype.push.apply(array, items);
2090 function forEach (array, callback, thisObj)
2092 for (var i=0; i<array.length; i++)
2094 if (array.hasOwnProperty(i))
2096 callback.call(thisObj, array[i], i, array);
2115 function expose(object, name)
2117 var components = name.split(".");
2118 var target = window;
2119 for (var i=0; i<components.length - 1; i++)
2121 if (!(components[i] in target))
2123 target[components[i]] = {};
2125 target = target[components[i]];
2127 target[components[components.length - 1]] = object;
2130 function forEach_windows(callback) {
2131 // Iterate of the the windows [self ... top, opener]. The callback is passed
2132 // two objects, the first one is the windows object itself, the second one
2133 // is a boolean indicating whether or not its on the same origin as the
2135 var cache = forEach_windows.result_cache;
2137 cache = [[self, true]];
2141 var origins = location.ancestorOrigins;
2142 while (w != w.parent)
2145 // In WebKit, calls to parent windows' properties that aren't on the same
2146 // origin cause an error message to be displayed in the error console but
2147 // don't throw an exception. This is a deviation from the current HTML5
2148 // spec. See: https://bugs.webkit.org/show_bug.cgi?id=43504
2149 // The problem with WebKit's behavior is that it pollutes the error console
2150 // with error messages that can't be caught.
2152 // This issue can be mitigated by relying on the (for now) proprietary
2153 // `location.ancestorOrigins` property which returns an ordered list of
2154 // the origins of enclosing windows. See:
2155 // http://trac.webkit.org/changeset/113945.
2157 so = (location.origin == origins[i]);
2161 so = is_same_origin(w);
2163 cache.push([w, so]);
2169 // window.opener isn't included in the `location.ancestorOrigins` prop.
2170 // We'll just have to deal with a simple check and an error msg on WebKit
2171 // browsers in this case.
2172 cache.push([w, is_same_origin(w)]);
2174 forEach_windows.result_cache = cache;
2180 callback.apply(null, a);
2184 function is_same_origin(w) {
2193 function supports_post_message(w)
2197 // Given IE implements postMessage across nested iframes but not across
2198 // windows or tabs, you can't infer cross-origin communication from the presence
2199 // of postMessage on the current window object only.
2201 // Touching the postMessage prop on a window can throw if the window is
2202 // not from the same origin AND post message is not supported in that
2203 // browser. So just doing an existence test here won't do, you also need
2204 // to wrap it in a try..cacth block.
2207 type = typeof w.postMessage;
2208 if (type === "function")
2212 // IE8 supports postMessage, but implements it as a host object which
2213 // returns "object" as its `typeof`.
2214 else if (type === "object")
2218 // This is the case where postMessage isn't supported AND accessing a
2219 // window property across origins does NOT throw (e.g. old Safari browser).
2226 // This is the case where postMessage isn't supported AND accessing a
2227 // window property across origins throws (e.g. old Firefox browser).
2233 // vim: set expandtab shiftwidth=4 tabstop=4: