diff --git a/tests/E2E.NUnit.Tests/Dialog/PageDialogTests.cs b/tests/E2E.NUnit.Tests/Dialog/PageDialogTests.cs new file mode 100644 index 000000000..c3da0206d --- /dev/null +++ b/tests/E2E.NUnit.Tests/Dialog/PageDialogTests.cs @@ -0,0 +1,166 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using E2E.Engine; +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.Dialog; + +/// +/// test.describe('page dialog') of upstream's apps/testbed/tests/dialog.e2e.ts (Playwright's +/// page-dialog.spec.ts). page.on('dialog') is Browser.OnDialogAsync. A dialog no handler answers is dismissed as +/// in Playwright, and e2e also fails the next step for it. Not ported, as upstream: should fire dialogclosed when dialog is accepted, +/// should fire dialogclosed when dialog is dismissed, should fire dialogclosed for auto-dismissed dialogs (no dialogclosed event), +/// should be able to close context with open alert (e2e answers every dialog). The defaultValue() assertions are dropped: +/// e2e dialogs have no default value. +/// +public sealed class PageDialogTests : PlaywrightTest +{ + [Test] + public async Task Should_fire() + { + await Browser.GotoAsync("/empty.html"); + DialogType? type = null; + string? message = null; + await Browser.OnDialogAsync(async dialog => + { + type = dialog.Type; + message = dialog.Message; + await dialog.AcceptAsync(); + }); + await Browser.EvaluateAsync("() => alert('yo')"); + Assert.That(type, Is.EqualTo(DialogType.Alert)); + Assert.That(message, Is.EqualTo("yo")); + } + + [Test] + public async Task Should_allow_accepting_prompts() + { + await Browser.GotoAsync("/empty.html"); + DialogType? type = null; + string? message = null; + await Browser.OnDialogAsync(async dialog => + { + type = dialog.Type; + message = dialog.Message; + await dialog.AcceptAsync("answer!"); + }); + var result = await Browser.EvaluateAsync("() => prompt('question?', 'yes.')"); + Assert.That(type, Is.EqualTo(DialogType.Prompt)); + Assert.That(message, Is.EqualTo("question?")); + Assert.That(result, Is.EqualTo("answer!")); + } + + [Test] + public async Task Should_dismiss_the_prompt() + { + await Browser.GotoAsync("/empty.html"); + await Browser.OnDialogAsync(dialog => dialog.DismissAsync()); + var result = await Browser.EvaluateAsync("() => prompt('question?')"); + Assert.That(result, Is.Null); + } + + [Test] + public async Task Should_accept_the_confirm_prompt() + { + await Browser.GotoAsync("/empty.html"); + await Browser.OnDialogAsync(async dialog => + { + await dialog.AcceptAsync(); + }); + var result = await Browser.EvaluateAsync("() => confirm('boolean?')"); + Assert.That(result, Is.True); + } + + [Test] + public async Task Should_dismiss_the_confirm_prompt() + { + await Browser.GotoAsync("/empty.html"); + await Browser.OnDialogAsync(async dialog => + { + await dialog.DismissAsync(); + }); + var result = await Browser.EvaluateAsync("() => confirm('boolean?')"); + Assert.That(result, Is.False); + } + + [Test] + public async Task Should_handle_multiple_alerts() + { + var seen = 0; + await Browser.OnDialogAsync(async dialog => + { + Interlocked.Increment(ref seen); + try + { + await dialog.AcceptAsync(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Upstream: `.catch(() => {})`. + } + }); + await Browser.GotoAsync(Content(""" +

Hello World

+ + """)); + Assert.That(await Browser.Locator("p").TextContentAsync(), Is.EqualTo("Hello World")); + Assert.That(Volatile.Read(ref seen), Is.EqualTo(3)); + } + + [Test] + public async Task Should_handle_multiple_confirms() + { + var seen = 0; + await Browser.OnDialogAsync(async dialog => + { + Interlocked.Increment(ref seen); + try + { + await dialog.AcceptAsync(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Upstream: `.catch(() => {})`. + } + }); + await Browser.GotoAsync(Content(""" +

Hello World

