JavaScriptTestRunner.h 20 KB

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