JavaScriptTestRunner.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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/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&, JS::GlobalObject&);
  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() = default;
  168. virtual ~TestRunnerGlobalObject() override = default;
  169. virtual void initialize_global_object() override;
  170. };
  171. inline void TestRunnerGlobalObject::initialize_global_object()
  172. {
  173. Base::initialize_global_object();
  174. define_direct_property("global", this, JS::Attribute::Enumerable);
  175. for (auto& entry : s_exposed_global_functions) {
  176. define_native_function(
  177. entry.key, [fn = entry.value.function](auto& vm, auto& global_object) {
  178. return fn(vm, global_object);
  179. },
  180. entry.value.length, JS::default_attributes);
  181. }
  182. }
  183. inline ByteBuffer load_entire_file(StringView path)
  184. {
  185. auto try_load_entire_file = [](StringView const& path) -> ErrorOr<ByteBuffer> {
  186. auto file = TRY(Core::Stream::File::open(path, Core::Stream::OpenMode::Read));
  187. auto file_size = TRY(file->size());
  188. auto content = TRY(ByteBuffer::create_uninitialized(file_size));
  189. TRY(file->read(content.bytes()));
  190. return content;
  191. };
  192. auto buffer_or_error = try_load_entire_file(path);
  193. if (buffer_or_error.is_error()) {
  194. warnln("Failed to open the following file: \"{}\", error: {}", path, buffer_or_error.release_error());
  195. cleanup_and_exit();
  196. }
  197. return buffer_or_error.release_value();
  198. }
  199. inline AK::Result<NonnullRefPtr<JS::Script>, ParserError> parse_script(StringView path, JS::Realm& realm)
  200. {
  201. auto contents = load_entire_file(path);
  202. auto script_or_errors = JS::Script::parse(contents, realm, path);
  203. if (script_or_errors.is_error()) {
  204. auto errors = script_or_errors.release_error();
  205. return ParserError { errors[0], errors[0].source_location_hint(contents) };
  206. }
  207. return script_or_errors.release_value();
  208. }
  209. inline AK::Result<NonnullRefPtr<JS::SourceTextModule>, ParserError> parse_module(StringView path, JS::Realm& realm)
  210. {
  211. auto contents = load_entire_file(path);
  212. auto script_or_errors = JS::SourceTextModule::parse(contents, realm, path);
  213. if (script_or_errors.is_error()) {
  214. auto errors = script_or_errors.release_error();
  215. return ParserError { errors[0], errors[0].source_location_hint(contents) };
  216. }
  217. return script_or_errors.release_value();
  218. }
  219. inline ErrorOr<JsonValue> get_test_results(JS::Interpreter& interpreter)
  220. {
  221. auto results = MUST(interpreter.global_object().get("__TestResults__"));
  222. auto json_string = MUST(JS::JSONObject::stringify_impl(interpreter.global_object(), results, JS::js_undefined(), JS::js_undefined()));
  223. return JsonValue::from_string(json_string);
  224. }
  225. inline void TestRunner::do_run_single_test(String const& test_path, size_t, size_t)
  226. {
  227. auto file_result = run_file_test(test_path);
  228. if (!m_print_json)
  229. print_file_result(file_result);
  230. if (needs_detailed_suites())
  231. ensure_suites().extend(file_result.suites);
  232. }
  233. inline Vector<String> TestRunner::get_test_paths() const
  234. {
  235. Vector<String> paths;
  236. iterate_directory_recursively(m_test_root, [&](String const& file_path) {
  237. if (!file_path.ends_with(".js"))
  238. return;
  239. if (!file_path.ends_with("test-common.js"))
  240. paths.append(file_path);
  241. });
  242. quick_sort(paths);
  243. return paths;
  244. }
  245. inline JSFileResult TestRunner::run_file_test(String const& test_path)
  246. {
  247. g_currently_running_test = test_path;
  248. #ifdef __serenity__
  249. auto string_id = perf_register_string(test_path.characters(), test_path.length());
  250. perf_event(PERF_EVENT_SIGNPOST, string_id, 0);
  251. #endif
  252. double start_time = get_time_in_ms();
  253. auto interpreter = JS::Interpreter::create<TestRunnerGlobalObject>(*g_vm);
  254. // Since g_vm is reused for each new interpreter, Interpreter::create will end up pushing multiple
  255. // global execution contexts onto the VM's execution context stack. To prevent this, we immediately
  256. // pop the global execution context off the execution context stack and manually handle pushing
  257. // and popping it. Since the global execution context should be the only thing on the stack
  258. // at interpreter creation, let's assert there is only one.
  259. VERIFY(g_vm->execution_context_stack().size() == 1);
  260. auto& global_execution_context = *g_vm->execution_context_stack().take_first();
  261. // FIXME: This is a hack while we're refactoring Interpreter/VM stuff.
  262. JS::VM::InterpreterExecutionScope scope(*interpreter);
  263. interpreter->heap().set_should_collect_on_every_allocation(g_collect_on_every_allocation);
  264. if (g_run_file) {
  265. auto result = g_run_file(test_path, *interpreter, global_execution_context);
  266. if (result.is_error() && result.error() == RunFileHookResult::SkipFile) {
  267. return {
  268. test_path,
  269. {},
  270. 0,
  271. Test::Result::Skip,
  272. {},
  273. {}
  274. };
  275. }
  276. if (!result.is_error()) {
  277. auto value = result.release_value();
  278. for (auto& suite : value.suites) {
  279. if (suite.most_severe_test_result == Result::Pass)
  280. m_counts.suites_passed++;
  281. else if (suite.most_severe_test_result == Result::Fail)
  282. m_counts.suites_failed++;
  283. for (auto& test : suite.tests) {
  284. if (test.result == Result::Pass)
  285. m_counts.tests_passed++;
  286. else if (test.result == Result::Fail)
  287. m_counts.tests_failed++;
  288. else if (test.result == Result::Skip)
  289. m_counts.tests_skipped++;
  290. }
  291. }
  292. ++m_counts.files_total;
  293. m_total_elapsed_time_in_ms += value.time_taken;
  294. return value;
  295. }
  296. }
  297. // 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.
  298. // Find a way to cache this.
  299. auto result = parse_script(m_common_path, interpreter->realm());
  300. if (result.is_error()) {
  301. warnln("Unable to parse test-common.js");
  302. warnln("{}", result.error().error.to_string());
  303. warnln("{}", result.error().hint);
  304. cleanup_and_exit();
  305. }
  306. auto test_script = result.release_value();
  307. if (g_run_bytecode) {
  308. auto executable = MUST(JS::Bytecode::Generator::generate(test_script->parse_node()));
  309. executable->name = test_path;
  310. if (JS::Bytecode::g_dump_bytecode)
  311. executable->dump();
  312. JS::Bytecode::Interpreter bytecode_interpreter(interpreter->global_object(), interpreter->realm());
  313. MUST(bytecode_interpreter.run(*executable));
  314. } else {
  315. g_vm->push_execution_context(global_execution_context);
  316. MUST(interpreter->run(*test_script));
  317. g_vm->pop_execution_context();
  318. }
  319. auto file_script = parse_script(test_path, interpreter->realm());
  320. if (file_script.is_error())
  321. return { test_path, file_script.error() };
  322. if (g_run_bytecode) {
  323. auto executable_result = JS::Bytecode::Generator::generate(file_script.value()->parse_node());
  324. if (!executable_result.is_error()) {
  325. auto executable = executable_result.release_value();
  326. executable->name = test_path;
  327. if (JS::Bytecode::g_dump_bytecode)
  328. executable->dump();
  329. JS::Bytecode::Interpreter bytecode_interpreter(interpreter->global_object(), interpreter->realm());
  330. (void)bytecode_interpreter.run(*executable);
  331. }
  332. } else {
  333. g_vm->push_execution_context(global_execution_context);
  334. (void)interpreter->run(file_script.value());
  335. g_vm->pop_execution_context();
  336. }
  337. auto test_json = get_test_results(*interpreter);
  338. if (test_json.is_error()) {
  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 user_output = MUST(interpreter->global_object().get("__UserOutput__"));
  345. auto& arr = user_output.as_array();
  346. for (auto& entry : arr.indexed_properties()) {
  347. auto message = MUST(arr.get(entry.index()));
  348. file_result.logged_messages.append(message.to_string_without_side_effects());
  349. }
  350. test_json.value().as_object().for_each_member([&](String const& suite_name, JsonValue const& suite_value) {
  351. Test::Suite suite { test_path, suite_name };
  352. VERIFY(suite_value.is_object());
  353. suite_value.as_object().for_each_member([&](const String& test_name, const JsonValue& test_value) {
  354. Test::Case test { test_name, Test::Result::Fail, "", 0 };
  355. VERIFY(test_value.is_object());
  356. VERIFY(test_value.as_object().has("result"));
  357. auto result = test_value.as_object().get("result");
  358. VERIFY(result.is_string());
  359. auto result_string = result.as_string();
  360. if (result_string == "pass") {
  361. test.result = Test::Result::Pass;
  362. m_counts.tests_passed++;
  363. } else if (result_string == "fail") {
  364. test.result = Test::Result::Fail;
  365. m_counts.tests_failed++;
  366. suite.most_severe_test_result = Test::Result::Fail;
  367. VERIFY(test_value.as_object().has("details"));
  368. auto details = test_value.as_object().get("details");
  369. VERIFY(result.is_string());
  370. test.details = details.as_string();
  371. } else {
  372. test.result = Test::Result::Skip;
  373. if (suite.most_severe_test_result == Test::Result::Pass)
  374. suite.most_severe_test_result = Test::Result::Skip;
  375. m_counts.tests_skipped++;
  376. }
  377. test.duration_us = test_value.as_object().get("duration").to_u64(0);
  378. suite.tests.append(test);
  379. });
  380. if (suite.most_severe_test_result == Test::Result::Fail) {
  381. m_counts.suites_failed++;
  382. file_result.most_severe_test_result = Test::Result::Fail;
  383. } else {
  384. if (suite.most_severe_test_result == Test::Result::Skip && file_result.most_severe_test_result == Test::Result::Pass)
  385. file_result.most_severe_test_result = Test::Result::Skip;
  386. m_counts.suites_passed++;
  387. }
  388. file_result.suites.append(suite);
  389. });
  390. m_counts.files_total++;
  391. file_result.time_taken = get_time_in_ms() - start_time;
  392. m_total_elapsed_time_in_ms += file_result.time_taken;
  393. return file_result;
  394. }
  395. inline void TestRunner::print_file_result(JSFileResult const& file_result) const
  396. {
  397. if (file_result.most_severe_test_result == Test::Result::Fail || file_result.error.has_value()) {
  398. print_modifiers({ BG_RED, FG_BLACK, FG_BOLD });
  399. out(" FAIL ");
  400. print_modifiers({ CLEAR });
  401. } else {
  402. if (m_print_times || file_result.most_severe_test_result != Test::Result::Pass) {
  403. print_modifiers({ BG_GREEN, FG_BLACK, FG_BOLD });
  404. out(" PASS ");
  405. print_modifiers({ CLEAR });
  406. } else {
  407. return;
  408. }
  409. }
  410. out(" {}", file_result.name);
  411. if (m_print_times) {
  412. print_modifiers({ CLEAR, ITALIC, FG_GRAY });
  413. if (file_result.time_taken < 1000) {
  414. outln(" ({}ms)", static_cast<int>(file_result.time_taken));
  415. } else {
  416. outln(" ({:3}s)", file_result.time_taken / 1000.0);
  417. }
  418. print_modifiers({ CLEAR });
  419. } else {
  420. outln();
  421. }
  422. if (!file_result.logged_messages.is_empty()) {
  423. print_modifiers({ FG_GRAY, FG_BOLD });
  424. #ifdef __serenity__
  425. outln(" ℹ Console output:");
  426. #else
  427. // This emoji has a second invisible byte after it. The one above does not
  428. outln(" ℹ️ Console output:");
  429. #endif
  430. print_modifiers({ CLEAR, FG_GRAY });
  431. for (auto& message : file_result.logged_messages)
  432. outln(" {}", message);
  433. }
  434. if (file_result.error.has_value()) {
  435. auto test_error = file_result.error.value();
  436. print_modifiers({ FG_RED });
  437. #ifdef __serenity__
  438. outln(" ❌ The file failed to parse");
  439. #else
  440. // No invisible byte here, but the spacing still needs to be altered on the host
  441. outln(" ❌ The file failed to parse");
  442. #endif
  443. outln();
  444. print_modifiers({ FG_GRAY });
  445. for (auto& message : test_error.hint.split('\n', true)) {
  446. outln(" {}", message);
  447. }
  448. print_modifiers({ FG_RED });
  449. outln(" {}", test_error.error.to_string());
  450. outln();
  451. return;
  452. }
  453. if (file_result.most_severe_test_result != Test::Result::Pass) {
  454. for (auto& suite : file_result.suites) {
  455. if (suite.most_severe_test_result == Test::Result::Pass)
  456. continue;
  457. bool failed = suite.most_severe_test_result == Test::Result::Fail;
  458. print_modifiers({ FG_GRAY, FG_BOLD });
  459. if (failed) {
  460. #ifdef __serenity__
  461. out(" ❌ Suite: ");
  462. #else
  463. // No invisible byte here, but the spacing still needs to be altered on the host
  464. out(" ❌ Suite: ");
  465. #endif
  466. } else {
  467. #ifdef __serenity__
  468. out(" ⚠ Suite: ");
  469. #else
  470. // This emoji has a second invisible byte after it. The one above does not
  471. out(" ⚠️ Suite: ");
  472. #endif
  473. }
  474. print_modifiers({ CLEAR, FG_GRAY });
  475. if (suite.name == TOP_LEVEL_TEST_NAME) {
  476. outln("<top-level>");
  477. } else {
  478. outln("{}", suite.name);
  479. }
  480. print_modifiers({ CLEAR });
  481. for (auto& test : suite.tests) {
  482. if (test.result == Test::Result::Pass)
  483. continue;
  484. print_modifiers({ FG_GRAY, FG_BOLD });
  485. out(" Test: ");
  486. if (test.result == Test::Result::Fail) {
  487. print_modifiers({ CLEAR, FG_RED });
  488. outln("{} (failed):", test.name);
  489. outln(" {}", test.details);
  490. } else {
  491. print_modifiers({ CLEAR, FG_ORANGE });
  492. outln("{} (skipped)", test.name);
  493. }
  494. print_modifiers({ CLEAR });
  495. }
  496. }
  497. }
  498. }
  499. }