JavaScriptTestRunner.h 21 KB

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