utils.mjs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * Utils for test suite
  3. *
  4. * @author d98762625@gmail.com
  5. * @author tlwr [toby@toby.codes]
  6. * @author n1474335 [n1474335@gmail.com]
  7. * @copyright Crown Copyright 2018
  8. * @license Apache-2.0
  9. */
  10. // Define global environment functions
  11. global.ENVIRONMENT_IS_WORKER = function() {
  12. return typeof importScripts === "function";
  13. };
  14. global.ENVIRONMENT_IS_NODE = function() {
  15. return typeof process === "object" && typeof require === "function";
  16. };
  17. global.ENVIRONMENT_IS_WEB = function() {
  18. return typeof window === "object";
  19. };
  20. /**
  21. * Helper function to convert a status to an icon.
  22. *
  23. * @param {string} status
  24. * @returns {string}
  25. */
  26. const statusToIcon = function statusToIcon(status) {
  27. const icons = {
  28. erroring: "🔥",
  29. failing: "❌",
  30. passing: "✔️️",
  31. };
  32. return icons[status] || "?";
  33. };
  34. /**
  35. * Displays a given test result in the console.
  36. * Counts test statuses.
  37. *
  38. * @param {Object} testStatusCounts
  39. * @param {Object} testResult
  40. */
  41. function handleTestResult(testStatus, testResult) {
  42. testStatus.allTestsPassing = testStatus.allTestsPassing && testResult.status === "passing";
  43. const newCount = (testStatus.counts[testResult.status] || 0) + 1;
  44. testStatus.counts[testResult.status] = newCount;
  45. testStatus.counts.total += 1;
  46. console.log([
  47. statusToIcon(testResult.status),
  48. testResult.test.name
  49. ].join(" "));
  50. if (testResult.output) {
  51. console.log(
  52. testResult.output
  53. .trim()
  54. .replace(/^/, "\t")
  55. .replace(/\n/g, "\n\t")
  56. );
  57. }
  58. }
  59. /**
  60. * Log each test result, count tests and failures. Log test suite run duration.
  61. *
  62. * @param {Object} testStatus - object describing test run data
  63. * @param {Object[]} results - results from TestRegister
  64. */
  65. export function logTestReport(testStatus, results) {
  66. results.forEach(r => handleTestResult(testStatus, r));
  67. console.log("\n");
  68. for (const testStatusCount in testStatus.counts) {
  69. const count = testStatus.counts[testStatusCount];
  70. if (count > 0) {
  71. console.log(testStatusCount.toUpperCase(), count);
  72. }
  73. }
  74. process.exit(testStatus.allTestsPassing ? 0 : 1);
  75. }
  76. /**
  77. * Fail if the process takes longer than 60 seconds.
  78. */
  79. export function setLongTestFailure() {
  80. setTimeout(function() {
  81. console.log("Tests took longer than 60 seconds to run, returning.");
  82. process.exit(1);
  83. }, 60 * 1000);
  84. }