test-js.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <matthewcolsson@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/JsonObject.h>
  27. #include <AK/JsonValue.h>
  28. #include <AK/LogStream.h>
  29. #include <AK/QuickSort.h>
  30. #include <LibCore/ArgsParser.h>
  31. #include <LibCore/DirIterator.h>
  32. #include <LibCore/File.h>
  33. #include <LibJS/Interpreter.h>
  34. #include <LibJS/Lexer.h>
  35. #include <LibJS/Parser.h>
  36. #include <LibJS/Runtime/Array.h>
  37. #include <LibJS/Runtime/GlobalObject.h>
  38. #include <LibJS/Runtime/JSONObject.h>
  39. #include <signal.h>
  40. #include <stdlib.h>
  41. #include <sys/time.h>
  42. #define TOP_LEVEL_TEST_NAME "__$$TOP_LEVEL$$__"
  43. RefPtr<JS::VM> vm;
  44. static bool collect_on_every_allocation = false;
  45. static String currently_running_test;
  46. enum class TestResult {
  47. Pass,
  48. Fail,
  49. Skip,
  50. };
  51. struct JSTest {
  52. String name;
  53. TestResult result;
  54. String details;
  55. };
  56. struct JSSuite {
  57. String name;
  58. // A failed test takes precedence over a skipped test, which both have
  59. // precedence over a passed test
  60. TestResult most_severe_test_result { TestResult::Pass };
  61. Vector<JSTest> tests {};
  62. };
  63. struct ParserError {
  64. JS::Parser::Error error;
  65. String hint;
  66. };
  67. struct JSFileResult {
  68. String name;
  69. Optional<ParserError> error {};
  70. double time_taken { 0 };
  71. // A failed test takes precedence over a skipped test, which both have
  72. // precedence over a passed test
  73. TestResult most_severe_test_result { TestResult::Pass };
  74. Vector<JSSuite> suites {};
  75. Vector<String> logged_messages {};
  76. };
  77. struct JSTestRunnerCounts {
  78. int tests_failed { 0 };
  79. int tests_passed { 0 };
  80. int tests_skipped { 0 };
  81. int suites_failed { 0 };
  82. int suites_passed { 0 };
  83. int files_total { 0 };
  84. };
  85. class TestRunnerGlobalObject : public JS::GlobalObject {
  86. public:
  87. TestRunnerGlobalObject();
  88. virtual ~TestRunnerGlobalObject() override;
  89. virtual void initialize() override;
  90. private:
  91. virtual const char* class_name() const override { return "TestRunnerGlobalObject"; }
  92. JS_DECLARE_NATIVE_FUNCTION(is_strict_mode);
  93. };
  94. class TestRunner {
  95. public:
  96. static TestRunner* the()
  97. {
  98. return s_the;
  99. }
  100. TestRunner(String test_root, bool print_times)
  101. : m_test_root(move(test_root))
  102. , m_print_times(print_times)
  103. {
  104. ASSERT(!s_the);
  105. s_the = this;
  106. }
  107. void run();
  108. const JSTestRunnerCounts& counts() const { return m_counts; }
  109. private:
  110. static TestRunner* s_the;
  111. JSFileResult run_file_test(const String& test_path);
  112. void print_file_result(const JSFileResult& file_result) const;
  113. void print_test_results() const;
  114. String m_test_root;
  115. bool m_print_times;
  116. double m_total_elapsed_time_in_ms { 0 };
  117. JSTestRunnerCounts m_counts;
  118. RefPtr<JS::Program> m_test_program;
  119. };
  120. TestRunner* TestRunner::s_the = nullptr;
  121. TestRunnerGlobalObject::TestRunnerGlobalObject()
  122. {
  123. }
  124. TestRunnerGlobalObject::~TestRunnerGlobalObject()
  125. {
  126. }
  127. void TestRunnerGlobalObject::initialize()
  128. {
  129. JS::GlobalObject::initialize();
  130. define_property("global", this, JS::Attribute::Enumerable);
  131. define_native_function("isStrictMode", is_strict_mode);
  132. }
  133. JS_DEFINE_NATIVE_FUNCTION(TestRunnerGlobalObject::is_strict_mode)
  134. {
  135. return JS::Value(vm.in_strict_mode());
  136. }
  137. static void cleanup_and_exit()
  138. {
  139. // Clear the taskbar progress.
  140. #ifdef __serenity__
  141. fprintf(stderr, "\033]9;-1;\033\\");
  142. #endif
  143. exit(1);
  144. }
  145. static void handle_sigabrt(int)
  146. {
  147. dbg() << "test-js: SIGABRT received, cleaning up.";
  148. cleanup_and_exit();
  149. }
  150. static double get_time_in_ms()
  151. {
  152. struct timeval tv1;
  153. auto return_code = gettimeofday(&tv1, nullptr);
  154. ASSERT(return_code >= 0);
  155. return static_cast<double>(tv1.tv_sec) * 1000.0 + static_cast<double>(tv1.tv_usec) / 1000.0;
  156. }
  157. template<typename Callback>
  158. static void iterate_directory_recursively(const String& directory_path, Callback callback)
  159. {
  160. Core::DirIterator directory_iterator(directory_path, Core::DirIterator::Flags::SkipDots);
  161. while (directory_iterator.has_next()) {
  162. auto file_path = String::format("%s/%s", directory_path.characters(), directory_iterator.next_path().characters());
  163. if (Core::File::is_directory(file_path)) {
  164. iterate_directory_recursively(file_path, callback);
  165. } else {
  166. callback(move(file_path));
  167. }
  168. }
  169. }
  170. static Vector<String> get_test_paths(const String& test_root)
  171. {
  172. Vector<String> paths;
  173. iterate_directory_recursively(test_root, [&](const String& file_path) {
  174. if (!file_path.ends_with("test-common.js"))
  175. paths.append(file_path);
  176. });
  177. quick_sort(paths);
  178. return paths;
  179. }
  180. void TestRunner::run()
  181. {
  182. size_t progress_counter = 0;
  183. auto test_paths = get_test_paths(m_test_root);
  184. for (auto& path : test_paths) {
  185. ++progress_counter;
  186. print_file_result(run_file_test(path));
  187. #ifdef __serenity__
  188. fprintf(stderr, "\033]9;%zu;%zu;\033\\", progress_counter, test_paths.size());
  189. #endif
  190. }
  191. #ifdef __serenity__
  192. fprintf(stderr, "\033]9;-1;\033\\");
  193. #endif
  194. print_test_results();
  195. }
  196. static Result<NonnullRefPtr<JS::Program>, ParserError> parse_file(const String& file_path)
  197. {
  198. auto file = Core::File::construct(file_path);
  199. auto result = file->open(Core::IODevice::ReadOnly);
  200. if (!result) {
  201. printf("Failed to open the following file: \"%s\"\n", file_path.characters());
  202. cleanup_and_exit();
  203. }
  204. auto contents = file->read_all();
  205. String test_file_string(reinterpret_cast<const char*>(contents.data()), contents.size());
  206. file->close();
  207. auto parser = JS::Parser(JS::Lexer(test_file_string));
  208. auto program = parser.parse_program();
  209. if (parser.has_errors()) {
  210. auto error = parser.errors()[0];
  211. return Result<NonnullRefPtr<JS::Program>, ParserError>(ParserError { error, error.source_location_hint(test_file_string) });
  212. }
  213. return Result<NonnullRefPtr<JS::Program>, ParserError>(program);
  214. }
  215. static Optional<JsonValue> get_test_results(JS::Interpreter& interpreter)
  216. {
  217. auto result = vm->get_variable("__TestResults__", interpreter.global_object());
  218. auto json_string = JS::JSONObject::stringify_impl(interpreter.global_object(), result, JS::js_undefined(), JS::js_undefined());
  219. auto json = JsonValue::from_string(json_string);
  220. if (!json.has_value())
  221. return {};
  222. return json.value();
  223. }
  224. JSFileResult TestRunner::run_file_test(const String& test_path)
  225. {
  226. currently_running_test = test_path;
  227. double start_time = get_time_in_ms();
  228. auto interpreter = JS::Interpreter::create<TestRunnerGlobalObject>(*vm);
  229. // FIXME: This is a hack while we're refactoring Interpreter/VM stuff.
  230. JS::VM::InterpreterExecutionScope scope(*interpreter);
  231. interpreter->heap().set_should_collect_on_every_allocation(collect_on_every_allocation);
  232. if (!m_test_program) {
  233. auto result = parse_file(String::format("%s/test-common.js", m_test_root.characters()));
  234. if (result.is_error()) {
  235. printf("Unable to parse test-common.js\n");
  236. printf("%s\n", result.error().error.to_string().characters());
  237. printf("%s\n", result.error().hint.characters());
  238. cleanup_and_exit();
  239. ;
  240. }
  241. m_test_program = result.value();
  242. }
  243. interpreter->run(interpreter->global_object(), *m_test_program);
  244. auto file_program = parse_file(test_path);
  245. if (file_program.is_error())
  246. return { test_path, file_program.error() };
  247. interpreter->run(interpreter->global_object(), *file_program.value());
  248. auto test_json = get_test_results(*interpreter);
  249. if (!test_json.has_value()) {
  250. printf("Received malformed JSON from test \"%s\"\n", test_path.characters());
  251. cleanup_and_exit();
  252. }
  253. JSFileResult file_result { test_path.substring(m_test_root.length() + 1, test_path.length() - m_test_root.length() - 1) };
  254. // Collect logged messages
  255. auto& arr = interpreter->vm().get_variable("__UserOutput__", interpreter->global_object()).as_array();
  256. for (auto& entry : arr.indexed_properties()) {
  257. auto message = entry.value_and_attributes(&interpreter->global_object()).value;
  258. file_result.logged_messages.append(message.to_string_without_side_effects());
  259. }
  260. test_json.value().as_object().for_each_member([&](const String& suite_name, const JsonValue& suite_value) {
  261. JSSuite suite { suite_name };
  262. ASSERT(suite_value.is_object());
  263. suite_value.as_object().for_each_member([&](const String& test_name, const JsonValue& test_value) {
  264. JSTest test { test_name, TestResult::Fail, "" };
  265. ASSERT(test_value.is_object());
  266. ASSERT(test_value.as_object().has("result"));
  267. auto result = test_value.as_object().get("result");
  268. ASSERT(result.is_string());
  269. auto result_string = result.as_string();
  270. if (result_string == "pass") {
  271. test.result = TestResult::Pass;
  272. m_counts.tests_passed++;
  273. } else if (result_string == "fail") {
  274. test.result = TestResult::Fail;
  275. m_counts.tests_failed++;
  276. suite.most_severe_test_result = TestResult::Fail;
  277. ASSERT(test_value.as_object().has("details"));
  278. auto details = test_value.as_object().get("details");
  279. ASSERT(result.is_string());
  280. test.details = details.as_string();
  281. } else {
  282. test.result = TestResult::Skip;
  283. if (suite.most_severe_test_result == TestResult::Pass)
  284. suite.most_severe_test_result = TestResult::Skip;
  285. m_counts.tests_skipped++;
  286. }
  287. suite.tests.append(test);
  288. });
  289. if (suite.most_severe_test_result == TestResult::Fail) {
  290. m_counts.suites_failed++;
  291. file_result.most_severe_test_result = TestResult::Fail;
  292. } else {
  293. if (suite.most_severe_test_result == TestResult::Skip && file_result.most_severe_test_result == TestResult::Pass)
  294. file_result.most_severe_test_result = TestResult::Skip;
  295. m_counts.suites_passed++;
  296. }
  297. file_result.suites.append(suite);
  298. });
  299. m_counts.files_total++;
  300. file_result.time_taken = get_time_in_ms() - start_time;
  301. m_total_elapsed_time_in_ms += file_result.time_taken;
  302. return file_result;
  303. }
  304. enum Modifier {
  305. BG_RED,
  306. BG_GREEN,
  307. FG_RED,
  308. FG_GREEN,
  309. FG_ORANGE,
  310. FG_GRAY,
  311. FG_BLACK,
  312. FG_BOLD,
  313. ITALIC,
  314. CLEAR,
  315. };
  316. static void print_modifiers(Vector<Modifier> modifiers)
  317. {
  318. for (auto& modifier : modifiers) {
  319. auto code = [&]() -> String {
  320. switch (modifier) {
  321. case BG_RED:
  322. return "\033[48;2;255;0;102m";
  323. case BG_GREEN:
  324. return "\033[48;2;102;255;0m";
  325. case FG_RED:
  326. return "\033[38;2;255;0;102m";
  327. case FG_GREEN:
  328. return "\033[38;2;102;255;0m";
  329. case FG_ORANGE:
  330. return "\033[38;2;255;102;0m";
  331. case FG_GRAY:
  332. return "\033[38;2;135;139;148m";
  333. case FG_BLACK:
  334. return "\033[30m";
  335. case FG_BOLD:
  336. return "\033[1m";
  337. case ITALIC:
  338. return "\033[3m";
  339. case CLEAR:
  340. return "\033[0m";
  341. }
  342. ASSERT_NOT_REACHED();
  343. };
  344. printf("%s", code().characters());
  345. }
  346. }
  347. void TestRunner::print_file_result(const JSFileResult& file_result) const
  348. {
  349. if (file_result.most_severe_test_result == TestResult::Fail || file_result.error.has_value()) {
  350. print_modifiers({ BG_RED, FG_BLACK, FG_BOLD });
  351. printf(" FAIL ");
  352. print_modifiers({ CLEAR });
  353. } else {
  354. if (m_print_times || file_result.most_severe_test_result != TestResult::Pass) {
  355. print_modifiers({ BG_GREEN, FG_BLACK, FG_BOLD });
  356. printf(" PASS ");
  357. print_modifiers({ CLEAR });
  358. } else {
  359. return;
  360. }
  361. }
  362. printf(" %s", file_result.name.characters());
  363. if (m_print_times) {
  364. print_modifiers({ CLEAR, ITALIC, FG_GRAY });
  365. if (file_result.time_taken < 1000) {
  366. printf(" (%dms)\n", static_cast<int>(file_result.time_taken));
  367. } else {
  368. printf(" (%.3fs)\n", file_result.time_taken / 1000.0);
  369. }
  370. print_modifiers({ CLEAR });
  371. } else {
  372. printf("\n");
  373. }
  374. if (!file_result.logged_messages.is_empty()) {
  375. print_modifiers({ FG_GRAY, FG_BOLD });
  376. #ifdef __serenity__
  377. printf(" ℹ Console output:\n");
  378. #else
  379. // This emoji has a second invisible byte after it. The one above does not
  380. printf(" ℹ️ Console output:\n");
  381. #endif
  382. print_modifiers({ CLEAR, FG_GRAY });
  383. for (auto& message : file_result.logged_messages)
  384. printf(" %s\n", message.characters());
  385. }
  386. if (file_result.error.has_value()) {
  387. auto test_error = file_result.error.value();
  388. print_modifiers({ FG_RED });
  389. #ifdef __serenity__
  390. printf(" ❌ The file failed to parse\n\n");
  391. #else
  392. // No invisible byte here, but the spacing still needs to be altered on the host
  393. printf(" ❌ The file failed to parse\n\n");
  394. #endif
  395. print_modifiers({ FG_GRAY });
  396. for (auto& message : test_error.hint.split('\n', true)) {
  397. printf(" %s\n", message.characters());
  398. }
  399. print_modifiers({ FG_RED });
  400. printf(" %s\n\n", test_error.error.to_string().characters());
  401. return;
  402. }
  403. if (file_result.most_severe_test_result != TestResult::Pass) {
  404. for (auto& suite : file_result.suites) {
  405. if (suite.most_severe_test_result == TestResult::Pass)
  406. continue;
  407. bool failed = suite.most_severe_test_result == TestResult::Fail;
  408. print_modifiers({ FG_GRAY, FG_BOLD });
  409. if (failed) {
  410. #ifdef __serenity__
  411. printf(" ❌ Suite: ");
  412. #else
  413. // No invisible byte here, but the spacing still needs to be altered on the host
  414. printf(" ❌ Suite: ");
  415. #endif
  416. } else {
  417. #ifdef __serenity__
  418. printf(" ⚠ Suite: ");
  419. #else
  420. // This emoji has a second invisible byte after it. The one above does not
  421. printf(" ⚠️ Suite: ");
  422. #endif
  423. }
  424. print_modifiers({ CLEAR, FG_GRAY });
  425. if (suite.name == TOP_LEVEL_TEST_NAME) {
  426. printf("<top-level>\n");
  427. } else {
  428. printf("%s\n", suite.name.characters());
  429. }
  430. print_modifiers({ CLEAR });
  431. for (auto& test : suite.tests) {
  432. if (test.result == TestResult::Pass)
  433. continue;
  434. print_modifiers({ FG_GRAY, FG_BOLD });
  435. printf(" Test: ");
  436. if (test.result == TestResult::Fail) {
  437. print_modifiers({ CLEAR, FG_RED });
  438. printf("%s (failed):\n", test.name.characters());
  439. printf(" %s\n", test.details.characters());
  440. } else {
  441. print_modifiers({ CLEAR, FG_ORANGE });
  442. printf("%s (skipped)\n", test.name.characters());
  443. }
  444. print_modifiers({ CLEAR });
  445. }
  446. }
  447. }
  448. }
  449. void TestRunner::print_test_results() const
  450. {
  451. printf("\nTest Suites: ");
  452. if (m_counts.suites_failed) {
  453. print_modifiers({ FG_RED });
  454. printf("%d failed, ", m_counts.suites_failed);
  455. print_modifiers({ CLEAR });
  456. }
  457. if (m_counts.suites_passed) {
  458. print_modifiers({ FG_GREEN });
  459. printf("%d passed, ", m_counts.suites_passed);
  460. print_modifiers({ CLEAR });
  461. }
  462. printf("%d total\n", m_counts.suites_failed + m_counts.suites_passed);
  463. printf("Tests: ");
  464. if (m_counts.tests_failed) {
  465. print_modifiers({ FG_RED });
  466. printf("%d failed, ", m_counts.tests_failed);
  467. print_modifiers({ CLEAR });
  468. }
  469. if (m_counts.tests_skipped) {
  470. print_modifiers({ FG_ORANGE });
  471. printf("%d skipped, ", m_counts.tests_skipped);
  472. print_modifiers({ CLEAR });
  473. }
  474. if (m_counts.tests_passed) {
  475. print_modifiers({ FG_GREEN });
  476. printf("%d passed, ", m_counts.tests_passed);
  477. print_modifiers({ CLEAR });
  478. }
  479. printf("%d total\n", m_counts.tests_failed + m_counts.tests_passed);
  480. printf("Files: %d total\n", m_counts.files_total);
  481. printf("Time: ");
  482. if (m_total_elapsed_time_in_ms < 1000.0) {
  483. printf("%dms\n\n", static_cast<int>(m_total_elapsed_time_in_ms));
  484. } else {
  485. printf("%-.3fs\n\n", m_total_elapsed_time_in_ms / 1000.0);
  486. }
  487. }
  488. int main(int argc, char** argv)
  489. {
  490. bool print_times = false;
  491. struct sigaction act;
  492. memset(&act, 0, sizeof(act));
  493. act.sa_flags = SA_NOCLDWAIT;
  494. act.sa_handler = handle_sigabrt;
  495. int rc = sigaction(SIGABRT, &act, nullptr);
  496. if (rc < 0) {
  497. perror("sigaction");
  498. return 1;
  499. }
  500. #ifdef SIGINFO
  501. signal(SIGINFO, [](int) {
  502. static char buffer[4096];
  503. auto& counts = TestRunner::the()->counts();
  504. 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());
  505. write(STDOUT_FILENO, buffer, len);
  506. });
  507. #endif
  508. Core::ArgsParser args_parser;
  509. args_parser.add_option(print_times, "Show duration of each test", "show-time", 't');
  510. args_parser.add_option(collect_on_every_allocation, "Collect garbage after every allocation", "collect-often", 'g');
  511. args_parser.parse(argc, argv);
  512. if (getenv("DISABLE_DBG_OUTPUT")) {
  513. DebugLogStream::set_enabled(false);
  514. }
  515. vm = JS::VM::create();
  516. #ifdef __serenity__
  517. TestRunner("/home/anon/js-tests", print_times).run();
  518. #else
  519. char* serenity_root = getenv("SERENITY_ROOT");
  520. if (!serenity_root) {
  521. printf("test-js requires the SERENITY_ROOT environment variable to be set");
  522. return 1;
  523. }
  524. TestRunner(String::format("%s/Libraries/LibJS/Tests", serenity_root), print_times).run();
  525. #endif
  526. vm = nullptr;
  527. return 0;
  528. }