JavaScriptTestRunner.h 20 KB

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