test-common.js 23 KB

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