test-js.cpp 25 KB

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