test-js.cpp 24 KB

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