test-js.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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/JsonObject.h>
  28. #include <AK/JsonValue.h>
  29. #include <AK/LexicalPath.h>
  30. #include <AK/LogStream.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 <signal.h>
  42. #include <stdlib.h>
  43. #include <sys/time.h>
  44. #define TOP_LEVEL_TEST_NAME "__$$TOP_LEVEL$$__"
  45. RefPtr<JS::VM> vm;
  46. static bool collect_on_every_allocation = false;
  47. static String currently_running_test;
  48. enum class TestResult {
  49. Pass,
  50. Fail,
  51. Skip,
  52. };
  53. struct JSTest {
  54. String name;
  55. TestResult result;
  56. String details;
  57. };
  58. struct JSSuite {
  59. String name;
  60. // A failed test takes precedence over a skipped test, which both have
  61. // precedence over a passed test
  62. TestResult most_severe_test_result { TestResult::Pass };
  63. Vector<JSTest> tests {};
  64. };
  65. struct ParserError {
  66. JS::Parser::Error error;
  67. String hint;
  68. };
  69. struct JSFileResult {
  70. String name;
  71. Optional<ParserError> error {};
  72. double time_taken { 0 };
  73. // A failed test takes precedence over a skipped test, which both have
  74. // precedence over a passed test
  75. TestResult most_severe_test_result { TestResult::Pass };
  76. Vector<JSSuite> suites {};
  77. Vector<String> logged_messages {};
  78. };
  79. struct JSTestRunnerCounts {
  80. int tests_failed { 0 };
  81. int tests_passed { 0 };
  82. int tests_skipped { 0 };
  83. int suites_failed { 0 };
  84. int suites_passed { 0 };
  85. int files_total { 0 };
  86. };
  87. class TestRunnerGlobalObject : public JS::GlobalObject {
  88. public:
  89. TestRunnerGlobalObject();
  90. virtual ~TestRunnerGlobalObject() override;
  91. virtual void initialize() override;
  92. private:
  93. virtual const char* class_name() const override { return "TestRunnerGlobalObject"; }
  94. JS_DECLARE_NATIVE_FUNCTION(is_strict_mode);
  95. };
  96. class TestRunner {
  97. public:
  98. static TestRunner* the()
  99. {
  100. return s_the;
  101. }
  102. TestRunner(String test_root, bool print_times)
  103. : m_test_root(move(test_root))
  104. , m_print_times(print_times)
  105. {
  106. ASSERT(!s_the);
  107. s_the = this;
  108. }
  109. void run();
  110. const JSTestRunnerCounts& counts() const { return m_counts; }
  111. protected:
  112. static TestRunner* s_the;
  113. virtual Vector<String> get_test_paths() const;
  114. virtual JSFileResult run_file_test(const String& test_path);
  115. void print_file_result(const JSFileResult& file_result) const;
  116. void print_test_results() const;
  117. String m_test_root;
  118. bool m_print_times;
  119. double m_total_elapsed_time_in_ms { 0 };
  120. JSTestRunnerCounts m_counts;
  121. RefPtr<JS::Program> m_test_program;
  122. };
  123. TestRunner* TestRunner::s_the = nullptr;
  124. TestRunnerGlobalObject::TestRunnerGlobalObject()
  125. {
  126. }
  127. TestRunnerGlobalObject::~TestRunnerGlobalObject()
  128. {
  129. }
  130. void TestRunnerGlobalObject::initialize()
  131. {
  132. JS::GlobalObject::initialize();
  133. static FlyString global_property_name { "global" };
  134. static FlyString is_strict_mode_property_name { "isStrictMode" };
  135. define_property(global_property_name, this, JS::Attribute::Enumerable);
  136. define_native_function(is_strict_mode_property_name, is_strict_mode);
  137. }
  138. JS_DEFINE_NATIVE_FUNCTION(TestRunnerGlobalObject::is_strict_mode)
  139. {
  140. return JS::Value(vm.in_strict_mode());
  141. }
  142. static void cleanup_and_exit()
  143. {
  144. // Clear the taskbar progress.
  145. #ifdef __serenity__
  146. fprintf(stderr, "\033]9;-1;\033\\");
  147. #endif
  148. exit(1);
  149. }
  150. static void handle_sigabrt(int)
  151. {
  152. dbg() << "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. ASSERT(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::format("%s/%s", directory_path.characters(), directory_iterator.next_path().characters());
  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. #ifdef __serenity__
  193. fprintf(stderr, "\033]9;%zu;%zu;\033\\", progress_counter, test_paths.size());
  194. #endif
  195. }
  196. #ifdef __serenity__
  197. fprintf(stderr, "\033]9;-1;\033\\");
  198. #endif
  199. print_test_results();
  200. }
  201. static Result<NonnullRefPtr<JS::Program>, ParserError> parse_file(const String& file_path)
  202. {
  203. auto file = Core::File::construct(file_path);
  204. auto result = file->open(Core::IODevice::ReadOnly);
  205. if (!result) {
  206. printf("Failed to open the following file: \"%s\"\n", file_path.characters());
  207. cleanup_and_exit();
  208. }
  209. auto contents = file->read_all();
  210. String test_file_string(reinterpret_cast<const char*>(contents.data()), contents.size());
  211. file->close();
  212. auto parser = JS::Parser(JS::Lexer(test_file_string));
  213. auto program = parser.parse_program();
  214. if (parser.has_errors()) {
  215. auto error = parser.errors()[0];
  216. return Result<NonnullRefPtr<JS::Program>, ParserError>(ParserError { error, error.source_location_hint(test_file_string) });
  217. }
  218. return Result<NonnullRefPtr<JS::Program>, ParserError>(program);
  219. }
  220. static Optional<JsonValue> get_test_results(JS::Interpreter& interpreter)
  221. {
  222. auto result = vm->get_variable("__TestResults__", interpreter.global_object());
  223. auto json_string = JS::JSONObject::stringify_impl(interpreter.global_object(), result, JS::js_undefined(), JS::js_undefined());
  224. auto json = JsonValue::from_string(json_string);
  225. if (!json.has_value())
  226. return {};
  227. return json.value();
  228. }
  229. JSFileResult TestRunner::run_file_test(const String& test_path)
  230. {
  231. currently_running_test = test_path;
  232. double start_time = get_time_in_ms();
  233. auto interpreter = JS::Interpreter::create<TestRunnerGlobalObject>(*vm);
  234. // FIXME: This is a hack while we're refactoring Interpreter/VM stuff.
  235. JS::VM::InterpreterExecutionScope scope(*interpreter);
  236. interpreter->heap().set_should_collect_on_every_allocation(collect_on_every_allocation);
  237. if (!m_test_program) {
  238. auto result = parse_file(String::format("%s/test-common.js", m_test_root.characters()));
  239. if (result.is_error()) {
  240. printf("Unable to parse test-common.js\n");
  241. printf("%s\n", result.error().error.to_string().characters());
  242. printf("%s\n", result.error().hint.characters());
  243. cleanup_and_exit();
  244. }
  245. m_test_program = result.value();
  246. }
  247. interpreter->run(interpreter->global_object(), *m_test_program);
  248. auto file_program = parse_file(test_path);
  249. if (file_program.is_error())
  250. return { test_path, file_program.error() };
  251. interpreter->run(interpreter->global_object(), *file_program.value());
  252. auto test_json = get_test_results(*interpreter);
  253. if (!test_json.has_value()) {
  254. printf("Received malformed JSON from test \"%s\"\n", test_path.characters());
  255. cleanup_and_exit();
  256. }
  257. JSFileResult file_result { test_path.substring(m_test_root.length() + 1, test_path.length() - m_test_root.length() - 1) };
  258. // Collect logged messages
  259. auto& arr = interpreter->vm().get_variable("__UserOutput__", interpreter->global_object()).as_array();
  260. for (auto& entry : arr.indexed_properties()) {
  261. auto message = entry.value_and_attributes(&interpreter->global_object()).value;
  262. file_result.logged_messages.append(message.to_string_without_side_effects());
  263. }
  264. test_json.value().as_object().for_each_member([&](const String& suite_name, const JsonValue& suite_value) {
  265. JSSuite suite { suite_name };
  266. ASSERT(suite_value.is_object());
  267. suite_value.as_object().for_each_member([&](const String& test_name, const JsonValue& test_value) {
  268. JSTest test { test_name, TestResult::Fail, "" };
  269. ASSERT(test_value.is_object());
  270. ASSERT(test_value.as_object().has("result"));
  271. auto result = test_value.as_object().get("result");
  272. ASSERT(result.is_string());
  273. auto result_string = result.as_string();
  274. if (result_string == "pass") {
  275. test.result = TestResult::Pass;
  276. m_counts.tests_passed++;
  277. } else if (result_string == "fail") {
  278. test.result = TestResult::Fail;
  279. m_counts.tests_failed++;
  280. suite.most_severe_test_result = TestResult::Fail;
  281. ASSERT(test_value.as_object().has("details"));
  282. auto details = test_value.as_object().get("details");
  283. ASSERT(result.is_string());
  284. test.details = details.as_string();
  285. } else {
  286. test.result = TestResult::Skip;
  287. if (suite.most_severe_test_result == TestResult::Pass)
  288. suite.most_severe_test_result = TestResult::Skip;
  289. m_counts.tests_skipped++;
  290. }
  291. suite.tests.append(test);
  292. });
  293. if (suite.most_severe_test_result == TestResult::Fail) {
  294. m_counts.suites_failed++;
  295. file_result.most_severe_test_result = TestResult::Fail;
  296. } else {
  297. if (suite.most_severe_test_result == TestResult::Skip && file_result.most_severe_test_result == TestResult::Pass)
  298. file_result.most_severe_test_result = TestResult::Skip;
  299. m_counts.suites_passed++;
  300. }
  301. file_result.suites.append(suite);
  302. });
  303. m_counts.files_total++;
  304. file_result.time_taken = get_time_in_ms() - start_time;
  305. m_total_elapsed_time_in_ms += file_result.time_taken;
  306. return file_result;
  307. }
  308. enum Modifier {
  309. BG_RED,
  310. BG_GREEN,
  311. FG_RED,
  312. FG_GREEN,
  313. FG_ORANGE,
  314. FG_GRAY,
  315. FG_BLACK,
  316. FG_BOLD,
  317. ITALIC,
  318. CLEAR,
  319. };
  320. static void print_modifiers(Vector<Modifier> modifiers)
  321. {
  322. for (auto& modifier : modifiers) {
  323. auto code = [&]() -> String {
  324. switch (modifier) {
  325. case BG_RED:
  326. return "\033[48;2;255;0;102m";
  327. case BG_GREEN:
  328. return "\033[48;2;102;255;0m";
  329. case FG_RED:
  330. return "\033[38;2;255;0;102m";
  331. case FG_GREEN:
  332. return "\033[38;2;102;255;0m";
  333. case FG_ORANGE:
  334. return "\033[38;2;255;102;0m";
  335. case FG_GRAY:
  336. return "\033[38;2;135;139;148m";
  337. case FG_BLACK:
  338. return "\033[30m";
  339. case FG_BOLD:
  340. return "\033[1m";
  341. case ITALIC:
  342. return "\033[3m";
  343. case CLEAR:
  344. return "\033[0m";
  345. }
  346. ASSERT_NOT_REACHED();
  347. };
  348. printf("%s", code().characters());
  349. }
  350. }
  351. void TestRunner::print_file_result(const JSFileResult& file_result) const
  352. {
  353. if (file_result.most_severe_test_result == TestResult::Fail || file_result.error.has_value()) {
  354. print_modifiers({ BG_RED, FG_BLACK, FG_BOLD });
  355. printf(" FAIL ");
  356. print_modifiers({ CLEAR });
  357. } else {
  358. if (m_print_times || file_result.most_severe_test_result != TestResult::Pass) {
  359. print_modifiers({ BG_GREEN, FG_BLACK, FG_BOLD });
  360. printf(" PASS ");
  361. print_modifiers({ CLEAR });
  362. } else {
  363. return;
  364. }
  365. }
  366. printf(" %s", file_result.name.characters());
  367. if (m_print_times) {
  368. print_modifiers({ CLEAR, ITALIC, FG_GRAY });
  369. if (file_result.time_taken < 1000) {
  370. printf(" (%dms)\n", static_cast<int>(file_result.time_taken));
  371. } else {
  372. printf(" (%.3fs)\n", file_result.time_taken / 1000.0);
  373. }
  374. print_modifiers({ CLEAR });
  375. } else {
  376. printf("\n");
  377. }
  378. if (!file_result.logged_messages.is_empty()) {
  379. print_modifiers({ FG_GRAY, FG_BOLD });
  380. #ifdef __serenity__
  381. printf(" ℹ Console output:\n");
  382. #else
  383. // This emoji has a second invisible byte after it. The one above does not
  384. printf(" ℹ️ Console output:\n");
  385. #endif
  386. print_modifiers({ CLEAR, FG_GRAY });
  387. for (auto& message : file_result.logged_messages)
  388. printf(" %s\n", message.characters());
  389. }
  390. if (file_result.error.has_value()) {
  391. auto test_error = file_result.error.value();
  392. print_modifiers({ FG_RED });
  393. #ifdef __serenity__
  394. printf(" ❌ The file failed to parse\n\n");
  395. #else
  396. // No invisible byte here, but the spacing still needs to be altered on the host
  397. printf(" ❌ The file failed to parse\n\n");
  398. #endif
  399. print_modifiers({ FG_GRAY });
  400. for (auto& message : test_error.hint.split('\n', true)) {
  401. printf(" %s\n", message.characters());
  402. }
  403. print_modifiers({ FG_RED });
  404. printf(" %s\n\n", test_error.error.to_string().characters());
  405. return;
  406. }
  407. if (file_result.most_severe_test_result != TestResult::Pass) {
  408. for (auto& suite : file_result.suites) {
  409. if (suite.most_severe_test_result == TestResult::Pass)
  410. continue;
  411. bool failed = suite.most_severe_test_result == TestResult::Fail;
  412. print_modifiers({ FG_GRAY, FG_BOLD });
  413. if (failed) {
  414. #ifdef __serenity__
  415. printf(" ❌ Suite: ");
  416. #else
  417. // No invisible byte here, but the spacing still needs to be altered on the host
  418. printf(" ❌ Suite: ");
  419. #endif
  420. } else {
  421. #ifdef __serenity__
  422. printf(" ⚠ Suite: ");
  423. #else
  424. // This emoji has a second invisible byte after it. The one above does not
  425. printf(" ⚠️ Suite: ");
  426. #endif
  427. }
  428. print_modifiers({ CLEAR, FG_GRAY });
  429. if (suite.name == TOP_LEVEL_TEST_NAME) {
  430. printf("<top-level>\n");
  431. } else {
  432. printf("%s\n", suite.name.characters());
  433. }
  434. print_modifiers({ CLEAR });
  435. for (auto& test : suite.tests) {
  436. if (test.result == TestResult::Pass)
  437. continue;
  438. print_modifiers({ FG_GRAY, FG_BOLD });
  439. printf(" Test: ");
  440. if (test.result == TestResult::Fail) {
  441. print_modifiers({ CLEAR, FG_RED });
  442. printf("%s (failed):\n", test.name.characters());
  443. printf(" %s\n", test.details.characters());
  444. } else {
  445. print_modifiers({ CLEAR, FG_ORANGE });
  446. printf("%s (skipped)\n", test.name.characters());
  447. }
  448. print_modifiers({ CLEAR });
  449. }
  450. }
  451. }
  452. }
  453. void TestRunner::print_test_results() const
  454. {
  455. printf("\nTest Suites: ");
  456. if (m_counts.suites_failed) {
  457. print_modifiers({ FG_RED });
  458. printf("%d failed, ", m_counts.suites_failed);
  459. print_modifiers({ CLEAR });
  460. }
  461. if (m_counts.suites_passed) {
  462. print_modifiers({ FG_GREEN });
  463. printf("%d passed, ", m_counts.suites_passed);
  464. print_modifiers({ CLEAR });
  465. }
  466. printf("%d total\n", m_counts.suites_failed + m_counts.suites_passed);
  467. printf("Tests: ");
  468. if (m_counts.tests_failed) {
  469. print_modifiers({ FG_RED });
  470. printf("%d failed, ", m_counts.tests_failed);
  471. print_modifiers({ CLEAR });
  472. }
  473. if (m_counts.tests_skipped) {
  474. print_modifiers({ FG_ORANGE });
  475. printf("%d skipped, ", m_counts.tests_skipped);
  476. print_modifiers({ CLEAR });
  477. }
  478. if (m_counts.tests_passed) {
  479. print_modifiers({ FG_GREEN });
  480. printf("%d passed, ", m_counts.tests_passed);
  481. print_modifiers({ CLEAR });
  482. }
  483. printf("%d total\n", m_counts.tests_failed + m_counts.tests_skipped + m_counts.tests_passed);
  484. printf("Files: %d total\n", m_counts.files_total);
  485. printf("Time: ");
  486. if (m_total_elapsed_time_in_ms < 1000.0) {
  487. printf("%dms\n\n", static_cast<int>(m_total_elapsed_time_in_ms));
  488. } else {
  489. printf("%-.3fs\n\n", m_total_elapsed_time_in_ms / 1000.0);
  490. }
  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. ASSERT_NOT_REACHED();
  521. }
  522. auto start_time = get_time_in_ms();
  523. String details = "";
  524. TestResult test_result;
  525. if (test_path.ends_with(".module.js")) {
  526. test_result = TestResult::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 = TestResult::Pass;
  534. } else {
  535. test_result = TestResult::Fail;
  536. details = parse_result.error().error.to_string();
  537. }
  538. } else {
  539. if (parse_result.is_error()) {
  540. test_result = TestResult::Pass;
  541. } else {
  542. test_result = TestResult::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. JSTest test { expecting_file_to_parse ? "file should parse" : "file should not parse", test_result, details };
  554. JSSuite 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 == TestResult::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 test262_parser_tests = false;
  594. const char* test_root = nullptr;
  595. Core::ArgsParser args_parser;
  596. args_parser.add_option(print_times, "Show duration of each test", "show-time", 't');
  597. args_parser.add_option(collect_on_every_allocation, "Collect garbage after every allocation", "collect-often", 'g');
  598. args_parser.add_option(test262_parser_tests, "Run test262 parser tests", "test262-parser-tests", 0);
  599. args_parser.add_positional_argument(test_root, "Tests root directory", "path", Core::ArgsParser::Required::No);
  600. args_parser.parse(argc, argv);
  601. if (test262_parser_tests) {
  602. if (collect_on_every_allocation) {
  603. fprintf(stderr, "--collect-often and --test262-parser-tests options must not be used together\n");
  604. return 1;
  605. }
  606. if (!test_root) {
  607. fprintf(stderr, "Test root is required with --test262-parser-tests\n");
  608. return 1;
  609. }
  610. }
  611. if (getenv("DISABLE_DBG_OUTPUT")) {
  612. DebugLogStream::set_enabled(false);
  613. }
  614. if (!test_root) {
  615. #ifdef __serenity__
  616. test_root = "/home/anon/js-tests";
  617. #else
  618. char* serenity_root = getenv("SERENITY_ROOT");
  619. if (!serenity_root) {
  620. printf("No test root given, test-js requires the SERENITY_ROOT environment variable to be set");
  621. return 1;
  622. }
  623. test_root = String::formatted("{}/Libraries/LibJS/Tests", serenity_root).characters();
  624. #endif
  625. }
  626. if (!Core::File::is_directory(test_root)) {
  627. fprintf(stderr, "Test root is not a directory: %s\n", test_root);
  628. return 1;
  629. }
  630. vm = JS::VM::create();
  631. if (test262_parser_tests)
  632. Test262ParserTestRunner(test_root, print_times).run();
  633. else
  634. TestRunner(test_root, print_times).run();
  635. vm = nullptr;
  636. return TestRunner::the()->counts().tests_failed > 0 ? 1 : 0;
  637. }