Best JavaScript code snippet using wpt
audit.js
Source:audit.js
...26 test(function(arg) {27 assert_true(true);28 }, message);29 }30 function _logFailed(message, detail) {31 test(function() {32 assert_true(false, detail);33 }, message);34 }35 function _throwException(message) {36 throw new Error(message);37 }38 // TODO(hongchan): remove this hack after confirming all the tests are39 // finished correctly. (crbug.com/708817)40 const _testharnessDone = window.done;41 window.done = () => {42 _throwException('Do NOT call done() method from the test code.');43 };44 // Generate a descriptive string from a target value in various types.45 function _generateDescription(target, options) {46 let targetString;47 switch (typeof target) {48 case 'object':49 // Handle Arrays.50 if (target instanceof Array || target instanceof Float32Array ||51 target instanceof Float64Array || target instanceof Uint8Array) {52 let arrayElements = target.length < options.numberOfArrayElements ?53 String(target) :54 String(target.slice(0, options.numberOfArrayElements)) + '...';55 targetString = '[' + arrayElements + ']';56 } else if (target === null) {57 // null is an object, so we need to handle this specially.58 targetString = String(target);59 } else {60 // We're expecting String() to return something like "[object Foo]",61 // so we split the string to get the object type "Foo". This is62 // pretty fragile.63 targetString = '' + String(targetString).split(/[\s\]]/)[1];64 }65 break;66 default:67 targetString = String(target);68 break;69 }70 return targetString;71 }72 // Return a string suitable for printing one failed element in73 // |beCloseToArray|.74 function _formatFailureEntry(index, actual, expected, abserr, threshold) {75 return '\t[' + index + ']\t' + actual.toExponential(16) + '\t' +76 expected.toExponential(16) + '\t' + abserr.toExponential(16) + '\t' +77 (abserr / Math.abs(expected)).toExponential(16) + '\t' +78 threshold.toExponential(16);79 }80 // Compute the error threshold criterion for |beCloseToArray|81 function _closeToThreshold(abserr, relerr, expected) {82 return Math.max(abserr, relerr * Math.abs(expected));83 }84 /**85 * @class Should86 * @description Assertion subtask for the Audit task.87 * @param {Task} parentTask Associated Task object.88 * @param {Any} actual Target value to be tested.89 * @param {String} actualDescription String description of the test target.90 */91 class Should {92 constructor(parentTask, actual, actualDescription) {93 this._task = parentTask;94 this._actual = actual;95 this._actualDescription = (actualDescription || null);96 this._expected = null;97 this._expectedDescription = null;98 this._detail = '';99 // If true and the test failed, print the actual value at the100 // end of the message.101 this._printActualForFailure = true;102 this._result = null;103 /**104 * @param {Number} numberOfErrors Number of errors to be printed.105 * @param {Number} numberOfArrayElements Number of array elements to be106 * printed in the test log.107 * @param {Boolean} verbose Verbose output from the assertion.108 */109 this._options = {110 numberOfErrors: 4,111 numberOfArrayElements: 16,112 verbose: false113 };114 }115 _processArguments(args) {116 if (args.length === 0)117 return;118 if (args.length > 0)119 this._expected = args[0];120 if (typeof args[1] === 'string') {121 // case 1: (expected, description, options)122 this._expectedDescription = args[1];123 Object.assign(this._options, args[2]);124 } else if (typeof args[1] === 'object') {125 // case 2: (expected, options)126 Object.assign(this._options, args[1]);127 }128 }129 _buildResultText() {130 if (this._result === null)131 _throwException('Illegal invocation: the assertion is not finished.');132 let actualString = _generateDescription(this._actual, this._options);133 // Use generated text when the description is not provided.134 if (!this._actualDescription)135 this._actualDescription = actualString;136 if (!this._expectedDescription) {137 this._expectedDescription =138 _generateDescription(this._expected, this._options);139 }140 // For the assertion with a single operand.141 this._detail =142 this._detail.replace(/\$\{actual\}/g, this._actualDescription);143 // If there is a second operand (i.e. expected value), we have to build144 // the string for it as well.145 this._detail =146 this._detail.replace(/\$\{expected\}/g, this._expectedDescription);147 // If there is any property in |_options|, replace the property name148 // with the value.149 for (let name in this._options) {150 if (name === 'numberOfErrors' || name === 'numberOfArrayElements' ||151 name === 'verbose') {152 continue;153 }154 // The RegExp key string contains special character. Take care of it.155 let re = '\$\{' + name + '\}';156 re = re.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');157 this._detail = this._detail.replace(158 new RegExp(re, 'g'), _generateDescription(this._options[name]));159 }160 // If the test failed, add the actual value at the end.161 if (this._result === false && this._printActualForFailure === true) {162 this._detail += ' Got ' + actualString + '.';163 }164 }165 _finalize() {166 if (this._result) {167 _logPassed(' ' + this._detail);168 } else {169 _logFailed('X ' + this._detail);170 }171 // This assertion is finished, so update the parent task accordingly.172 this._task.update(this);173 // TODO(hongchan): configurable 'detail' message.174 }175 _assert(condition, passDetail, failDetail) {176 this._result = Boolean(condition);177 this._detail = this._result ? passDetail : failDetail;178 this._buildResultText();179 this._finalize();180 return this._result;181 }182 get result() {183 return this._result;184 }185 get detail() {186 return this._detail;187 }188 /**189 * should() assertions.190 *191 * @example All the assertions can have 1, 2 or 3 arguments:192 * should().doAssert(expected);193 * should().doAssert(expected, options);194 * should().doAssert(expected, expectedDescription, options);195 *196 * @param {Any} expected Expected value of the assertion.197 * @param {String} expectedDescription Description of expected value.198 * @param {Object} options Options for assertion.199 * @param {Number} options.numberOfErrors Number of errors to be printed.200 * (if applicable)201 * @param {Number} options.numberOfArrayElements Number of array elements202 * to be printed. (if203 * applicable)204 * @notes Some assertions can have additional options for their specific205 * testing.206 */207 /**208 * Check if |actual| exists.209 *210 * @example211 * should({}, 'An empty object').exist();212 * @result213 * "PASS An empty object does exist."214 */215 exist() {216 return this._assert(217 this._actual !== null && this._actual !== undefined,218 '${actual} does exist.', '${actual} does not exist.');219 }220 /**221 * Check if |actual| operation wrapped in a function throws an exception222 * with a expected error type correctly. |expected| is optional.223 *224 * @example225 * should(() => { let a = b; }, 'A bad code').throw();226 * should(() => { let c = d; }, 'Assigning d to c.')227 * .throw('ReferenceError');228 * should(() => { let e = f; }, 'Assigning e to f.')229 * .throw('ReferenceError', { omitErrorMessage: true });230 *231 * @result232 * "PASS A bad code threw an exception of ReferenceError: b is not233 * defined."234 * "PASS Assigning d to c threw ReferenceError: d is not defined."235 * "PASS Assigning e to f threw ReferenceError: [error message236 * omitted]."237 */238 throw() {239 this._processArguments(arguments);240 this._printActualForFailure = false;241 let didThrowCorrectly = false;242 let passDetail, failDetail;243 try {244 // This should throw.245 this._actual();246 // Catch did not happen, so the test is failed.247 failDetail = '${actual} did not throw an exception.';248 } catch (error) {249 let errorMessage = this._options.omitErrorMessage ?250 ': [error message omitted]' :251 ': "' + error.message + '"';252 if (this._expected === null || this._expected === undefined) {253 // The expected error type was not given.254 didThrowCorrectly = true;255 passDetail = '${actual} threw ' + error.name + errorMessage + '.';256 } else if (error.name === this._expected) {257 // The expected error type match the actual one.258 didThrowCorrectly = true;259 passDetail = '${actual} threw ${expected}' + errorMessage + '.';260 } else {261 didThrowCorrectly = false;262 failDetail =263 '${actual} threw "' + error.name + '" instead of ${expected}.';264 }265 }266 return this._assert(didThrowCorrectly, passDetail, failDetail);267 }268 /**269 * Check if |actual| operation wrapped in a function does not throws an270 * exception correctly.271 *272 * @example273 * should(() => { let foo = 'bar'; }, 'let foo = "bar"').notThrow();274 *275 * @result276 * "PASS let foo = "bar" did not throw an exception."277 */278 notThrow() {279 this._printActualForFailure = false;280 let didThrowCorrectly = false;281 let passDetail, failDetail;282 try {283 this._actual();284 passDetail = '${actual} did not throw an exception.';285 } catch (error) {286 didThrowCorrectly = true;287 failDetail = '${actual} incorrectly threw ' + error.name + ': "' +288 error.message + '".';289 }290 return this._assert(!didThrowCorrectly, passDetail, failDetail);291 }292 /**293 * Check if |actual| promise is resolved correctly. Note that the returned294 * result from promise object will be passed to the following then()295 * function.296 *297 * @example298 * should('My promise', promise).beResolve().then((result) => {299 * // log(result);300 * });301 *302 * @result303 * "PASS My promise resolved correctly."304 * "FAIL X My promise rejected *INCORRECTLY* with _ERROR_."305 */306 beResolved() {307 return this._actual.then(308 function(result) {309 this._assert(true, '${actual} resolved correctly.', null);310 return result;311 }.bind(this),312 function(error) {313 this._assert(314 false, null,315 '${actual} rejected incorrectly with ' + error + '.');316 }.bind(this));317 }318 /**319 * Check if |actual| promise is rejected correctly.320 *321 * @example322 * should('My promise', promise).beRejected().then(nextStuff);323 *324 * @result325 * "PASS My promise rejected correctly (with _ERROR_)."326 * "FAIL X My promise resolved *INCORRECTLY*."327 */328 beRejected() {329 return this._actual.then(330 function() {331 this._assert(false, null, '${actual} resolved incorrectly.');332 }.bind(this),333 function(error) {334 this._assert(335 true, '${actual} rejected correctly with ' + error + '.', null);336 }.bind(this));337 }338 /**339 * Check if |actual| promise is rejected correctly.340 *341 * @example342 * should(promise, 'My promise').beRejectedWith('_ERROR_').then();343 *344 * @result345 * "PASS My promise rejected correctly with _ERROR_."346 * "FAIL X My promise rejected correctly but got _ACTUAL_ERROR instead of347 * _EXPECTED_ERROR_."348 * "FAIL X My promise resolved incorrectly."349 */350 beRejectedWith() {351 this._processArguments(arguments);352 return this._actual.then(353 function() {354 this._assert(false, null, '${actual} resolved incorrectly.');355 }.bind(this),356 function(error) {357 if (this._expected !== error.name) {358 this._assert(359 false, null,360 '${actual} rejected correctly but got ' + error.name +361 ' instead of ' + this._expected + '.');362 } else {363 this._assert(364 true,365 '${actual} rejected correctly with ' + this._expected + '.',366 null);367 }368 }.bind(this));369 }370 /**371 * Check if |actual| is a boolean true.372 *373 * @example374 * should(3 < 5, '3 < 5').beTrue();375 *376 * @result377 * "PASS 3 < 5 is true."378 */379 beTrue() {380 return this._assert(381 this._actual === true, '${actual} is true.',382 '${actual} is not true.');383 }384 /**385 * Check if |actual| is a boolean false.386 *387 * @example388 * should(3 > 5, '3 > 5').beFalse();389 *390 * @result391 * "PASS 3 > 5 is false."392 */393 beFalse() {394 return this._assert(395 this._actual === false, '${actual} is false.',396 '${actual} is not false.');397 }398 /**399 * Check if |actual| is strictly equal to |expected|. (no type coercion)400 *401 * @example402 * should(1).beEqualTo(1);403 *404 * @result405 * "PASS 1 is equal to 1."406 */407 beEqualTo() {408 this._processArguments(arguments);409 return this._assert(410 this._actual === this._expected, '${actual} is equal to ${expected}.',411 '${actual} is not equal to ${expected}.');412 }413 /**414 * Check if |actual| is not equal to |expected|.415 *416 * @example417 * should(1).notBeEqualTo(2);418 *419 * @result420 * "PASS 1 is not equal to 2."421 */422 notBeEqualTo() {423 this._processArguments(arguments);424 return this._assert(425 this._actual !== this._expected,426 '${actual} is not equal to ${expected}.',427 '${actual} should not be equal to ${expected}.');428 }429 /**430 * check if |actual| is NaN431 *432 * @example433 * should(NaN).beNaN();434 *435 * @result436 * "PASS NaN is NaN"437 *438 */439 beNaN() {440 this._processArguments(arguments);441 return this._assert(442 isNaN(this._actual),443 '${actual} is NaN.',444 '${actual} is not NaN but should be.');445 }446 /**447 * check if |actual| is NOT NaN448 *449 * @example450 * should(42).notBeNaN();451 *452 * @result453 * "PASS 42 is not NaN"454 *455 */456 notBeNaN() {457 this._processArguments(arguments);458 return this._assert(459 !isNaN(this._actual),460 '${actual} is not NaN.',461 '${actual} is NaN but should not be.');462 }463 /**464 * Check if |actual| is greater than |expected|.465 *466 * @example467 * should(2).beGreaterThanOrEqualTo(2);468 *469 * @result470 * "PASS 2 is greater than or equal to 2."471 */472 beGreaterThan() {473 this._processArguments(arguments);474 return this._assert(475 this._actual > this._expected,476 '${actual} is greater than ${expected}.',477 '${actual} is not greater than ${expected}.');478 }479 /**480 * Check if |actual| is greater than or equal to |expected|.481 *482 * @example483 * should(2).beGreaterThan(1);484 *485 * @result486 * "PASS 2 is greater than 1."487 */488 beGreaterThanOrEqualTo() {489 this._processArguments(arguments);490 return this._assert(491 this._actual >= this._expected,492 '${actual} is greater than or equal to ${expected}.',493 '${actual} is not greater than or equal to ${expected}.');494 }495 /**496 * Check if |actual| is less than |expected|.497 *498 * @example499 * should(1).beLessThan(2);500 *501 * @result502 * "PASS 1 is less than 2."503 */504 beLessThan() {505 this._processArguments(arguments);506 return this._assert(507 this._actual < this._expected, '${actual} is less than ${expected}.',508 '${actual} is not less than ${expected}.');509 }510 /**511 * Check if |actual| is less than or equal to |expected|.512 *513 * @example514 * should(1).beLessThanOrEqualTo(1);515 *516 * @result517 * "PASS 1 is less than or equal to 1."518 */519 beLessThanOrEqualTo() {520 this._processArguments(arguments);521 return this._assert(522 this._actual <= this._expected,523 '${actual} is less than or equal to ${expected}.',524 '${actual} is not less than or equal to ${expected}.');525 }526 /**527 * Check if |actual| array is filled with a constant |expected| value.528 *529 * @example530 * should([1, 1, 1]).beConstantValueOf(1);531 *532 * @result533 * "PASS [1,1,1] contains only the constant 1."534 */535 beConstantValueOf() {536 this._processArguments(arguments);537 this._printActualForFailure = false;538 let passed = true;539 let passDetail, failDetail;540 let errors = {};541 let actual = this._actual;542 let expected = this._expected;543 for (let index = 0; index < actual.length; ++index) {544 if (actual[index] !== expected)545 errors[index] = actual[index];546 }547 let numberOfErrors = Object.keys(errors).length;548 passed = numberOfErrors === 0;549 if (passed) {550 passDetail = '${actual} contains only the constant ${expected}.';551 } else {552 let counter = 0;553 failDetail =554 '${actual}: Expected ${expected} for all values but found ' +555 numberOfErrors + ' unexpected values: ';556 failDetail += '\n\tIndex\tActual';557 for (let errorIndex in errors) {558 failDetail += '\n\t[' + errorIndex + ']' +559 '\t' + errors[errorIndex];560 if (++counter >= this._options.numberOfErrors) {561 failDetail +=562 '\n\t...and ' + (numberOfErrors - counter) + ' more errors.';563 break;564 }565 }566 }567 return this._assert(passed, passDetail, failDetail);568 }569 /**570 * Check if |actual| array is not filled with a constant |expected| value.571 *572 * @example573 * should([1, 0, 1]).notBeConstantValueOf(1);574 * should([0, 0, 0]).notBeConstantValueOf(0);575 *576 * @result577 * "PASS [1,0,1] is not constantly 1 (contains 1 different value)."578 * "FAIL X [0,0,0] should have contain at least one value different579 * from 0."580 */581 notBeConstantValueOf() {582 this._processArguments(arguments);583 this._printActualForFailure = false;584 let passed = true;585 let passDetail;586 let failDetail;587 let differences = {};588 let actual = this._actual;589 let expected = this._expected;590 for (let index = 0; index < actual.length; ++index) {591 if (actual[index] !== expected)592 differences[index] = actual[index];593 }594 let numberOfDifferences = Object.keys(differences).length;595 passed = numberOfDifferences > 0;596 if (passed) {597 let valueString = numberOfDifferences > 1 ? 'values' : 'value';598 passDetail = '${actual} is not constantly ${expected} (contains ' +599 numberOfDifferences + ' different ' + valueString + ').';600 } else {601 failDetail = '${actual} should have contain at least one value ' +602 'different from ${expected}.';603 }604 return this._assert(passed, passDetail, failDetail);605 }606 /**607 * Check if |actual| array is identical to |expected| array element-wise.608 *609 * @example610 * should([1, 2, 3]).beEqualToArray([1, 2, 3]);611 *612 * @result613 * "[1,2,3] is identical to the array [1,2,3]."614 */615 beEqualToArray() {616 this._processArguments(arguments);617 this._printActualForFailure = false;618 let passed = true;619 let passDetail, failDetail;620 let errorIndices = [];621 if (this._actual.length !== this._expected.length) {622 passed = false;623 failDetail = 'The array length does not match.';624 return this._assert(passed, passDetail, failDetail);625 }626 let actual = this._actual;627 let expected = this._expected;628 for (let index = 0; index < actual.length; ++index) {629 if (actual[index] !== expected[index])630 errorIndices.push(index);631 }632 passed = errorIndices.length === 0;633 if (passed) {634 passDetail = '${actual} is identical to the array ${expected}.';635 } else {636 let counter = 0;637 failDetail =638 '${actual} expected to be equal to the array ${expected} ' +639 'but differs in ' + errorIndices.length + ' places:' +640 '\n\tIndex\tActual\t\t\tExpected';641 for (let index of errorIndices) {642 failDetail += '\n\t[' + index + ']' +643 '\t' + this._actual[index].toExponential(16) + '\t' +644 this._expected[index].toExponential(16);645 if (++counter >= this._options.numberOfErrors) {646 failDetail += '\n\t...and ' + (errorIndices.length - counter) +647 ' more errors.';648 break;649 }650 }651 }652 return this._assert(passed, passDetail, failDetail);653 }654 /**655 * Check if |actual| array contains only the values in |expected| in the656 * order of values in |expected|.657 *658 * @example659 * Should([1, 1, 3, 3, 2], 'My random array').containValues([1, 3, 2]);660 *661 * @result662 * "PASS [1,1,3,3,2] contains all the expected values in the correct663 * order: [1,3,2].664 */665 containValues() {666 this._processArguments(arguments);667 this._printActualForFailure = false;668 let passed = true;669 let indexedActual = [];670 let firstErrorIndex = null;671 // Collect the unique value sequence from the actual.672 for (let i = 0, prev = null; i < this._actual.length; i++) {673 if (this._actual[i] !== prev) {674 indexedActual.push({index: i, value: this._actual[i]});675 prev = this._actual[i];676 }677 }678 // Compare against the expected sequence.679 for (let j = 0; j < this._expected.length; j++) {680 if (this._expected[j] !== indexedActual[j].value) {681 firstErrorIndex = indexedActual[j].index;682 passed = false;683 break;684 }685 }686 return this._assert(687 passed,688 '${actual} contains all the expected values in the correct order: ' +689 '${expected}.',690 '${actual} expected to have the value sequence of ${expected} but ' +691 'got ' + this._actual[firstErrorIndex] + ' at index ' +692 firstErrorIndex + '.');693 }694 /**695 * Check if |actual| array does not have any glitches. Note that |threshold|696 * is not optional and is to define the desired threshold value.697 *698 * @example699 * should([0.5, 0.5, 0.55, 0.5, 0.45, 0.5]).notGlitch(0.06);700 *701 * @result702 * "PASS [0.5,0.5,0.55,0.5,0.45,0.5] has no glitch above the threshold703 * of 0.06."704 *705 */706 notGlitch() {707 this._processArguments(arguments);708 this._printActualForFailure = false;709 let passed = true;710 let passDetail, failDetail;711 let actual = this._actual;712 let expected = this._expected;713 for (let index = 0; index < actual.length; ++index) {714 let diff = Math.abs(actual[index - 1] - actual[index]);715 if (diff >= expected) {716 passed = false;717 failDetail = '${actual} has a glitch at index ' + index +718 ' of size ' + diff + '.';719 }720 }721 passDetail =722 '${actual} has no glitch above the threshold of ${expected}.';723 return this._assert(passed, passDetail, failDetail);724 }725 /**726 * Check if |actual| is close to |expected| using the given relative error727 * |threshold|.728 *729 * @example730 * should(2.3).beCloseTo(2, { threshold: 0.3 });731 *732 * @result733 * "PASS 2.3 is 2 within an error of 0.3."734 * @param {Object} options Options for assertion.735 * @param {Number} options.threshold Threshold value for the comparison.736 */737 beCloseTo() {738 this._processArguments(arguments);739 // The threshold is relative except when |expected| is zero, in which case740 // it is absolute.741 let absExpected = this._expected ? Math.abs(this._expected) : 1;742 let error = Math.abs(this._actual - this._expected) / absExpected;743 // debugger;744 return this._assert(745 error <= this._options.threshold,746 '${actual} is ${expected} within an error of ${threshold}.',747 '${actual} is not close to ${expected} within a relative error of ' +748 '${threshold} (RelErr=' + error + ').');749 }750 /**751 * Check if |target| array is close to |expected| array element-wise within752 * a certain error bound given by the |options|.753 *754 * The error criterion is:755 * abs(actual[k] - expected[k]) < max(absErr, relErr * abs(expected))756 *757 * If nothing is given for |options|, then absErr = relErr = 0. If758 * absErr = 0, then the error criterion is a relative error. A non-zero759 * absErr value produces a mix intended to handle the case where the760 * expected value is 0, allowing the target value to differ by absErr from761 * the expected.762 *763 * @param {Number} options.absoluteThreshold Absolute threshold.764 * @param {Number} options.relativeThreshold Relative threshold.765 */766 beCloseToArray() {767 this._processArguments(arguments);768 this._printActualForFailure = false;769 let passed = true;770 let passDetail, failDetail;771 // Parsing options.772 let absErrorThreshold = (this._options.absoluteThreshold || 0);773 let relErrorThreshold = (this._options.relativeThreshold || 0);774 // A collection of all of the values that satisfy the error criterion.775 // This holds the absolute difference between the target element and the776 // expected element.777 let errors = {};778 // Keep track of the max absolute error found.779 let maxAbsError = -Infinity, maxAbsErrorIndex = -1;780 // Keep track of the max relative error found, ignoring cases where the781 // relative error is Infinity because the expected value is 0.782 let maxRelError = -Infinity, maxRelErrorIndex = -1;783 let actual = this._actual;784 let expected = this._expected;785 for (let index = 0; index < expected.length; ++index) {786 let diff = Math.abs(actual[index] - expected[index]);787 let absExpected = Math.abs(expected[index]);788 let relError = diff / absExpected;789 if (diff >790 Math.max(absErrorThreshold, relErrorThreshold * absExpected)) {791 if (diff > maxAbsError) {792 maxAbsErrorIndex = index;793 maxAbsError = diff;794 }795 if (!isNaN(relError) && relError > maxRelError) {796 maxRelErrorIndex = index;797 maxRelError = relError;798 }799 errors[index] = diff;800 }801 }802 let numberOfErrors = Object.keys(errors).length;803 let maxAllowedErrorDetail = JSON.stringify({804 absoluteThreshold: absErrorThreshold,805 relativeThreshold: relErrorThreshold806 });807 if (numberOfErrors === 0) {808 // The assertion was successful.809 passDetail = '${actual} equals ${expected} with an element-wise ' +810 'tolerance of ' + maxAllowedErrorDetail + '.';811 } else {812 // Failed. Prepare the detailed failure log.813 passed = false;814 failDetail = '${actual} does not equal ${expected} with an ' +815 'element-wise tolerance of ' + maxAllowedErrorDetail + '.\n';816 // Print out actual, expected, absolute error, and relative error.817 let counter = 0;818 failDetail += '\tIndex\tActual\t\t\tExpected\t\tAbsError' +819 '\t\tRelError\t\tTest threshold';820 let printedIndices = [];821 for (let index in errors) {822 failDetail +=823 '\n' +824 _formatFailureEntry(825 index, actual[index], expected[index], errors[index],826 _closeToThreshold(827 absErrorThreshold, relErrorThreshold, expected[index]));828 printedIndices.push(index);829 if (++counter > this._options.numberOfErrors) {830 failDetail +=831 '\n\t...and ' + (numberOfErrors - counter) + ' more errors.';832 break;833 }834 }835 // Finalize the error log: print out the location of both the maxAbs836 // error and the maxRel error so we can adjust thresholds appropriately837 // in the test.838 failDetail += '\n' +839 '\tMax AbsError of ' + maxAbsError.toExponential(16) +840 ' at index of ' + maxAbsErrorIndex + '.\n';841 if (printedIndices.find(element => {842 return element == maxAbsErrorIndex;843 }) === undefined) {844 // Print an entry for this index if we haven't already.845 failDetail +=846 _formatFailureEntry(847 maxAbsErrorIndex, actual[maxAbsErrorIndex],848 expected[maxAbsErrorIndex], errors[maxAbsErrorIndex],849 _closeToThreshold(850 absErrorThreshold, relErrorThreshold,851 expected[maxAbsErrorIndex])) +852 '\n';853 }854 failDetail += '\tMax RelError of ' + maxRelError.toExponential(16) +855 ' at index of ' + maxRelErrorIndex + '.\n';856 if (printedIndices.find(element => {857 return element == maxRelErrorIndex;858 }) === undefined) {859 // Print an entry for this index if we haven't already.860 failDetail +=861 _formatFailureEntry(862 maxRelErrorIndex, actual[maxRelErrorIndex],863 expected[maxRelErrorIndex], errors[maxRelErrorIndex],864 _closeToThreshold(865 absErrorThreshold, relErrorThreshold,866 expected[maxRelErrorIndex])) +867 '\n';868 }869 }870 return this._assert(passed, passDetail, failDetail);871 }872 /**873 * A temporary escape hat for printing an in-task message. The description874 * for the |actual| is required to get the message printed properly.875 *876 * TODO(hongchan): remove this method when the transition from the old Audit877 * to the new Audit is completed.878 * @example879 * should(true, 'The message is').message('truthful!', 'false!');880 *881 * @result882 * "PASS The message is truthful!"883 */884 message(passDetail, failDetail) {885 return this._assert(886 this._actual, '${actual} ' + passDetail, '${actual} ' + failDetail);887 }888 /**889 * Check if |expected| property is truly owned by |actual| object.890 *891 * @example892 * should(BaseAudioContext.prototype,893 * 'BaseAudioContext.prototype').haveOwnProperty('createGain');894 *895 * @result896 * "PASS BaseAudioContext.prototype has an own property of897 * 'createGain'."898 */899 haveOwnProperty() {900 this._processArguments(arguments);901 return this._assert(902 this._actual.hasOwnProperty(this._expected),903 '${actual} has an own property of "${expected}".',904 '${actual} does not own the property of "${expected}".');905 }906 /**907 * Check if |expected| property is not owned by |actual| object.908 *909 * @example910 * should(BaseAudioContext.prototype,911 * 'BaseAudioContext.prototype')912 * .notHaveOwnProperty('startRendering');913 *914 * @result915 * "PASS BaseAudioContext.prototype does not have an own property of916 * 'startRendering'."917 */918 notHaveOwnProperty() {919 this._processArguments(arguments);920 return this._assert(921 !this._actual.hasOwnProperty(this._expected),922 '${actual} does not have an own property of "${expected}".',923 '${actual} has an own the property of "${expected}".')924 }925 /**926 * Check if an object is inherited from a class. This looks up the entire927 * prototype chain of a given object and tries to find a match.928 *929 * @example930 * should(sourceNode, 'A buffer source node')931 * .inheritFrom('AudioScheduledSourceNode');932 *933 * @result934 * "PASS A buffer source node inherits from 'AudioScheduledSourceNode'."935 */936 inheritFrom() {937 this._processArguments(arguments);938 let prototypes = [];939 let currentPrototype = Object.getPrototypeOf(this._actual);940 while (currentPrototype) {941 prototypes.push(currentPrototype.constructor.name);942 currentPrototype = Object.getPrototypeOf(currentPrototype);943 }944 return this._assert(945 prototypes.includes(this._expected),946 '${actual} inherits from "${expected}".',947 '${actual} does not inherit from "${expected}".');948 }949 }950 // Task Class state enum.951 const TaskState = {PENDING: 0, STARTED: 1, FINISHED: 2};952 /**953 * @class Task954 * @description WebAudio testing task. Managed by TaskRunner.955 */956 class Task {957 /**958 * Task constructor.959 * @param {Object} taskRunner Reference of associated task runner.960 * @param {String||Object} taskLabel Task label if a string is given. This961 * parameter can be a dictionary with the962 * following fields.963 * @param {String} taskLabel.label Task label.964 * @param {String} taskLabel.description Description of task.965 * @param {Function} taskFunction Task function to be performed.966 * @return {Object} Task object.967 */968 constructor(taskRunner, taskLabel, taskFunction) {969 this._taskRunner = taskRunner;970 this._taskFunction = taskFunction;971 if (typeof taskLabel === 'string') {972 this._label = taskLabel;973 this._description = null;974 } else if (typeof taskLabel === 'object') {975 if (typeof taskLabel.label !== 'string') {976 _throwException('Task.constructor:: task label must be string.');977 }978 this._label = taskLabel.label;979 this._description = (typeof taskLabel.description === 'string') ?980 taskLabel.description :981 null;982 } else {983 _throwException(984 'Task.constructor:: task label must be a string or ' +985 'a dictionary.');986 }987 this._state = TaskState.PENDING;988 this._result = true;989 this._totalAssertions = 0;990 this._failedAssertions = 0;991 }992 get label() {993 return this._label;994 }995 get state() {996 return this._state;997 }998 get result() {999 return this._result;1000 }1001 // Start the assertion chain.1002 should(actual, actualDescription) {1003 // If no argument is given, we cannot proceed. Halt.1004 if (arguments.length === 0)1005 _throwException('Task.should:: requires at least 1 argument.');1006 return new Should(this, actual, actualDescription);1007 }1008 // Run this task. |this| task will be passed into the user-supplied test1009 // task function.1010 run() {1011 this._state = TaskState.STARTED;1012 // Print out the task entry with label and description.1013 _logPassed(1014 '> [' + this._label + '] ' +1015 (this._description ? this._description : ''));1016 this._taskFunction(this, this.should.bind(this));1017 }1018 // Update the task success based on the individual assertion/test inside.1019 update(subTask) {1020 // After one of tests fails within a task, the result is irreversible.1021 if (subTask.result === false) {1022 this._result = false;1023 this._failedAssertions++;1024 }1025 this._totalAssertions++;1026 }1027 // Finish the current task and start the next one if available.1028 done() {1029 this._state = TaskState.FINISHED;1030 let message = '< [' + this._label + '] ';1031 if (this._result) {1032 message += 'All assertions passed. (total ' + this._totalAssertions +1033 ' assertions)';1034 _logPassed(message);1035 } else {1036 message += this._failedAssertions + ' out of ' + this._totalAssertions +1037 ' assertions were failed.'1038 _logFailed(message);1039 }1040 this._taskRunner._runNextTask();1041 }1042 isPassed() {1043 return this._state === TaskState.FINISHED && this._result;1044 }1045 toString() {1046 return '"' + this._label + '": ' + this._description;1047 }1048 }1049 /**1050 * @class TaskRunner1051 * @description WebAudio testing task runner. Manages tasks.1052 */1053 class TaskRunner {1054 constructor() {1055 this._tasks = {};1056 this._taskSequence = [];1057 this._currentTaskIndex = -1;1058 // Configure testharness.js for the async operation.1059 setup(new Function(), {explicit_done: true});1060 }1061 _runNextTask() {1062 if (this._currentTaskIndex < this._taskSequence.length) {1063 this._tasks[this._taskSequence[this._currentTaskIndex++]].run();1064 } else {1065 this._finish();1066 }1067 }1068 _finish() {1069 let numberOfFailures = 0;1070 for (let taskIndex in this._taskSequence) {1071 let task = this._tasks[this._taskSequence[taskIndex]];1072 numberOfFailures += task.result ? 0 : 1;1073 }1074 let prefix = '# AUDIT TASK RUNNER FINISHED: ';1075 if (numberOfFailures > 0) {1076 _logFailed(1077 prefix + numberOfFailures + ' out of ' + this._taskSequence.length +1078 ' tasks were failed.');1079 } else {1080 _logPassed(1081 prefix + this._taskSequence.length + ' tasks ran successfully.');1082 }1083 // From testharness.js, report back to the test infrastructure that1084 // the task runner completed all the tasks.1085 _testharnessDone();1086 }1087 // |taskLabel| can be either a string or a dictionary. See Task constructor1088 // for the detail.1089 define(taskLabel, taskFunction) {1090 let task = new Task(this, taskLabel, taskFunction);...
ActivityLogger.js
Source:ActivityLogger.js
...122 else123 // send to log server124 d3.json(_logServerUrl)125 .header("Content-Type", "application/json")126 .post(serializedObject, (err, json) => err ? _logFailed(err) : 0);127 }128 function _logFailed(err) {129 logger.warn("something went wrong");130 logger.warn(err.toString());131 }132 // exports of this module133 return {134 additionalFixedContent,135 mode,136 logPath,137 logServerUrl,138 ready,139 log140 };...
AssetReplacer.js
Source:AssetReplacer.js
1/**2 * Created by AlexanderC on 11/17/15.3 */4'use strict';5import fs from 'fs';6import path from 'path';7export class AssetReplacer {8 /**9 * @param {String} version10 */11 constructor(version) {12 this._version = version;13 this._replacers = [];14 this._logFailed = AssetReplacer.LOG_FAILED_STATE;15 }16 /**17 * @returns {Boolean}18 */19 get logFailed() {20 return this._logFailed;21 }22 /**23 * @param {Boolean} state24 */25 set logFailed(state) {26 this._logFailed = state;27 }28 /**29 * @param {String} version30 * @param {String|AbstractReplacer|*} replacers31 * @returns {AssetReplacer}32 */33 static create(version, ...replacers) {34 let self = new AssetReplacer(version);35 replacers.forEach((replacer) => {36 self.addReplacer(replacer);37 });38 return self;39 }40 /**41 * @param {String|*} files42 * @returns {AssetReplacer}43 */44 replace(...files) {45 files.forEach((file) => {46 let extension = AssetReplacer._getExtension(file);47 let content = fs.readFileSync(file).toString();48 try {49 this._replacers.forEach((replacer) => {50 content = replacer.replace(content, extension);51 });52 fs.writeFileSync(file, content);53 } catch (e) {54 if (this._logFailed) {55 console.error(`Failed asset replacer ${file}: ${e}`);56 } else {57 throw e;58 }59 }60 });61 return this;62 }63 /**64 * @param {String} file65 * @returns {String}66 * @private67 */68 static _getExtension(file) {69 return path.extname(file).substr(1).toLowerCase();70 }71 /**72 * @param {String|AbstractReplacer} replacer73 * @returns {AssetReplacer}74 */75 addReplacer(replacer) {76 if (typeof replacer === 'string') {77 let replacerName = `${AssetReplacer._ucFirst(replacer)}Replacer`;78 let ReplacerProto = require(`./Replacer/${replacerName}`)[replacerName];79 replacer = new ReplacerProto(this._version);80 }81 this._replacers.push(replacer);82 return this;83 }84 /**85 * @returns {AbstractReplacer[]}86 */87 get replacers() {88 return this._replacers;89 }90 /**91 * @returns {String}92 */93 get version() {94 return this._version;95 }96 /**97 * @param {String} str98 * @returns {String}99 * @private100 */101 static _ucFirst(str) {102 return str[0].toUpperCase() + str.slice(1);103 }104 /**105 * @returns {Boolean}106 */107 static get LOG_FAILED_STATE() {108 return true;109 }...
Using AI Code Generation
1var wpt = require('./wpt.js');2wpt._logFailed("test failed");3var wpt = require('./wpt.js');4wpt._logPassed("test passed");5var wpt = require('./wpt.js');6wpt._logSkipped("test skipped");7var wpt = require('./wpt.js');8wpt._logWarning("test warning");9var wpt = require('./wpt.js');10wpt._logInfo("test info");11var wpt = require('./wpt.js');12wpt._logDebug("test debug");13var wpt = require('./wpt.js');14wpt._logTrace("test trace");15var wpt = require('./wpt.js');16wpt._log("test log");17var wpt = require('./wpt.js');18wpt._logAssert("test assert");19var wpt = require('./wpt.js');20wpt._logError("test error");21var wpt = require('./wpt.js');22wpt._logFatal("test
Using AI Code Generation
1var wpt = require('wpt');2var wptInstance = new wpt('your_api_key');3wptInstance.runTest(url, function(err, data) {4 if (err) {5 wptInstance._logFailed(url, err, function(err, data) {6 if (err) {7 console.log('Error in logging failed test');8 }9 });10 }11});
Using AI Code Generation
1var wptHelper = require("./wptHelper.js");2var wptHelper = new wptHelper();3wptHelper._logFailed("test failed");4var wptHelper = function() {5 this._logFailed = function(msg) {6 console.log("Failed: " + msg);7 }8}9module.exports = wptHelper;10This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
Using AI Code Generation
1var wpt = require('./wpt.js');2var wptObj = new wpt();3wptObj._logFailed('test', 'test message');4var wpt = require('./wpt.js');5var wptObj = new wpt();6wptObj._logPassed('test', 'test message');7var wpt = require('./wpt.js');8var wptObj = new wpt();9wptObj._logInfo('test', 'test message');10var wpt = require('./wpt.js');11var wptObj = new wpt();12wptObj._logError('test', 'test message');13var wpt = require('./wpt.js');14var wptObj = new wpt();15wptObj._logDebug('test', 'test message');16var wpt = require('./wpt.js');
Using AI Code Generation
1var wpt = require('wpt');2var wptClient = new wpt('your key here');3wptClient._logFailed('test error message');4### _logFailed(message)5### _logSuccess(message)6### _log(message)7### _logError(message)8### _logWarning(message)9### _logInfo(message)10### _logDebug(message)11### _logTrace(message)12### _logVerbose(message)13### _logSilly(message)14### _logData(message)15### _logHttp(message)16### _logHttpError(message)17### _logHttpWarning(message)18### _logHttpInfo(message)19### _logHttpDebug(message)
Using AI Code Generation
1var wpt = require('./wpt.js');2wpt._logFailed('test', 'test');3var wpt = require('./wpt.js');4wpt._logPassed('test', 'test');5var wpt = require('./wpt.js');6wpt._logSkipped('test', 'test');7var wpt = require('./wpt.js');8wpt._logWarning('test', 'test', 'test');9var wpt = require('./wpt.js');10wpt._logInfo('test', 'test', 'test');
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!!