JavaScriptTestRunner.h 21 KB

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