Test.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /*
  2. * Copyright (c) 2024, Tim Flynn <trflynn89@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteBuffer.h>
  7. #include <AK/ByteString.h>
  8. #include <AK/Enumerate.h>
  9. #include <AK/LexicalPath.h>
  10. #include <AK/QuickSort.h>
  11. #include <AK/Vector.h>
  12. #include <Ladybird/Headless/Application.h>
  13. #include <Ladybird/Headless/HeadlessWebView.h>
  14. #include <Ladybird/Headless/Test.h>
  15. #include <LibCore/ConfigFile.h>
  16. #include <LibCore/DirIterator.h>
  17. #include <LibCore/Directory.h>
  18. #include <LibCore/EventLoop.h>
  19. #include <LibCore/File.h>
  20. #include <LibCore/Timer.h>
  21. #include <LibDiff/Format.h>
  22. #include <LibDiff/Generator.h>
  23. #include <LibFileSystem/FileSystem.h>
  24. #include <LibGfx/Bitmap.h>
  25. #include <LibGfx/ImageFormats/PNGWriter.h>
  26. #include <LibURL/URL.h>
  27. #include <LibWeb/HTML/SelectedFile.h>
  28. namespace Ladybird {
  29. static Vector<ByteString> s_skipped_tests;
  30. static ErrorOr<void> load_test_config(StringView test_root_path)
  31. {
  32. auto config_path = LexicalPath::join(test_root_path, "TestConfig.ini"sv);
  33. auto config_or_error = Core::ConfigFile::open(config_path.string());
  34. if (config_or_error.is_error()) {
  35. if (config_or_error.error().code() == ENOENT)
  36. return {};
  37. warnln("Unable to open test config {}", config_path);
  38. return config_or_error.release_error();
  39. }
  40. auto config = config_or_error.release_value();
  41. for (auto const& group : config->groups()) {
  42. if (group == "Skipped"sv) {
  43. for (auto& key : config->keys(group))
  44. s_skipped_tests.append(TRY(FileSystem::real_path(LexicalPath::join(test_root_path, key).string())));
  45. } else {
  46. warnln("Unknown group '{}' in config {}", group, config_path);
  47. }
  48. }
  49. return {};
  50. }
  51. static ErrorOr<void> collect_dump_tests(Vector<Test>& tests, StringView path, StringView trail, TestMode mode)
  52. {
  53. Core::DirIterator it(ByteString::formatted("{}/input/{}", path, trail), Core::DirIterator::Flags::SkipDots);
  54. while (it.has_next()) {
  55. auto name = it.next_path();
  56. auto input_path = TRY(FileSystem::real_path(ByteString::formatted("{}/input/{}/{}", path, trail, name)));
  57. if (FileSystem::is_directory(input_path)) {
  58. TRY(collect_dump_tests(tests, path, ByteString::formatted("{}/{}", trail, name), mode));
  59. continue;
  60. }
  61. if (!name.ends_with(".html"sv) && !name.ends_with(".svg"sv) && !name.ends_with(".xhtml"sv) && !name.ends_with(".xht"sv))
  62. continue;
  63. auto expectation_path = ByteString::formatted("{}/expected/{}/{}.txt", path, trail, LexicalPath::title(name));
  64. tests.append({ mode, input_path, move(expectation_path), {} });
  65. }
  66. return {};
  67. }
  68. static ErrorOr<void> collect_ref_tests(Vector<Test>& tests, StringView path, StringView trail)
  69. {
  70. Core::DirIterator it(ByteString::formatted("{}/input/{}", path, trail), Core::DirIterator::Flags::SkipDots);
  71. while (it.has_next()) {
  72. auto name = it.next_path();
  73. auto input_path = TRY(FileSystem::real_path(ByteString::formatted("{}/input/{}/{}", path, trail, name)));
  74. if (FileSystem::is_directory(input_path)) {
  75. TRY(collect_ref_tests(tests, path, ByteString::formatted("{}/{}", trail, name)));
  76. continue;
  77. }
  78. tests.append({ TestMode::Ref, input_path, {}, {} });
  79. }
  80. return {};
  81. }
  82. void run_dump_test(HeadlessWebView& view, Test& test, URL::URL const& url, int timeout_in_milliseconds)
  83. {
  84. auto timer = Core::Timer::create_single_shot(timeout_in_milliseconds, [&view, &test]() {
  85. view.on_load_finish = {};
  86. view.on_text_test_finish = {};
  87. view.on_test_complete({ test, TestResult::Timeout });
  88. });
  89. auto handle_completed_test = [&test, url]() -> ErrorOr<TestResult> {
  90. if (test.expectation_path.is_empty()) {
  91. outln("{}", test.text);
  92. return TestResult::Pass;
  93. }
  94. auto open_expectation_file = [&](auto mode) {
  95. auto expectation_file_or_error = Core::File::open(test.expectation_path, mode);
  96. if (expectation_file_or_error.is_error())
  97. warnln("Failed opening '{}': {}", test.expectation_path, expectation_file_or_error.error());
  98. return expectation_file_or_error;
  99. };
  100. ByteBuffer expectation;
  101. if (auto expectation_file = open_expectation_file(Core::File::OpenMode::Read); !expectation_file.is_error()) {
  102. expectation = TRY(expectation_file.value()->read_until_eof());
  103. auto result_trimmed = StringView { test.text }.trim("\n"sv, TrimMode::Right);
  104. auto expectation_trimmed = StringView { expectation }.trim("\n"sv, TrimMode::Right);
  105. if (result_trimmed == expectation_trimmed)
  106. return TestResult::Pass;
  107. } else if (!Application::the().rebaseline) {
  108. return expectation_file.release_error();
  109. }
  110. if (Application::the().rebaseline) {
  111. auto expectation_file = TRY(open_expectation_file(Core::File::OpenMode::Write));
  112. TRY(expectation_file->write_until_depleted(test.text));
  113. return TestResult::Pass;
  114. }
  115. auto const color_output = isatty(STDOUT_FILENO) ? Diff::ColorOutput::Yes : Diff::ColorOutput::No;
  116. if (color_output == Diff::ColorOutput::Yes)
  117. outln("\n\033[33;1mTest failed\033[0m: {}", url);
  118. else
  119. outln("\nTest failed: {}", url);
  120. auto hunks = TRY(Diff::from_text(expectation, test.text, 3));
  121. auto out = TRY(Core::File::standard_output());
  122. TRY(Diff::write_unified_header(test.expectation_path, test.expectation_path, *out));
  123. for (auto const& hunk : hunks)
  124. TRY(Diff::write_unified(hunk, *out, color_output));
  125. return TestResult::Fail;
  126. };
  127. auto on_test_complete = [&view, &test, timer, handle_completed_test]() {
  128. timer->stop();
  129. view.on_load_finish = {};
  130. view.on_text_test_finish = {};
  131. if (auto result = handle_completed_test(); result.is_error())
  132. view.on_test_complete({ test, TestResult::Fail });
  133. else
  134. view.on_test_complete({ test, result.value() });
  135. };
  136. if (test.mode == TestMode::Layout) {
  137. view.on_load_finish = [&view, &test, url, on_test_complete = move(on_test_complete)](auto const& loaded_url) {
  138. // We don't want subframe loads to trigger the test finish.
  139. if (!url.equals(loaded_url, URL::ExcludeFragment::Yes))
  140. return;
  141. // NOTE: We take a screenshot here to force the lazy layout of SVG-as-image documents to happen.
  142. // It also causes a lot more code to run, which is good for finding bugs. :^)
  143. view.take_screenshot()->when_resolved([&view, &test, on_test_complete = move(on_test_complete)](auto) {
  144. auto promise = view.request_internal_page_info(WebView::PageInfoType::LayoutTree | WebView::PageInfoType::PaintTree);
  145. promise->when_resolved([&test, on_test_complete = move(on_test_complete)](auto const& text) {
  146. test.text = text;
  147. on_test_complete();
  148. });
  149. });
  150. };
  151. } else if (test.mode == TestMode::Text) {
  152. view.on_load_finish = [&view, &test, on_test_complete, url](auto const& loaded_url) {
  153. // We don't want subframe loads to trigger the test finish.
  154. if (!url.equals(loaded_url, URL::ExcludeFragment::Yes))
  155. return;
  156. test.did_finish_loading = true;
  157. if (test.expectation_path.is_empty()) {
  158. auto promise = view.request_internal_page_info(WebView::PageInfoType::Text);
  159. promise->when_resolved([&test, on_test_complete = move(on_test_complete)](auto const& text) {
  160. test.text = text;
  161. on_test_complete();
  162. });
  163. } else if (test.did_finish_test) {
  164. on_test_complete();
  165. }
  166. };
  167. view.on_text_test_finish = [&test, on_test_complete](auto const& text) {
  168. test.text = text;
  169. test.did_finish_test = true;
  170. if (test.did_finish_loading)
  171. on_test_complete();
  172. };
  173. }
  174. view.load(url);
  175. timer->start();
  176. }
  177. static void run_ref_test(HeadlessWebView& view, Test& test, URL::URL const& url, int timeout_in_milliseconds)
  178. {
  179. auto timer = Core::Timer::create_single_shot(timeout_in_milliseconds, [&view, &test]() {
  180. view.on_load_finish = {};
  181. view.on_text_test_finish = {};
  182. view.on_test_complete({ test, TestResult::Timeout });
  183. });
  184. auto handle_completed_test = [&test, url]() -> ErrorOr<TestResult> {
  185. if (test.actual_screenshot->visually_equals(*test.expectation_screenshot))
  186. return TestResult::Pass;
  187. if (Application::the().dump_failed_ref_tests) {
  188. warnln("\033[33;1mRef test {} failed; dumping screenshots\033[0m", url);
  189. auto dump_screenshot = [&](Gfx::Bitmap& bitmap, StringView path) -> ErrorOr<void> {
  190. auto screenshot_file = TRY(Core::File::open(path, Core::File::OpenMode::Write));
  191. auto encoded_data = TRY(Gfx::PNGWriter::encode(bitmap));
  192. TRY(screenshot_file->write_until_depleted(encoded_data));
  193. outln("\033[33;1mDumped {}\033[0m", TRY(FileSystem::real_path(path)));
  194. return {};
  195. };
  196. TRY(Core::Directory::create("test-dumps"sv, Core::Directory::CreateDirectories::Yes));
  197. auto title = LexicalPath::title(URL::percent_decode(url.serialize_path()));
  198. TRY(dump_screenshot(*test.actual_screenshot, ByteString::formatted("test-dumps/{}.png", title)));
  199. TRY(dump_screenshot(*test.expectation_screenshot, ByteString::formatted("test-dumps/{}-ref.png", title)));
  200. }
  201. return TestResult::Fail;
  202. };
  203. auto on_test_complete = [&view, &test, timer, handle_completed_test]() {
  204. timer->stop();
  205. view.on_load_finish = {};
  206. view.on_text_test_finish = {};
  207. if (auto result = handle_completed_test(); result.is_error())
  208. view.on_test_complete({ test, TestResult::Fail });
  209. else
  210. view.on_test_complete({ test, result.value() });
  211. };
  212. view.on_load_finish = [&view, &test, on_test_complete = move(on_test_complete)](auto const&) {
  213. if (test.actual_screenshot) {
  214. view.take_screenshot()->when_resolved([&test, on_test_complete = move(on_test_complete)](RefPtr<Gfx::Bitmap> screenshot) {
  215. test.expectation_screenshot = move(screenshot);
  216. on_test_complete();
  217. });
  218. } else {
  219. view.take_screenshot()->when_resolved([&view, &test](RefPtr<Gfx::Bitmap> screenshot) {
  220. test.actual_screenshot = move(screenshot);
  221. view.debug_request("load-reference-page");
  222. });
  223. }
  224. };
  225. view.on_text_test_finish = [&](auto const&) {
  226. dbgln("Unexpected text test finished during ref test for {}", url);
  227. };
  228. view.load(url);
  229. timer->start();
  230. }
  231. static void run_test(HeadlessWebView& view, Test& test, Application& app)
  232. {
  233. // Clear the current document.
  234. // FIXME: Implement a debug-request to do this more thoroughly.
  235. auto promise = Core::Promise<Empty>::construct();
  236. view.on_load_finish = [promise](auto const& url) {
  237. if (!url.equals("about:blank"sv))
  238. return;
  239. Core::deferred_invoke([promise]() {
  240. promise->resolve({});
  241. });
  242. };
  243. view.on_text_test_finish = {};
  244. view.on_request_file_picker = [&](auto const& accepted_file_types, auto allow_multiple_files) {
  245. // Create some dummy files for tests.
  246. Vector<Web::HTML::SelectedFile> selected_files;
  247. bool add_txt_files = accepted_file_types.filters.is_empty();
  248. bool add_cpp_files = false;
  249. for (auto const& filter : accepted_file_types.filters) {
  250. filter.visit(
  251. [](Web::HTML::FileFilter::FileType) {},
  252. [&](Web::HTML::FileFilter::MimeType const& mime_type) {
  253. if (mime_type.value == "text/plain"sv)
  254. add_txt_files = true;
  255. },
  256. [&](Web::HTML::FileFilter::Extension const& extension) {
  257. if (extension.value == "cpp"sv)
  258. add_cpp_files = true;
  259. });
  260. }
  261. if (add_txt_files) {
  262. selected_files.empend("file1"sv, MUST(ByteBuffer::copy("Contents for file1"sv.bytes())));
  263. if (allow_multiple_files == Web::HTML::AllowMultipleFiles::Yes) {
  264. selected_files.empend("file2"sv, MUST(ByteBuffer::copy("Contents for file2"sv.bytes())));
  265. selected_files.empend("file3"sv, MUST(ByteBuffer::copy("Contents for file3"sv.bytes())));
  266. selected_files.empend("file4"sv, MUST(ByteBuffer::copy("Contents for file4"sv.bytes())));
  267. }
  268. }
  269. if (add_cpp_files) {
  270. selected_files.empend("file1.cpp"sv, MUST(ByteBuffer::copy("int main() {{ return 1; }}"sv.bytes())));
  271. if (allow_multiple_files == Web::HTML::AllowMultipleFiles::Yes) {
  272. selected_files.empend("file2.cpp"sv, MUST(ByteBuffer::copy("int main() {{ return 2; }}"sv.bytes())));
  273. }
  274. }
  275. view.file_picker_closed(move(selected_files));
  276. };
  277. promise->when_resolved([&view, &test, &app](auto) {
  278. auto url = URL::create_with_file_scheme(MUST(FileSystem::real_path(test.input_path)));
  279. switch (test.mode) {
  280. case TestMode::Text:
  281. case TestMode::Layout:
  282. run_dump_test(view, test, url, app.per_test_timeout_in_seconds * 1000);
  283. return;
  284. case TestMode::Ref:
  285. run_ref_test(view, test, url, app.per_test_timeout_in_seconds * 1000);
  286. return;
  287. }
  288. VERIFY_NOT_REACHED();
  289. });
  290. view.load("about:blank"sv);
  291. }
  292. ErrorOr<void> run_tests(Core::AnonymousBuffer const& theme, Gfx::IntSize window_size)
  293. {
  294. auto& app = Application::the();
  295. TRY(load_test_config(app.test_root_path));
  296. Vector<Test> tests;
  297. auto test_glob = ByteString::formatted("*{}*", app.test_glob);
  298. TRY(collect_dump_tests(tests, ByteString::formatted("{}/Layout", app.test_root_path), "."sv, TestMode::Layout));
  299. TRY(collect_dump_tests(tests, ByteString::formatted("{}/Text", app.test_root_path), "."sv, TestMode::Text));
  300. TRY(collect_ref_tests(tests, ByteString::formatted("{}/Ref", app.test_root_path), "."sv));
  301. #if !defined(AK_OS_MACOS)
  302. TRY(collect_ref_tests(tests, ByteString::formatted("{}/Screenshot", app.test_root_path), "."sv));
  303. #endif
  304. tests.remove_all_matching([&](auto const& test) {
  305. return !test.input_path.matches(test_glob, CaseSensitivity::CaseSensitive);
  306. });
  307. if (app.test_dry_run) {
  308. outln("Found {} tests...", tests.size());
  309. for (auto const& [i, test] : enumerate(tests))
  310. outln("{}/{}: {}", i + 1, tests.size(), *LexicalPath::relative_path(test.input_path, app.test_root_path));
  311. return {};
  312. }
  313. if (tests.is_empty()) {
  314. if (app.test_glob.is_empty())
  315. return Error::from_string_literal("No tests found");
  316. return Error::from_string_literal("No tests found matching filter");
  317. }
  318. auto concurrency = min(app.test_concurrency, tests.size());
  319. size_t loaded_web_views = 0;
  320. for (size_t i = 0; i < concurrency; ++i) {
  321. auto& view = app.create_web_view(theme, window_size);
  322. view.on_load_finish = [&](auto const&) { ++loaded_web_views; };
  323. }
  324. // We need to wait for the initial about:blank load to complete before starting the tests, otherwise we may load the
  325. // test URL before the about:blank load completes. WebContent currently cannot handle this, and will drop the test URL.
  326. Core::EventLoop::current().spin_until([&]() {
  327. return loaded_web_views == concurrency;
  328. });
  329. size_t pass_count = 0;
  330. size_t fail_count = 0;
  331. size_t timeout_count = 0;
  332. size_t skipped_count = 0;
  333. bool is_tty = isatty(STDOUT_FILENO);
  334. outln("Running {} tests...", tests.size());
  335. auto all_tests_complete = Core::Promise<Empty>::construct();
  336. auto tests_remaining = tests.size();
  337. auto current_test = 0uz;
  338. Vector<TestCompletion> non_passing_tests;
  339. app.for_each_web_view([&](auto& view) {
  340. view.clear_content_filters();
  341. auto run_next_test = [&]() {
  342. auto index = current_test++;
  343. if (index >= tests.size())
  344. return;
  345. auto& test = tests[index];
  346. test.start_time = UnixDateTime::now();
  347. if (is_tty) {
  348. // Keep clearing and reusing the same line if stdout is a TTY.
  349. out("\33[2K\r");
  350. }
  351. out("{}/{}: {}", index + 1, tests.size(), LexicalPath::relative_path(test.input_path, app.test_root_path));
  352. if (is_tty)
  353. fflush(stdout);
  354. else
  355. outln("");
  356. Core::deferred_invoke([&]() mutable {
  357. if (s_skipped_tests.contains_slow(test.input_path))
  358. view.on_test_complete({ test, TestResult::Skipped });
  359. else
  360. run_test(view, test, app);
  361. });
  362. };
  363. view.test_promise().when_resolved([&, run_next_test](auto result) {
  364. result.test.end_time = UnixDateTime::now();
  365. switch (result.result) {
  366. case TestResult::Pass:
  367. ++pass_count;
  368. break;
  369. case TestResult::Fail:
  370. ++fail_count;
  371. break;
  372. case TestResult::Timeout:
  373. ++timeout_count;
  374. break;
  375. case TestResult::Skipped:
  376. ++skipped_count;
  377. break;
  378. }
  379. if (result.result != TestResult::Pass)
  380. non_passing_tests.append(move(result));
  381. if (--tests_remaining == 0)
  382. all_tests_complete->resolve({});
  383. else
  384. run_next_test();
  385. });
  386. Core::deferred_invoke([run_next_test]() {
  387. run_next_test();
  388. });
  389. });
  390. MUST(all_tests_complete->await());
  391. if (is_tty)
  392. outln("\33[2K\rDone!");
  393. outln("==================================================");
  394. outln("Pass: {}, Fail: {}, Skipped: {}, Timeout: {}", pass_count, fail_count, skipped_count, timeout_count);
  395. outln("==================================================");
  396. for (auto const& non_passing_test : non_passing_tests)
  397. outln("{}: {}", test_result_to_string(non_passing_test.result), non_passing_test.test.input_path);
  398. if (app.log_slowest_tests) {
  399. auto tests_to_print = min(10uz, tests.size());
  400. outln("\nSlowest {} tests:", tests_to_print);
  401. quick_sort(tests, [&](auto const& lhs, auto const& rhs) {
  402. auto lhs_duration = lhs.end_time - lhs.start_time;
  403. auto rhs_duration = rhs.end_time - rhs.start_time;
  404. return lhs_duration > rhs_duration;
  405. });
  406. for (auto const& test : tests.span().trim(tests_to_print)) {
  407. auto name = LexicalPath::relative_path(test.input_path, app.test_root_path);
  408. auto duration = test.end_time - test.start_time;
  409. outln("{}: {}ms", name, duration.to_milliseconds());
  410. }
  411. }
  412. if (app.dump_gc_graph) {
  413. app.for_each_web_view([&](auto& view) {
  414. if (auto path = view.dump_gc_graph(); path.is_error())
  415. warnln("Failed to dump GC graph: {}", path.error());
  416. else
  417. outln("GC graph dumped to {}", path.value());
  418. });
  419. }
  420. app.destroy_web_views();
  421. if (timeout_count == 0 && fail_count == 0)
  422. return {};
  423. return Error::from_string_literal("Failed LibWeb tests");
  424. }
  425. }