JavaScriptTestRunner.h 24 KB

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