test-js.cpp 17 KB

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