JavaScriptTestRunner.h 20 KB

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