JavaScriptTestRunner.h 21 KB

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