test-js.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <matthewcolsson@gmail.com>
  3. * Copyright (c) 2020-2021, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/JsonObject.h>
  29. #include <AK/JsonValue.h>
  30. #include <AK/LexicalPath.h>
  31. #include <AK/QuickSort.h>
  32. #include <LibCore/ArgsParser.h>
  33. #include <LibCore/DirIterator.h>
  34. #include <LibCore/File.h>
  35. #include <LibJS/Interpreter.h>
  36. #include <LibJS/Lexer.h>
  37. #include <LibJS/Parser.h>
  38. #include <LibJS/Runtime/Array.h>
  39. #include <LibJS/Runtime/GlobalObject.h>
  40. #include <LibJS/Runtime/JSONObject.h>
  41. #include <LibTest/Results.h>
  42. #include <signal.h>
  43. #include <stdlib.h>
  44. #include <sys/time.h>
  45. #include <unistd.h>
  46. #define TOP_LEVEL_TEST_NAME "__$$TOP_LEVEL$$__"
  47. RefPtr<JS::VM> vm;
  48. static bool collect_on_every_allocation = false;
  49. static String currently_running_test;
  50. struct ParserError {
  51. JS::Parser::Error error;
  52. String hint;
  53. };
  54. struct JSFileResult {
  55. String name;
  56. Optional<ParserError> error {};
  57. double time_taken { 0 };
  58. // A failed test takes precedence over a skipped test, which both have
  59. // precedence over a passed test
  60. Test::Result most_severe_test_result { Test::Result::Pass };
  61. Vector<Test::Suite> suites {};
  62. Vector<String> logged_messages {};
  63. };
  64. class TestRunnerGlobalObject final : public JS::GlobalObject {
  65. JS_OBJECT(TestRunnerGlobalObject, JS::GlobalObject);
  66. public:
  67. TestRunnerGlobalObject();
  68. virtual ~TestRunnerGlobalObject() override;
  69. virtual void initialize_global_object() override;
  70. private:
  71. JS_DECLARE_NATIVE_FUNCTION(is_strict_mode);
  72. JS_DECLARE_NATIVE_FUNCTION(can_parse_source);
  73. JS_DECLARE_NATIVE_FUNCTION(run_queued_promise_jobs);
  74. };
  75. class TestRunner {
  76. public:
  77. static TestRunner* the()
  78. {
  79. return s_the;
  80. }
  81. TestRunner(String test_root, bool print_times, bool print_progress)
  82. : m_test_root(move(test_root))
  83. , m_print_times(print_times)
  84. , m_print_progress(print_progress)
  85. {
  86. VERIFY(!s_the);
  87. s_the = this;
  88. }
  89. virtual ~TestRunner() = default;
  90. void run();
  91. const Test::Counts& counts() const { return m_counts; }
  92. bool is_printing_progress() const { return m_print_progress; }
  93. protected:
  94. static TestRunner* s_the;
  95. virtual Vector<String> get_test_paths() const;
  96. virtual JSFileResult run_file_test(const String& test_path);
  97. void print_file_result(const JSFileResult& file_result) const;
  98. void print_test_results() const;
  99. String m_test_root;
  100. bool m_print_times;
  101. bool m_print_progress;
  102. double m_total_elapsed_time_in_ms { 0 };
  103. Test::Counts m_counts;
  104. RefPtr<JS::Program> m_test_program;
  105. };
  106. TestRunner* TestRunner::s_the = nullptr;
  107. TestRunnerGlobalObject::TestRunnerGlobalObject()
  108. {
  109. }
  110. TestRunnerGlobalObject::~TestRunnerGlobalObject()
  111. {
  112. }
  113. void TestRunnerGlobalObject::initialize_global_object()
  114. {
  115. Base::initialize_global_object();
  116. static FlyString global_property_name { "global" };
  117. static FlyString is_strict_mode_property_name { "isStrictMode" };
  118. static FlyString can_parse_source_property_name { "canParseSource" };
  119. static FlyString run_queued_promise_jobs_property_name { "runQueuedPromiseJobs" };
  120. define_property(global_property_name, this, JS::Attribute::Enumerable);
  121. define_native_function(is_strict_mode_property_name, is_strict_mode);
  122. define_native_function(can_parse_source_property_name, can_parse_source);
  123. define_native_function(run_queued_promise_jobs_property_name, run_queued_promise_jobs);
  124. }
  125. JS_DEFINE_NATIVE_FUNCTION(TestRunnerGlobalObject::is_strict_mode)
  126. {
  127. return JS::Value(vm.in_strict_mode());
  128. }
  129. JS_DEFINE_NATIVE_FUNCTION(TestRunnerGlobalObject::can_parse_source)
  130. {
  131. auto source = vm.argument(0).to_string(global_object);
  132. if (vm.exception())
  133. return {};
  134. auto parser = JS::Parser(JS::Lexer(source));
  135. parser.parse_program();
  136. return JS::Value(!parser.has_errors());
  137. }
  138. JS_DEFINE_NATIVE_FUNCTION(TestRunnerGlobalObject::run_queued_promise_jobs)
  139. {
  140. vm.run_queued_promise_jobs();
  141. return JS::js_undefined();
  142. }
  143. static void cleanup_and_exit()
  144. {
  145. // Clear the taskbar progress.
  146. if (TestRunner::the() && TestRunner::the()->is_printing_progress())
  147. warn("\033]9;-1;\033\\");
  148. exit(1);
  149. }
  150. static void handle_sigabrt(int)
  151. {
  152. dbgln("test-js: SIGABRT received, cleaning up.");
  153. cleanup_and_exit();
  154. }
  155. static double get_time_in_ms()
  156. {
  157. struct timeval tv1;
  158. auto return_code = gettimeofday(&tv1, nullptr);
  159. VERIFY(return_code >= 0);
  160. return static_cast<double>(tv1.tv_sec) * 1000.0 + static_cast<double>(tv1.tv_usec) / 1000.0;
  161. }
  162. template<typename Callback>
  163. static void iterate_directory_recursively(const String& directory_path, Callback callback)
  164. {
  165. Core::DirIterator directory_iterator(directory_path, Core::DirIterator::Flags::SkipDots);
  166. while (directory_iterator.has_next()) {
  167. auto file_path = String::formatted("{}/{}", directory_path, directory_iterator.next_path());
  168. if (Core::File::is_directory(file_path)) {
  169. iterate_directory_recursively(file_path, callback);
  170. } else {
  171. callback(move(file_path));
  172. }
  173. }
  174. }
  175. Vector<String> TestRunner::get_test_paths() const
  176. {
  177. Vector<String> paths;
  178. iterate_directory_recursively(m_test_root, [&](const String& file_path) {
  179. if (!file_path.ends_with("test-common.js"))
  180. paths.append(file_path);
  181. });
  182. quick_sort(paths);
  183. return paths;
  184. }
  185. void TestRunner::run()
  186. {
  187. size_t progress_counter = 0;
  188. auto test_paths = get_test_paths();
  189. for (auto& path : test_paths) {
  190. ++progress_counter;
  191. print_file_result(run_file_test(path));
  192. if (m_print_progress)
  193. warn("\033]9;{};{};\033\\", progress_counter, test_paths.size());
  194. }
  195. if (m_print_progress)
  196. warn("\033]9;-1;\033\\");
  197. print_test_results();
  198. }
  199. static Result<NonnullRefPtr<JS::Program>, ParserError> parse_file(const String& file_path)
  200. {
  201. auto file = Core::File::construct(file_path);
  202. auto result = file->open(Core::IODevice::ReadOnly);
  203. if (!result) {
  204. warnln("Failed to open the following file: \"{}\"", file_path);
  205. cleanup_and_exit();
  206. }
  207. auto contents = file->read_all();
  208. String test_file_string(reinterpret_cast<const char*>(contents.data()), contents.size());
  209. file->close();
  210. auto parser = JS::Parser(JS::Lexer(test_file_string));
  211. auto program = parser.parse_program();
  212. if (parser.has_errors()) {
  213. auto error = parser.errors()[0];
  214. return Result<NonnullRefPtr<JS::Program>, ParserError>(ParserError { error, error.source_location_hint(test_file_string) });
  215. }
  216. return Result<NonnullRefPtr<JS::Program>, ParserError>(program);
  217. }
  218. static Optional<JsonValue> get_test_results(JS::Interpreter& interpreter)
  219. {
  220. auto result = vm->get_variable("__TestResults__", interpreter.global_object());
  221. auto json_string = JS::JSONObject::stringify_impl(interpreter.global_object(), result, JS::js_undefined(), JS::js_undefined());
  222. auto json = JsonValue::from_string(json_string);
  223. if (!json.has_value())
  224. return {};
  225. return json.value();
  226. }
  227. JSFileResult TestRunner::run_file_test(const String& test_path)
  228. {
  229. currently_running_test = test_path;
  230. double start_time = get_time_in_ms();
  231. auto interpreter = JS::Interpreter::create<TestRunnerGlobalObject>(*vm);
  232. // FIXME: This is a hack while we're refactoring Interpreter/VM stuff.
  233. JS::VM::InterpreterExecutionScope scope(*interpreter);
  234. interpreter->heap().set_should_collect_on_every_allocation(collect_on_every_allocation);
  235. if (!m_test_program) {
  236. auto result = parse_file(String::formatted("{}/test-common.js", m_test_root));
  237. if (result.is_error()) {
  238. warnln("Unable to parse test-common.js");
  239. warnln("{}", result.error().error.to_string());
  240. warnln("{}", result.error().hint);
  241. cleanup_and_exit();
  242. }
  243. m_test_program = result.value();
  244. }
  245. interpreter->run(interpreter->global_object(), *m_test_program);
  246. auto file_program = parse_file(test_path);
  247. if (file_program.is_error())
  248. return { test_path, file_program.error() };
  249. interpreter->run(interpreter->global_object(), *file_program.value());
  250. auto test_json = get_test_results(*interpreter);
  251. if (!test_json.has_value()) {
  252. warnln("Received malformed JSON from test \"{}\"", test_path);
  253. cleanup_and_exit();
  254. }
  255. JSFileResult file_result { test_path.substring(m_test_root.length() + 1, test_path.length() - m_test_root.length() - 1) };
  256. // Collect logged messages
  257. auto& arr = interpreter->vm().get_variable("__UserOutput__", interpreter->global_object()).as_array();
  258. for (auto& entry : arr.indexed_properties()) {
  259. auto message = entry.value_and_attributes(&interpreter->global_object()).value;
  260. file_result.logged_messages.append(message.to_string_without_side_effects());
  261. }
  262. test_json.value().as_object().for_each_member([&](const String& suite_name, const JsonValue& suite_value) {
  263. Test::Suite suite { suite_name };
  264. VERIFY(suite_value.is_object());
  265. suite_value.as_object().for_each_member([&](const String& test_name, const JsonValue& test_value) {
  266. Test::Case test { test_name, Test::Result::Fail, "" };
  267. VERIFY(test_value.is_object());
  268. VERIFY(test_value.as_object().has("result"));
  269. auto result = test_value.as_object().get("result");
  270. VERIFY(result.is_string());
  271. auto result_string = result.as_string();
  272. if (result_string == "pass") {
  273. test.result = Test::Result::Pass;
  274. m_counts.tests_passed++;
  275. } else if (result_string == "fail") {
  276. test.result = Test::Result::Fail;
  277. m_counts.tests_failed++;
  278. suite.most_severe_test_result = Test::Result::Fail;
  279. VERIFY(test_value.as_object().has("details"));
  280. auto details = test_value.as_object().get("details");
  281. VERIFY(result.is_string());
  282. test.details = details.as_string();
  283. } else {
  284. test.result = Test::Result::Skip;
  285. if (suite.most_severe_test_result == Test::Result::Pass)
  286. suite.most_severe_test_result = Test::Result::Skip;
  287. m_counts.tests_skipped++;
  288. }
  289. suite.tests.append(test);
  290. });
  291. if (suite.most_severe_test_result == Test::Result::Fail) {
  292. m_counts.suites_failed++;
  293. file_result.most_severe_test_result = Test::Result::Fail;
  294. } else {
  295. if (suite.most_severe_test_result == Test::Result::Skip && file_result.most_severe_test_result == Test::Result::Pass)
  296. file_result.most_severe_test_result = Test::Result::Skip;
  297. m_counts.suites_passed++;
  298. }
  299. file_result.suites.append(suite);
  300. });
  301. m_counts.files_total++;
  302. file_result.time_taken = get_time_in_ms() - start_time;
  303. m_total_elapsed_time_in_ms += file_result.time_taken;
  304. return file_result;
  305. }
  306. enum Modifier {
  307. BG_RED,
  308. BG_GREEN,
  309. FG_RED,
  310. FG_GREEN,
  311. FG_ORANGE,
  312. FG_GRAY,
  313. FG_BLACK,
  314. FG_BOLD,
  315. ITALIC,
  316. CLEAR,
  317. };
  318. static void print_modifiers(Vector<Modifier> modifiers)
  319. {
  320. for (auto& modifier : modifiers) {
  321. auto code = [&] {
  322. switch (modifier) {
  323. case BG_RED:
  324. return "\033[48;2;255;0;102m";
  325. case BG_GREEN:
  326. return "\033[48;2;102;255;0m";
  327. case FG_RED:
  328. return "\033[38;2;255;0;102m";
  329. case FG_GREEN:
  330. return "\033[38;2;102;255;0m";
  331. case FG_ORANGE:
  332. return "\033[38;2;255;102;0m";
  333. case FG_GRAY:
  334. return "\033[38;2;135;139;148m";
  335. case FG_BLACK:
  336. return "\033[30m";
  337. case FG_BOLD:
  338. return "\033[1m";
  339. case ITALIC:
  340. return "\033[3m";
  341. case CLEAR:
  342. return "\033[0m";
  343. }
  344. VERIFY_NOT_REACHED();
  345. }();
  346. out("{}", code);
  347. }
  348. }
  349. void TestRunner::print_file_result(const JSFileResult& file_result) const
  350. {
  351. if (file_result.most_severe_test_result == Test::Result::Fail || file_result.error.has_value()) {
  352. print_modifiers({ BG_RED, FG_BLACK, FG_BOLD });
  353. out(" FAIL ");
  354. print_modifiers({ CLEAR });
  355. } else {
  356. if (m_print_times || file_result.most_severe_test_result != Test::Result::Pass) {
  357. print_modifiers({ BG_GREEN, FG_BLACK, FG_BOLD });
  358. out(" PASS ");
  359. print_modifiers({ CLEAR });
  360. } else {
  361. return;
  362. }
  363. }
  364. out(" {}", file_result.name);
  365. if (m_print_times) {
  366. print_modifiers({ CLEAR, ITALIC, FG_GRAY });
  367. if (file_result.time_taken < 1000) {
  368. outln(" ({}ms)", static_cast<int>(file_result.time_taken));
  369. } else {
  370. outln(" ({:3}s)", file_result.time_taken / 1000.0);
  371. }
  372. print_modifiers({ CLEAR });
  373. } else {
  374. outln();
  375. }
  376. if (!file_result.logged_messages.is_empty()) {
  377. print_modifiers({ FG_GRAY, FG_BOLD });
  378. #ifdef __serenity__
  379. outln(" ℹ Console output:");
  380. #else
  381. // This emoji has a second invisible byte after it. The one above does not
  382. outln(" ℹ️ Console output:");
  383. #endif
  384. print_modifiers({ CLEAR, FG_GRAY });
  385. for (auto& message : file_result.logged_messages)
  386. outln(" {}", message);
  387. }
  388. if (file_result.error.has_value()) {
  389. auto test_error = file_result.error.value();
  390. print_modifiers({ FG_RED });
  391. #ifdef __serenity__
  392. outln(" ❌ The file failed to parse");
  393. #else
  394. // No invisible byte here, but the spacing still needs to be altered on the host
  395. outln(" ❌ The file failed to parse");
  396. #endif
  397. outln();
  398. print_modifiers({ FG_GRAY });
  399. for (auto& message : test_error.hint.split('\n', true)) {
  400. outln(" {}", message);
  401. }
  402. print_modifiers({ FG_RED });
  403. outln(" {}", test_error.error.to_string());
  404. outln();
  405. return;
  406. }
  407. if (file_result.most_severe_test_result != Test::Result::Pass) {
  408. for (auto& suite : file_result.suites) {
  409. if (suite.most_severe_test_result == Test::Result::Pass)
  410. continue;
  411. bool failed = suite.most_severe_test_result == Test::Result::Fail;
  412. print_modifiers({ FG_GRAY, FG_BOLD });
  413. if (failed) {
  414. #ifdef __serenity__
  415. out(" ❌ Suite: ");
  416. #else
  417. // No invisible byte here, but the spacing still needs to be altered on the host
  418. out(" ❌ Suite: ");
  419. #endif
  420. } else {
  421. #ifdef __serenity__
  422. out(" ⚠ Suite: ");
  423. #else
  424. // This emoji has a second invisible byte after it. The one above does not
  425. out(" ⚠️ Suite: ");
  426. #endif
  427. }
  428. print_modifiers({ CLEAR, FG_GRAY });
  429. if (suite.name == TOP_LEVEL_TEST_NAME) {
  430. outln("<top-level>");
  431. } else {
  432. outln("{}", suite.name);
  433. }
  434. print_modifiers({ CLEAR });
  435. for (auto& test : suite.tests) {
  436. if (test.result == Test::Result::Pass)
  437. continue;
  438. print_modifiers({ FG_GRAY, FG_BOLD });
  439. out(" Test: ");
  440. if (test.result == Test::Result::Fail) {
  441. print_modifiers({ CLEAR, FG_RED });
  442. outln("{} (failed):", test.name);
  443. outln(" {}", test.details);
  444. } else {
  445. print_modifiers({ CLEAR, FG_ORANGE });
  446. outln("{} (skipped)", test.name);
  447. }
  448. print_modifiers({ CLEAR });
  449. }
  450. }
  451. }
  452. }
  453. void TestRunner::print_test_results() const
  454. {
  455. out("\nTest Suites: ");
  456. if (m_counts.suites_failed) {
  457. print_modifiers({ FG_RED });
  458. out("{} failed, ", m_counts.suites_failed);
  459. print_modifiers({ CLEAR });
  460. }
  461. if (m_counts.suites_passed) {
  462. print_modifiers({ FG_GREEN });
  463. out("{} passed, ", m_counts.suites_passed);
  464. print_modifiers({ CLEAR });
  465. }
  466. outln("{} total", m_counts.suites_failed + m_counts.suites_passed);
  467. out("Tests: ");
  468. if (m_counts.tests_failed) {
  469. print_modifiers({ FG_RED });
  470. out("{} failed, ", m_counts.tests_failed);
  471. print_modifiers({ CLEAR });
  472. }
  473. if (m_counts.tests_skipped) {
  474. print_modifiers({ FG_ORANGE });
  475. out("{} skipped, ", m_counts.tests_skipped);
  476. print_modifiers({ CLEAR });
  477. }
  478. if (m_counts.tests_passed) {
  479. print_modifiers({ FG_GREEN });
  480. out("{} passed, ", m_counts.tests_passed);
  481. print_modifiers({ CLEAR });
  482. }
  483. outln("{} total", m_counts.tests_failed + m_counts.tests_skipped + m_counts.tests_passed);
  484. outln("Files: {} total", m_counts.files_total);
  485. out("Time: ");
  486. if (m_total_elapsed_time_in_ms < 1000.0) {
  487. outln("{}ms", static_cast<int>(m_total_elapsed_time_in_ms));
  488. } else {
  489. outln("{:>.3}s", m_total_elapsed_time_in_ms / 1000.0);
  490. }
  491. outln();
  492. }
  493. class Test262ParserTestRunner final : public TestRunner {
  494. public:
  495. using TestRunner::TestRunner;
  496. private:
  497. virtual Vector<String> get_test_paths() const override;
  498. virtual JSFileResult run_file_test(const String& test_path) override;
  499. };
  500. Vector<String> Test262ParserTestRunner::get_test_paths() const
  501. {
  502. Vector<String> paths;
  503. iterate_directory_recursively(m_test_root, [&](const String& file_path) {
  504. auto dirname = LexicalPath(file_path).dirname();
  505. if (dirname.ends_with("early") || dirname.ends_with("fail") || dirname.ends_with("pass") || dirname.ends_with("pass-explicit"))
  506. paths.append(file_path);
  507. });
  508. quick_sort(paths);
  509. return paths;
  510. }
  511. JSFileResult Test262ParserTestRunner::run_file_test(const String& test_path)
  512. {
  513. currently_running_test = test_path;
  514. auto dirname = LexicalPath(test_path).dirname();
  515. bool expecting_file_to_parse;
  516. if (dirname.ends_with("early") || dirname.ends_with("fail")) {
  517. expecting_file_to_parse = false;
  518. } else if (dirname.ends_with("pass") || dirname.ends_with("pass-explicit")) {
  519. expecting_file_to_parse = true;
  520. } else {
  521. VERIFY_NOT_REACHED();
  522. }
  523. auto start_time = get_time_in_ms();
  524. String details = "";
  525. Test::Result test_result;
  526. if (test_path.ends_with(".module.js")) {
  527. test_result = Test::Result::Skip;
  528. m_counts.tests_skipped++;
  529. m_counts.suites_passed++;
  530. } else {
  531. auto parse_result = parse_file(test_path);
  532. if (expecting_file_to_parse) {
  533. if (!parse_result.is_error()) {
  534. test_result = Test::Result::Pass;
  535. } else {
  536. test_result = Test::Result::Fail;
  537. details = parse_result.error().error.to_string();
  538. }
  539. } else {
  540. if (parse_result.is_error()) {
  541. test_result = Test::Result::Pass;
  542. } else {
  543. test_result = Test::Result::Fail;
  544. details = "File was expected to produce a parser error but didn't";
  545. }
  546. }
  547. }
  548. // test262-parser-tests doesn't have "suites" and "tests" in the usual sense, it just has files
  549. // and an expectation whether they should parse or not. We add one suite with one test nonetheless:
  550. //
  551. // - This makes interpreting skipped test easier as their file is shown as "PASS"
  552. // - That way we can show additional information such as "file parsed but shouldn't have" or
  553. // parser errors for files that should parse respectively
  554. Test::Case test { expecting_file_to_parse ? "file should parse" : "file should not parse", test_result, details };
  555. Test::Suite suite { "Parse file", test_result, { test } };
  556. JSFileResult file_result {
  557. test_path.substring(m_test_root.length() + 1, test_path.length() - m_test_root.length() - 1),
  558. {},
  559. get_time_in_ms() - start_time,
  560. test_result,
  561. { suite }
  562. };
  563. if (test_result == Test::Result::Fail) {
  564. m_counts.tests_failed++;
  565. m_counts.suites_failed++;
  566. } else {
  567. m_counts.tests_passed++;
  568. m_counts.suites_passed++;
  569. }
  570. m_counts.files_total++;
  571. m_total_elapsed_time_in_ms += file_result.time_taken;
  572. return file_result;
  573. }
  574. int main(int argc, char** argv)
  575. {
  576. struct sigaction act;
  577. memset(&act, 0, sizeof(act));
  578. act.sa_flags = SA_NOCLDWAIT;
  579. act.sa_handler = handle_sigabrt;
  580. int rc = sigaction(SIGABRT, &act, nullptr);
  581. if (rc < 0) {
  582. perror("sigaction");
  583. return 1;
  584. }
  585. #ifdef SIGINFO
  586. signal(SIGINFO, [](int) {
  587. static char buffer[4096];
  588. auto& counts = TestRunner::the()->counts();
  589. int len = snprintf(buffer, sizeof(buffer), "Pass: %d, Fail: %d, Skip: %d\nCurrent test: %s\n", counts.tests_passed, counts.tests_failed, counts.tests_skipped, currently_running_test.characters());
  590. write(STDOUT_FILENO, buffer, len);
  591. });
  592. #endif
  593. bool print_times = false;
  594. bool print_progress =
  595. #ifdef __serenity__
  596. true; // Use OSC 9 to print progress
  597. #else
  598. false;
  599. #endif
  600. bool test262_parser_tests = false;
  601. const char* specified_test_root = nullptr;
  602. Core::ArgsParser args_parser;
  603. args_parser.add_option(print_times, "Show duration of each test", "show-time", 't');
  604. args_parser.add_option(Core::ArgsParser::Option {
  605. .requires_argument = true,
  606. .help_string = "Show progress with OSC 9 (true, false)",
  607. .long_name = "show-progress",
  608. .short_name = 'p',
  609. .accept_value = [&](auto* str) {
  610. if (StringView { "true" } == str)
  611. print_progress = true;
  612. else if (StringView { "false" } == str)
  613. print_progress = false;
  614. else
  615. return false;
  616. return true;
  617. },
  618. });
  619. args_parser.add_option(collect_on_every_allocation, "Collect garbage after every allocation", "collect-often", 'g');
  620. args_parser.add_option(test262_parser_tests, "Run test262 parser tests", "test262-parser-tests", 0);
  621. args_parser.add_positional_argument(specified_test_root, "Tests root directory", "path", Core::ArgsParser::Required::No);
  622. args_parser.parse(argc, argv);
  623. if (test262_parser_tests) {
  624. if (collect_on_every_allocation) {
  625. warnln("--collect-often and --test262-parser-tests options must not be used together");
  626. return 1;
  627. }
  628. if (!specified_test_root) {
  629. warnln("Test root is required with --test262-parser-tests");
  630. return 1;
  631. }
  632. }
  633. if (getenv("DISABLE_DBG_OUTPUT")) {
  634. AK::set_debug_enabled(false);
  635. }
  636. String test_root;
  637. if (specified_test_root) {
  638. test_root = String { specified_test_root };
  639. } else {
  640. #ifdef __serenity__
  641. test_root = "/home/anon/js-tests";
  642. #else
  643. char* serenity_source_dir = getenv("SERENITY_SOURCE_DIR");
  644. if (!serenity_source_dir) {
  645. warnln("No test root given, test-js requires the SERENITY_SOURCE_DIR environment variable to be set");
  646. return 1;
  647. }
  648. test_root = String::formatted("{}/Userland/Libraries/LibJS/Tests", serenity_source_dir);
  649. #endif
  650. }
  651. if (!Core::File::is_directory(test_root)) {
  652. warnln("Test root is not a directory: {}", test_root);
  653. return 1;
  654. }
  655. vm = JS::VM::create();
  656. if (test262_parser_tests)
  657. Test262ParserTestRunner(test_root, print_times, print_progress).run();
  658. else
  659. TestRunner(test_root, print_times, print_progress).run();
  660. vm = nullptr;
  661. return TestRunner::the()->counts().tests_failed > 0 ? 1 : 0;
  662. }