Test.cpp 19 KB

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