JavaScriptTestRunner.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2020-2022, 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/DirIterator.h>
  18. #include <LibCore/File.h>
  19. #include <LibCore/Stream.h>
  20. #include <LibJS/Bytecode/Interpreter.h>
  21. #include <LibJS/Interpreter.h>
  22. #include <LibJS/Lexer.h>
  23. #include <LibJS/Parser.h>
  24. #include <LibJS/Runtime/Array.h>
  25. #include <LibJS/Runtime/GlobalObject.h>
  26. #include <LibJS/Runtime/JSONObject.h>
  27. #include <LibJS/Runtime/TypedArray.h>
  28. #include <LibJS/Runtime/WeakMap.h>
  29. #include <LibJS/Runtime/WeakSet.h>
  30. #include <LibJS/Script.h>
  31. #include <LibJS/SourceTextModule.h>
  32. #include <LibTest/Results.h>
  33. #include <LibTest/TestRunner.h>
  34. #include <fcntl.h>
  35. #include <sys/time.h>
  36. #include <unistd.h>
  37. #ifdef __serenity__
  38. # include <serenity.h>
  39. #endif
  40. #define STRCAT(x, y) __STRCAT(x, y)
  41. #define STRSTRCAT(x, y) __STRSTRCAT(x, y)
  42. #define __STRCAT(x, y) x #y
  43. #define __STRSTRCAT(x, y) x y
  44. // Note: This is a little weird, so here's an explanation:
  45. // If the vararg isn't given, the tuple initializer will simply expand to `fn, ::Test::JS::__testjs_last<1>()`
  46. // 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`
  47. // and if multiple args are given, the static_assert will be sad.
  48. #define __TESTJS_REGISTER_GLOBAL_FUNCTION(name, fn, ...) \
  49. struct __TestJS_register_##fn { \
  50. static_assert( \
  51. ::Test::JS::__testjs_count(__VA_ARGS__) <= 1, \
  52. STRCAT(STRSTRCAT(STRCAT("Expected at most three arguments to TESTJS_GLOBAL_FUNCTION at line", __LINE__), ", in file "), __FILE__)); \
  53. __TestJS_register_##fn() noexcept \
  54. { \
  55. ::Test::JS::s_exposed_global_functions.set( \
  56. name, \
  57. { fn, ::Test::JS::__testjs_last<1, ##__VA_ARGS__>() }); \
  58. } \
  59. } __testjs_register_##fn {};
  60. #define TESTJS_GLOBAL_FUNCTION(function, exposed_name, ...) \
  61. JS_DECLARE_NATIVE_FUNCTION(function); \
  62. __TESTJS_REGISTER_GLOBAL_FUNCTION(#exposed_name, function, ##__VA_ARGS__); \
  63. JS_DEFINE_NATIVE_FUNCTION(function)
  64. #define TESTJS_MAIN_HOOK() \
  65. struct __TestJS_main_hook { \
  66. __TestJS_main_hook() \
  67. { \
  68. ::Test::JS::g_main_hook = hook; \
  69. } \
  70. static void hook(); \
  71. } __testjs_common_register_##name {}; \
  72. void __TestJS_main_hook::hook()
  73. #define TESTJS_PROGRAM_FLAG(flag, help_string, long_name, short_name) \
  74. bool flag { false }; \
  75. struct __TestJS_flag_hook_##flag { \
  76. __TestJS_flag_hook_##flag() \
  77. { \
  78. ::Test::JS::g_extra_args.set(&(flag), { help_string, long_name, short_name }); \
  79. }; \
  80. } __testjs_flag_hook_##flag;
  81. #define TEST_ROOT(path) \
  82. String Test::JS::g_test_root_fragment = path
  83. #define TESTJS_RUN_FILE_FUNCTION(...) \
  84. struct __TestJS_run_file { \
  85. __TestJS_run_file() \
  86. { \
  87. ::Test::JS::g_run_file = hook; \
  88. } \
  89. static ::Test::JS::IntermediateRunFileResult hook(String const&, JS::Interpreter&, JS::ExecutionContext&); \
  90. } __testjs_common_run_file {}; \
  91. ::Test::JS::IntermediateRunFileResult __TestJS_run_file::hook(__VA_ARGS__)
  92. #define TESTJS_CREATE_INTERPRETER_HOOK(...) \
  93. struct __TestJS_create_interpreter_hook { \
  94. __TestJS_create_interpreter_hook() \
  95. { \
  96. ::Test::JS::g_create_interpreter_hook = hook; \
  97. } \
  98. static NonnullOwnPtr<JS::Interpreter> hook(); \
  99. } __testjs_create_interpreter_hook {}; \
  100. NonnullOwnPtr<JS::Interpreter> __TestJS_create_interpreter_hook::hook(__VA_ARGS__)
  101. namespace Test::JS {
  102. namespace JS = ::JS;
  103. template<typename... Args>
  104. static consteval size_t __testjs_count(Args...) { return sizeof...(Args); }
  105. template<auto... Values>
  106. static consteval size_t __testjs_last()
  107. {
  108. Array values { Values... };
  109. return values[values.size() - 1U];
  110. }
  111. static constexpr auto TOP_LEVEL_TEST_NAME = "__$$TOP_LEVEL$$__";
  112. extern RefPtr<JS::VM> g_vm;
  113. extern bool g_collect_on_every_allocation;
  114. extern bool g_run_bytecode;
  115. extern String g_currently_running_test;
  116. struct FunctionWithLength {
  117. JS::ThrowCompletionOr<JS::Value> (*function)(JS::VM&);
  118. size_t length { 0 };
  119. };
  120. extern HashMap<String, FunctionWithLength> s_exposed_global_functions;
  121. extern String g_test_root_fragment;
  122. extern String g_test_root;
  123. extern int g_test_argc;
  124. extern char** g_test_argv;
  125. extern Function<void()> g_main_hook;
  126. extern Function<NonnullOwnPtr<JS::Interpreter>()> g_create_interpreter_hook;
  127. extern HashMap<bool*, Tuple<String, String, char>> g_extra_args;
  128. struct ParserError {
  129. JS::Parser::Error error;
  130. String hint;
  131. };
  132. struct JSFileResult {
  133. String name;
  134. Optional<ParserError> error {};
  135. double time_taken { 0 };
  136. // A failed test takes precedence over a skipped test, which both have
  137. // precedence over a passed test
  138. Test::Result most_severe_test_result { Test::Result::Pass };
  139. Vector<Test::Suite> suites {};
  140. Vector<String> logged_messages {};
  141. };
  142. enum class RunFileHookResult {
  143. RunAsNormal,
  144. SkipFile,
  145. };
  146. using IntermediateRunFileResult = AK::Result<JSFileResult, RunFileHookResult>;
  147. extern IntermediateRunFileResult (*g_run_file)(String const&, JS::Interpreter&, JS::ExecutionContext&);
  148. class TestRunner : public ::Test::TestRunner {
  149. public:
  150. TestRunner(String test_root, String common_path, bool print_times, bool print_progress, bool print_json, bool detailed_json)
  151. : ::Test::TestRunner(move(test_root), print_times, print_progress, print_json, detailed_json)
  152. , m_common_path(move(common_path))
  153. {
  154. g_test_root = m_test_root;
  155. }
  156. virtual ~TestRunner() = default;
  157. protected:
  158. virtual void do_run_single_test(String const& test_path, size_t, size_t) override;
  159. virtual Vector<String> get_test_paths() const override;
  160. virtual JSFileResult run_file_test(String const& test_path);
  161. void print_file_result(JSFileResult const& file_result) const;
  162. String m_common_path;
  163. };
  164. class TestRunnerGlobalObject final : public JS::GlobalObject {
  165. JS_OBJECT(TestRunnerGlobalObject, JS::GlobalObject);
  166. public:
  167. TestRunnerGlobalObject(JS::Realm& realm)
  168. : JS::GlobalObject(realm)
  169. {
  170. }
  171. virtual ~TestRunnerGlobalObject() override = default;
  172. virtual void initialize_global_object() override;
  173. };
  174. inline void TestRunnerGlobalObject::initialize_global_object()
  175. {
  176. Base::initialize_global_object();
  177. define_direct_property("global", this, JS::Attribute::Enumerable);
  178. for (auto& entry : s_exposed_global_functions) {
  179. define_native_function(
  180. entry.key, [fn = entry.value.function](auto& vm) {
  181. return fn(vm);
  182. },
  183. entry.value.length, JS::default_attributes);
  184. }
  185. }
  186. inline ByteBuffer load_entire_file(StringView path)
  187. {
  188. auto try_load_entire_file = [](StringView const& path) -> ErrorOr<ByteBuffer> {
  189. auto file = TRY(Core::Stream::File::open(path, Core::Stream::OpenMode::Read));
  190. auto file_size = TRY(file->size());
  191. auto content = TRY(ByteBuffer::create_uninitialized(file_size));
  192. TRY(file->read(content.bytes()));
  193. return content;
  194. };
  195. auto buffer_or_error = try_load_entire_file(path);
  196. if (buffer_or_error.is_error()) {
  197. warnln("Failed to open the following file: \"{}\", error: {}", path, buffer_or_error.release_error());
  198. cleanup_and_exit();
  199. }
  200. return buffer_or_error.release_value();
  201. }
  202. inline AK::Result<NonnullRefPtr<JS::Script>, ParserError> parse_script(StringView path, JS::Realm& realm)
  203. {
  204. auto contents = load_entire_file(path);
  205. auto script_or_errors = JS::Script::parse(contents, realm, path);
  206. if (script_or_errors.is_error()) {
  207. auto errors = script_or_errors.release_error();
  208. return ParserError { errors[0], errors[0].source_location_hint(contents) };
  209. }
  210. return script_or_errors.release_value();
  211. }
  212. inline AK::Result<NonnullRefPtr<JS::SourceTextModule>, ParserError> parse_module(StringView path, JS::Realm& realm)
  213. {
  214. auto contents = load_entire_file(path);
  215. auto script_or_errors = JS::SourceTextModule::parse(contents, realm, path);
  216. if (script_or_errors.is_error()) {
  217. auto errors = script_or_errors.release_error();
  218. return ParserError { errors[0], errors[0].source_location_hint(contents) };
  219. }
  220. return script_or_errors.release_value();
  221. }
  222. inline ErrorOr<JsonValue> get_test_results(JS::Interpreter& interpreter)
  223. {
  224. auto results = MUST(interpreter.global_object().get("__TestResults__"));
  225. auto json_string = MUST(JS::JSONObject::stringify_impl(*g_vm, results, JS::js_undefined(), JS::js_undefined()));
  226. return JsonValue::from_string(json_string);
  227. }
  228. inline void TestRunner::do_run_single_test(String const& test_path, size_t, size_t)
  229. {
  230. auto file_result = run_file_test(test_path);
  231. if (!m_print_json)
  232. print_file_result(file_result);
  233. if (needs_detailed_suites())
  234. ensure_suites().extend(file_result.suites);
  235. }
  236. inline Vector<String> TestRunner::get_test_paths() const
  237. {
  238. Vector<String> paths;
  239. iterate_directory_recursively(m_test_root, [&](String const& file_path) {
  240. if (!file_path.ends_with(".js"sv))
  241. return;
  242. if (!file_path.ends_with("test-common.js"sv))
  243. paths.append(file_path);
  244. });
  245. quick_sort(paths);
  246. return paths;
  247. }
  248. inline JSFileResult TestRunner::run_file_test(String const& test_path)
  249. {
  250. g_currently_running_test = test_path;
  251. #ifdef __serenity__
  252. auto string_id = perf_register_string(test_path.characters(), test_path.length());
  253. perf_event(PERF_EVENT_SIGNPOST, string_id, 0);
  254. #endif
  255. double start_time = get_time_in_ms();
  256. auto interpreter = JS::Interpreter::create<TestRunnerGlobalObject>(*g_vm);
  257. // Since g_vm is reused for each new interpreter, Interpreter::create will end up pushing multiple
  258. // global execution contexts onto the VM's execution context stack. To prevent this, we immediately
  259. // pop the global execution context off the execution context stack and manually handle pushing
  260. // and popping it. Since the global execution context should be the only thing on the stack
  261. // at interpreter creation, let's assert there is only one.
  262. VERIFY(g_vm->execution_context_stack().size() == 1);
  263. auto& global_execution_context = *g_vm->execution_context_stack().take_first();
  264. // FIXME: This is a hack while we're refactoring Interpreter/VM stuff.
  265. JS::VM::InterpreterExecutionScope scope(*interpreter);
  266. interpreter->heap().set_should_collect_on_every_allocation(g_collect_on_every_allocation);
  267. if (g_run_file) {
  268. auto result = g_run_file(test_path, *interpreter, global_execution_context);
  269. if (result.is_error() && result.error() == RunFileHookResult::SkipFile) {
  270. return {
  271. test_path,
  272. {},
  273. 0,
  274. Test::Result::Skip,
  275. {},
  276. {}
  277. };
  278. }
  279. if (!result.is_error()) {
  280. auto value = result.release_value();
  281. for (auto& suite : value.suites) {
  282. if (suite.most_severe_test_result == Result::Pass)
  283. m_counts.suites_passed++;
  284. else if (suite.most_severe_test_result == Result::Fail)
  285. m_counts.suites_failed++;
  286. for (auto& test : suite.tests) {
  287. if (test.result == Result::Pass)
  288. m_counts.tests_passed++;
  289. else if (test.result == Result::Fail)
  290. m_counts.tests_failed++;
  291. else if (test.result == Result::Skip)
  292. m_counts.tests_skipped++;
  293. }
  294. }
  295. ++m_counts.files_total;
  296. m_total_elapsed_time_in_ms += value.time_taken;
  297. return value;
  298. }
  299. }
  300. // FIXME: Since a new interpreter is created every time with a new realm, we no longer cache the test-common.js file as scripts are parsed for the current realm only.
  301. // Find a way to cache this.
  302. auto result = parse_script(m_common_path, interpreter->realm());
  303. if (result.is_error()) {
  304. warnln("Unable to parse test-common.js");
  305. warnln("{}", result.error().error.to_string());
  306. warnln("{}", result.error().hint);
  307. cleanup_and_exit();
  308. }
  309. auto test_script = result.release_value();
  310. if (g_run_bytecode) {
  311. auto executable = MUST(JS::Bytecode::Generator::generate(test_script->parse_node()));
  312. executable->name = test_path;
  313. if (JS::Bytecode::g_dump_bytecode)
  314. executable->dump();
  315. JS::Bytecode::Interpreter bytecode_interpreter(interpreter->global_object(), interpreter->realm());
  316. MUST(bytecode_interpreter.run(*executable));
  317. } else {
  318. g_vm->push_execution_context(global_execution_context);
  319. MUST(interpreter->run(*test_script));
  320. g_vm->pop_execution_context();
  321. }
  322. auto file_script = parse_script(test_path, interpreter->realm());
  323. if (file_script.is_error())
  324. return { test_path, file_script.error() };
  325. if (g_run_bytecode) {
  326. auto executable_result = JS::Bytecode::Generator::generate(file_script.value()->parse_node());
  327. if (!executable_result.is_error()) {
  328. auto executable = executable_result.release_value();
  329. executable->name = test_path;
  330. if (JS::Bytecode::g_dump_bytecode)
  331. executable->dump();
  332. JS::Bytecode::Interpreter bytecode_interpreter(interpreter->global_object(), interpreter->realm());
  333. (void)bytecode_interpreter.run(*executable);
  334. }
  335. } else {
  336. g_vm->push_execution_context(global_execution_context);
  337. (void)interpreter->run(file_script.value());
  338. g_vm->pop_execution_context();
  339. }
  340. g_vm->push_execution_context(global_execution_context);
  341. auto test_json = get_test_results(*interpreter);
  342. g_vm->pop_execution_context();
  343. if (test_json.is_error()) {
  344. warnln("Received malformed JSON from test \"{}\"", test_path);
  345. cleanup_and_exit();
  346. }
  347. JSFileResult file_result { test_path.substring(m_test_root.length() + 1, test_path.length() - m_test_root.length() - 1) };
  348. // Collect logged messages
  349. auto user_output = MUST(interpreter->global_object().get("__UserOutput__"));
  350. auto& arr = user_output.as_array();
  351. for (auto& entry : arr.indexed_properties()) {
  352. auto message = MUST(arr.get(entry.index()));
  353. file_result.logged_messages.append(message.to_string_without_side_effects());
  354. }
  355. test_json.value().as_object().for_each_member([&](String const& suite_name, JsonValue const& suite_value) {
  356. Test::Suite suite { test_path, suite_name };
  357. VERIFY(suite_value.is_object());
  358. suite_value.as_object().for_each_member([&](const String& test_name, const JsonValue& test_value) {
  359. Test::Case test { test_name, Test::Result::Fail, "", 0 };
  360. VERIFY(test_value.is_object());
  361. VERIFY(test_value.as_object().has("result"sv));
  362. auto result = test_value.as_object().get("result"sv);
  363. VERIFY(result.is_string());
  364. auto result_string = result.as_string();
  365. if (result_string == "pass") {
  366. test.result = Test::Result::Pass;
  367. m_counts.tests_passed++;
  368. } else if (result_string == "fail") {
  369. test.result = Test::Result::Fail;
  370. m_counts.tests_failed++;
  371. suite.most_severe_test_result = Test::Result::Fail;
  372. VERIFY(test_value.as_object().has("details"sv));
  373. auto details = test_value.as_object().get("details"sv);
  374. VERIFY(result.is_string());
  375. test.details = details.as_string();
  376. } else {
  377. test.result = Test::Result::Skip;
  378. if (suite.most_severe_test_result == Test::Result::Pass)
  379. suite.most_severe_test_result = Test::Result::Skip;
  380. m_counts.tests_skipped++;
  381. }
  382. test.duration_us = test_value.as_object().get("duration"sv).to_u64(0);
  383. suite.tests.append(test);
  384. });
  385. if (suite.most_severe_test_result == Test::Result::Fail) {
  386. m_counts.suites_failed++;
  387. file_result.most_severe_test_result = Test::Result::Fail;
  388. } else {
  389. if (suite.most_severe_test_result == Test::Result::Skip && file_result.most_severe_test_result == Test::Result::Pass)
  390. file_result.most_severe_test_result = Test::Result::Skip;
  391. m_counts.suites_passed++;
  392. }
  393. file_result.suites.append(suite);
  394. });
  395. m_counts.files_total++;
  396. file_result.time_taken = get_time_in_ms() - start_time;
  397. m_total_elapsed_time_in_ms += file_result.time_taken;
  398. return file_result;
  399. }
  400. inline void TestRunner::print_file_result(JSFileResult const& file_result) const
  401. {
  402. if (file_result.most_severe_test_result == Test::Result::Fail || file_result.error.has_value()) {
  403. print_modifiers({ BG_RED, FG_BLACK, FG_BOLD });
  404. out(" FAIL ");
  405. print_modifiers({ CLEAR });
  406. } else {
  407. if (m_print_times || file_result.most_severe_test_result != Test::Result::Pass) {
  408. print_modifiers({ BG_GREEN, FG_BLACK, FG_BOLD });
  409. out(" PASS ");
  410. print_modifiers({ CLEAR });
  411. } else {
  412. return;
  413. }
  414. }
  415. out(" {}", file_result.name);
  416. if (m_print_times) {
  417. print_modifiers({ CLEAR, ITALIC, FG_GRAY });
  418. if (file_result.time_taken < 1000) {
  419. outln(" ({}ms)", static_cast<int>(file_result.time_taken));
  420. } else {
  421. outln(" ({:3}s)", file_result.time_taken / 1000.0);
  422. }
  423. print_modifiers({ CLEAR });
  424. } else {
  425. outln();
  426. }
  427. if (!file_result.logged_messages.is_empty()) {
  428. print_modifiers({ FG_GRAY, FG_BOLD });
  429. #ifdef __serenity__
  430. outln(" ℹ Console output:");
  431. #else
  432. // This emoji has a second invisible byte after it. The one above does not
  433. outln(" ℹ️ Console output:");
  434. #endif
  435. print_modifiers({ CLEAR, FG_GRAY });
  436. for (auto& message : file_result.logged_messages)
  437. outln(" {}", message);
  438. }
  439. if (file_result.error.has_value()) {
  440. auto test_error = file_result.error.value();
  441. print_modifiers({ FG_RED });
  442. #ifdef __serenity__
  443. outln(" ❌ The file failed to parse");
  444. #else
  445. // No invisible byte here, but the spacing still needs to be altered on the host
  446. outln(" ❌ The file failed to parse");
  447. #endif
  448. outln();
  449. print_modifiers({ FG_GRAY });
  450. for (auto& message : test_error.hint.split('\n', true)) {
  451. outln(" {}", message);
  452. }
  453. print_modifiers({ FG_RED });
  454. outln(" {}", test_error.error.to_string());
  455. outln();
  456. return;
  457. }
  458. if (file_result.most_severe_test_result != Test::Result::Pass) {
  459. for (auto& suite : file_result.suites) {
  460. if (suite.most_severe_test_result == Test::Result::Pass)
  461. continue;
  462. bool failed = suite.most_severe_test_result == Test::Result::Fail;
  463. print_modifiers({ FG_GRAY, FG_BOLD });
  464. if (failed) {
  465. #ifdef __serenity__
  466. out(" ❌ Suite: ");
  467. #else
  468. // No invisible byte here, but the spacing still needs to be altered on the host
  469. out(" ❌ Suite: ");
  470. #endif
  471. } else {
  472. #ifdef __serenity__
  473. out(" ⚠ Suite: ");
  474. #else
  475. // This emoji has a second invisible byte after it. The one above does not
  476. out(" ⚠️ Suite: ");
  477. #endif
  478. }
  479. print_modifiers({ CLEAR, FG_GRAY });
  480. if (suite.name == TOP_LEVEL_TEST_NAME) {
  481. outln("<top-level>");
  482. } else {
  483. outln("{}", suite.name);
  484. }
  485. print_modifiers({ CLEAR });
  486. for (auto& test : suite.tests) {
  487. if (test.result == Test::Result::Pass)
  488. continue;
  489. print_modifiers({ FG_GRAY, FG_BOLD });
  490. out(" Test: ");
  491. if (test.result == Test::Result::Fail) {
  492. print_modifiers({ CLEAR, FG_RED });
  493. outln("{} (failed):", test.name);
  494. outln(" {}", test.details);
  495. } else {
  496. print_modifiers({ CLEAR, FG_ORANGE });
  497. outln("{} (skipped)", test.name);
  498. }
  499. print_modifiers({ CLEAR });
  500. }
  501. }
  502. }
  503. }
  504. }