test-common.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. var describe;
  2. var test;
  3. var expect;
  4. var withinSameSecond;
  5. // Stores the results of each test and suite. Has a terrible
  6. // name to avoid name collision.
  7. var __TestResults__ = {};
  8. // So test names like "toString" don't automatically produce an error
  9. Object.setPrototypeOf(__TestResults__, null);
  10. // This array is used to communicate with the C++ program. It treats
  11. // each message in this array as a separate message. Has a terrible
  12. // name to avoid name collision.
  13. var __UserOutput__ = [];
  14. // We also rebind console.log here to use the array above
  15. console.log = (...args) => {
  16. __UserOutput__.push(args.join(" "));
  17. };
  18. class ExpectationError extends Error {
  19. constructor(message) {
  20. super(message);
  21. this.name = "ExpectationError";
  22. }
  23. }
  24. // Use an IIFE to avoid polluting the global namespace as much as possible
  25. (() => {
  26. const deepEquals = (a, b) => {
  27. if (Object.is(a, b)) return true; // Handles identical references and primitives
  28. if ((a !== null && b === null) || (a === null && b !== null)) return false;
  29. if (Array.isArray(a)) return Array.isArray(b) && deepArrayEquals(a, b);
  30. if (typeof a === "object") return typeof b === "object" && deepObjectEquals(a, b);
  31. };
  32. const deepArrayEquals = (a, b) => {
  33. if (a.length !== b.length) return false;
  34. for (let i = 0; i < a.length; ++i) {
  35. if (!deepEquals(a[i], b[i])) return false;
  36. }
  37. return true;
  38. };
  39. const deepObjectEquals = (a, b) => {
  40. const keysA = Reflect.ownKeys(a);
  41. const keysB = Reflect.ownKeys(b);
  42. if (keysA.length !== keysB.length) return false;
  43. for (let key of keysA) {
  44. if (!deepEquals(a[key], b[key])) return false;
  45. }
  46. return true;
  47. };
  48. const valueToString = value => {
  49. try {
  50. if (value === 0 && 1 / value < 0) {
  51. return "-0";
  52. }
  53. return String(value);
  54. } catch {
  55. // e.g for objects without a prototype, the above throws.
  56. return Object.prototype.toString.call(value);
  57. }
  58. };
  59. class Expector {
  60. constructor(target, inverted) {
  61. this.target = target;
  62. this.inverted = !!inverted;
  63. }
  64. get not() {
  65. return new Expector(this.target, !this.inverted);
  66. }
  67. toBe(value) {
  68. this.__doMatcher(() => {
  69. this.__expect(
  70. Object.is(this.target, value),
  71. () =>
  72. `toBe: expected _${valueToString(value)}_, got _${valueToString(
  73. this.target
  74. )}_`
  75. );
  76. });
  77. }
  78. toBeCloseTo(value, precision = 5) {
  79. this.__expect(
  80. typeof this.target === "number",
  81. () => `toBeCloseTo: expected target of type number, got ${typeof this.target}`
  82. );
  83. this.__expect(
  84. typeof value === "number",
  85. () => `toBeCloseTo: expected argument of type number, got ${typeof value}`
  86. );
  87. this.__expect(
  88. typeof precision === "number",
  89. () => `toBeCloseTo: expected precision of type number, got ${typeof precision}`
  90. );
  91. const epsilon = 10 ** -precision / 2;
  92. this.__doMatcher(() => {
  93. this.__expect(Math.abs(this.target - value) < epsilon);
  94. });
  95. }
  96. toHaveLength(length) {
  97. this.__expect(
  98. typeof this.target.length === "number",
  99. () => "toHaveLength: target.length not of type number"
  100. );
  101. this.__doMatcher(() => {
  102. this.__expect(Object.is(this.target.length, length));
  103. });
  104. }
  105. toHaveSize(size) {
  106. this.__expect(
  107. typeof this.target.size === "number",
  108. () => "toHaveSize: target.size not of type number"
  109. );
  110. this.__doMatcher(() => {
  111. this.__expect(Object.is(this.target.size, size));
  112. });
  113. }
  114. toHaveProperty(property, value) {
  115. this.__doMatcher(() => {
  116. let object = this.target;
  117. if (typeof property === "string" && property.includes(".")) {
  118. let propertyArray = [];
  119. while (property.includes(".")) {
  120. let index = property.indexOf(".");
  121. propertyArray.push(property.substring(0, index));
  122. if (index + 1 >= property.length) break;
  123. property = property.substring(index + 1, property.length);
  124. }
  125. propertyArray.push(property);
  126. property = propertyArray;
  127. }
  128. if (Array.isArray(property)) {
  129. for (let key of property) {
  130. this.__expect(
  131. object !== undefined && object !== null,
  132. "got undefined or null as array key"
  133. );
  134. object = object[key];
  135. }
  136. } else {
  137. object = object[property];
  138. }
  139. this.__expect(object !== undefined, "should not be undefined");
  140. if (value !== undefined)
  141. this.__expect(
  142. deepEquals(object, value),
  143. `value does not equal property ${valueToString(object)} vs ${valueToString(
  144. value
  145. )}`
  146. );
  147. });
  148. }
  149. toBeDefined() {
  150. this.__doMatcher(() => {
  151. this.__expect(
  152. this.target !== undefined,
  153. () => "toBeDefined: expected target to be defined, got undefined"
  154. );
  155. });
  156. }
  157. toBeInstanceOf(class_) {
  158. this.__doMatcher(() => {
  159. this.__expect(
  160. this.target instanceof class_,
  161. `Expected ${valueToString(this.target)} to be instance of ${class_.name}`
  162. );
  163. });
  164. }
  165. toBeNull() {
  166. this.__doMatcher(() => {
  167. this.__expect(
  168. this.target === null,
  169. `Expected target to be null got ${valueToString(this.target)}`
  170. );
  171. });
  172. }
  173. toBeUndefined() {
  174. this.__doMatcher(() => {
  175. this.__expect(
  176. this.target === undefined,
  177. () =>
  178. `toBeUndefined: expected target to be undefined, got _${valueToString(
  179. this.target
  180. )}_`
  181. );
  182. });
  183. }
  184. toBeNaN() {
  185. this.__doMatcher(() => {
  186. this.__expect(
  187. isNaN(this.target),
  188. () => `toBeNaN: expected target to be NaN, got _${valueToString(this.target)}_`
  189. );
  190. });
  191. }
  192. toBeTrue(customDetails = undefined) {
  193. this.__doMatcher(() => {
  194. this.__expect(
  195. this.target === true,
  196. () =>
  197. `toBeTrue: expected target to be true, got _${valueToString(this.target)}_${
  198. customDetails ? ` (${customDetails})` : ""
  199. }`
  200. );
  201. });
  202. }
  203. toBeFalse(customDetails = undefined) {
  204. this.__doMatcher(() => {
  205. this.__expect(
  206. this.target === false,
  207. () =>
  208. `toBeFalse: expected target to be false, got _${valueToString(
  209. this.target
  210. )}_${customDetails ?? ""}`
  211. );
  212. });
  213. }
  214. __validateNumericComparisonTypes(value) {
  215. this.__expect(typeof this.target === "number" || typeof this.target === "bigint");
  216. this.__expect(typeof value === "number" || typeof value === "bigint");
  217. this.__expect(typeof this.target === typeof value);
  218. }
  219. toBeLessThan(value) {
  220. this.__validateNumericComparisonTypes(value);
  221. this.__doMatcher(() => {
  222. this.__expect(this.target < value);
  223. });
  224. }
  225. toBeLessThanOrEqual(value) {
  226. this.__validateNumericComparisonTypes(value);
  227. this.__doMatcher(() => {
  228. this.__expect(this.target <= value);
  229. });
  230. }
  231. toBeGreaterThan(value) {
  232. this.__validateNumericComparisonTypes(value);
  233. this.__doMatcher(() => {
  234. this.__expect(this.target > value);
  235. });
  236. }
  237. toBeGreaterThanOrEqual(value) {
  238. this.__validateNumericComparisonTypes(value);
  239. this.__doMatcher(() => {
  240. this.__expect(this.target >= value);
  241. });
  242. }
  243. toContain(item) {
  244. this.__doMatcher(() => {
  245. for (let element of this.target) {
  246. if (item === element) return;
  247. }
  248. throw new ExpectationError();
  249. });
  250. }
  251. toContainEqual(item) {
  252. this.__doMatcher(() => {
  253. for (let element of this.target) {
  254. if (deepEquals(item, element)) return;
  255. }
  256. throw new ExpectationError();
  257. });
  258. }
  259. toEqual(value) {
  260. this.__doMatcher(() => {
  261. this.__expect(
  262. deepEquals(this.target, value),
  263. () =>
  264. `Expected _${valueToString(value)}_, but got _${valueToString(
  265. this.target
  266. )}_`
  267. );
  268. });
  269. }
  270. toThrow(value) {
  271. this.__expect(typeof this.target === "function");
  272. this.__expect(
  273. typeof value === "string" ||
  274. typeof value === "function" ||
  275. typeof value === "object" ||
  276. value === undefined
  277. );
  278. this.__doMatcher(() => {
  279. let threw = true;
  280. try {
  281. this.target();
  282. threw = false;
  283. } catch (e) {
  284. if (typeof value === "string") {
  285. this.__expect(
  286. e.message.includes(value),
  287. `Expected ${this.target.toString()} to throw and message to include "${value}" but message "${
  288. e.message
  289. }" did not contain it`
  290. );
  291. } else if (typeof value === "function") {
  292. this.__expect(
  293. e instanceof value,
  294. `Expected ${this.target.toString()} to throw and be of type ${value} but it threw ${e}`
  295. );
  296. } else if (typeof value === "object") {
  297. this.__expect(
  298. e.message === value.message,
  299. `Expected ${this.target.toString()} to throw and message to be ${value} but it threw with message ${
  300. e.message
  301. }`
  302. );
  303. }
  304. }
  305. this.__expect(
  306. threw,
  307. `Expected ${this.target.toString()} to throw but it didn't throw anything`
  308. );
  309. });
  310. }
  311. pass(message) {
  312. // FIXME: This does nothing. If we want to implement things
  313. // like assertion count, this will have to do something
  314. }
  315. // jest-extended
  316. fail(message) {
  317. this.__doMatcher(() => {
  318. this.__expect(false, message);
  319. });
  320. }
  321. // jest-extended
  322. toThrowWithMessage(class_, message) {
  323. this.__expect(typeof this.target === "function");
  324. this.__expect(class_ !== undefined);
  325. this.__expect(message !== undefined);
  326. this.__doMatcher(() => {
  327. try {
  328. this.target();
  329. this.__expect(false, () => "toThrowWithMessage: target function did not throw");
  330. } catch (e) {
  331. this.__expect(
  332. e instanceof class_,
  333. () =>
  334. `toThrowWithMessage: expected error to be instance of ${valueToString(
  335. class_.name
  336. )}, got ${valueToString(e.name)}`
  337. );
  338. this.__expect(
  339. e.message.includes(message),
  340. () =>
  341. `toThrowWithMessage: expected error message to include _${valueToString(
  342. message
  343. )}_, got _${valueToString(e.message)}_`
  344. );
  345. }
  346. });
  347. }
  348. // Test for syntax errors; target must be a string
  349. toEval() {
  350. this.__expect(typeof this.target === "string");
  351. const success = canParseSource(this.target);
  352. this.__expect(
  353. this.inverted ? !success : success,
  354. () =>
  355. `Expected _${valueToString(this.target)}_ ` +
  356. (this.inverted ? "not to eval but it did" : "to eval but it didn't")
  357. );
  358. }
  359. // Must compile regardless of inverted-ness
  360. toEvalTo(value) {
  361. this.__expect(typeof this.target === "string");
  362. let result;
  363. try {
  364. result = eval(this.target);
  365. } catch (e) {
  366. throw new ExpectationError(
  367. `Expected _${valueToString(this.target)}_ to eval but it failed with ${e}`
  368. );
  369. }
  370. this.__doMatcher(() => {
  371. this.__expect(
  372. deepEquals(value, result),
  373. () =>
  374. `Expected _${valueToString(this.target)}_ to eval to ` +
  375. `_${valueToString(value)}_ but got _${valueToString(result)}_`
  376. );
  377. });
  378. }
  379. toHaveConfigurableProperty(property) {
  380. this.__expect(this.target !== undefined && this.target !== null);
  381. let d = Object.getOwnPropertyDescriptor(this.target, property);
  382. this.__expect(d !== undefined);
  383. this.__doMatcher(() => {
  384. this.__expect(d.configurable);
  385. });
  386. }
  387. toHaveEnumerableProperty(property) {
  388. this.__expect(this.target !== undefined && this.target !== null);
  389. let d = Object.getOwnPropertyDescriptor(this.target, property);
  390. this.__expect(d !== undefined);
  391. this.__doMatcher(() => {
  392. this.__expect(d.enumerable);
  393. });
  394. }
  395. toHaveWritableProperty(property) {
  396. this.__expect(this.target !== undefined && this.target !== null);
  397. let d = Object.getOwnPropertyDescriptor(this.target, property);
  398. this.__expect(d !== undefined);
  399. this.__doMatcher(() => {
  400. this.__expect(d.writable);
  401. });
  402. }
  403. toHaveValueProperty(property, value) {
  404. this.__expect(this.target !== undefined && this.target !== null);
  405. let d = Object.getOwnPropertyDescriptor(this.target, property);
  406. this.__expect(d !== undefined);
  407. this.__doMatcher(() => {
  408. this.__expect(d.value !== undefined);
  409. if (value !== undefined) this.__expect(deepEquals(value, d.value));
  410. });
  411. }
  412. toHaveGetterProperty(property) {
  413. this.__expect(this.target !== undefined && this.target !== null);
  414. let d = Object.getOwnPropertyDescriptor(this.target, property);
  415. this.__expect(d !== undefined);
  416. this.__doMatcher(() => {
  417. this.__expect(d.get !== undefined);
  418. });
  419. }
  420. toHaveSetterProperty(property) {
  421. this.__expect(this.target !== undefined && this.target !== null);
  422. let d = Object.getOwnPropertyDescriptor(this.target, property);
  423. this.__expect(d !== undefined);
  424. this.__doMatcher(() => {
  425. this.__expect(d.set !== undefined);
  426. });
  427. }
  428. toBeIteratorResultWithValue(value) {
  429. this.__expect(this.target !== undefined && this.target !== null);
  430. this.__doMatcher(() => {
  431. this.__expect(
  432. this.target.done === false,
  433. () =>
  434. `toGiveIteratorResultWithValue: expected 'done' to be _false_ got ${valueToString(
  435. this.target.done
  436. )}`
  437. );
  438. this.__expect(
  439. deepEquals(value, this.target.value),
  440. () =>
  441. `toGiveIteratorResultWithValue: expected 'value' to be _${valueToString(
  442. value
  443. )}_ got ${valueToString(this.target.value)}`
  444. );
  445. });
  446. }
  447. toBeIteratorResultDone() {
  448. this.__expect(this.target !== undefined && this.target !== null);
  449. this.__doMatcher(() => {
  450. this.__expect(
  451. this.target.done === true,
  452. () =>
  453. `toGiveIteratorResultDone: expected 'done' to be _true_ got ${valueToString(
  454. this.target.done
  455. )}`
  456. );
  457. this.__expect(
  458. this.target.value === undefined,
  459. () =>
  460. `toGiveIteratorResultDone: expected 'value' to be _undefined_ got ${valueToString(
  461. this.target.value
  462. )}`
  463. );
  464. });
  465. }
  466. __doMatcher(matcher) {
  467. if (!this.inverted) {
  468. matcher();
  469. } else {
  470. let threw = false;
  471. try {
  472. matcher();
  473. } catch (e) {
  474. if (e.name === "ExpectationError") threw = true;
  475. }
  476. if (!threw) throw new ExpectationError("not: test didn't fail");
  477. }
  478. }
  479. __expect(value, details) {
  480. if (value !== true) {
  481. if (details !== undefined) {
  482. if (details instanceof Function) throw new ExpectationError(details());
  483. else throw new ExpectationError(details);
  484. } else {
  485. throw new ExpectationError();
  486. }
  487. }
  488. }
  489. }
  490. expect = value => new Expector(value);
  491. // describe is able to lump test results inside of it by using this context
  492. // variable. Top level tests have the default suite message
  493. const defaultSuiteMessage = "__$$TOP_LEVEL$$__";
  494. let suiteMessage = defaultSuiteMessage;
  495. describe = (message, callback) => {
  496. suiteMessage = message;
  497. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  498. try {
  499. callback();
  500. } catch (e) {
  501. __TestResults__[suiteMessage][defaultSuiteMessage] = {
  502. result: "fail",
  503. details: String(e),
  504. duration: 0,
  505. };
  506. }
  507. suiteMessage = defaultSuiteMessage;
  508. };
  509. test = (message, callback) => {
  510. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  511. const suite = __TestResults__[suiteMessage];
  512. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  513. suite[message] = {
  514. result: "fail",
  515. details: "Another test with the same message did already run",
  516. duration: 0,
  517. };
  518. return;
  519. }
  520. const now = () => Temporal.Now.instant().epochNanoseconds;
  521. const start = now();
  522. const time_us = () => Number(BigInt.asIntN(53, (now() - start) / 1000n));
  523. try {
  524. callback();
  525. suite[message] = {
  526. result: "pass",
  527. duration: time_us(),
  528. };
  529. } catch (e) {
  530. suite[message] = {
  531. result: "fail",
  532. details: String(e),
  533. duration: time_us(),
  534. };
  535. }
  536. };
  537. test.skip = (message, callback) => {
  538. if (typeof callback !== "function")
  539. throw new Error("test.skip has invalid second argument (must be a function)");
  540. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  541. const suite = __TestResults__[suiteMessage];
  542. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  543. suite[message] = {
  544. result: "fail",
  545. details: "Another test with the same message did already run",
  546. duration: 0,
  547. };
  548. return;
  549. }
  550. suite[message] = {
  551. result: "skip",
  552. duration: 0,
  553. };
  554. };
  555. test.xfail = (message, callback) => {
  556. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  557. const suite = __TestResults__[suiteMessage];
  558. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  559. suite[message] = {
  560. result: "fail",
  561. details: "Another test with the same message did already run",
  562. duration: 0,
  563. };
  564. return;
  565. }
  566. const now = () => Temporal.Now.instant().epochNanoseconds;
  567. const start = now();
  568. const time_us = () => Number(BigInt.asIntN(53, (now() - start) / 1000n));
  569. try {
  570. callback();
  571. suite[message] = {
  572. result: "fail",
  573. details: "Expected test to fail, but it passed",
  574. duration: time_us(),
  575. };
  576. } catch (e) {
  577. suite[message] = {
  578. result: "xfail",
  579. duration: time_us(),
  580. };
  581. }
  582. };
  583. test.xfailIf = (condition, message, callback) => {
  584. condition ? test.xfail(message, callback) : test(message, callback);
  585. };
  586. withinSameSecond = callback => {
  587. let callbackDuration;
  588. for (let tries = 0; tries < 5; tries++) {
  589. const start = Temporal.Now.instant();
  590. const result = callback();
  591. const end = Temporal.Now.instant();
  592. if (start.epochSeconds !== end.epochSeconds) {
  593. callbackDuration = start.until(end);
  594. continue;
  595. }
  596. return result;
  597. }
  598. throw new ExpectationError(
  599. `Tried to execute callback '${callback}' 5 times within the same second but ` +
  600. `failed. Make sure the callback does as little work as possible (the last run ` +
  601. `took ${callbackDuration.total(
  602. "milliseconds"
  603. )} ms) and the machine is not overloaded. If you see this ` +
  604. `error appearing in the CI it is most likely a flaky failure!`
  605. );
  606. };
  607. })();