test-js.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. enum class TestResult {
  44. Pass,
  45. Fail,
  46. Skip,
  47. };
  48. struct JSTest {
  49. String name;
  50. TestResult result;
  51. String details;
  52. };
  53. struct JSSuite {
  54. String name;
  55. // A failed test takes precedence over a skipped test, which both have
  56. // precedence over a passed test
  57. TestResult most_severe_test_result { TestResult::Pass };
  58. Vector<JSTest> tests {};
  59. };
  60. struct ParserError {
  61. JS::Parser::Error error;
  62. String hint;
  63. };
  64. struct JSFileResult {
  65. String name;
  66. Optional<ParserError> error {};
  67. double time_taken { 0 };
  68. // A failed test takes precedence over a skipped test, which both have
  69. // precedence over a passed test
  70. TestResult most_severe_test_result { TestResult::Pass };
  71. Vector<JSSuite> suites {};
  72. Vector<String> logged_messages {};
  73. };
  74. struct JSTestRunnerCounts {
  75. int tests_failed { 0 };
  76. int tests_passed { 0 };
  77. int tests_skipped { 0 };
  78. int suites_failed { 0 };
  79. int suites_passed { 0 };
  80. int files_total { 0 };
  81. };
  82. class TestRunnerGlobalObject : public JS::GlobalObject {
  83. public:
  84. TestRunnerGlobalObject();
  85. virtual ~TestRunnerGlobalObject() override;
  86. virtual void initialize() override;
  87. private:
  88. virtual const char* class_name() const override { return "TestRunnerGlobalObject"; }
  89. JS_DECLARE_NATIVE_FUNCTION(is_strict_mode);
  90. };
  91. class TestRunner {
  92. public:
  93. TestRunner(String test_root, bool print_times)
  94. : m_test_root(move(test_root))
  95. , m_print_times(print_times)
  96. {
  97. }
  98. void run();
  99. private:
  100. JSFileResult run_file_test(const String& test_path);
  101. void print_file_result(const JSFileResult& file_result) const;
  102. void print_test_results() const;
  103. String m_test_root;
  104. bool m_print_times;
  105. double m_total_elapsed_time_in_ms { 0 };
  106. JSTestRunnerCounts m_counts;
  107. RefPtr<JS::Program> m_test_program;
  108. };
  109. TestRunnerGlobalObject::TestRunnerGlobalObject()
  110. {
  111. }
  112. TestRunnerGlobalObject::~TestRunnerGlobalObject()
  113. {
  114. }
  115. void TestRunnerGlobalObject::initialize()
  116. {
  117. JS::GlobalObject::initialize();
  118. define_property("global", this, JS::Attribute::Enumerable);
  119. define_native_function("isStrictMode", is_strict_mode);
  120. }
  121. JS_DEFINE_NATIVE_FUNCTION(TestRunnerGlobalObject::is_strict_mode)
  122. {
  123. return JS::Value(interpreter.in_strict_mode());
  124. }
  125. static void cleanup_and_exit()
  126. {
  127. // Clear the taskbar progress.
  128. #ifdef __serenity__
  129. fprintf(stderr, "\033]9;-1;\033\\");
  130. #endif
  131. exit(1);
  132. }
  133. static void handle_sigabrt(int)
  134. {
  135. dbg() << "test-js: SIGABRT received, cleaning up.";
  136. cleanup_and_exit();
  137. }
  138. static double get_time_in_ms()
  139. {
  140. struct timeval tv1;
  141. auto return_code = gettimeofday(&tv1, nullptr);
  142. ASSERT(return_code >= 0);
  143. return static_cast<double>(tv1.tv_sec) * 1000.0 + static_cast<double>(tv1.tv_usec) / 1000.0;
  144. }
  145. template<typename Callback>
  146. static void iterate_directory_recursively(const String& directory_path, Callback callback)
  147. {
  148. Core::DirIterator directory_iterator(directory_path, Core::DirIterator::Flags::SkipDots);
  149. while (directory_iterator.has_next()) {
  150. auto file_path = String::format("%s/%s", directory_path.characters(), directory_iterator.next_path().characters());
  151. if (Core::File::is_directory(file_path)) {
  152. iterate_directory_recursively(file_path, callback);
  153. } else {
  154. callback(move(file_path));
  155. }
  156. }
  157. }
  158. static Vector<String> get_test_paths(const String& test_root)
  159. {
  160. Vector<String> paths;
  161. iterate_directory_recursively(test_root, [&](const String& file_path) {
  162. if (!file_path.ends_with("test-common.js"))
  163. paths.append(file_path);
  164. });
  165. quick_sort(paths);
  166. return paths;
  167. }
  168. void TestRunner::run()
  169. {
  170. size_t progress_counter = 0;
  171. auto test_paths = get_test_paths(m_test_root);
  172. for (auto& path : test_paths) {
  173. ++progress_counter;
  174. print_file_result(run_file_test(path));
  175. #ifdef __serenity__
  176. fprintf(stderr, "\033]9;%zu;%zu;\033\\", progress_counter, test_paths.size());
  177. #endif
  178. }
  179. #ifdef __serenity__
  180. fprintf(stderr, "\033]9;-1;\033\\");
  181. #endif
  182. print_test_results();
  183. }
  184. static Result<NonnullRefPtr<JS::Program>, ParserError> parse_file(const String& file_path)
  185. {
  186. auto file = Core::File::construct(file_path);
  187. auto result = file->open(Core::IODevice::ReadOnly);
  188. if (!result) {
  189. printf("Failed to open the following file: \"%s\"\n", file_path.characters());
  190. cleanup_and_exit();
  191. }
  192. auto contents = file->read_all();
  193. String test_file_string(reinterpret_cast<const char*>(contents.data()), contents.size());
  194. file->close();
  195. auto parser = JS::Parser(JS::Lexer(test_file_string));
  196. auto program = parser.parse_program();
  197. if (parser.has_errors()) {
  198. auto error = parser.errors()[0];
  199. return Result<NonnullRefPtr<JS::Program>, ParserError>(ParserError { error, error.source_location_hint(test_file_string) });
  200. }
  201. return Result<NonnullRefPtr<JS::Program>, ParserError>(program);
  202. }
  203. static Optional<JsonValue> get_test_results(JS::Interpreter& interpreter)
  204. {
  205. auto result = interpreter.get_variable("__TestResults__", interpreter.global_object());
  206. auto json_string = JS::JSONObject::stringify_impl(interpreter, interpreter.global_object(), result, JS::js_undefined(), JS::js_undefined());
  207. auto json = JsonValue::from_string(json_string);
  208. if (!json.has_value())
  209. return {};
  210. return json.value();
  211. }
  212. JSFileResult TestRunner::run_file_test(const String& test_path)
  213. {
  214. double start_time = get_time_in_ms();
  215. auto interpreter = JS::Interpreter::create<TestRunnerGlobalObject>();
  216. if (!m_test_program) {
  217. auto result = parse_file(String::format("%s/test-common.js", m_test_root.characters()));
  218. if (result.is_error()) {
  219. printf("Unable to parse test-common.js\n");
  220. printf("%s\n", result.error().error.to_string().characters());
  221. printf("%s\n", result.error().hint.characters());
  222. cleanup_and_exit();
  223. ;
  224. }
  225. m_test_program = result.value();
  226. }
  227. interpreter->run(interpreter->global_object(), *m_test_program);
  228. auto file_program = parse_file(test_path);
  229. if (file_program.is_error())
  230. return { test_path, file_program.error() };
  231. interpreter->run(interpreter->global_object(), *file_program.value());
  232. auto test_json = get_test_results(*interpreter);
  233. if (!test_json.has_value()) {
  234. printf("Received malformed JSON from test \"%s\"\n", test_path.characters());
  235. cleanup_and_exit();
  236. }
  237. JSFileResult file_result { test_path.substring(m_test_root.length() + 1, test_path.length() - m_test_root.length() - 1) };
  238. // Collect logged messages
  239. auto& arr = interpreter->get_variable("__UserOutput__", interpreter->global_object()).as_array();
  240. for (auto& entry : arr.indexed_properties()) {
  241. auto message = entry.value_and_attributes(&interpreter->global_object()).value;
  242. file_result.logged_messages.append(message.to_string_without_side_effects());
  243. }
  244. test_json.value().as_object().for_each_member([&](const String& suite_name, const JsonValue& suite_value) {
  245. JSSuite suite { suite_name };
  246. ASSERT(suite_value.is_object());
  247. suite_value.as_object().for_each_member([&](const String& test_name, const JsonValue& test_value) {
  248. JSTest test { test_name, TestResult::Fail, "" };
  249. ASSERT(test_value.is_object());
  250. ASSERT(test_value.as_object().has("result"));
  251. auto result = test_value.as_object().get("result");
  252. ASSERT(result.is_string());
  253. auto result_string = result.as_string();
  254. if (result_string == "pass") {
  255. test.result = TestResult::Pass;
  256. m_counts.tests_passed++;
  257. } else if (result_string == "fail") {
  258. test.result = TestResult::Fail;
  259. m_counts.tests_failed++;
  260. suite.most_severe_test_result = TestResult::Fail;
  261. ASSERT(test_value.as_object().has("details"));
  262. auto details = test_value.as_object().get("details");
  263. ASSERT(result.is_string());
  264. test.details = details.as_string();
  265. } else {
  266. test.result = TestResult::Skip;
  267. if (suite.most_severe_test_result == TestResult::Pass)
  268. suite.most_severe_test_result = TestResult::Skip;
  269. m_counts.tests_skipped++;
  270. }
  271. suite.tests.append(test);
  272. });
  273. if (suite.most_severe_test_result == TestResult::Fail) {
  274. m_counts.suites_failed++;
  275. file_result.most_severe_test_result = TestResult::Fail;
  276. } else {
  277. if (suite.most_severe_test_result == TestResult::Skip && file_result.most_severe_test_result == TestResult::Pass)
  278. file_result.most_severe_test_result = TestResult::Skip;
  279. m_counts.suites_passed++;
  280. }
  281. file_result.suites.append(suite);
  282. });
  283. m_counts.files_total++;
  284. file_result.time_taken = get_time_in_ms() - start_time;
  285. m_total_elapsed_time_in_ms += file_result.time_taken;
  286. return file_result;
  287. }
  288. enum Modifier {
  289. BG_RED,
  290. BG_GREEN,
  291. FG_RED,
  292. FG_GREEN,
  293. FG_ORANGE,
  294. FG_GRAY,
  295. FG_BLACK,
  296. FG_BOLD,
  297. ITALIC,
  298. CLEAR,
  299. };
  300. static void print_modifiers(Vector<Modifier> modifiers)
  301. {
  302. for (auto& modifier : modifiers) {
  303. auto code = [&]() -> String {
  304. switch (modifier) {
  305. case BG_RED:
  306. return "\033[48;2;255;0;102m";
  307. case BG_GREEN:
  308. return "\033[48;2;102;255;0m";
  309. case FG_RED:
  310. return "\033[38;2;255;0;102m";
  311. case FG_GREEN:
  312. return "\033[38;2;102;255;0m";
  313. case FG_ORANGE:
  314. return "\033[38;2;255;102;0m";
  315. case FG_GRAY:
  316. return "\033[38;2;135;139;148m";
  317. case FG_BLACK:
  318. return "\033[30m";
  319. case FG_BOLD:
  320. return "\033[1m";
  321. case ITALIC:
  322. return "\033[3m";
  323. case CLEAR:
  324. return "\033[0m";
  325. }
  326. ASSERT_NOT_REACHED();
  327. };
  328. printf("%s", code().characters());
  329. }
  330. }
  331. void TestRunner::print_file_result(const JSFileResult& file_result) const
  332. {
  333. if (file_result.most_severe_test_result == TestResult::Fail || file_result.error.has_value()) {
  334. print_modifiers({ BG_RED, FG_BLACK, FG_BOLD });
  335. printf(" FAIL ");
  336. print_modifiers({ CLEAR });
  337. } else {
  338. if (m_print_times || file_result.most_severe_test_result != TestResult::Pass) {
  339. print_modifiers({ BG_GREEN, FG_BLACK, FG_BOLD });
  340. printf(" PASS ");
  341. print_modifiers({ CLEAR });
  342. } else {
  343. return;
  344. }
  345. }
  346. printf(" %s", file_result.name.characters());
  347. if (m_print_times) {
  348. print_modifiers({ CLEAR, ITALIC, FG_GRAY });
  349. if (file_result.time_taken < 1000) {
  350. printf(" (%dms)\n", static_cast<int>(file_result.time_taken));
  351. } else {
  352. printf(" (%.3fs)\n", file_result.time_taken / 1000.0);
  353. }
  354. print_modifiers({ CLEAR });
  355. } else {
  356. printf("\n");
  357. }
  358. if (!file_result.logged_messages.is_empty()) {
  359. print_modifiers({ FG_GRAY, FG_BOLD });
  360. #ifdef __serenity__
  361. printf(" ℹ Console output:\n");
  362. #else
  363. // This emoji has a second invisible byte after it. The one above does not
  364. printf(" ℹ️ Console output:\n");
  365. #endif
  366. print_modifiers({ CLEAR, FG_GRAY });
  367. for (auto& message : file_result.logged_messages)
  368. printf(" %s\n", message.characters());
  369. }
  370. if (file_result.error.has_value()) {
  371. auto test_error = file_result.error.value();
  372. print_modifiers({ FG_RED });
  373. #ifdef __serenity__
  374. printf(" ❌ The file failed to parse\n\n");
  375. #else
  376. // No invisible byte here, but the spacing still needs to be altered on the host
  377. printf(" ❌ The file failed to parse\n\n");
  378. #endif
  379. print_modifiers({ FG_GRAY });
  380. for (auto& message : test_error.hint.split('\n', true)) {
  381. printf(" %s\n", message.characters());
  382. }
  383. print_modifiers({ FG_RED });
  384. printf(" %s\n\n", test_error.error.to_string().characters());
  385. return;
  386. }
  387. if (file_result.most_severe_test_result != TestResult::Pass) {
  388. for (auto& suite : file_result.suites) {
  389. if (suite.most_severe_test_result == TestResult::Pass)
  390. continue;
  391. bool failed = suite.most_severe_test_result == TestResult::Fail;
  392. print_modifiers({ FG_GRAY, FG_BOLD });
  393. if (failed) {
  394. #ifdef __serenity__
  395. printf(" ❌ Suite: ");
  396. #else
  397. // No invisible byte here, but the spacing still needs to be altered on the host
  398. printf(" ❌ Suite: ");
  399. #endif
  400. } else {
  401. #ifdef __serenity__
  402. printf(" ⚠ Suite: ");
  403. #else
  404. // This emoji has a second invisible byte after it. The one above does not
  405. printf(" ⚠️ Suite: ");
  406. #endif
  407. }
  408. print_modifiers({ CLEAR, FG_GRAY });
  409. if (suite.name == TOP_LEVEL_TEST_NAME) {
  410. printf("<top-level>\n");
  411. } else {
  412. printf("%s\n", suite.name.characters());
  413. }
  414. print_modifiers({ CLEAR });
  415. for (auto& test : suite.tests) {
  416. if (test.result == TestResult::Pass)
  417. continue;
  418. print_modifiers({ FG_GRAY, FG_BOLD });
  419. printf(" Test: ");
  420. if (test.result == TestResult::Fail) {
  421. print_modifiers({ CLEAR, FG_RED });
  422. printf("%s (failed):\n", test.name.characters());
  423. printf(" %s\n", test.details.characters());
  424. } else {
  425. print_modifiers({ CLEAR, FG_ORANGE });
  426. printf("%s (skipped)\n", test.name.characters());
  427. }
  428. print_modifiers({ CLEAR });
  429. }
  430. }
  431. }
  432. }
  433. void TestRunner::print_test_results() const
  434. {
  435. printf("\nTest Suites: ");
  436. if (m_counts.suites_failed) {
  437. print_modifiers({ FG_RED });
  438. printf("%d failed, ", m_counts.suites_failed);
  439. print_modifiers({ CLEAR });
  440. }
  441. if (m_counts.suites_passed) {
  442. print_modifiers({ FG_GREEN });
  443. printf("%d passed, ", m_counts.suites_passed);
  444. print_modifiers({ CLEAR });
  445. }
  446. printf("%d total\n", m_counts.suites_failed + m_counts.suites_passed);
  447. printf("Tests: ");
  448. if (m_counts.tests_failed) {
  449. print_modifiers({ FG_RED });
  450. printf("%d failed, ", m_counts.tests_failed);
  451. print_modifiers({ CLEAR });
  452. }
  453. if (m_counts.tests_skipped) {
  454. print_modifiers({ FG_ORANGE });
  455. printf("%d skipped, ", m_counts.tests_skipped);
  456. print_modifiers({ CLEAR });
  457. }
  458. if (m_counts.tests_passed) {
  459. print_modifiers({ FG_GREEN });
  460. printf("%d passed, ", m_counts.tests_passed);
  461. print_modifiers({ CLEAR });
  462. }
  463. printf("%d total\n", m_counts.tests_failed + m_counts.tests_passed);
  464. printf("Files: %d total\n", m_counts.files_total);
  465. printf("Time: ");
  466. if (m_total_elapsed_time_in_ms < 1000.0) {
  467. printf("%dms\n\n", static_cast<int>(m_total_elapsed_time_in_ms));
  468. } else {
  469. printf("%-.3fs\n\n", m_total_elapsed_time_in_ms / 1000.0);
  470. }
  471. }
  472. int main(int argc, char** argv)
  473. {
  474. bool print_times = false;
  475. struct sigaction act;
  476. memset(&act, 0, sizeof(act));
  477. act.sa_flags = SA_NOCLDWAIT;
  478. act.sa_handler = handle_sigabrt;
  479. int rc = sigaction(SIGABRT, &act, nullptr);
  480. if (rc < 0) {
  481. perror("sigaction");
  482. return 1;
  483. }
  484. Core::ArgsParser args_parser;
  485. args_parser.add_option(print_times, "Show duration of each test", "show-time", 't');
  486. args_parser.parse(argc, argv);
  487. #ifdef __serenity__
  488. TestRunner("/home/anon/js-tests", print_times).run();
  489. #else
  490. char* serenity_root = getenv("SERENITY_ROOT");
  491. if (!serenity_root) {
  492. printf("test-js requires the SERENITY_ROOT environment variable to be set");
  493. return 1;
  494. }
  495. TestRunner(String::format("%s/Libraries/LibJS/Tests", serenity_root), print_times).run();
  496. #endif
  497. return 0;
  498. }