Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.invariant = invariant;
  6. exports.parseSingleTestResult =
  7. exports.addErrorToEachTestUnderDescribe =
  8. exports.getTestID =
  9. exports.makeSingleTestResult =
  10. exports.makeRunResult =
  11. exports.getTestDuration =
  12. exports.callAsyncCircusFn =
  13. exports.describeBlockHasTests =
  14. exports.getEachHooksForTest =
  15. exports.getAllHooksForDescribe =
  16. exports.makeTest =
  17. exports.makeDescribe =
  18. void 0;
  19. var path = _interopRequireWildcard(require('path'));
  20. var _co = _interopRequireDefault(require('co'));
  21. var _dedent = _interopRequireDefault(require('dedent'));
  22. var _isGeneratorFn = _interopRequireDefault(require('is-generator-fn'));
  23. var _slash = _interopRequireDefault(require('slash'));
  24. var _stackUtils = _interopRequireDefault(require('stack-utils'));
  25. var _jestUtil = require('jest-util');
  26. var _prettyFormat = require('pretty-format');
  27. var _state = require('./state');
  28. function _interopRequireDefault(obj) {
  29. return obj && obj.__esModule ? obj : {default: obj};
  30. }
  31. function _getRequireWildcardCache(nodeInterop) {
  32. if (typeof WeakMap !== 'function') return null;
  33. var cacheBabelInterop = new WeakMap();
  34. var cacheNodeInterop = new WeakMap();
  35. return (_getRequireWildcardCache = function (nodeInterop) {
  36. return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
  37. })(nodeInterop);
  38. }
  39. function _interopRequireWildcard(obj, nodeInterop) {
  40. if (!nodeInterop && obj && obj.__esModule) {
  41. return obj;
  42. }
  43. if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
  44. return {default: obj};
  45. }
  46. var cache = _getRequireWildcardCache(nodeInterop);
  47. if (cache && cache.has(obj)) {
  48. return cache.get(obj);
  49. }
  50. var newObj = {};
  51. var hasPropertyDescriptor =
  52. Object.defineProperty && Object.getOwnPropertyDescriptor;
  53. for (var key in obj) {
  54. if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
  55. var desc = hasPropertyDescriptor
  56. ? Object.getOwnPropertyDescriptor(obj, key)
  57. : null;
  58. if (desc && (desc.get || desc.set)) {
  59. Object.defineProperty(newObj, key, desc);
  60. } else {
  61. newObj[key] = obj[key];
  62. }
  63. }
  64. }
  65. newObj.default = obj;
  66. if (cache) {
  67. cache.set(obj, newObj);
  68. }
  69. return newObj;
  70. }
  71. var global = (function () {
  72. if (typeof globalThis !== 'undefined') {
  73. return globalThis;
  74. } else if (typeof global !== 'undefined') {
  75. return global;
  76. } else if (typeof self !== 'undefined') {
  77. return self;
  78. } else if (typeof window !== 'undefined') {
  79. return window;
  80. } else {
  81. return Function('return this')();
  82. }
  83. })();
  84. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  85. var global = (function () {
  86. if (typeof globalThis !== 'undefined') {
  87. return globalThis;
  88. } else if (typeof global !== 'undefined') {
  89. return global;
  90. } else if (typeof self !== 'undefined') {
  91. return self;
  92. } else if (typeof window !== 'undefined') {
  93. return window;
  94. } else {
  95. return Function('return this')();
  96. }
  97. })();
  98. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  99. var global = (function () {
  100. if (typeof globalThis !== 'undefined') {
  101. return globalThis;
  102. } else if (typeof global !== 'undefined') {
  103. return global;
  104. } else if (typeof self !== 'undefined') {
  105. return self;
  106. } else if (typeof window !== 'undefined') {
  107. return window;
  108. } else {
  109. return Function('return this')();
  110. }
  111. })();
  112. var jestNow = global[Symbol.for('jest-native-now')] || global.Date.now;
  113. var global = (function () {
  114. if (typeof globalThis !== 'undefined') {
  115. return globalThis;
  116. } else if (typeof global !== 'undefined') {
  117. return global;
  118. } else if (typeof self !== 'undefined') {
  119. return self;
  120. } else if (typeof window !== 'undefined') {
  121. return window;
  122. } else {
  123. return Function('return this')();
  124. }
  125. })();
  126. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  127. var global = (function () {
  128. if (typeof globalThis !== 'undefined') {
  129. return globalThis;
  130. } else if (typeof global !== 'undefined') {
  131. return global;
  132. } else if (typeof self !== 'undefined') {
  133. return self;
  134. } else if (typeof window !== 'undefined') {
  135. return window;
  136. } else {
  137. return Function('return this')();
  138. }
  139. })();
  140. var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
  141. const stackUtils = new _stackUtils.default({
  142. cwd: 'A path that does not exist'
  143. });
  144. const jestEachBuildDir = (0, _slash.default)(
  145. path.dirname(require.resolve('jest-each'))
  146. );
  147. function takesDoneCallback(fn) {
  148. return fn.length > 0;
  149. }
  150. function isGeneratorFunction(fn) {
  151. return (0, _isGeneratorFn.default)(fn);
  152. }
  153. const makeDescribe = (name, parent, mode) => {
  154. let _mode = mode;
  155. if (parent && !mode) {
  156. // If not set explicitly, inherit from the parent describe.
  157. _mode = parent.mode;
  158. }
  159. return {
  160. type: 'describeBlock',
  161. // eslint-disable-next-line sort-keys
  162. children: [],
  163. hooks: [],
  164. mode: _mode,
  165. name: (0, _jestUtil.convertDescriptorToString)(name),
  166. parent,
  167. tests: []
  168. };
  169. };
  170. exports.makeDescribe = makeDescribe;
  171. const makeTest = (fn, mode, name, parent, timeout, asyncError) => ({
  172. type: 'test',
  173. // eslint-disable-next-line sort-keys
  174. asyncError,
  175. duration: null,
  176. errors: [],
  177. fn,
  178. invocations: 0,
  179. mode,
  180. name: (0, _jestUtil.convertDescriptorToString)(name),
  181. parent,
  182. seenDone: false,
  183. startedAt: null,
  184. status: null,
  185. timeout
  186. }); // Traverse the tree of describe blocks and return true if at least one describe
  187. // block has an enabled test.
  188. exports.makeTest = makeTest;
  189. const hasEnabledTest = describeBlock => {
  190. const {hasFocusedTests, testNamePattern} = (0, _state.getState)();
  191. return describeBlock.children.some(child =>
  192. child.type === 'describeBlock'
  193. ? hasEnabledTest(child)
  194. : !(
  195. child.mode === 'skip' ||
  196. (hasFocusedTests && child.mode !== 'only') ||
  197. (testNamePattern && !testNamePattern.test(getTestID(child)))
  198. )
  199. );
  200. };
  201. const getAllHooksForDescribe = describe => {
  202. const result = {
  203. afterAll: [],
  204. beforeAll: []
  205. };
  206. if (hasEnabledTest(describe)) {
  207. for (const hook of describe.hooks) {
  208. switch (hook.type) {
  209. case 'beforeAll':
  210. result.beforeAll.push(hook);
  211. break;
  212. case 'afterAll':
  213. result.afterAll.push(hook);
  214. break;
  215. }
  216. }
  217. }
  218. return result;
  219. };
  220. exports.getAllHooksForDescribe = getAllHooksForDescribe;
  221. const getEachHooksForTest = test => {
  222. const result = {
  223. afterEach: [],
  224. beforeEach: []
  225. };
  226. let block = test.parent;
  227. do {
  228. const beforeEachForCurrentBlock = []; // TODO: inline after https://github.com/microsoft/TypeScript/pull/34840 is released
  229. let hook;
  230. for (hook of block.hooks) {
  231. switch (hook.type) {
  232. case 'beforeEach':
  233. beforeEachForCurrentBlock.push(hook);
  234. break;
  235. case 'afterEach':
  236. result.afterEach.push(hook);
  237. break;
  238. }
  239. } // 'beforeEach' hooks are executed from top to bottom, the opposite of the
  240. // way we traversed it.
  241. result.beforeEach = [...beforeEachForCurrentBlock, ...result.beforeEach];
  242. } while ((block = block.parent));
  243. return result;
  244. };
  245. exports.getEachHooksForTest = getEachHooksForTest;
  246. const describeBlockHasTests = describe =>
  247. describe.children.some(
  248. child => child.type === 'test' || describeBlockHasTests(child)
  249. );
  250. exports.describeBlockHasTests = describeBlockHasTests;
  251. const _makeTimeoutMessage = (timeout, isHook) =>
  252. `Exceeded timeout of ${(0, _jestUtil.formatTime)(timeout)} for a ${
  253. isHook ? 'hook' : 'test'
  254. }.\nUse jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.`; // Global values can be overwritten by mocks or tests. We'll capture
  255. // the original values in the variables before we require any files.
  256. const {setTimeout, clearTimeout} = global;
  257. function checkIsError(error) {
  258. return !!(error && error.message && error.stack);
  259. }
  260. const callAsyncCircusFn = (testOrHook, testContext, {isHook, timeout}) => {
  261. let timeoutID;
  262. let completed = false;
  263. const {fn, asyncError} = testOrHook;
  264. return new Promise((resolve, reject) => {
  265. timeoutID = setTimeout(
  266. () => reject(_makeTimeoutMessage(timeout, isHook)),
  267. timeout
  268. ); // If this fn accepts `done` callback we return a promise that fulfills as
  269. // soon as `done` called.
  270. if (takesDoneCallback(fn)) {
  271. let returnedValue = undefined;
  272. const done = reason => {
  273. // We need to keep a stack here before the promise tick
  274. const errorAtDone = new _jestUtil.ErrorWithStack(undefined, done);
  275. if (!completed && testOrHook.seenDone) {
  276. errorAtDone.message =
  277. 'Expected done to be called once, but it was called multiple times.';
  278. if (reason) {
  279. errorAtDone.message +=
  280. ' Reason: ' +
  281. (0, _prettyFormat.format)(reason, {
  282. maxDepth: 3
  283. });
  284. }
  285. reject(errorAtDone);
  286. throw errorAtDone;
  287. } else {
  288. testOrHook.seenDone = true;
  289. } // Use `Promise.resolve` to allow the event loop to go a single tick in case `done` is called synchronously
  290. Promise.resolve().then(() => {
  291. if (returnedValue !== undefined) {
  292. asyncError.message = (0, _dedent.default)`
  293. Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise.
  294. Returned value: ${(0, _prettyFormat.format)(returnedValue, {
  295. maxDepth: 3
  296. })}
  297. `;
  298. return reject(asyncError);
  299. }
  300. let errorAsErrorObject;
  301. if (checkIsError(reason)) {
  302. errorAsErrorObject = reason;
  303. } else {
  304. errorAsErrorObject = errorAtDone;
  305. errorAtDone.message = `Failed: ${(0, _prettyFormat.format)(reason, {
  306. maxDepth: 3
  307. })}`;
  308. } // Consider always throwing, regardless if `reason` is set or not
  309. if (completed && reason) {
  310. errorAsErrorObject.message =
  311. 'Caught error after test environment was torn down\n\n' +
  312. errorAsErrorObject.message;
  313. throw errorAsErrorObject;
  314. }
  315. return reason ? reject(errorAsErrorObject) : resolve();
  316. });
  317. };
  318. returnedValue = fn.call(testContext, done);
  319. return;
  320. }
  321. let returnedValue;
  322. if (isGeneratorFunction(fn)) {
  323. returnedValue = _co.default.wrap(fn).call({});
  324. } else {
  325. try {
  326. returnedValue = fn.call(testContext);
  327. } catch (error) {
  328. reject(error);
  329. return;
  330. }
  331. } // If it's a Promise, return it. Test for an object with a `then` function
  332. // to support custom Promise implementations.
  333. if (
  334. typeof returnedValue === 'object' &&
  335. returnedValue !== null &&
  336. typeof returnedValue.then === 'function'
  337. ) {
  338. returnedValue.then(() => resolve(), reject);
  339. return;
  340. }
  341. if (!isHook && returnedValue !== undefined) {
  342. reject(
  343. new Error((0, _dedent.default)`
  344. test functions can only return Promise or undefined.
  345. Returned value: ${(0, _prettyFormat.format)(returnedValue, {
  346. maxDepth: 3
  347. })}
  348. `)
  349. );
  350. return;
  351. } // Otherwise this test is synchronous, and if it didn't throw it means
  352. // it passed.
  353. resolve();
  354. })
  355. .then(() => {
  356. var _timeoutID$unref, _timeoutID;
  357. completed = true; // If timeout is not cleared/unrefed the node process won't exit until
  358. // it's resolved.
  359. (_timeoutID$unref = (_timeoutID = timeoutID).unref) === null ||
  360. _timeoutID$unref === void 0
  361. ? void 0
  362. : _timeoutID$unref.call(_timeoutID);
  363. clearTimeout(timeoutID);
  364. })
  365. .catch(error => {
  366. var _timeoutID$unref2, _timeoutID2;
  367. completed = true;
  368. (_timeoutID$unref2 = (_timeoutID2 = timeoutID).unref) === null ||
  369. _timeoutID$unref2 === void 0
  370. ? void 0
  371. : _timeoutID$unref2.call(_timeoutID2);
  372. clearTimeout(timeoutID);
  373. throw error;
  374. });
  375. };
  376. exports.callAsyncCircusFn = callAsyncCircusFn;
  377. const getTestDuration = test => {
  378. const {startedAt} = test;
  379. return typeof startedAt === 'number' ? jestNow() - startedAt : null;
  380. };
  381. exports.getTestDuration = getTestDuration;
  382. const makeRunResult = (describeBlock, unhandledErrors) => ({
  383. testResults: makeTestResults(describeBlock),
  384. unhandledErrors: unhandledErrors.map(_getError).map(getErrorStack)
  385. });
  386. exports.makeRunResult = makeRunResult;
  387. const makeSingleTestResult = test => {
  388. const {includeTestLocationInResult} = (0, _state.getState)();
  389. const testPath = [];
  390. let parent = test;
  391. const {status} = test;
  392. invariant(status, 'Status should be present after tests are run.');
  393. do {
  394. testPath.unshift(parent.name);
  395. } while ((parent = parent.parent));
  396. let location = null;
  397. if (includeTestLocationInResult) {
  398. var _parsedLine, _parsedLine$file;
  399. const stackLines = test.asyncError.stack.split('\n');
  400. const stackLine = stackLines[1];
  401. let parsedLine = stackUtils.parseLine(stackLine);
  402. if (
  403. (_parsedLine = parsedLine) !== null &&
  404. _parsedLine !== void 0 &&
  405. (_parsedLine$file = _parsedLine.file) !== null &&
  406. _parsedLine$file !== void 0 &&
  407. _parsedLine$file.startsWith(jestEachBuildDir)
  408. ) {
  409. const stackLine = stackLines[4];
  410. parsedLine = stackUtils.parseLine(stackLine);
  411. }
  412. if (
  413. parsedLine &&
  414. typeof parsedLine.column === 'number' &&
  415. typeof parsedLine.line === 'number'
  416. ) {
  417. location = {
  418. column: parsedLine.column,
  419. line: parsedLine.line
  420. };
  421. }
  422. }
  423. const errorsDetailed = test.errors.map(_getError);
  424. return {
  425. duration: test.duration,
  426. errors: errorsDetailed.map(getErrorStack),
  427. errorsDetailed,
  428. invocations: test.invocations,
  429. location,
  430. status,
  431. testPath: Array.from(testPath)
  432. };
  433. };
  434. exports.makeSingleTestResult = makeSingleTestResult;
  435. const makeTestResults = describeBlock => {
  436. const testResults = [];
  437. for (const child of describeBlock.children) {
  438. switch (child.type) {
  439. case 'describeBlock': {
  440. testResults.push(...makeTestResults(child));
  441. break;
  442. }
  443. case 'test': {
  444. testResults.push(makeSingleTestResult(child));
  445. break;
  446. }
  447. }
  448. }
  449. return testResults;
  450. }; // Return a string that identifies the test (concat of parent describe block
  451. // names + test title)
  452. const getTestID = test => {
  453. const titles = [];
  454. let parent = test;
  455. do {
  456. titles.unshift(parent.name);
  457. } while ((parent = parent.parent));
  458. titles.shift(); // remove TOP_DESCRIBE_BLOCK_NAME
  459. return titles.join(' ');
  460. };
  461. exports.getTestID = getTestID;
  462. const _getError = errors => {
  463. let error;
  464. let asyncError;
  465. if (Array.isArray(errors)) {
  466. error = errors[0];
  467. asyncError = errors[1];
  468. } else {
  469. error = errors;
  470. asyncError = new Error();
  471. }
  472. if (error && (typeof error.stack === 'string' || error.message)) {
  473. return error;
  474. }
  475. asyncError.message = `thrown: ${(0, _prettyFormat.format)(error, {
  476. maxDepth: 3
  477. })}`;
  478. return asyncError;
  479. };
  480. const getErrorStack = error =>
  481. typeof error.stack === 'string' ? error.stack : error.message;
  482. const addErrorToEachTestUnderDescribe = (describeBlock, error, asyncError) => {
  483. for (const child of describeBlock.children) {
  484. switch (child.type) {
  485. case 'describeBlock':
  486. addErrorToEachTestUnderDescribe(child, error, asyncError);
  487. break;
  488. case 'test':
  489. child.errors.push([error, asyncError]);
  490. break;
  491. }
  492. }
  493. };
  494. exports.addErrorToEachTestUnderDescribe = addErrorToEachTestUnderDescribe;
  495. function invariant(condition, message) {
  496. if (!condition) {
  497. throw new Error(message);
  498. }
  499. }
  500. const parseSingleTestResult = testResult => {
  501. let status;
  502. if (testResult.status === 'skip') {
  503. status = 'pending';
  504. } else if (testResult.status === 'todo') {
  505. status = 'todo';
  506. } else if (testResult.errors.length > 0) {
  507. status = 'failed';
  508. } else {
  509. status = 'passed';
  510. }
  511. const ancestorTitles = testResult.testPath.filter(
  512. name => name !== _state.ROOT_DESCRIBE_BLOCK_NAME
  513. );
  514. const title = ancestorTitles.pop();
  515. return {
  516. ancestorTitles,
  517. duration: testResult.duration,
  518. failureDetails: testResult.errorsDetailed,
  519. failureMessages: Array.from(testResult.errors),
  520. fullName: title
  521. ? ancestorTitles.concat(title).join(' ')
  522. : ancestorTitles.join(' '),
  523. invocations: testResult.invocations,
  524. location: testResult.location,
  525. numPassingAsserts: 0,
  526. status,
  527. title: testResult.testPath[testResult.testPath.length - 1]
  528. };
  529. };
  530. exports.parseSingleTestResult = parseSingleTestResult;