test-js.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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/JsonValue.h>
  27. #include <AK/JsonObject.h>
  28. #include <AK/LogStream.h>
  29. #include <LibCore/File.h>
  30. #include <LibJS/Interpreter.h>
  31. #include <LibJS/Lexer.h>
  32. #include <LibJS/Parser.h>
  33. #include <LibJS/Runtime/Array.h>
  34. #include <LibJS/Runtime/GlobalObject.h>
  35. #include <LibJS/Runtime/JSONObject.h>
  36. #include <LibJS/Runtime/MarkedValueList.h>
  37. #include <sys/time.h>
  38. #include <stdlib.h>
  39. #define TOP_LEVEL_TEST_NAME "__$$TOP_LEVEL$$__"
  40. // FIXME: Will eventually not be necessary when all tests are converted
  41. Vector<String> tests_to_run = {
  42. "builtins/Boolean/Boolean.js",
  43. "builtins/Boolean/Boolean.prototype.js",
  44. "builtins/Boolean/Boolean.prototype.toString.js",
  45. "builtins/Boolean/Boolean.prototype.valueOf.js",
  46. "builtins/Date/Date.js",
  47. "builtins/Date/Date.now.js",
  48. "builtins/Date/Date.prototype.getDate.js",
  49. "builtins/Date/Date.prototype.getDay.js",
  50. "builtins/Date/Date.prototype.getFullYear.js",
  51. "builtins/Date/Date.prototype.getHours.js",
  52. "builtins/Date/Date.prototype.getMilliseconds.js",
  53. "builtins/Date/Date.prototype.getMinutes.js",
  54. "builtins/Date/Date.prototype.getMonth.js",
  55. "builtins/Date/Date.prototype.getSeconds.js",
  56. "builtins/Date/Date.prototype.getTime.js",
  57. "builtins/Error/Error.js",
  58. "builtins/Error/Error.prototype.name.js",
  59. "builtins/Error/Error.prototype.toString.js",
  60. "builtins/Function/Function.js",
  61. "builtins/Function/Function.prototype.apply.js",
  62. "builtins/Function/Function.prototype.bind.js",
  63. "builtins/Function/Function.prototype.call.js",
  64. "builtins/Function/Function.prototype.toString.js",
  65. "builtins/functions/isFinite.js",
  66. "builtins/functions/isNaN.js",
  67. "builtins/functions/parseFloat.js",
  68. "builtins/Infinity/Infinity.js",
  69. "builtins/JSON/JSON.parse.js",
  70. "builtins/JSON/JSON.parse-reviver.js",
  71. "builtins/JSON/JSON.stringify.js",
  72. "builtins/JSON/JSON.stringify-order.js",
  73. "builtins/JSON/JSON.stringify-proxy.js",
  74. "builtins/JSON/JSON.stringify-replacer.js",
  75. "builtins/JSON/JSON.stringify-space.js",
  76. "builtins/Math/Math-constants.js",
  77. "builtins/Math/Math.abs.js",
  78. "builtins/Math/Math.acosh.js",
  79. "builtins/Math/Math.asinh.js",
  80. "builtins/Math/Math.atanh.js",
  81. "builtins/Math/Math.cbrt.js",
  82. "builtins/Math/Math.ceil.js",
  83. "builtins/Math/Math.clz32.js",
  84. "builtins/Math/Math.cos.js",
  85. "builtins/Math/Math.exp.js",
  86. "builtins/Math/Math.expm1.js",
  87. "builtins/Math/Math.floor.js",
  88. "builtins/Math/Math.log1p.js",
  89. "builtins/Math/Math.max.js",
  90. "builtins/Math/Math.min.js",
  91. "builtins/Math/Math.pow.js",
  92. "builtins/Math/Math.sign.js",
  93. "builtins/Math/Math.sqrt.js",
  94. "builtins/Math/Math.tan.js",
  95. "builtins/Math/Math.trunc.js",
  96. "builtins/NaN/NaN.js",
  97. "builtins/Number/Number.js",
  98. "builtins/Number/Number-constants.js",
  99. "builtins/Number/Number.isFinite.js",
  100. "builtins/Number/Number.isInteger.js",
  101. "builtins/Number/Number.isNaN.js",
  102. "builtins/Number/Number.isSafeInteger.js",
  103. "builtins/Number/Number.parseFloat.js",
  104. "builtins/Number/Number.prototype.js",
  105. "builtins/Object/Object.js",
  106. "builtins/Object/Object.defineProperty.js",
  107. "builtins/Object/Object.entries.js",
  108. "builtins/Object/Object.getOwnPropertyDescriptor.js",
  109. "builtins/Object/Object.getOwnPropertyNames.js",
  110. "builtins/Object/Object.getPrototypeOf.js",
  111. "builtins/Object/Object.is.js",
  112. "builtins/Object/Object.isExtensible.js",
  113. "builtins/Object/Object.keys.js",
  114. "builtins/Object/Object.preventExtensions.js",
  115. "builtins/Object/Object.prototype.js",
  116. "builtins/Object/Object.prototype.constructor.js",
  117. "builtins/Object/Object.prototype.hasOwnProperty.js",
  118. "builtins/Object/Object.prototype.toLocaleString.js",
  119. "builtins/Object/Object.prototype.toString.js",
  120. "builtins/Object/Object.setPrototypeOf.js",
  121. "builtins/Object/Object.values.js",
  122. "builtins/Proxy/Proxy.js",
  123. "builtins/Proxy/Proxy.handler-apply.js",
  124. "builtins/Proxy/Proxy.handler-construct.js",
  125. "builtins/Proxy/Proxy.handler-defineProperty.js",
  126. "builtins/Proxy/Proxy.handler-deleteProperty.js",
  127. "builtins/Proxy/Proxy.handler-get.js",
  128. "builtins/Proxy/Proxy.handler-getOwnPropertyDescriptor.js",
  129. "builtins/Proxy/Proxy.handler-getPrototypeOf.js",
  130. "builtins/Proxy/Proxy.handler-has.js",
  131. "builtins/Proxy/Proxy.handler-isExtensible.js",
  132. "builtins/Proxy/Proxy.handler-preventExtensions.js",
  133. "builtins/Proxy/Proxy.handler-set.js",
  134. "builtins/Proxy/Proxy.handler-setPrototypeOf.js",\
  135. "builtins/Reflect/Reflect.apply.js",
  136. "builtins/Reflect/Reflect.construct.js",
  137. "builtins/Reflect/Reflect.defineProperty.js",
  138. "builtins/Reflect/Reflect.deleteProperty.js",
  139. "builtins/Reflect/Reflect.get.js",
  140. "builtins/Reflect/Reflect.getOwnPropertyDescriptor.js",
  141. "builtins/Reflect/Reflect.getPrototypeOf.js",
  142. "builtins/Reflect/Reflect.has.js",
  143. "builtins/Reflect/Reflect.isExtensible.js",
  144. "builtins/Reflect/Reflect.ownKeys.js",
  145. "builtins/Reflect/Reflect.preventExtensions.js",
  146. "builtins/Reflect/Reflect.set.js",
  147. "builtins/Reflect/Reflect.setPrototypeOf.js",
  148. "builtins/String/String.js",
  149. "builtins/String/String.fromCharCode.js",
  150. "builtins/String/String.prototype.js",
  151. "builtins/String/String.prototype-generic-functions.js",
  152. "builtins/String/String.prototype.charAt.js",
  153. "builtins/String/String.prototype.includes.js",
  154. "builtins/String/String.prototype.indexOf.js",
  155. "builtins/String/String.prototype.lastIndexOf.js",
  156. "builtins/String/String.prototype.padEnd.js",
  157. "builtins/String/String.prototype.padStart.js",
  158. "builtins/String/String.prototype.repeat.js",
  159. "builtins/String/String.prototype.slice.js",
  160. "builtins/String/String.prototype.startsWith.js",
  161. "builtins/String/String.prototype.substring.js",
  162. "builtins/String/String.prototype.toLowerCase.js",
  163. "builtins/String/String.prototype.toString.js",
  164. "builtins/String/String.prototype.toUpperCase.js",
  165. "builtins/String/String.prototype.trim.js",
  166. "builtins/String/String.prototype.valueOf.js",
  167. "builtins/String/String.raw.js",
  168. "add-values-to-primitive.js",
  169. "automatic-semicolon-insertion.js",
  170. "comments-basic.js",
  171. "debugger-statement.js",
  172. "empty-statements.js",
  173. "exception-ReferenceError.js",
  174. "exponentiation-basic.js",
  175. "indexed-access-string-object.js",
  176. "invalid-lhs-in-assignment.js",
  177. "let-scoping.js",
  178. "new-expression.js",
  179. "numeric-literals-basic.js",
  180. "object-getter-setter-shorthand.js",
  181. "object-method-shorthand.js",
  182. "object-spread.js",
  183. "tagged-template-literals.js",
  184. "test-common-tests.js",
  185. "switch-basic.js",
  186. "update-expression-on-member-expression.js",
  187. };
  188. enum class TestResult {
  189. Pass,
  190. Fail,
  191. Skip,
  192. };
  193. struct JSTest {
  194. String name;
  195. TestResult result;
  196. };
  197. struct JSSuite {
  198. String name;
  199. // A failed test takes precedence over a skipped test, which both have
  200. // precedence over a passed test
  201. TestResult most_severe_test_result { TestResult::Pass };
  202. Vector<JSTest> tests {};
  203. };
  204. struct ParserError {
  205. JS::Parser::Error error;
  206. String hint;
  207. };
  208. struct JSFileResult {
  209. String name;
  210. Optional<ParserError> error {};
  211. // A failed test takes precedence over a skipped test, which both have
  212. // precedence over a passed test
  213. TestResult most_severe_test_result { TestResult::Pass };
  214. Vector<JSSuite> suites {};
  215. };
  216. struct JSTestRunnerCounts {
  217. int tests_failed { 0 };
  218. int tests_passed { 0 };
  219. int tests_skipped { 0 };
  220. int suites_failed { 0 };
  221. int suites_passed { 0 };
  222. int files_total { 0 };
  223. };
  224. using JSTestRunnerResult = Vector<JSFileResult>;
  225. double get_time()
  226. {
  227. struct timeval tv1;
  228. struct timezone tz1;
  229. auto return_code = gettimeofday(&tv1, &tz1);
  230. ASSERT(return_code >= 0);
  231. return static_cast<double>(tv1.tv_sec) + static_cast<double>(tv1.tv_usec) / 1'000'000;
  232. }
  233. class TestRunner {
  234. public:
  235. TestRunner(String test_root)
  236. : m_test_root(move(test_root))
  237. {
  238. }
  239. void run();
  240. private:
  241. JSFileResult run_file_test(const String& test_path);
  242. static void print_file_result(const JSFileResult& file_result);
  243. void print_test_results() const;
  244. String m_test_root;
  245. double m_start_time;
  246. double m_end_time;
  247. JSTestRunnerCounts m_counts;
  248. };
  249. void TestRunner::run()
  250. {
  251. m_start_time = get_time();
  252. // FIXME: The way this currently works, the time it takes to print is
  253. // counted in the total test duration. In order to change this, we'd have to
  254. // loop over the paths and collect the results, record then time, and then
  255. // print. However, doing it this way provides no feedback to the user at
  256. // first, and then all the feedback at once. Both ways have their pros and
  257. // cons, but which one we prefer still needs to be decided.
  258. for (auto& test_path : tests_to_run)
  259. print_file_result(run_file_test(test_path));
  260. m_end_time = get_time();
  261. print_test_results();
  262. }
  263. Optional<ParserError> parse_and_run_file(JS::Interpreter& interpreter, const String& path)
  264. {
  265. auto file = Core::File::construct(path);
  266. auto result = file->open(Core::IODevice::ReadOnly);
  267. if (!result) {
  268. printf("Failed to open the following file: \"%s\"\n", path.characters());
  269. exit(1);
  270. }
  271. auto contents = file->read_all();
  272. String test_file_string(reinterpret_cast<const char*>(contents.data()), contents.size());
  273. file->close();
  274. auto parser = JS::Parser(JS::Lexer(test_file_string));
  275. auto program = parser.parse_program();
  276. if (parser.has_errors()) {
  277. auto error = parser.errors()[0];
  278. return ParserError { error, error.source_location_hint(test_file_string) };
  279. } else {
  280. interpreter.run(interpreter.global_object(), *program);
  281. }
  282. return {};
  283. }
  284. Optional<JsonValue> get_test_results(JS::Interpreter& interpreter)
  285. {
  286. auto result = interpreter.get_variable("__TestResults__", interpreter.global_object());
  287. auto json_string = JS::JSONObject::stringify_impl(interpreter, interpreter.global_object(), result, JS::js_undefined(), JS::js_undefined());
  288. auto json = JsonValue::from_string(json_string);
  289. if (!json.has_value())
  290. return {};
  291. return json.value();
  292. }
  293. JSFileResult TestRunner::run_file_test(const String& test_path)
  294. {
  295. auto interpreter = JS::Interpreter::create<JS::GlobalObject>();
  296. if (parse_and_run_file(*interpreter, String::format("%s/test-common.js", m_test_root.characters())).has_value()) {
  297. dbg() << "test-common.js failed to parse";
  298. exit(1);
  299. }
  300. auto source_file_result = parse_and_run_file(*interpreter, String::format("%s/%s", m_test_root.characters(), test_path.characters()));
  301. if (source_file_result.has_value())
  302. return { test_path, source_file_result };
  303. // Print any output
  304. // FIXME: Should be printed to stdout in a nice format
  305. auto& arr = interpreter->get_variable("__UserOutput__", interpreter->global_object()).as_array();
  306. for (auto& entry : arr.indexed_properties()) {
  307. dbg() << test_path << ": " << entry.value_and_attributes(&interpreter->global_object()).value.to_string_without_side_effects();
  308. }
  309. auto test_json = get_test_results(*interpreter);
  310. if (!test_json.has_value()) {
  311. printf("Received malformed JSON from test \"%s\"\n", test_path.characters());
  312. exit(1);
  313. }
  314. JSFileResult file_result { test_path };
  315. test_json.value().as_object().for_each_member([&](const String& suite_name, const JsonValue& suite_value) {
  316. JSSuite suite { suite_name };
  317. if (!suite_value.is_object()) {
  318. printf("Test JSON has a suite which is not an object (\"%s\")\n", test_path.characters());
  319. exit(1);
  320. }
  321. suite_value.as_object().for_each_member([&](const String& test_name, const JsonValue& test_value) {
  322. JSTest test { test_name, TestResult::Fail };
  323. ASSERT(test_value.is_object());
  324. ASSERT(test_value.as_object().has("result"));
  325. auto result = test_value.as_object().get("result");
  326. ASSERT(result.is_string());
  327. auto result_string = result.as_string();
  328. if (result_string == "pass") {
  329. test.result = TestResult::Pass;
  330. m_counts.tests_passed++;
  331. } else if (result_string == "fail") {
  332. test.result = TestResult::Fail;
  333. m_counts.tests_failed++;
  334. suite.most_severe_test_result = TestResult::Fail;
  335. } else {
  336. test.result = TestResult::Skip;
  337. if (suite.most_severe_test_result == TestResult::Pass)
  338. suite.most_severe_test_result = TestResult::Skip;
  339. m_counts.tests_skipped++;
  340. }
  341. suite.tests.append(test);
  342. });
  343. if (suite.most_severe_test_result == TestResult::Fail) {
  344. m_counts.suites_failed++;
  345. file_result.most_severe_test_result = TestResult::Fail;
  346. } else {
  347. if (suite.most_severe_test_result == TestResult::Skip && file_result.most_severe_test_result == TestResult::Pass)
  348. file_result.most_severe_test_result = TestResult::Skip;
  349. m_counts.suites_passed++;
  350. }
  351. file_result.suites.append(suite);
  352. });
  353. m_counts.files_total++;
  354. return file_result;
  355. }
  356. enum Modifier {
  357. BG_RED,
  358. BG_GREEN,
  359. FG_RED,
  360. FG_GREEN,
  361. FG_ORANGE,
  362. FG_GRAY,
  363. FG_BLACK,
  364. FG_BOLD,
  365. CLEAR,
  366. };
  367. void print_modifiers(Vector<Modifier> modifiers)
  368. {
  369. for (auto& modifier : modifiers) {
  370. auto code = [&]() -> String {
  371. switch (modifier) {
  372. case BG_RED:
  373. return "\033[48;2;255;0;102m";
  374. case BG_GREEN:
  375. return "\033[48;2;102;255;0m";
  376. case FG_RED:
  377. return "\033[38;2;255;0;102m";
  378. case FG_GREEN:
  379. return "\033[38;2;102;255;0m";
  380. case FG_ORANGE:
  381. return "\033[38;2;255;102;0m";
  382. case FG_GRAY:
  383. return "\033[38;2;135;139;148m";
  384. case FG_BLACK:
  385. return "\033[30m";
  386. case FG_BOLD:
  387. return "\033[1m";
  388. case CLEAR:
  389. return "\033[0m";
  390. }
  391. ASSERT_NOT_REACHED();
  392. };
  393. printf("%s", code().characters());
  394. }
  395. }
  396. void TestRunner::print_file_result(const JSFileResult& file_result)
  397. {
  398. if (file_result.most_severe_test_result == TestResult::Fail || file_result.error.has_value()) {
  399. print_modifiers({ BG_RED, FG_BLACK, FG_BOLD });
  400. printf(" FAIL ");
  401. print_modifiers({ CLEAR });
  402. } else {
  403. print_modifiers({ BG_GREEN, FG_BLACK, FG_BOLD });
  404. printf(" PASS ");
  405. print_modifiers({ CLEAR });
  406. }
  407. printf(" %s\n", file_result.name.characters());
  408. if (file_result.error.has_value()) {
  409. auto test_error = file_result.error.value();
  410. print_modifiers({ FG_RED });
  411. printf(" ❌ The file failed to parse\n\n");
  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. printf(" ❌ Suite: ");
  428. } else {
  429. printf(" ⚠️️ Suite: ");
  430. }
  431. print_modifiers({ CLEAR, FG_GRAY });
  432. if (suite.name == TOP_LEVEL_TEST_NAME) {
  433. printf("<top-level>\n");
  434. } else {
  435. printf("%s\n", suite.name.characters());
  436. }
  437. print_modifiers({ CLEAR });
  438. for (auto& test : suite.tests) {
  439. if (test.result == TestResult::Pass)
  440. continue;
  441. print_modifiers({ FG_GRAY, FG_BOLD });
  442. printf(" Test: ");
  443. if (test.result == TestResult::Fail) {
  444. print_modifiers({ CLEAR, FG_RED });
  445. printf("%s (failed)\n", test.name.characters());
  446. } else {
  447. print_modifiers({ CLEAR, FG_ORANGE });
  448. printf("%s (skipped)\n", test.name.characters());
  449. }
  450. print_modifiers({ CLEAR });
  451. }
  452. }
  453. }
  454. }
  455. void TestRunner::print_test_results() const
  456. {
  457. printf("\nTest Suites: ");
  458. if (m_counts.suites_failed) {
  459. print_modifiers({ FG_RED });
  460. printf("%d failed, ", m_counts.suites_failed);
  461. print_modifiers({ CLEAR });
  462. }
  463. if (m_counts.suites_passed) {
  464. print_modifiers({ FG_GREEN });
  465. printf("%d passed, ", m_counts.suites_passed);
  466. print_modifiers({ CLEAR });
  467. }
  468. printf("%d total\n", m_counts.suites_failed + m_counts.suites_passed);
  469. printf("Tests: ");
  470. if (m_counts.tests_failed) {
  471. print_modifiers({ FG_RED });
  472. printf("%d failed, ", m_counts.tests_failed);
  473. print_modifiers({ CLEAR });
  474. }
  475. if (m_counts.tests_skipped) {
  476. print_modifiers({ FG_ORANGE });
  477. printf("%d skipped, ", m_counts.tests_skipped);
  478. print_modifiers({ CLEAR });
  479. }
  480. if (m_counts.tests_passed) {
  481. print_modifiers({ FG_GREEN });
  482. printf("%d passed, ", m_counts.tests_passed);
  483. print_modifiers({ CLEAR });
  484. }
  485. printf("%d total\n", m_counts.tests_failed + m_counts.tests_passed);
  486. printf("Files: %d total\n", m_counts.files_total);
  487. printf("Time: %-.3fs\n\n", m_end_time - m_start_time);
  488. }
  489. int main(int, char**)
  490. {
  491. #ifdef __serenity__
  492. TestRunner("/home/anon/js-tests").run();
  493. #else
  494. char* serenity_root = getenv("SERENITY_ROOT");
  495. if (!serenity_root) {
  496. printf("test-js requires the SERENITY_ROOT environment variable to be set");
  497. return 1;
  498. }
  499. TestRunner(String::format("%s/Libraries/LibJS/Tests", serenity_root)).run();
  500. #endif
  501. return 0;
  502. }