JavaScriptTestRunner.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  5. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #pragma once
  10. #include <AK/ByteBuffer.h>
  11. #include <AK/JsonObject.h>
  12. #include <AK/JsonValue.h>
  13. #include <AK/LexicalPath.h>
  14. #include <AK/QuickSort.h>
  15. #include <AK/Result.h>
  16. #include <AK/Tuple.h>
  17. #include <LibCore/ArgsParser.h>
  18. #include <LibCore/DirIterator.h>
  19. #include <LibCore/File.h>
  20. #include <LibJS/Interpreter.h>
  21. #include <LibJS/Lexer.h>
  22. #include <LibJS/Parser.h>
  23. #include <LibJS/Runtime/Array.h>
  24. #include <LibJS/Runtime/GlobalObject.h>
  25. #include <LibJS/Runtime/JSONObject.h>
  26. #include <LibJS/Runtime/TypedArray.h>
  27. #include <LibJS/Runtime/WeakSet.h>
  28. #include <LibTest/Results.h>
  29. #include <fcntl.h>
  30. #include <sys/time.h>
  31. #include <unistd.h>
  32. #define STRCAT(x, y) __STRCAT(x, y)
  33. #define STRSTRCAT(x, y) __STRSTRCAT(x, y)
  34. #define __STRCAT(x, y) x #y
  35. #define __STRSTRCAT(x, y) x y
  36. // Note: This is a little weird, so here's an explanation:
  37. // If the vararg isn't given, the tuple initializer will simply expand to `fn, ::Test::JS::__testjs_last<1>()`
  38. // and if it _is_ given (say as `A`), the tuple initializer will expand to `fn, ::Test::JS::__testjs_last<1, A>()`, which will end up being evaluated as `A`
  39. // and if multiple args are given, the static_assert will be sad.
  40. #define __TESTJS_REGISTER_GLOBAL_FUNCTION(name, fn, ...) \
  41. struct __TestJS_register_##fn { \
  42. static_assert( \
  43. ::Test::JS::__testjs_count(__VA_ARGS__) <= 1, \
  44. STRCAT(STRSTRCAT(STRCAT("Expected at most three arguments to TESTJS_GLOBAL_FUNCTION at line", __LINE__), ", in file "), __FILE__)); \
  45. __TestJS_register_##fn() noexcept \
  46. { \
  47. ::Test::JS::s_exposed_global_functions.set( \
  48. name, \
  49. { fn, ::Test::JS::__testjs_last<1, ##__VA_ARGS__>() }); \
  50. } \
  51. } __testjs_register_##fn {};
  52. #define TESTJS_GLOBAL_FUNCTION(function, exposed_name, ...) \
  53. JS_DECLARE_NATIVE_FUNCTION(function); \
  54. __TESTJS_REGISTER_GLOBAL_FUNCTION(#exposed_name, function, ##__VA_ARGS__); \
  55. JS_DEFINE_NATIVE_FUNCTION(function)
  56. #define TESTJS_MAIN_HOOK() \
  57. struct __TestJS_main_hook { \
  58. __TestJS_main_hook() \
  59. { \
  60. ::Test::JS::g_main_hook = hook; \
  61. } \
  62. static void hook(); \
  63. } __testjs_common_register_##name {}; \
  64. void __TestJS_main_hook::hook()
  65. #define TESTJS_PROGRAM_FLAG(flag, help_string, long_name, short_name) \
  66. bool flag { false }; \
  67. struct __TestJS_flag_hook_##flag { \
  68. __TestJS_flag_hook_##flag() \
  69. { \
  70. ::Test::JS::g_extra_args.set(&(flag), { help_string, long_name, short_name }); \
  71. }; \
  72. } __testjs_flag_hook_##flag;
  73. #define TEST_ROOT(path) \
  74. String Test::JS::g_test_root_fragment = path
  75. #define TESTJS_RUN_FILE_FUNCTION(...) \
  76. struct __TestJS_run_file { \
  77. __TestJS_run_file() \
  78. { \
  79. ::Test::JS::g_run_file = hook; \
  80. } \
  81. static ::Test::JS::IntermediateRunFileResult hook(const String&, JS::Interpreter&); \
  82. } __testjs_common_run_file {}; \
  83. ::Test::JS::IntermediateRunFileResult __TestJS_run_file::hook(__VA_ARGS__)
  84. namespace Test::JS {
  85. namespace JS = ::JS;
  86. template<typename... Args>
  87. static consteval size_t __testjs_count(Args...) { return sizeof...(Args); }
  88. template<auto... Values>
  89. static consteval size_t __testjs_last() { return (AK::Detail::IntegralConstant<size_t, Values> {}, ...).value; }
  90. static constexpr auto TOP_LEVEL_TEST_NAME = "__$$TOP_LEVEL$$__";
  91. extern RefPtr<JS::VM> g_vm;
  92. extern bool g_collect_on_every_allocation;
  93. extern String g_currently_running_test;
  94. extern String g_test_glob;
  95. struct FunctionWithLength {
  96. JS::Value (*function)(JS::VM&, JS::GlobalObject&);
  97. size_t length { 0 };
  98. };
  99. extern HashMap<String, FunctionWithLength> s_exposed_global_functions;
  100. extern String g_test_root_fragment;
  101. extern String g_test_root;
  102. extern int g_test_argc;
  103. extern char** g_test_argv;
  104. extern Function<void()> g_main_hook;
  105. extern HashMap<bool*, Tuple<String, String, char>> g_extra_args;
  106. struct ParserError {
  107. JS::Parser::Error error;
  108. String hint;
  109. };
  110. struct JSFileResult {
  111. String name;
  112. Optional<ParserError> error {};
  113. double time_taken { 0 };
  114. // A failed test takes precedence over a skipped test, which both have
  115. // precedence over a passed test
  116. Test::Result most_severe_test_result { Test::Result::Pass };
  117. Vector<Test::Suite> suites {};
  118. Vector<String> logged_messages {};
  119. };
  120. enum class RunFileHookResult {
  121. RunAsNormal,
  122. SkipFile,
  123. };
  124. using IntermediateRunFileResult = AK::Result<JSFileResult, RunFileHookResult>;
  125. extern IntermediateRunFileResult (*g_run_file)(const String&, JS::Interpreter&);
  126. class TestRunner {
  127. public:
  128. static TestRunner* the()
  129. {
  130. return s_the;
  131. }
  132. TestRunner(String test_root, String common_path, bool print_times, bool print_progress, bool print_json)
  133. : m_common_path(move(common_path))
  134. , m_test_root(move(test_root))
  135. , m_print_times(print_times)
  136. , m_print_progress(print_progress)
  137. , m_print_json(print_json)
  138. {
  139. VERIFY(!s_the);
  140. s_the = this;
  141. g_test_root = m_test_root;
  142. }
  143. virtual ~TestRunner() = default;
  144. void run();
  145. const Test::Counts& counts() const { return m_counts; }
  146. bool is_printing_progress() const { return m_print_progress; }
  147. protected:
  148. static TestRunner* s_the;
  149. virtual Vector<String> get_test_paths() const;
  150. virtual JSFileResult run_file_test(const String& test_path);
  151. void print_file_result(const JSFileResult& file_result) const;
  152. void print_test_results() const;
  153. void print_test_results_as_json() const;
  154. String m_common_path;
  155. String m_test_root;
  156. bool m_print_times;
  157. bool m_print_progress;
  158. bool m_print_json;
  159. double m_total_elapsed_time_in_ms { 0 };
  160. Test::Counts m_counts;
  161. RefPtr<JS::Program> m_test_program;
  162. };
  163. class TestRunnerGlobalObject final : public JS::GlobalObject {
  164. JS_OBJECT(TestRunnerGlobalObject, JS::GlobalObject);
  165. public:
  166. TestRunnerGlobalObject() = default;
  167. virtual ~TestRunnerGlobalObject() override = default;
  168. virtual void initialize_global_object() override;
  169. };
  170. inline void TestRunnerGlobalObject::initialize_global_object()
  171. {
  172. Base::initialize_global_object();
  173. define_property("global", this, JS::Attribute::Enumerable);
  174. for (auto& entry : s_exposed_global_functions) {
  175. define_native_function(
  176. entry.key, [fn = entry.value.function](auto& vm, auto& global_object) {
  177. return fn(vm, global_object);
  178. },
  179. entry.value.length);
  180. }
  181. }
  182. inline void cleanup()
  183. {
  184. // Clear the taskbar progress.
  185. if (TestRunner::the() && TestRunner::the()->is_printing_progress())
  186. warn("\033]9;-1;\033\\");
  187. }
  188. inline void cleanup_and_exit()
  189. {
  190. cleanup();
  191. exit(1);
  192. }
  193. inline double get_time_in_ms()
  194. {
  195. struct timeval tv1;
  196. auto return_code = gettimeofday(&tv1, nullptr);
  197. VERIFY(return_code >= 0);
  198. return static_cast<double>(tv1.tv_sec) * 1000.0 + static_cast<double>(tv1.tv_usec) / 1000.0;
  199. }
  200. template<typename Callback>
  201. inline void iterate_directory_recursively(const String& directory_path, Callback callback)
  202. {
  203. Core::DirIterator directory_iterator(directory_path, Core::DirIterator::Flags::SkipDots);
  204. while (directory_iterator.has_next()) {
  205. auto name = directory_iterator.next_path();
  206. struct stat st = {};
  207. if (fstatat(directory_iterator.fd(), name.characters(), &st, AT_SYMLINK_NOFOLLOW) < 0)
  208. continue;
  209. bool is_directory = S_ISDIR(st.st_mode);
  210. auto full_path = String::formatted("{}/{}", directory_path, name);
  211. if (is_directory && name != "/Fixtures"sv) {
  212. iterate_directory_recursively(full_path, callback);
  213. } else if (!is_directory) {
  214. callback(full_path);
  215. }
  216. }
  217. }
  218. inline Vector<String> TestRunner::get_test_paths() const
  219. {
  220. Vector<String> paths;
  221. iterate_directory_recursively(m_test_root, [&](const String& file_path) {
  222. if (!file_path.ends_with(".js"))
  223. return;
  224. if (!file_path.ends_with("test-common.js"))
  225. paths.append(file_path);
  226. });
  227. quick_sort(paths);
  228. return paths;
  229. }
  230. inline void TestRunner::run()
  231. {
  232. size_t progress_counter = 0;
  233. auto test_paths = get_test_paths();
  234. for (auto& path : test_paths) {
  235. if (!path.matches(g_test_glob))
  236. continue;
  237. ++progress_counter;
  238. auto file_result = run_file_test(path);
  239. if (!m_print_json)
  240. print_file_result(file_result);
  241. if (m_print_progress)
  242. warn("\033]9;{};{};\033\\", progress_counter, test_paths.size());
  243. }
  244. if (m_print_progress)
  245. warn("\033]9;-1;\033\\");
  246. if (!m_print_json)
  247. print_test_results();
  248. else
  249. print_test_results_as_json();
  250. }
  251. inline AK::Result<NonnullRefPtr<JS::Program>, ParserError> parse_file(const String& file_path)
  252. {
  253. auto file = Core::File::construct(file_path);
  254. auto result = file->open(Core::OpenMode::ReadOnly);
  255. if (!result) {
  256. warnln("Failed to open the following file: \"{}\"", file_path);
  257. cleanup_and_exit();
  258. }
  259. auto contents = file->read_all();
  260. String test_file_string(reinterpret_cast<const char*>(contents.data()), contents.size());
  261. file->close();
  262. auto parser = JS::Parser(JS::Lexer(test_file_string));
  263. auto program = parser.parse_program();
  264. if (parser.has_errors()) {
  265. auto error = parser.errors()[0];
  266. return AK::Result<NonnullRefPtr<JS::Program>, ParserError>(ParserError { error, error.source_location_hint(test_file_string) });
  267. }
  268. return AK::Result<NonnullRefPtr<JS::Program>, ParserError>(program);
  269. }
  270. inline Optional<JsonValue> get_test_results(JS::Interpreter& interpreter)
  271. {
  272. auto result = g_vm->get_variable("__TestResults__", interpreter.global_object());
  273. auto json_string = JS::JSONObject::stringify_impl(interpreter.global_object(), result, JS::js_undefined(), JS::js_undefined());
  274. auto json = JsonValue::from_string(json_string);
  275. if (!json.has_value())
  276. return {};
  277. return json.value();
  278. }
  279. inline JSFileResult TestRunner::run_file_test(const String& test_path)
  280. {
  281. g_currently_running_test = test_path;
  282. double start_time = get_time_in_ms();
  283. auto interpreter = JS::Interpreter::create<TestRunnerGlobalObject>(*g_vm);
  284. // FIXME: This is a hack while we're refactoring Interpreter/VM stuff.
  285. JS::VM::InterpreterExecutionScope scope(*interpreter);
  286. interpreter->heap().set_should_collect_on_every_allocation(g_collect_on_every_allocation);
  287. if (g_run_file) {
  288. auto result = g_run_file(test_path, *interpreter);
  289. if (result.is_error() && result.error() == RunFileHookResult::SkipFile) {
  290. return {
  291. test_path,
  292. {},
  293. 0,
  294. Test::Result::Skip,
  295. {},
  296. {}
  297. };
  298. }
  299. if (!result.is_error()) {
  300. auto value = result.release_value();
  301. for (auto& suite : value.suites) {
  302. if (suite.most_severe_test_result == Result::Pass)
  303. m_counts.suites_passed++;
  304. else if (suite.most_severe_test_result == Result::Fail)
  305. m_counts.suites_failed++;
  306. for (auto& test : suite.tests) {
  307. if (test.result == Result::Pass)
  308. m_counts.tests_passed++;
  309. else if (test.result == Result::Fail)
  310. m_counts.tests_failed++;
  311. else if (test.result == Result::Skip)
  312. m_counts.tests_skipped++;
  313. }
  314. }
  315. ++m_counts.files_total;
  316. m_total_elapsed_time_in_ms += value.time_taken;
  317. return value;
  318. }
  319. }
  320. if (!m_test_program) {
  321. auto result = parse_file(m_common_path);
  322. if (result.is_error()) {
  323. warnln("Unable to parse test-common.js");
  324. warnln("{}", result.error().error.to_string());
  325. warnln("{}", result.error().hint);
  326. cleanup_and_exit();
  327. }
  328. m_test_program = result.value();
  329. }
  330. interpreter->run(interpreter->global_object(), *m_test_program);
  331. auto file_program = parse_file(test_path);
  332. if (file_program.is_error())
  333. return { test_path, file_program.error() };
  334. interpreter->run(interpreter->global_object(), *file_program.value());
  335. if (g_vm->exception())
  336. g_vm->clear_exception();
  337. auto test_json = get_test_results(*interpreter);
  338. if (!test_json.has_value()) {
  339. warnln("Received malformed JSON from test \"{}\"", test_path);
  340. cleanup_and_exit();
  341. }
  342. JSFileResult file_result { test_path.substring(m_test_root.length() + 1, test_path.length() - m_test_root.length() - 1) };
  343. // Collect logged messages
  344. auto& arr = interpreter->vm().get_variable("__UserOutput__", interpreter->global_object()).as_array();
  345. for (auto& entry : arr.indexed_properties()) {
  346. auto message = entry.value_and_attributes(&interpreter->global_object()).value;
  347. file_result.logged_messages.append(message.to_string_without_side_effects());
  348. }
  349. test_json.value().as_object().for_each_member([&](const String& suite_name, const JsonValue& suite_value) {
  350. Test::Suite suite { suite_name };
  351. VERIFY(suite_value.is_object());
  352. suite_value.as_object().for_each_member([&](const String& test_name, const JsonValue& test_value) {
  353. Test::Case test { test_name, Test::Result::Fail, "" };
  354. VERIFY(test_value.is_object());
  355. VERIFY(test_value.as_object().has("result"));
  356. auto result = test_value.as_object().get("result");
  357. VERIFY(result.is_string());
  358. auto result_string = result.as_string();
  359. if (result_string == "pass") {
  360. test.result = Test::Result::Pass;
  361. m_counts.tests_passed++;
  362. } else if (result_string == "fail") {
  363. test.result = Test::Result::Fail;
  364. m_counts.tests_failed++;
  365. suite.most_severe_test_result = Test::Result::Fail;
  366. VERIFY(test_value.as_object().has("details"));
  367. auto details = test_value.as_object().get("details");
  368. VERIFY(result.is_string());
  369. test.details = details.as_string();
  370. } else {
  371. test.result = Test::Result::Skip;
  372. if (suite.most_severe_test_result == Test::Result::Pass)
  373. suite.most_severe_test_result = Test::Result::Skip;
  374. m_counts.tests_skipped++;
  375. }
  376. suite.tests.append(test);
  377. });
  378. if (suite.most_severe_test_result == Test::Result::Fail) {
  379. m_counts.suites_failed++;
  380. file_result.most_severe_test_result = Test::Result::Fail;
  381. } else {
  382. if (suite.most_severe_test_result == Test::Result::Skip && file_result.most_severe_test_result == Test::Result::Pass)
  383. file_result.most_severe_test_result = Test::Result::Skip;
  384. m_counts.suites_passed++;
  385. }
  386. file_result.suites.append(suite);
  387. });
  388. m_counts.files_total++;
  389. file_result.time_taken = get_time_in_ms() - start_time;
  390. m_total_elapsed_time_in_ms += file_result.time_taken;
  391. return file_result;
  392. }
  393. enum Modifier {
  394. BG_RED,
  395. BG_GREEN,
  396. FG_RED,
  397. FG_GREEN,
  398. FG_ORANGE,
  399. FG_GRAY,
  400. FG_BLACK,
  401. FG_BOLD,
  402. ITALIC,
  403. CLEAR,
  404. };
  405. inline void print_modifiers(Vector<Modifier> modifiers)
  406. {
  407. for (auto& modifier : modifiers) {
  408. auto code = [&] {
  409. switch (modifier) {
  410. case BG_RED:
  411. return "\033[48;2;255;0;102m";
  412. case BG_GREEN:
  413. return "\033[48;2;102;255;0m";
  414. case FG_RED:
  415. return "\033[38;2;255;0;102m";
  416. case FG_GREEN:
  417. return "\033[38;2;102;255;0m";
  418. case FG_ORANGE:
  419. return "\033[38;2;255;102;0m";
  420. case FG_GRAY:
  421. return "\033[38;2;135;139;148m";
  422. case FG_BLACK:
  423. return "\033[30m";
  424. case FG_BOLD:
  425. return "\033[1m";
  426. case ITALIC:
  427. return "\033[3m";
  428. case CLEAR:
  429. return "\033[0m";
  430. }
  431. VERIFY_NOT_REACHED();
  432. }();
  433. out("{}", code);
  434. }
  435. }
  436. inline void TestRunner::print_file_result(const JSFileResult& file_result) const
  437. {
  438. if (file_result.most_severe_test_result == Test::Result::Fail || file_result.error.has_value()) {
  439. print_modifiers({ BG_RED, FG_BLACK, FG_BOLD });
  440. out(" FAIL ");
  441. print_modifiers({ CLEAR });
  442. } else {
  443. if (m_print_times || file_result.most_severe_test_result != Test::Result::Pass) {
  444. print_modifiers({ BG_GREEN, FG_BLACK, FG_BOLD });
  445. out(" PASS ");
  446. print_modifiers({ CLEAR });
  447. } else {
  448. return;
  449. }
  450. }
  451. out(" {}", file_result.name);
  452. if (m_print_times) {
  453. print_modifiers({ CLEAR, ITALIC, FG_GRAY });
  454. if (file_result.time_taken < 1000) {
  455. outln(" ({}ms)", static_cast<int>(file_result.time_taken));
  456. } else {
  457. outln(" ({:3}s)", file_result.time_taken / 1000.0);
  458. }
  459. print_modifiers({ CLEAR });
  460. } else {
  461. outln();
  462. }
  463. if (!file_result.logged_messages.is_empty()) {
  464. print_modifiers({ FG_GRAY, FG_BOLD });
  465. #ifdef __serenity__
  466. outln(" ℹ Console output:");
  467. #else
  468. // This emoji has a second invisible byte after it. The one above does not
  469. outln(" ℹ️ Console output:");
  470. #endif
  471. print_modifiers({ CLEAR, FG_GRAY });
  472. for (auto& message : file_result.logged_messages)
  473. outln(" {}", message);
  474. }
  475. if (file_result.error.has_value()) {
  476. auto test_error = file_result.error.value();
  477. print_modifiers({ FG_RED });
  478. #ifdef __serenity__
  479. outln(" ❌ The file failed to parse");
  480. #else
  481. // No invisible byte here, but the spacing still needs to be altered on the host
  482. outln(" ❌ The file failed to parse");
  483. #endif
  484. outln();
  485. print_modifiers({ FG_GRAY });
  486. for (auto& message : test_error.hint.split('\n', true)) {
  487. outln(" {}", message);
  488. }
  489. print_modifiers({ FG_RED });
  490. outln(" {}", test_error.error.to_string());
  491. outln();
  492. return;
  493. }
  494. if (file_result.most_severe_test_result != Test::Result::Pass) {
  495. for (auto& suite : file_result.suites) {
  496. if (suite.most_severe_test_result == Test::Result::Pass)
  497. continue;
  498. bool failed = suite.most_severe_test_result == Test::Result::Fail;
  499. print_modifiers({ FG_GRAY, FG_BOLD });
  500. if (failed) {
  501. #ifdef __serenity__
  502. out(" ❌ Suite: ");
  503. #else
  504. // No invisible byte here, but the spacing still needs to be altered on the host
  505. out(" ❌ Suite: ");
  506. #endif
  507. } else {
  508. #ifdef __serenity__
  509. out(" ⚠ Suite: ");
  510. #else
  511. // This emoji has a second invisible byte after it. The one above does not
  512. out(" ⚠️ Suite: ");
  513. #endif
  514. }
  515. print_modifiers({ CLEAR, FG_GRAY });
  516. if (suite.name == TOP_LEVEL_TEST_NAME) {
  517. outln("<top-level>");
  518. } else {
  519. outln("{}", suite.name);
  520. }
  521. print_modifiers({ CLEAR });
  522. for (auto& test : suite.tests) {
  523. if (test.result == Test::Result::Pass)
  524. continue;
  525. print_modifiers({ FG_GRAY, FG_BOLD });
  526. out(" Test: ");
  527. if (test.result == Test::Result::Fail) {
  528. print_modifiers({ CLEAR, FG_RED });
  529. outln("{} (failed):", test.name);
  530. outln(" {}", test.details);
  531. } else {
  532. print_modifiers({ CLEAR, FG_ORANGE });
  533. outln("{} (skipped)", test.name);
  534. }
  535. print_modifiers({ CLEAR });
  536. }
  537. }
  538. }
  539. }
  540. inline void TestRunner::print_test_results() const
  541. {
  542. out("\nTest Suites: ");
  543. if (m_counts.suites_failed) {
  544. print_modifiers({ FG_RED });
  545. out("{} failed, ", m_counts.suites_failed);
  546. print_modifiers({ CLEAR });
  547. }
  548. if (m_counts.suites_passed) {
  549. print_modifiers({ FG_GREEN });
  550. out("{} passed, ", m_counts.suites_passed);
  551. print_modifiers({ CLEAR });
  552. }
  553. outln("{} total", m_counts.suites_failed + m_counts.suites_passed);
  554. out("Tests: ");
  555. if (m_counts.tests_failed) {
  556. print_modifiers({ FG_RED });
  557. out("{} failed, ", m_counts.tests_failed);
  558. print_modifiers({ CLEAR });
  559. }
  560. if (m_counts.tests_skipped) {
  561. print_modifiers({ FG_ORANGE });
  562. out("{} skipped, ", m_counts.tests_skipped);
  563. print_modifiers({ CLEAR });
  564. }
  565. if (m_counts.tests_passed) {
  566. print_modifiers({ FG_GREEN });
  567. out("{} passed, ", m_counts.tests_passed);
  568. print_modifiers({ CLEAR });
  569. }
  570. outln("{} total", m_counts.tests_failed + m_counts.tests_skipped + m_counts.tests_passed);
  571. outln("Files: {} total", m_counts.files_total);
  572. out("Time: ");
  573. if (m_total_elapsed_time_in_ms < 1000.0) {
  574. outln("{}ms", static_cast<int>(m_total_elapsed_time_in_ms));
  575. } else {
  576. outln("{:>.3}s", m_total_elapsed_time_in_ms / 1000.0);
  577. }
  578. outln();
  579. }
  580. inline void TestRunner::print_test_results_as_json() const
  581. {
  582. JsonObject suites;
  583. suites.set("failed", m_counts.suites_failed);
  584. suites.set("passed", m_counts.suites_passed);
  585. suites.set("total", m_counts.suites_failed + m_counts.suites_passed);
  586. JsonObject tests;
  587. tests.set("failed", m_counts.tests_failed);
  588. tests.set("passed", m_counts.tests_passed);
  589. tests.set("skipped", m_counts.tests_skipped);
  590. tests.set("total", m_counts.tests_failed + m_counts.tests_passed + m_counts.tests_skipped);
  591. JsonObject results;
  592. results.set("suites", suites);
  593. results.set("tests", tests);
  594. JsonObject root;
  595. root.set("results", results);
  596. root.set("files_total", m_counts.files_total);
  597. root.set("duration", m_total_elapsed_time_in_ms / 1000.0);
  598. outln("{}", root.to_string());
  599. }
  600. }