JavaScriptTestRunner.h 22 KB

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