+ + """)); + Assert.That(await Browser.Locator("p").TextContentAsync(), Is.EqualTo("Hello World")); + Assert.That(Volatile.Read(ref seen), Is.EqualTo(3)); + } + + [Test] + public async Task Should_auto_dismiss_the_prompt_without_listeners() + { + await Browser.GotoAsync("/empty.html"); + var result = await Browser.EvaluateAsync("() => prompt('question?')"); + Assert.That(result, Is.Null); + var error = await Failure(() => Browser.TitleAsync()); + Assert.That(error?.Message, Does.Contain("unhandled prompt dialog: question?")); + } + + [Test] + public async Task Should_auto_dismiss_the_alert_without_listeners() + { + await Browser.GotoAsync(Content("""
Click me
""")); + var error = await Failure(async () => + { + await Browser.Locator("div").TapAsync(); + await Browser.TitleAsync(); + }); + Assert.That(error?.Message, Does.Contain("unhandled alert dialog: 123")); + Assert.That(await Browser.EvaluateAsync("window._clicked"), Is.True); + } +} diff --git a/tests/E2E.NUnit.Tests/Download/DownloadEventTests.cs b/tests/E2E.NUnit.Tests/Download/DownloadEventTests.cs new file mode 100644 index 000000000..2ea79d7e8 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Download/DownloadEventTests.cs @@ -0,0 +1,168 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using E2E.Engine; +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.Download; + +/// +/// test.describe('download event') of upstream's apps/testbed/tests/download.e2e.ts (Playwright's +/// download.spec.ts). page.waitForEvent('download') is Browser.WaitForDownloadAsync(trigger), which saves the +/// file, and download.path() is the saved file's AbsolutePath. e2e has no download.url(), so its assertions are +/// dropped. Not ported, as upstream: should report downloads with acceptDownloads: false, should report proper download url when +/// download is from download attribute, should save to user-specified path without updating original path, should save to two +/// different paths with multiple saveAs calls, should save to overwritten filepath, should create subdirectories when saving to +/// non-existent user-specified path, should error when saving with downloads disabled, should error when saving after deletion, +/// should delete file, should expose stream, should delete downloads on context destruction, should delete downloads on browser +/// gone, should save downloads to artifactsDir, should close the context without awaiting the failed download, should close the +/// context without awaiting the download, should throw if browser dies, should be able to cancel pending downloads, should not fail +/// explicitly to cancel a download even if that is already finished, should save to user-specified path (no +/// download.saveAs, delete, createReadStream, cancel, failure, acceptDownloads, context or +/// browser control from the test). +/// +public sealed class DownloadEventTests : PlaywrightTest +{ + [Test] + public async Task Should_report_download_when_navigation_turns_into_download_smoke() + { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await Browser.GotoAsync("/empty.html"); + Exception? responseOrError = null; + var download = await Browser.WaitForDownloadAsync(async () => + { + responseOrError = await Failure(() => Browser.GotoAsync($"{PREFIX}/download")); + }); + Assert.That(File.Exists(download.AbsolutePath), Is.True); + Assert.That(await File.ReadAllTextAsync(download.AbsolutePath), Is.EqualTo("Hello world")); + Assert.That(responseOrError, Is.Not.Null); + Assert.That(responseOrError!.Message, Does.Contain("Download is starting")); + Assert.That(await Browser.UrlAsync(), Is.EqualTo($"{PREFIX}/empty.html")); + } + + [Test] + public async Task Should_work_with_Cross_Origin_Opener_Policy() + { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await Browser.GotoAsync("/empty.html"); + Exception? responseOrError = null; + var url = Respond(new Dictionary + { + ["content-type"] = "application/octet-stream", + ["content-disposition"] = "attachment", + ["cross-origin-opener-policy"] = "same-origin", + }); + var download = await Browser.WaitForDownloadAsync(async () => + { + responseOrError = await Failure(() => Browser.GotoAsync(url)); + }); + Assert.That(File.Exists(download.AbsolutePath), Is.True); + Assert.That(await File.ReadAllTextAsync(download.AbsolutePath), Is.EqualTo("Hello world")); + Assert.That(responseOrError, Is.Not.Null); + Assert.That(responseOrError!.Message, Does.Contain("Download is starting")); + Assert.That(await Browser.UrlAsync(), Is.EqualTo($"{PREFIX}/empty.html")); + } + + [Test] + public async Task Should_report_downloads_with_acceptDownloads_true() + { + await Browser.GotoAsync(Content($"""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + Assert.That(File.Exists(download.AbsolutePath), Is.True); + Assert.That(await File.ReadAllTextAsync(download.AbsolutePath), Is.EqualTo("Hello world")); + } + + [Test] + public async Task Should_report_downloads_for_download_attribute() + { + await Browser.GotoAsync("/empty.html"); + await Browser.GotoAsync(Content($"""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + Assert.That(download.SuggestedFilename, Is.EqualTo("foo.zip")); + Assert.That(File.Exists(download.AbsolutePath), Is.True); + } + + [Test] + public async Task Should_report_non_navigation_downloads() + { + await Browser.GotoAsync("/empty.html"); + await Browser.GotoAsync(Content($"""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + Assert.That(download.SuggestedFilename, Is.EqualTo("file.txt")); + Assert.That(File.Exists(download.AbsolutePath), Is.True); + Assert.That(await File.ReadAllTextAsync(download.AbsolutePath), Is.EqualTo("Hello world")); + } + + [Test] + public async Task Should_report_download_path_within_page_on_download_handler_for_Files() + { + await Browser.GotoAsync(Content($"""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + Assert.That(await File.ReadAllTextAsync(download.AbsolutePath), Is.EqualTo("Hello world")); + } + + [Test] + public async Task Should_report_download_path_within_page_on_download_handler_for_Blobs() + { + await Browser.GotoAsync("/download-blob.html"); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + Assert.That(await File.ReadAllTextAsync(download.AbsolutePath), Is.EqualTo("Hello world")); + } + + [Test] + public async Task Should_report_alt_click_downloads() + { + await Browser.GotoAsync("/empty.html"); + await Browser.GotoAsync(Content($"""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync(new ClickOptions { Modifiers = [KeyModifier.Alt] })); + Assert.That(File.Exists(download.AbsolutePath), Is.True); + Assert.That(await File.ReadAllTextAsync(download.AbsolutePath), Is.EqualTo("Hello world")); + } + + [Test] + public async Task Should_report_new_window_downloads() + { + await Browser.GotoAsync(Content($"""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + Assert.That(File.Exists(download.AbsolutePath), Is.True); + } + + [Test] + public async Task Should_download_large_binary_zip() + { + var fileContent = new byte[1 << 20]; + for (var i = 0; i < fileContent.Length; i++) + { + fileContent[i] = (byte)(((uint)(i + 1) * 2654435761u) >> 24); + } + + await Browser.GotoAsync("/empty.html"); + await Browser.GotoAsync(Content($"""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + var downloaded = await File.ReadAllBytesAsync(download.AbsolutePath); + Assert.That(downloaded, Has.Length.EqualTo(fileContent.Length)); + Assert.That(downloaded.AsSpan().SequenceEqual(fileContent), Is.True); + } + + [Test] + public async Task Should_report_downloads_with_interception() + { + await Browser.RouteAsync(new System.Text.RegularExpressions.Regex(".*"), route => route.ContinueAsync()); + await Browser.GotoAsync(Content($"""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + Assert.That(File.Exists(download.AbsolutePath), Is.True); + Assert.That(await File.ReadAllTextAsync(download.AbsolutePath), Is.EqualTo("Hello world")); + } + + [Test] + public async Task Should_emit_download_event_from_nested_iframes() + { + var third = Content($""" download"""); + var second = Content($""""""); + await Browser.GotoAsync(Content($"""""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.FrameLocator("iframe").FrameLocator("iframe").Locator("a").TapAsync()); + Assert.That(File.Exists(download.AbsolutePath), Is.True); + Assert.That(await File.ReadAllTextAsync(download.AbsolutePath), Is.EqualTo("Hello world")); + } +} diff --git a/tests/E2E.NUnit.Tests/Download/DownloadTests.cs b/tests/E2E.NUnit.Tests/Download/DownloadTests.cs new file mode 100644 index 000000000..08461b659 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Download/DownloadTests.cs @@ -0,0 +1,121 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using E2E.Engine; +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.Download; + +/// +/// test.describe('download') of upstream's apps/testbed/tests/download.e2e.ts (Playwright's +/// download.spec.ts); see for how downloads are read. +/// +public sealed class DownloadTests : PlaywrightTest +{ + [Test] + public async Task Should_be_able_to_download_a_PDF_file() + { + await Browser.GotoAsync("/empty.html"); + await Browser.GotoAsync(Content("""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + await AssertDownloadToPdf(download, Asset("empty.pdf")); + } + + // Upstream marks this test `fail`: `route.fulfill` bodies are strings, so binary bytes do not survive the round trip. + [Test] + public async Task Should_be_able_to_download_a_inline_PDF_file_via_response_interception() + { + await ExpectedToFailAsync("the downloaded bytes differ from the asset", async () => + { + await Browser.GotoAsync("/empty.html"); + await Browser.RouteAsync("**/empty.pdf", async route => + { + var response = await route.FetchAsync(); + var headers = new Dictionary(response.Headers) { ["Content-Disposition"] = "attachment" }; + await route.FulfillAsync(new RouteFulfillResponse { Status = response.Status, Headers = headers, Body = await response.TextAsync() }); + }); + await Browser.GotoAsync(Content("""open""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + await AssertDownloadToPdf(download, Asset("empty.pdf"), thrown: true); + }); + } + + [Test] + public async Task Should_be_able_to_download_a_inline_PDF_file_via_navigation() + { + await Browser.GotoAsync("/empty.html"); + await Browser.GotoAsync(Content("""open""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + await AssertDownloadToPdf(download, Asset("empty.pdf")); + } + + [Test] + public async Task Should_download_even_if_there_is_no_attachment_value() + { + await Browser.GotoAsync(Content($"""download""")); + await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + } + + [Test] + public async Task Should_convert_navigation_to_a_resource_with_unsupported_mime_type_into_download() + { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await Browser.GotoAsync("/empty.html"); + await Browser.WaitForDownloadAsync(async () => + { + try + { + await Browser.GotoAsync(Respond(new Dictionary { ["content-type"] = "application/octet-stream" })); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Upstream: `.catch(() => undefined)`. + } + }); + } + + [Test] + public async Task Should_download_links_with_data_url() + { + await Browser.GotoAsync(Content("""Download!""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + Assert.That(download.SuggestedFilename, Is.EqualTo("SomeFile.txt")); + } + + [Test] + public async Task Should_download_successfully_when_routing() + { + await Browser.RouteAsync("**/*", route => route.ContinueAsync()); + await Browser.GotoAsync("/empty.html"); + await Browser.GotoAsync(Content($"""download""")); + var download = await Browser.WaitForDownloadAsync(() => Browser.Locator("a").TapAsync()); + Assert.That(download.SuggestedFilename, Is.EqualTo("foo.zip")); + } + + /// + /// Checks a saved download is the file at byte for byte, PDF magic first, Playwright's + /// assertDownloadToPDF. With it throws instead of asserting (for a body run by ). + /// + private static async Task AssertDownloadToPdf(BrowserDownload download, string filePath, bool thrown = false) + { + var data = await File.ReadAllBytesAsync(download.AbsolutePath); + var expected = await File.ReadAllBytesAsync(filePath); + var magic = "%PDF"u8.ToArray(); + if (thrown) + { + // The known difference is the bytes only: the name is right and the file is a different size or has other content. + Equal(Path.GetFileName(filePath), download.SuggestedFilename); + if (!data.AsSpan().StartsWith(magic) || !data.AsSpan().SequenceEqual(expected)) + { + throw new InvalidOperationException($"the downloaded bytes differ from the asset ({data.Length} bytes, expected {expected.Length})"); + } + + return; + } + + Assert.That(download.SuggestedFilename, Is.EqualTo(Path.GetFileName(filePath))); + Assert.That(data.AsSpan().StartsWith(magic), Is.True); + Assert.That(data.AsSpan().SequenceEqual(expected), Is.True); + } +} diff --git a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs index eb30bd386..568a86256 100644 --- a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs +++ b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs @@ -39,6 +39,24 @@ public static async Task After(int milliseconds, Func next) /// Another origin on the same app, Playwright's server.CROSS_PROCESS_PREFIX. public static string CROSS => E2E.Playground.Testbed.Url.Replace("127.0.0.1", "localhost", StringComparison.Ordinal); + /// What threw, or null when it did not throw (upstream's failure). + public static async Task Failure(Func act) + { + try + { + await act().ConfigureAwait(false); + return null; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return ex; + } + } + + /// A path of /respond answering with and (upstream's respond). + public static string Respond(Dictionary headers, string body = "Hello world") => + $"/respond?headers={Uri.EscapeDataString(System.Text.Json.JsonSerializer.Serialize(headers))}&body={Uri.EscapeDataString(body)}"; + /// A path that serves as a page, for Playwright's page.setContent(html). public static string Content(string html) => "/content?html=" + Convert.ToBase64String(Encoding.UTF8.GetBytes(html)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/chromium-linux.zip b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/chromium-linux.zip new file mode 100644 index 000000000..9c00ec080 Binary files /dev/null and b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/chromium-linux.zip differ diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/download-blob.html b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/download-blob.html new file mode 100644 index 000000000..3c4a3d813 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/download-blob.html @@ -0,0 +1,29 @@ + + + + Blob Download Example + + + + Download + + diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/empty.pdf b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/empty.pdf new file mode 100644 index 000000000..ed845a637 Binary files /dev/null and b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/empty.pdf differ