JavaScriptTestRunner.h 21 KB

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