JavaScriptTestRunner.h 22 KB

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