Best JavaScript code snippet using wpt
testharness.js
Source:testharness.js
...361 }362 throw new Error("Unsupported test environment");363 }364 var test_environment = create_test_environment();365 function is_shared_worker(worker) {366 return 'SharedWorker' in self && worker instanceof SharedWorker;367 }368 function is_service_worker(worker) {369 return 'ServiceWorker' in self && worker instanceof ServiceWorker;370 }371 372 function test(func, name, properties)373 {374 var test_name = name ? name : test_environment.next_default_test_name();375 properties = properties ? properties : {};376 var test_obj = new Test(test_name, properties);377 test_obj.step(func, test_obj, test_obj);378 if (test_obj.phase === test_obj.phases.STARTED) {379 test_obj.done();380 }381 }382 function async_test(func, name, properties)383 {384 if (typeof func !== "function") {385 properties = name;386 name = func;387 func = null;388 }389 var test_name = name ? name : test_environment.next_default_test_name();390 properties = properties ? properties : {};391 var test_obj = new Test(test_name, properties);392 if (func) {393 test_obj.step(func, test_obj, test_obj);394 }395 return test_obj;396 }397 function promise_test(func, name, properties) {398 var test = async_test(name, properties);399 400 test.step(function() {401 if (!tests.promise_tests) {402 tests.promise_tests = Promise.resolve();403 }404 });405 tests.promise_tests = tests.promise_tests.then(function() {406 return Promise.resolve(test.step(func, test, test))407 .then(408 function() {409 test.done();410 })411 .catch(test.step_func(412 function(value) {413 if (value instanceof AssertionError) {414 throw value;415 }416 assert(false, "promise_test", null,417 "Unhandled rejection with value: ${value}", {value:value});418 }));419 });420 }421 function promise_rejects(test, expected, promise) {422 return promise.then(test.unreached_func("Should have rejected.")).catch(function(e) {423 assert_throws(expected, function() { throw e });424 });425 }426 427 function EventWatcher(test, watchedNode, eventTypes)428 {429 if (typeof eventTypes == 'string') {430 eventTypes = [eventTypes];431 }432 var waitingFor = null;433 var eventHandler = test.step_func(function(evt) {434 assert_true(!!waitingFor,435 'Not expecting event, but got ' + evt.type + ' event');436 assert_equals(evt.type, waitingFor.types[0],437 'Expected ' + waitingFor.types[0] + ' event, but got ' +438 evt.type + ' event instead');439 if (waitingFor.types.length > 1) {440 441 waitingFor.types.shift();442 return;443 }444 445 446 447 var resolveFunc = waitingFor.resolve;448 waitingFor = null;449 resolveFunc(evt);450 });451 for (var i = 0; i < eventTypes.length; i++) {452 watchedNode.addEventListener(eventTypes[i], eventHandler);453 }454 455 this.wait_for = function(types) {456 if (waitingFor) {457 return Promise.reject('Already waiting for an event or events');458 }459 if (typeof types == 'string') {460 types = [types];461 }462 return new Promise(function(resolve, reject) {463 waitingFor = {464 types: types,465 resolve: resolve,466 reject: reject467 };468 });469 };470 function stop_watching() {471 for (var i = 0; i < eventTypes.length; i++) {472 watchedNode.removeEventListener(eventTypes[i], eventHandler);473 }474 };475 test.add_cleanup(stop_watching);476 return this;477 }478 expose(EventWatcher, 'EventWatcher');479 function setup(func_or_properties, maybe_properties)480 {481 var func = null;482 var properties = {};483 if (arguments.length === 2) {484 func = func_or_properties;485 properties = maybe_properties;486 } else if (func_or_properties instanceof Function) {487 func = func_or_properties;488 } else {489 properties = func_or_properties;490 }491 tests.setup(func, properties);492 test_environment.on_new_harness_properties(properties);493 }494 function done() {495 if (tests.tests.length === 0) {496 tests.set_file_is_test();497 }498 if (tests.file_is_test) {499 tests.tests[0].done();500 }501 tests.end_wait();502 }503 function generate_tests(func, args, properties) {504 forEach(args, function(x, i)505 {506 var name = x[0];507 test(function()508 {509 func.apply(this, x.slice(1));510 },511 name,512 Array.isArray(properties) ? properties[i] : properties);513 });514 }515 function on_event(object, event, callback)516 {517 object.addEventListener(event, callback, false);518 }519 expose(test, 'test');520 expose(async_test, 'async_test');521 expose(promise_test, 'promise_test');522 expose(promise_rejects, 'promise_rejects');523 expose(generate_tests, 'generate_tests');524 expose(setup, 'setup');525 expose(done, 'done');526 expose(on_event, 'on_event');527 528 function truncate(s, len)529 {530 if (s.length > len) {531 return s.substring(0, len - 3) + "...";532 }533 return s;534 }535 536 function is_node(object)537 {538 539 540 541 542 if ("nodeType" in object &&543 "nodeName" in object &&544 "nodeValue" in object &&545 "childNodes" in object) {546 try {547 object.nodeType;548 } catch (e) {549 550 551 return false;552 }553 return true;554 }555 return false;556 }557 558 function format_value(val, seen)559 {560 if (!seen) {561 seen = [];562 }563 if (typeof val === "object" && val !== null) {564 if (seen.indexOf(val) >= 0) {565 return "[...]";566 }567 seen.push(val);568 }569 if (Array.isArray(val)) {570 return "[" + val.map(function(x) {return format_value(x, seen);}).join(", ") + "]";571 }572 switch (typeof val) {573 case "string":574 val = val.replace("\\", "\\\\");575 for (var i = 0; i < 32; i++) {576 var replace = "\\";577 switch (i) {578 case 0: replace += "0"; break;579 case 1: replace += "x01"; break;580 case 2: replace += "x02"; break;581 case 3: replace += "x03"; break;582 case 4: replace += "x04"; break;583 case 5: replace += "x05"; break;584 case 6: replace += "x06"; break;585 case 7: replace += "x07"; break;586 case 8: replace += "b"; break;587 case 9: replace += "t"; break;588 case 10: replace += "n"; break;589 case 11: replace += "v"; break;590 case 12: replace += "f"; break;591 case 13: replace += "r"; break;592 case 14: replace += "x0e"; break;593 case 15: replace += "x0f"; break;594 case 16: replace += "x10"; break;595 case 17: replace += "x11"; break;596 case 18: replace += "x12"; break;597 case 19: replace += "x13"; break;598 case 20: replace += "x14"; break;599 case 21: replace += "x15"; break;600 case 22: replace += "x16"; break;601 case 23: replace += "x17"; break;602 case 24: replace += "x18"; break;603 case 25: replace += "x19"; break;604 case 26: replace += "x1a"; break;605 case 27: replace += "x1b"; break;606 case 28: replace += "x1c"; break;607 case 29: replace += "x1d"; break;608 case 30: replace += "x1e"; break;609 case 31: replace += "x1f"; break;610 }611 val = val.replace(RegExp(String.fromCharCode(i), "g"), replace);612 }613 return '"' + val.replace(/"/g, '\\"') + '"';614 case "boolean":615 case "undefined":616 return String(val);617 case "number":618 619 620 if (val === -0 && 1/val === -Infinity) {621 return "-0";622 }623 return String(val);624 case "object":625 if (val === null) {626 return "null";627 }628 629 630 if (is_node(val)) {631 switch (val.nodeType) {632 case Node.ELEMENT_NODE:633 var ret = "<" + val.localName;634 for (var i = 0; i < val.attributes.length; i++) {635 ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"';636 }637 ret += ">" + val.innerHTML + "</" + val.localName + ">";638 return "Element node " + truncate(ret, 60);639 case Node.TEXT_NODE:640 return 'Text node "' + truncate(val.data, 60) + '"';641 case Node.PROCESSING_INSTRUCTION_NODE:642 return "ProcessingInstruction node with target " + format_value(truncate(val.target, 60)) + " and data " + format_value(truncate(val.data, 60));643 case Node.COMMENT_NODE:644 return "Comment node <!--" + truncate(val.data, 60) + "-->";645 case Node.DOCUMENT_NODE:646 return "Document node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");647 case Node.DOCUMENT_TYPE_NODE:648 return "DocumentType node";649 case Node.DOCUMENT_FRAGMENT_NODE:650 return "DocumentFragment node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");651 default:652 return "Node object of unknown type";653 }654 }655 656 default:657 return typeof val + ' "' + truncate(String(val), 60) + '"';658 }659 }660 expose(format_value, "format_value");661 662 function assert_true(actual, description)663 {664 assert(actual === true, "assert_true", description,665 "expected true got ${actual}", {actual:actual});666 }667 expose(assert_true, "assert_true");668 function assert_false(actual, description)669 {670 assert(actual === false, "assert_false", description,671 "expected false got ${actual}", {actual:actual});672 }673 expose(assert_false, "assert_false");674 function same_value(x, y) {675 if (y !== y) {676 677 return x !== x;678 }679 if (x === 0 && y === 0) {680 681 return 1/x === 1/y;682 }683 return x === y;684 }685 function assert_equals(actual, expected, description)686 {687 688 if (typeof actual != typeof expected) {689 assert(false, "assert_equals", description,690 "expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}",691 {expected:expected, actual:actual});692 return;693 }694 assert(same_value(actual, expected), "assert_equals", description,695 "expected ${expected} but got ${actual}",696 {expected:expected, actual:actual});697 }698 expose(assert_equals, "assert_equals");699 function assert_not_equals(actual, expected, description)700 {701 702 assert(!same_value(actual, expected), "assert_not_equals", description,703 "got disallowed value ${actual}",704 {actual:actual});705 }706 expose(assert_not_equals, "assert_not_equals");707 function assert_in_array(actual, expected, description)708 {709 assert(expected.indexOf(actual) != -1, "assert_in_array", description,710 "value ${actual} not in array ${expected}",711 {actual:actual, expected:expected});712 }713 expose(assert_in_array, "assert_in_array");714 function assert_object_equals(actual, expected, description)715 {716 717 function check_equal(actual, expected, stack)718 {719 stack.push(actual);720 var p;721 for (p in actual) {722 assert(expected.hasOwnProperty(p), "assert_object_equals", description,723 "unexpected property ${p}", {p:p});724 if (typeof actual[p] === "object" && actual[p] !== null) {725 if (stack.indexOf(actual[p]) === -1) {726 check_equal(actual[p], expected[p], stack);727 }728 } else {729 assert(same_value(actual[p], expected[p]), "assert_object_equals", description,730 "property ${p} expected ${expected} got ${actual}",731 {p:p, expected:expected, actual:actual});732 }733 }734 for (p in expected) {735 assert(actual.hasOwnProperty(p),736 "assert_object_equals", description,737 "expected property ${p} missing", {p:p});738 }739 stack.pop();740 }741 check_equal(actual, expected, []);742 }743 expose(assert_object_equals, "assert_object_equals");744 function assert_array_equals(actual, expected, description)745 {746 assert(actual.length === expected.length,747 "assert_array_equals", description,748 "lengths differ, expected ${expected} got ${actual}",749 {expected:expected.length, actual:actual.length});750 for (var i = 0; i < actual.length; i++) {751 assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),752 "assert_array_equals", description,753 "property ${i}, property expected to be ${expected} but was ${actual}",754 {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing",755 actual:actual.hasOwnProperty(i) ? "present" : "missing"});756 assert(same_value(expected[i], actual[i]),757 "assert_array_equals", description,758 "property ${i}, expected ${expected} but got ${actual}",759 {i:i, expected:expected[i], actual:actual[i]});760 }761 }762 expose(assert_array_equals, "assert_array_equals");763 function assert_approx_equals(actual, expected, epsilon, description)764 {765 766 assert(typeof actual === "number",767 "assert_approx_equals", description,768 "expected a number but got a ${type_actual}",769 {type_actual:typeof actual});770 assert(Math.abs(actual - expected) <= epsilon,771 "assert_approx_equals", description,772 "expected ${expected} +/- ${epsilon} but got ${actual}",773 {expected:expected, actual:actual, epsilon:epsilon});774 }775 expose(assert_approx_equals, "assert_approx_equals");776 function assert_less_than(actual, expected, description)777 {778 779 assert(typeof actual === "number",780 "assert_less_than", description,781 "expected a number but got a ${type_actual}",782 {type_actual:typeof actual});783 assert(actual < expected,784 "assert_less_than", description,785 "expected a number less than ${expected} but got ${actual}",786 {expected:expected, actual:actual});787 }788 expose(assert_less_than, "assert_less_than");789 function assert_greater_than(actual, expected, description)790 {791 792 assert(typeof actual === "number",793 "assert_greater_than", description,794 "expected a number but got a ${type_actual}",795 {type_actual:typeof actual});796 assert(actual > expected,797 "assert_greater_than", description,798 "expected a number greater than ${expected} but got ${actual}",799 {expected:expected, actual:actual});800 }801 expose(assert_greater_than, "assert_greater_than");802 function assert_between_exclusive(actual, lower, upper, description)803 {804 805 assert(typeof actual === "number",806 "assert_between_exclusive", description,807 "expected a number but got a ${type_actual}",808 {type_actual:typeof actual});809 assert(actual > lower && actual < upper,810 "assert_between_exclusive", description,811 "expected a number greater than ${lower} " +812 "and less than ${upper} but got ${actual}",813 {lower:lower, upper:upper, actual:actual});814 }815 expose(assert_between_exclusive, "assert_between_exclusive");816 function assert_less_than_equal(actual, expected, description)817 {818 819 assert(typeof actual === "number",820 "assert_less_than_equal", description,821 "expected a number but got a ${type_actual}",822 {type_actual:typeof actual});823 assert(actual <= expected,824 "assert_less_than_equal", description,825 "expected a number less than or equal to ${expected} but got ${actual}",826 {expected:expected, actual:actual});827 }828 expose(assert_less_than_equal, "assert_less_than_equal");829 function assert_greater_than_equal(actual, expected, description)830 {831 832 assert(typeof actual === "number",833 "assert_greater_than_equal", description,834 "expected a number but got a ${type_actual}",835 {type_actual:typeof actual});836 assert(actual >= expected,837 "assert_greater_than_equal", description,838 "expected a number greater than or equal to ${expected} but got ${actual}",839 {expected:expected, actual:actual});840 }841 expose(assert_greater_than_equal, "assert_greater_than_equal");842 function assert_between_inclusive(actual, lower, upper, description)843 {844 845 assert(typeof actual === "number",846 "assert_between_inclusive", description,847 "expected a number but got a ${type_actual}",848 {type_actual:typeof actual});849 assert(actual >= lower && actual <= upper,850 "assert_between_inclusive", description,851 "expected a number greater than or equal to ${lower} " +852 "and less than or equal to ${upper} but got ${actual}",853 {lower:lower, upper:upper, actual:actual});854 }855 expose(assert_between_inclusive, "assert_between_inclusive");856 function assert_regexp_match(actual, expected, description) {857 858 assert(expected.test(actual),859 "assert_regexp_match", description,860 "expected ${expected} but got ${actual}",861 {expected:expected, actual:actual});862 }863 expose(assert_regexp_match, "assert_regexp_match");864 function assert_class_string(object, class_string, description) {865 assert_equals({}.toString.call(object), "[object " + class_string + "]",866 description);867 }868 expose(assert_class_string, "assert_class_string");869 function _assert_own_property(name) {870 return function(object, property_name, description)871 {872 assert(object.hasOwnProperty(property_name),873 name, description,874 "expected property ${p} missing", {p:property_name});875 };876 }877 expose(_assert_own_property("assert_exists"), "assert_exists");878 expose(_assert_own_property("assert_own_property"), "assert_own_property");879 function assert_not_exists(object, property_name, description)880 {881 assert(!object.hasOwnProperty(property_name),882 "assert_not_exists", description,883 "unexpected property ${p} found", {p:property_name});884 }885 expose(assert_not_exists, "assert_not_exists");886 function _assert_inherits(name) {887 return function (object, property_name, description)888 {889 assert(typeof object === "object",890 name, description,891 "provided value is not an object");892 assert("hasOwnProperty" in object,893 name, description,894 "provided value is an object but has no hasOwnProperty method");895 assert(!object.hasOwnProperty(property_name),896 name, description,897 "property ${p} found on object expected in prototype chain",898 {p:property_name});899 assert(property_name in object,900 name, description,901 "property ${p} not found in prototype chain",902 {p:property_name});903 };904 }905 expose(_assert_inherits("assert_inherits"), "assert_inherits");906 expose(_assert_inherits("assert_idl_attribute"), "assert_idl_attribute");907 function assert_readonly(object, property_name, description)908 {909 var initial_value = object[property_name];910 try {911 912 913 object[property_name] = initial_value + "a"; 914 assert(same_value(object[property_name], initial_value),915 "assert_readonly", description,916 "changing property ${p} succeeded",917 {p:property_name});918 } finally {919 object[property_name] = initial_value;920 }921 }922 expose(assert_readonly, "assert_readonly");923 function assert_throws(code, func, description)924 {925 try {926 func.call(this);927 assert(false, "assert_throws", description,928 "${func} did not throw", {func:func});929 } catch (e) {930 if (e instanceof AssertionError) {931 throw e;932 }933 if (code === null) {934 return;935 }936 if (typeof code === "object") {937 assert(typeof e == "object" && "name" in e && e.name == code.name,938 "assert_throws", description,939 "${func} threw ${actual} (${actual_name}) expected ${expected} (${expected_name})",940 {func:func, actual:e, actual_name:e.name,941 expected:code,942 expected_name:code.name});943 return;944 }945 var code_name_map = {946 INDEX_SIZE_ERR: 'IndexSizeError',947 HIERARCHY_REQUEST_ERR: 'HierarchyRequestError',948 WRONG_DOCUMENT_ERR: 'WrongDocumentError',949 INVALID_CHARACTER_ERR: 'InvalidCharacterError',950 NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',951 NOT_FOUND_ERR: 'NotFoundError',952 NOT_SUPPORTED_ERR: 'NotSupportedError',953 INVALID_STATE_ERR: 'InvalidStateError',954 SYNTAX_ERR: 'SyntaxError',955 INVALID_MODIFICATION_ERR: 'InvalidModificationError',956 NAMESPACE_ERR: 'NamespaceError',957 INVALID_ACCESS_ERR: 'InvalidAccessError',958 TYPE_MISMATCH_ERR: 'TypeMismatchError',959 SECURITY_ERR: 'SecurityError',960 NETWORK_ERR: 'NetworkError',961 ABORT_ERR: 'AbortError',962 URL_MISMATCH_ERR: 'URLMismatchError',963 QUOTA_EXCEEDED_ERR: 'QuotaExceededError',964 TIMEOUT_ERR: 'TimeoutError',965 INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError',966 DATA_CLONE_ERR: 'DataCloneError'967 };968 var name = code in code_name_map ? code_name_map[code] : code;969 var name_code_map = {970 IndexSizeError: 1,971 HierarchyRequestError: 3,972 WrongDocumentError: 4,973 InvalidCharacterError: 5,974 NoModificationAllowedError: 7,975 NotFoundError: 8,976 NotSupportedError: 9,977 InvalidStateError: 11,978 SyntaxError: 12,979 InvalidModificationError: 13,980 NamespaceError: 14,981 InvalidAccessError: 15,982 TypeMismatchError: 17,983 SecurityError: 18,984 NetworkError: 19,985 AbortError: 20,986 URLMismatchError: 21,987 QuotaExceededError: 22,988 TimeoutError: 23,989 InvalidNodeTypeError: 24,990 DataCloneError: 25,991 EncodingError: 0,992 NotReadableError: 0,993 UnknownError: 0,994 ConstraintError: 0,995 DataError: 0,996 TransactionInactiveError: 0,997 ReadOnlyError: 0,998 VersionError: 0,999 OperationError: 0,1000 };1001 if (!(name in name_code_map)) {1002 throw new AssertionError('Test bug: unrecognized DOMException code "' + code + '" passed to assert_throws()');1003 }1004 var required_props = { code: name_code_map[name] };1005 if (required_props.code === 0 ||1006 (typeof e == "object" &&1007 "name" in e &&1008 e.name !== e.name.toUpperCase() &&1009 e.name !== "DOMException")) {1010 1011 required_props.name = name;1012 }1013 1014 1015 1016 1017 assert(typeof e == "object",1018 "assert_throws", description,1019 "${func} threw ${e} with type ${type}, not an object",1020 {func:func, e:e, type:typeof e});1021 for (var prop in required_props) {1022 assert(typeof e == "object" && prop in e && e[prop] == required_props[prop],1023 "assert_throws", description,1024 "${func} threw ${e} that is not a DOMException " + code + ": property ${prop} is equal to ${actual}, expected ${expected}",1025 {func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]});1026 }1027 }1028 }1029 expose(assert_throws, "assert_throws");1030 function assert_unreached(description) {1031 assert(false, "assert_unreached", description,1032 "Reached unreachable code");1033 }1034 expose(assert_unreached, "assert_unreached");1035 function assert_any(assert_func, actual, expected_array)1036 {1037 var args = [].slice.call(arguments, 3);1038 var errors = [];1039 var passed = false;1040 forEach(expected_array,1041 function(expected)1042 {1043 try {1044 assert_func.apply(this, [actual, expected].concat(args));1045 passed = true;1046 } catch (e) {1047 errors.push(e.message);1048 }1049 });1050 if (!passed) {1051 throw new AssertionError(errors.join("\n\n"));1052 }1053 }1054 expose(assert_any, "assert_any");1055 function Test(name, properties)1056 {1057 if (tests.file_is_test && tests.tests.length) {1058 throw new Error("Tried to create a test with file_is_test");1059 }1060 this.name = name;1061 this.phase = this.phases.INITIAL;1062 this.status = this.NOTRUN;1063 this.timeout_id = null;1064 this.index = null;1065 this.properties = properties;1066 var timeout = properties.timeout ? properties.timeout : settings.test_timeout;1067 if (timeout !== null) {1068 this.timeout_length = timeout * tests.timeout_multiplier;1069 } else {1070 this.timeout_length = null;1071 }1072 this.message = null;1073 this.stack = null;1074 this.steps = [];1075 this.cleanup_callbacks = [];1076 tests.push(this);1077 }1078 Test.statuses = {1079 PASS:0,1080 FAIL:1,1081 TIMEOUT:2,1082 NOTRUN:31083 };1084 Test.prototype = merge({}, Test.statuses);1085 Test.prototype.phases = {1086 INITIAL:0,1087 STARTED:1,1088 HAS_RESULT:2,1089 COMPLETE:31090 };1091 Test.prototype.structured_clone = function()1092 {1093 if (!this._structured_clone) {1094 var msg = this.message;1095 msg = msg ? String(msg) : msg;1096 this._structured_clone = merge({1097 name:String(this.name),1098 properties:merge({}, this.properties),1099 }, Test.statuses);1100 }1101 this._structured_clone.status = this.status;1102 this._structured_clone.message = this.message;1103 this._structured_clone.stack = this.stack;1104 this._structured_clone.index = this.index;1105 return this._structured_clone;1106 };1107 Test.prototype.step = function(func, this_obj)1108 {1109 if (this.phase > this.phases.STARTED) {1110 return;1111 }1112 this.phase = this.phases.STARTED;1113 1114 this.set_status(this.TIMEOUT, "Test timed out");1115 tests.started = true;1116 tests.notify_test_state(this);1117 if (this.timeout_id === null) {1118 this.set_timeout();1119 }1120 this.steps.push(func);1121 if (arguments.length === 1) {1122 this_obj = this;1123 }1124 try {1125 return func.apply(this_obj, Array.prototype.slice.call(arguments, 2));1126 } catch (e) {1127 if (this.phase >= this.phases.HAS_RESULT) {1128 return;1129 }1130 var message = String((typeof e === "object" && e !== null) ? e.message : e);1131 var stack = e.stack ? e.stack : null;1132 this.set_status(this.FAIL, message, stack);1133 this.phase = this.phases.HAS_RESULT;1134 this.done();1135 }1136 };1137 Test.prototype.step_func = function(func, this_obj)1138 {1139 var test_this = this;1140 if (arguments.length === 1) {1141 this_obj = test_this;1142 }1143 return function()1144 {1145 return test_this.step.apply(test_this, [func, this_obj].concat(1146 Array.prototype.slice.call(arguments)));1147 };1148 };1149 Test.prototype.step_func_done = function(func, this_obj)1150 {1151 var test_this = this;1152 if (arguments.length === 1) {1153 this_obj = test_this;1154 }1155 return function()1156 {1157 if (func) {1158 test_this.step.apply(test_this, [func, this_obj].concat(1159 Array.prototype.slice.call(arguments)));1160 }1161 test_this.done();1162 };1163 };1164 Test.prototype.unreached_func = function(description)1165 {1166 return this.step_func(function() {1167 assert_unreached(description);1168 });1169 };1170 Test.prototype.add_cleanup = function(callback) {1171 this.cleanup_callbacks.push(callback);1172 };1173 Test.prototype.force_timeout = function() {1174 this.set_status(this.TIMEOUT);1175 this.phase = this.phases.HAS_RESULT;1176 };1177 Test.prototype.set_timeout = function()1178 {1179 if (this.timeout_length !== null) {1180 var this_obj = this;1181 this.timeout_id = setTimeout(function()1182 {1183 this_obj.timeout();1184 }, this.timeout_length);1185 }1186 };1187 Test.prototype.set_status = function(status, message, stack)1188 {1189 this.status = status;1190 this.message = message;1191 this.stack = stack ? stack : null;1192 };1193 Test.prototype.timeout = function()1194 {1195 this.timeout_id = null;1196 this.set_status(this.TIMEOUT, "Test timed out");1197 this.phase = this.phases.HAS_RESULT;1198 this.done();1199 };1200 Test.prototype.done = function()1201 {1202 if (this.phase == this.phases.COMPLETE) {1203 return;1204 }1205 if (this.phase <= this.phases.STARTED) {1206 this.set_status(this.PASS, null);1207 }1208 this.phase = this.phases.COMPLETE;1209 clearTimeout(this.timeout_id);1210 tests.result(this);1211 this.cleanup();1212 };1213 Test.prototype.cleanup = function() {1214 forEach(this.cleanup_callbacks,1215 function(cleanup_callback) {1216 cleanup_callback();1217 });1218 };1219 1220 function RemoteTest(clone) {1221 var this_obj = this;1222 Object.keys(clone).forEach(1223 function(key) {1224 this_obj[key] = clone[key];1225 });1226 this.index = null;1227 this.phase = this.phases.INITIAL;1228 this.update_state_from(clone);1229 tests.push(this);1230 }1231 RemoteTest.prototype.structured_clone = function() {1232 var clone = {};1233 Object.keys(this).forEach(1234 (function(key) {1235 if (typeof(this[key]) === "object") {1236 clone[key] = merge({}, this[key]);1237 } else {1238 clone[key] = this[key];1239 }1240 }).bind(this));1241 clone.phases = merge({}, this.phases);1242 return clone;1243 };1244 RemoteTest.prototype.cleanup = function() {};1245 RemoteTest.prototype.phases = Test.prototype.phases;1246 RemoteTest.prototype.update_state_from = function(clone) {1247 this.status = clone.status;1248 this.message = clone.message;1249 this.stack = clone.stack;1250 if (this.phase === this.phases.INITIAL) {1251 this.phase = this.phases.STARTED;1252 }1253 };1254 RemoteTest.prototype.done = function() {1255 this.phase = this.phases.COMPLETE;1256 }1257 1258 function RemoteWorker(worker) {1259 this.running = true;1260 this.tests = new Array();1261 var this_obj = this;1262 worker.onerror = function(error) { this_obj.worker_error(error); };1263 var message_port;1264 if (is_service_worker(worker)) {1265 if (window.MessageChannel) {1266 1267 1268 1269 1270 1271 1272 var message_channel = new MessageChannel();1273 message_port = message_channel.port1;1274 message_port.start();1275 worker.postMessage({type: "connect"}, [message_channel.port2]);1276 } else {1277 1278 1279 1280 message_port = navigator.serviceWorker;1281 worker.postMessage({type: "connect"});1282 }1283 } else if (is_shared_worker(worker)) {1284 message_port = worker.port;1285 } else {1286 message_port = worker;1287 }1288 1289 1290 1291 this.worker = worker;1292 message_port.onmessage =1293 function(message) {1294 if (this_obj.running && (message.data.type in this_obj.message_handlers)) {1295 this_obj.message_handlers[message.data.type].call(this_obj, message.data);1296 }1297 };...
worker.js
Source:worker.js
1const IS_SHARED_WORKER = (2 typeof SharedWorkerGlobalScope !== 'undefined' &&3 self instanceof SharedWorkerGlobalScope4);5function uuidv4() {6 return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>7 (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)8 );9}10// If adding to requirements, you must make sure that we mirror new packages11// correctly if they exist in the Pyodide repo. Our repo only contains the12// subset that we use. (Packages not from Pyodide and only in PyPi will be13// fetched correctly.)14const requirements = {15 // organized by `import_name: package_name`16 // Pyodide built-ins17 'PIL.Image': 'Pillow',18 yaml: 'pyyaml',19 pytz: 'pytz',20 // PyPi21 django: 'Django==3.1.7',22 ratelimit: 'django-ratelimit==3.0.0',23 html2text: 'html2text==2020.1.16',24 importlib_resources: 'importlib_resources==5.2.2',25 markdown: 'Markdown==3.2.2',26 dateutil: 'python-dateutil==2.8.1',27 redis: 'redis==3.5.3',28 requests: 'requests==2.25.1',29 emoji: 'emoji==1.2.0', // server version is 1.5.030};31/*32interface PyodideWorkerGlobalScope extends SharedWorkerGlobalScope {33 XMLHttpRequest: any;34 loadPyodide(config: any);35 pyodide: any;36 context: Map<string, any>;37 requirements: Map<string, string>[];38 broadcastChannel: BroadcastChannel;39}40declare var self: PyodideWorkerGlobalScope;41*/42self.context = new Map();43self.requirements = requirements;44if (IS_SHARED_WORKER) {45 self.broadcastChannel = new BroadcastChannel('shared-worker-broadcast');46} else {47 self.broadcastChannel = self;48}49// const indexURL = 'https://cdn.jsdelivr.net/pyodide/v0.18.1/full/';50const indexURL = '/pyodide/v0.18.1/';51const syncFsPromise = (self) => {52 return new Promise((success, reject) => {53 self.pyodide.FS.syncfs(true, (err) => {54 if (err) reject(err);55 else success(undefined);56 });57 });58};59self.importScripts(`${indexURL}pyodide.js`);60async function loadPyodideAndPackages() {61 try {62 console.log('Checking IndexedDB');63 const testDbName = 'canary';64 const testDbPromise = new Promise((resolve, reject) => {65 const testDb = self.indexedDB.open(testDbName);66 testDb.onsuccess = resolve;67 testDb.onerror = reject;68 });69 await testDbPromise;70 self.indexedDB.deleteDatabase(testDbName);71 console.log('Starting load');72 self.pyodide = await self.loadPyodide({73 indexURL: indexURL,74 fullStdLib: false,75 });76 console.log('Loading cache');77 self.pyodide.FS.mkdir('/indexeddb');78 self.pyodide.FS.mount(self.pyodide.FS.filesystems.IDBFS, {}, '/indexeddb');79 const syncPromise = syncFsPromise(self);80 console.log('Awaiting sync')81 await syncPromise;82 console.log('Synced')83 // TODO: move into pyodide_entrypoint84 await self.pyodide.runPythonAsync(`85 import importlib86 import logging87 import os88 import sys89 import zipfile90 import js91 sys.path.append('/indexeddb/site-packages.zip')92 sys.path.append('/server.zip')93 sys_packages = []94 os.environ['SETUPTOOLS_USE_DISTUTILS'] = 'local'95 try:96 with zipfile.ZipFile('/indexeddb/immovable-site-packages.zip') as zipf:97 site_packages = '/lib/python3.9/site-packages'98 for name in zipf.namelist():99 if not os.path.isfile(os.path.join(site_packages, name)):100 zipf.extract(name, site_packages)101 except Exception as e:102 logging.warn(e)103 print('Checking packages')104 for pkg, override in [105 ('micropip', None),106 ('setuptools', None),107 ]:108 try:109 if override is not None:110 override()111 else:112 importlib.import_module(pkg)113 except ImportError as e:114 logging.warn(e)115 logging.warn(pkg)116 sys_packages.append(pkg)117 if sys_packages:118 await js.pyodide.loadPackage(sys_packages)119 import micropip120 packages = []121 for req, pkg in js.requirements.to_py().items():122 try:123 importlib.import_module(req)124 except ImportError as e:125 packages.append(pkg)126 tasks = []127 if packages:128 tasks.append(micropip.install(packages))129 print('Fetching server code')130 response = await js.fetch('/api/server.zip')131 js_buffer = await response.arrayBuffer()132 with open('/server.zip', 'wb') as f:133 f.write(js_buffer.to_py())134 print('Awaiting python install')135 for task in tasks:136 await task137 importlib.invalidate_caches()138 print('Dependencies loaded')139 import pyodide_entrypoint140 `);141 } catch (error) {142 console.error(error);143 pyodideUnavailable = true;144 self.broadcastChannel.postMessage({145 type: 'worker-unavailable',146 });147 throw Error(error);148 }149 console.log('Finished load');150 pyodideReady = true;151 self.broadcastChannel.postMessage({152 type: 'worker-ready',153 });154}155let pyodideReady = false;156let pyodideUnavailable = false;157const pyodideReadyPromise = loadPyodideAndPackages();158const onmessage = (port) => (event) => {159 const func = async () => {160 if (!pyodideReady) return;161 switch(event.data.type) {162 case 'python':163 {164 const { script } = event.data;165 // const reply : any = {166 const reply = {167 type: 'python',168 id: event.data.id,169 };170 try {171 const result = self.pyodide.runPython(script);172 reply.result = result;173 } catch (error) {174 reply.error = error.message;175 }176 port.postMessage(reply);177 }178 break;179 case 'websocket':180 {181 const {url, data} = event.data;182 const pathname = new URL(url, 'https://teamamtehunt.com').pathname;183 const regexPuzzlePath = /\/puzzles\/([^\/]+)/;184 const match = pathname.match(regexPuzzlePath);185 // let puzzle : string | undefined = undefined;186 let puzzle;187 if (match) puzzle = match[1];188 const id = uuidv4();189 self.context.set(id, { data, puzzle });190 await syncFsPromise(self).catch(() => {});191 self.pyodide.runPython(`192 import js193 from puzzles.consumers import ClientConsumer194 context = js.globalThis.context['${id}'].to_py()195 ClientConsumer().receive_json(196 context['data'],197 puzzle_slug_override=context['puzzle'],198 )199 None200 `);201 self.context.delete(id);202 }203 break;204 case 'fetch':205 {206 const {type, path, id, ...options} = event.data;207 self.context.set(id, { path, ...options });208 await syncFsPromise(self).catch(() => {});209 self.pyodide.runPython(`210 import js211 import pyodide212 context = js.globalThis.context['${id}'].to_py()213 from tph.utils import get_mock_response214 js.globalThis.context['${id}'].response = pyodide.to_js(215 get_mock_response(**context),216 dict_converter=js.Object.fromEntries,217 )218 None219 `);220 const response = self.context.get(id).response;221 self.context.delete(id);222 port.postMessage({223 type: 'fetch',224 id,225 response,226 });227 }228 break;229 default:230 break;231 }232 };233 func();234};235if (IS_SHARED_WORKER) {236 self.addEventListener('connect', (event) => {237 console.log('Client has connected to the shared worker.');238 const port = event.ports[0];239 port.onmessage = onmessage(port);240 if (pyodideReady) {241 self.broadcastChannel.postMessage({242 type: 'worker-ready',243 });244 }245 if (pyodideUnavailable) {246 self.broadcastChannel.postMessage({247 type: 'worker-unavailable',248 });249 }250 });251} else {252 console.log('Client has connected to the worker.');253 self.onmessage = onmessage(self);...
Using AI Code Generation
1var worker = new SharedWorker("resources/echo-worker.js");2worker.port.onmessage = function(e) {3 if (e.data === "DONE") {4 parentPort.postMessage("PASS");5 } else {6 parentPort.postMessage("FAIL");7 }8};9worker.port.postMessage("DONE");
Using AI Code Generation
1var wptserve = get_host_info();2function handleRequest(request, response) {3 var worker = new SharedWorker("worker.js");4 worker.port.onmessage = function(e) {5 response.setHeader("Content-Type", "text/plain");6 response.write(e.data);7 response.close();8 }9 worker.port.postMessage("hello");10}11function handleRequestWithNoSharedWorker(request, response) {12 response.setHeader("Content-Type", "text/plain");13 response.write("no shared worker");14 response.close();15}16if (wptserve.is_shared_worker()) {17 onconnect = function(e) {18 var port = e.ports[0];19 port.onmessage = function(e) {20 port.postMessage("hello from shared worker");21 }22 };23} else {24 var script_url = wptserve.script_url;25 if (script_url.indexOf("no_shared_worker") != -1) {26 var handler = handleRequestWithNoSharedWorker;27 } else {28 var handler = handleRequest;29 }30 wptserve.set_handler(handler);31}
Using AI Code Generation
1if (wpt.is_shared_worker()) {2 var worker = new SharedWorker('worker.js');3 worker.port.postMessage('Hello World');4 worker.port.onmessage = function(e) {5 console.log(e.data);6 };7 worker.port.close();8} else {9 console.log('SharedWorker not supported');10}11onmessage = function(e) {12 console.log(e.data);13 postMessage('Hello from worker');14};15if (wpt.is_service_worker()) {16 navigator.serviceWorker.register('service-worker.js').then(function(reg) {17 console.log('Registration succeeded. Scope is ' + reg.scope);18 }).catch(function(error) {19 console.log('Registration failed with ' + error);20 });21} else {22 console.log('ServiceWorker not supported');23}24self.addEventListener('install', function(event) {25 console.log('install');26});27if (wpt.is_websocket()) {28 ws.onopen = function() {29 ws.send('Hello World');30 console.log('Message is sent...');31 };32 ws.onmessage = function(evt) {33 var received_msg = evt.data;34 console.log('Message is received...');35 };36 ws.onclose = function() {
Using AI Code Generation
1importScripts("/resources/testharness.js");2importScripts("/resources/WebIDLParser.js");3importScripts("/resources/idlharness.js");4importScripts("wptreport.js");5var wpt = new WPTReport();6wpt.is_shared_worker();7wpt.done();
Using AI Code Generation
1function sharedWorkerTest(test, worker_url, scope, expected, description) {2 var worker = new SharedWorker(worker_url, scope);3 test.step(function() {4 worker.port.onmessage = test.step_func(function(e) {5 assert_equals(e.data, expected, description);6 test.done();7 });8 });9}
Using AI Code Generation
1function is_shared_worker() {2 if (typeof(Worker) !== "function") {3 return false;4 }5 var w = new Worker("is_shared_worker_worker.js");6 w.postMessage("ping");7 w.onmessage = function(e) {8 if (e.data == "pong") {9 postMessage(true);10 }11 else {12 postMessage(false);13 }14 };15}
Using AI Code Generation
1if (this.is_shared_worker) {2 onconnect = function(e) {3 var port = e.ports[0];4 port.onmessage = function(e) {5 port.postMessage(e.data);6 }7 }8}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!