diff --git a/src/Playwright.Nunit/Playwright.Nunit.csproj b/src/Playwright.Nunit/Playwright.Nunit.csproj new file mode 100644 index 0000000000..1a762cf088 --- /dev/null +++ b/src/Playwright.Nunit/Playwright.Nunit.csproj @@ -0,0 +1,15 @@ + + + + net10.0 + Microsoft.Playwright.Nunit + Microsoft.Playwright.Nunit + + + + + + + + + diff --git a/src/Playwright.Nunit/PlaywrightTestAttribute.cs b/src/Playwright.Nunit/PlaywrightTestAttribute.cs new file mode 100644 index 0000000000..4d37cc8298 --- /dev/null +++ b/src/Playwright.Nunit/PlaywrightTestAttribute.cs @@ -0,0 +1,75 @@ +using System; + +namespace Microsoft.Playwright.Nunit +{ + /// + /// Enables decorating test facts with information about the corresponding test in the upstream repository. + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + public class PlaywrightTestAttribute : Attribute + { + /// + /// Gets the product based on the PRODUCT environment variable. + /// + public static string Product => string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PRODUCT")) + ? "CHROMIUM" + : Environment.GetEnvironmentVariable("PRODUCT"); + + /// + /// Gets a value indicating whether we are testing Chromium. + /// + public static bool IsChromium => Product.Equals("CHROMIUM", StringComparison.OrdinalIgnoreCase); + + /// + /// Gets a value indicating whether we are testing Firefox. + /// + public static bool IsFirefox => Product.Equals("FIREFOX", StringComparison.OrdinalIgnoreCase); + + /// + /// Gets a value indicating whether we are testing WebKit. + /// + public static bool IsWebkit => Product.Equals("WEBKIT", StringComparison.OrdinalIgnoreCase); + + /// + /// Creates a new instance of the attribute. + /// + /// + /// + public PlaywrightTestAttribute(string fileName, string nameOfTest) + { + FileName = fileName; + TestName = nameOfTest; + } + + /// + /// Creates a new instance of the attribute. + /// + /// + /// + /// + public PlaywrightTestAttribute(string fileName, string describe, string nameOfTest) : this(fileName, nameOfTest) + { + Describe = describe; + } + + /// + /// The file name origin of the test. + /// + public string FileName { get; } + + /// + /// Returns the trimmed file name. + /// + public string TrimmedName => FileName.Substring(0, FileName.IndexOf('.')); + + /// + /// The name of the test, the decorated code is based on. + /// + public string TestName { get; } + + /// + /// The describe of the test, the decorated code is based on, if one exists. + /// + public string Describe { get; } + } +} diff --git a/src/Playwright.Tests/Attributes/SkipBrowserAndPlatformFact.cs b/src/Playwright.Tests/Attributes/SkipBrowserAndPlatformFact.cs index 092e9d1ef6..6eb6ec0ced 100644 --- a/src/Playwright.Tests/Attributes/SkipBrowserAndPlatformFact.cs +++ b/src/Playwright.Tests/Attributes/SkipBrowserAndPlatformFact.cs @@ -1,13 +1,25 @@ -using System.Runtime.InteropServices; -using Xunit; +using System; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using OSPlatform = System.Runtime.InteropServices.OSPlatform; +using RuntimeInformation = System.Runtime.InteropServices.RuntimeInformation; namespace Microsoft.Playwright.Tests.Attributes { /// /// Skip browsers and/or platforms /// - public class SkipBrowserAndPlatformFact : FactAttribute + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class SkipBrowserAndPlatformFact : NUnitAttribute, IApplyToTest { + private readonly bool _skipFirefox; + private readonly bool _skipChromium; + private readonly bool _skipWebkit; + private readonly bool _skipOSX; + private readonly bool _skipWindows; + private readonly bool _skipLinux; + /// /// Creates a new /// @@ -25,14 +37,26 @@ public SkipBrowserAndPlatformFact( bool skipWindows = false, bool skipLinux = false) { - Timeout = TestConstants.DefaultTestTimeout; + _skipFirefox = skipFirefox; + _skipChromium = skipChromium; + _skipWebkit = skipWebkit; + _skipOSX = skipOSX; + _skipWindows = skipWindows; + _skipLinux = skipLinux; + } - if (SkipBrowser(skipFirefox, skipChromium, skipWebkit) && SkipPlatform(skipOSX, skipWindows, skipLinux)) + public void ApplyToTest(Test test) + { + if (ShouldSkip()) { - Skip = "Skipped by browser/platform"; + test.RunState = RunState.Ignored; + test.Properties.Set(PropertyNames.SkipReason, "Skipped by browser/platform"); } } + private bool ShouldSkip() + => SkipBrowser(_skipFirefox, _skipChromium, _skipWebkit) && SkipPlatform(_skipOSX, _skipWindows, _skipLinux); + private static bool SkipPlatform(bool skipOSX, bool skipWindows, bool skipLinux) => ( diff --git a/src/Playwright.Tests/BaseTests/PlaywrightSharpBaseTest.cs b/src/Playwright.Tests/BaseTests/PlaywrightSharpBaseTest.cs index b927f3a7d0..8472e7c2f7 100644 --- a/src/Playwright.Tests/BaseTests/PlaywrightSharpBaseTest.cs +++ b/src/Playwright.Tests/BaseTests/PlaywrightSharpBaseTest.cs @@ -1,25 +1,14 @@ -using System; using System.IO; -using System.Reflection; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Microsoft.Playwright; -using Microsoft.Playwright.Testing.Xunit; -using Microsoft.Playwright.Tests.Helpers; using Microsoft.Playwright.Tests.TestServer; -using Microsoft.Playwright.Transport.Channels; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests.BaseTests { /// /// This base tests setup logging and http servers /// - public class PlaywrightSharpBaseTest : IDisposable + public class PlaywrightSharpBaseTest { - private readonly XunitLoggerProvider _loggerProvider; - private readonly ILogger _httpLogger; - internal IPlaywright Playwright => PlaywrightSharpBrowserLoaderFixture.Playwright; internal string BaseDirectory { get; set; } internal IBrowserType BrowserType => Playwright[TestConstants.Product]; @@ -27,7 +16,8 @@ public class PlaywrightSharpBaseTest : IDisposable internal SimpleServer Server => PlaywrightSharpLoader.Server; internal SimpleServer HttpsServer => PlaywrightSharpLoader.HttpsServer; - internal PlaywrightSharpBaseTest(ITestOutputHelper output) + [SetUp] + public void BaseSetUp() { BaseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "workspace"); var dirInfo = new DirectoryInfo(BaseDirectory); @@ -37,42 +27,8 @@ internal PlaywrightSharpBaseTest(ITestOutputHelper output) dirInfo.Create(); } - Initialize(); - - _loggerProvider = new XunitLoggerProvider(output); - _httpLogger = TestConstants.LoggerFactory.CreateLogger(); - TestConstants.LoggerFactory.AddProvider(_loggerProvider); - Server.RequestReceived += Server_RequestReceived; - HttpsServer.RequestReceived += Server_RequestReceived; - - output.WriteLine($"Running {GetDisplayName(output)}"); - } - - private void Server_RequestReceived(object sender, RequestReceivedEventArgs e) - { - _httpLogger.LogInformation($"Incoming request: {e.Request.Path}"); - } - - private static string GetDisplayName(ITestOutputHelper output) - { - var type = output.GetType(); - var testMember = type.GetField("test", BindingFlags.Instance | BindingFlags.NonPublic); - var test = (ITest)testMember.GetValue(output); - return test.DisplayName; - } - - internal void Initialize() - { Server.Reset(); HttpsServer.Reset(); } - - /// - public virtual void Dispose() - { - Server.RequestReceived -= Server_RequestReceived; - HttpsServer.RequestReceived -= Server_RequestReceived; - _loggerProvider.Dispose(); - } } } diff --git a/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserBaseTest.cs b/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserBaseTest.cs index 1132fd3668..8b7dd3e399 100644 --- a/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserBaseTest.cs +++ b/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserBaseTest.cs @@ -1,19 +1,10 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Xunit; -using Xunit.Abstractions; - namespace Microsoft.Playwright.Tests.BaseTests { /// - /// Based on , this base class also creates a new Browser + /// Based on , this base class also provides access to the Browser. /// public class PlaywrightSharpBrowserBaseTest : PlaywrightSharpBaseTest { internal IBrowser Browser => PlaywrightSharpBrowserLoaderFixture.Browser; - - internal PlaywrightSharpBrowserBaseTest(ITestOutputHelper output) : base(output) - { - } } } diff --git a/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserContextBaseTest.cs b/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserContextBaseTest.cs index 554a461c24..fc0b11eb69 100644 --- a/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserContextBaseTest.cs +++ b/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserContextBaseTest.cs @@ -1,34 +1,26 @@ -using System; -using System.IO; using System.Threading.Tasks; -using Microsoft.Playwright.Helpers; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests.BaseTests { /// - /// Based on , this calss creates a new + /// Based on , this class creates a new /// - public class PlaywrightSharpBrowserContextBaseTest : PlaywrightSharpBrowserBaseTest, IAsyncLifetime + public class PlaywrightSharpBrowserContextBaseTest : PlaywrightSharpBrowserBaseTest { - internal PlaywrightSharpBrowserContextBaseTest(ITestOutputHelper output) : base(output) - { - } - internal IBrowserContext Context { get; set; } - /// - public virtual async Task DisposeAsync() + [SetUp] + public virtual async Task ContextSetUp() { - await Context.CloseAsync(); + Context = await Browser.NewContextAsync(); + Context.DefaultTimeout = TestConstants.DefaultPuppeteerTimeout; } - /// - public virtual async Task InitializeAsync() + [TearDown] + public virtual async Task ContextTearDown() { - Context = await Browser.NewContextAsync(); - Context.DefaultTimeout = TestConstants.DefaultPuppeteerTimeout; + await Context.CloseAsync(); } } } diff --git a/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserLoaderCollection.cs b/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserLoaderCollection.cs deleted file mode 100644 index 13fd06d05b..0000000000 --- a/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserLoaderCollection.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Xunit; - -namespace Microsoft.Playwright.Tests.BaseTests -{ - /// This class has no code, and is never created. Its purpose is simply - /// to be the place to apply [CollectionDefinition] and all the ICollectionFixture interfaces. - /// Recipe from https://xunit.github.io/docs/shared-context.html#class-fixture - [CollectionDefinition(TestConstants.TestFixtureBrowserCollectionName, DisableParallelization = true)] - public class PlaywrightSharpBrowserLoaderCollection : ICollectionFixture - { - } -} diff --git a/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserLoaderFixture.cs b/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserLoaderFixture.cs index 5c94e810c8..535b808260 100644 --- a/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserLoaderFixture.cs +++ b/src/Playwright.Tests/BaseTests/PlaywrightSharpBrowserLoaderFixture.cs @@ -1,25 +1,18 @@ using System; using System.Threading.Tasks; -using Xunit; namespace Microsoft.Playwright.Tests.BaseTests { /// /// This class setup a single browser instance for tests. /// - public class PlaywrightSharpBrowserLoaderFixture : IAsyncLifetime + public class PlaywrightSharpBrowserLoaderFixture { internal static IPlaywright Playwright { get; private set; } internal static IBrowser Browser { get; private set; } - /// - public Task InitializeAsync() => LaunchBrowserAsync(); - - /// - public Task DisposeAsync() => ShutDownAsync(); - - private static async Task LaunchBrowserAsync() + internal static async Task LaunchBrowserAsync() { try { diff --git a/src/Playwright.Tests/BaseTests/PlaywrightSharpPageBaseTest.cs b/src/Playwright.Tests/BaseTests/PlaywrightSharpPageBaseTest.cs index e66b6b7388..c80a2f0f31 100644 --- a/src/Playwright.Tests/BaseTests/PlaywrightSharpPageBaseTest.cs +++ b/src/Playwright.Tests/BaseTests/PlaywrightSharpPageBaseTest.cs @@ -1,7 +1,7 @@ /* * MIT License * - * Copyright (c) 2020 Darío Kondratiuk + * Copyright (c) 2020 Dario Kondratiuk * Copyright (c) 2020 Meir Blachman * Modifications copyright (c) Microsoft Corporation. * @@ -23,31 +23,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -using System; using System.Threading.Tasks; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests.BaseTests { /// - /// Based on , this class will create a new Page. + /// Based on , this class will create a new Page. /// public class PlaywrightSharpPageBaseTest : PlaywrightSharpBrowserContextBaseTest { - internal PlaywrightSharpPageBaseTest(ITestOutputHelper output) : base(output) - { - } - /// /// Gets or sets the Page. /// protected IPage Page { get; set; } - /// - public override async Task InitializeAsync() + /// + public override async Task ContextSetUp() { - await base.InitializeAsync(); + await base.ContextSetUp(); Page = await Context.NewPageAsync(); } diff --git a/src/Playwright.Tests/BaseTests/PlaywrightSharpSetUpFixture.cs b/src/Playwright.Tests/BaseTests/PlaywrightSharpSetUpFixture.cs new file mode 100644 index 0000000000..672f523971 --- /dev/null +++ b/src/Playwright.Tests/BaseTests/PlaywrightSharpSetUpFixture.cs @@ -0,0 +1,25 @@ +using System.Threading.Tasks; +using NUnit.Framework; + +[assembly: NonParallelizable] + +namespace Microsoft.Playwright.Tests.BaseTests +{ + [SetUpFixture] + public class PlaywrightSharpSetUpFixture + { + [OneTimeSetUp] + public async Task GlobalSetUp() + { + await PlaywrightSharpLoader.SetupAsync(); + await PlaywrightSharpBrowserLoaderFixture.LaunchBrowserAsync(); + } + + [OneTimeTearDown] + public async Task GlobalTearDown() + { + await PlaywrightSharpBrowserLoaderFixture.ShutDownAsync(); + await PlaywrightSharpLoader.TeardownAsync(); + } + } +} diff --git a/src/Playwright.Tests/BaseTests/PlaywrightXunitTestAssemblyRunner.cs b/src/Playwright.Tests/BaseTests/PlaywrightXunitTestAssemblyRunner.cs deleted file mode 100644 index f6bad556d8..0000000000 --- a/src/Playwright.Tests/BaseTests/PlaywrightXunitTestAssemblyRunner.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Xunit; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Microsoft.Playwright.Tests.BaseTests -{ - /// - public class PlaywrightXunitTestAssemblyRunner : XunitTestAssemblyRunner - { - /// - public PlaywrightXunitTestAssemblyRunner(ITestAssembly testAssembly, IEnumerable testCases, IMessageSink diagnosticMessageSink, IMessageSink executionMessageSink, ITestFrameworkExecutionOptions executionOptions) : base(testAssembly, testCases, diagnosticMessageSink, executionMessageSink, executionOptions) - { - } - - /// - protected override async Task AfterTestAssemblyStartingAsync() - { - await base.AfterTestAssemblyStartingAsync(); - await PlaywrightSharpLoader.SetupAsync(); - } - - /// - protected override async Task BeforeTestAssemblyFinishedAsync() - { - await base.BeforeTestAssemblyFinishedAsync(); - await PlaywrightSharpLoader.TeardownAsync(); - } - } -} diff --git a/src/Playwright.Tests/BaseTests/PlaywrightXunitTestFramework.cs b/src/Playwright.Tests/BaseTests/PlaywrightXunitTestFramework.cs deleted file mode 100644 index da80650bf5..0000000000 --- a/src/Playwright.Tests/BaseTests/PlaywrightXunitTestFramework.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Reflection; -using Xunit; -using Xunit.Abstractions; -using Xunit.Sdk; - -[assembly: TestFramework("Microsoft.Playwright.Tests.BaseTests.PlaywrightXunitTestFramework", "Microsoft.Playwright.Tests")] -[assembly: CollectionBehavior(DisableTestParallelization = true)] - -namespace Microsoft.Playwright.Tests.BaseTests -{ - /// - public class PlaywrightXunitTestFramework : XunitTestFramework - { - /// - public PlaywrightXunitTestFramework(IMessageSink messageSink) : base(messageSink) - { - } - - /// - protected override ITestFrameworkExecutor CreateExecutor(AssemblyName assemblyName) - => new PlaywrightXunitTestFrameworkExecutor(assemblyName, SourceInformationProvider, DiagnosticMessageSink); - } -} diff --git a/src/Playwright.Tests/BaseTests/PlaywrightXunitTestFrameworkExecutor.cs b/src/Playwright.Tests/BaseTests/PlaywrightXunitTestFrameworkExecutor.cs deleted file mode 100644 index 841e629466..0000000000 --- a/src/Playwright.Tests/BaseTests/PlaywrightXunitTestFrameworkExecutor.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using System.Reflection; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Microsoft.Playwright.Tests.BaseTests -{ - /// - public class PlaywrightXunitTestFrameworkExecutor : XunitTestFrameworkExecutor - { - /// - public PlaywrightXunitTestFrameworkExecutor(AssemblyName assemblyName, ISourceInformationProvider sourceInformationProvider, IMessageSink diagnosticMessageSink) : base(assemblyName, sourceInformationProvider, diagnosticMessageSink) - { - } - - /// - protected override void RunTestCases(IEnumerable testCases, IMessageSink executionMessageSink, ITestFrameworkExecutionOptions executionOptions) - { - using (var assemblyRunner = new PlaywrightXunitTestAssemblyRunner(TestAssembly, testCases, DiagnosticMessageSink, executionMessageSink, executionOptions)) - { - assemblyRunner.RunAsync(); - } - } - } -} diff --git a/src/Playwright.Tests/BeforeUnloadTests.cs b/src/Playwright.Tests/BeforeUnloadTests.cs index a16fe6c81e..9be351dc9b 100644 --- a/src/Playwright.Tests/BeforeUnloadTests.cs +++ b/src/Playwright.Tests/BeforeUnloadTests.cs @@ -1,22 +1,13 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BeforeUnloadTests : PlaywrightSharpPageBaseTest - { - /// - public BeforeUnloadTests(ITestOutputHelper output) : base(output) - { - } - - - [PlaywrightTest("beforeunload.spec.ts", "should run beforeunload if asked for")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("beforeunload.spec.ts", "should run beforeunload if asked for")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRunBeforeunloadIfAskedFor() { var newPage = await Context.NewPageAsync(); @@ -28,19 +19,19 @@ public async Task ShouldRunBeforeunloadIfAskedFor() var dialogTask = newPage.WaitForEventAsync(PageEvent.Dialog); var pageClosingTask = newPage.CloseAsync(true); var dialog = await dialogTask; - Assert.Equal(DialogType.BeforeUnload, dialog.Type); - Assert.Empty(dialog.DefaultValue); + Assert.That(dialog.Type, Is.EqualTo(DialogType.BeforeUnload)); + Assert.That(dialog.DefaultValue, Is.Empty); if (TestConstants.IsChromium) { - Assert.Empty(dialog.Message); + Assert.That(dialog.Message, Is.Empty); } else if (TestConstants.IsWebKit) { - Assert.Equal("Leave?", dialog.Message); + Assert.That(dialog.Message, Is.EqualTo("Leave?")); } else { - Assert.Equal("This page is asking you to confirm that you want to leave - data you have entered may not be saved.", dialog.Message); + Assert.That(dialog.Message, Is.EqualTo("This page is asking you to confirm that you want to leave - data you have entered may not be saved.")); } await dialog.AcceptAsync(); @@ -48,7 +39,7 @@ public async Task ShouldRunBeforeunloadIfAskedFor() } [PlaywrightTest("beforeunload.spec.ts", "should *not* run beforeunload by default")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotRunBeforeunloadByDefault() { var newPage = await Context.NewPageAsync(); diff --git a/src/Playwright.Tests/BrowserContextAddCookiesTests.cs b/src/Playwright.Tests/BrowserContextAddCookiesTests.cs index 302f24c64e..9d96604bd9 100644 --- a/src/Playwright.Tests/BrowserContextAddCookiesTests.cs +++ b/src/Playwright.Tests/BrowserContextAddCookiesTests.cs @@ -2,23 +2,15 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextAddCookiesTests : PlaywrightSharpPageBaseTest - { - /// - public BrowserContextAddCookiesTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -28,22 +20,22 @@ public async Task ShouldWork() Name = "password", Value = "123456" } }); - Assert.Equal("password=123456", await Page.EvaluateAsync("document.cookie")); + Assert.That(await Page.EvaluateAsync("document.cookie"), Is.EqualTo("password=123456")); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should roundtrip cookie")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRoundtripCookie() { await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("username=John Doe", await Page.EvaluateAsync(@"timestamp => { + Assert.That(await Page.EvaluateAsync(@"timestamp => { const date = new Date(timestamp); document.cookie = `username=John Doe;expires=${date.toUTCString()}`; return document.cookie; - }", new DateTime(2038, 1, 1))); + }", new DateTime(2038, 1, 1)), Is.EqualTo("username=John Doe")); var cookies = await Context.GetCookiesAsync(); await Context.ClearCookiesAsync(); - Assert.Empty(await Context.GetCookiesAsync()); + Assert.That(await Context.GetCookiesAsync(), Is.Empty); await Context.AddCookiesAsync(cookies.Select(c => new Cookie() { Domain = c.Domain, @@ -56,11 +48,11 @@ public async Task ShouldRoundtripCookie() Value = c.Value })); var newCookies = await Context.GetCookiesAsync(); - Assert.Equal(cookies, newCookies); + Assert.That(newCookies, Is.EqualTo(cookies)); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should send cookie header")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendCookieHeader() { string cookie = string.Empty; @@ -79,11 +71,11 @@ await Context.AddCookiesAsync(new Cookie var page = await Context.NewPageAsync(); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("cookie=value", cookie); + Assert.That(cookie, Is.EqualTo("cookie=value")); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should isolate cookies in browser contexts")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIsolateCookiesInBrowserContexts() { await using var anotherContext = await Browser.NewContextAsync(); @@ -104,16 +96,16 @@ await anotherContext.AddCookiesAsync(new Cookie var cookies1 = await Context.GetCookiesAsync(); var cookies2 = await anotherContext.GetCookiesAsync(); - Assert.Single(cookies1); - Assert.Single(cookies2); - Assert.Equal("isolatecookie", cookies1.ElementAt(0).Name); - Assert.Equal("page1value", cookies1.ElementAt(0).Value); - Assert.Equal("isolatecookie", cookies2.ElementAt(0).Name); - Assert.Equal("page2value", cookies2.ElementAt(0).Value); + Assert.That(cookies1, Has.Count.EqualTo(1)); + Assert.That(cookies2, Has.Count.EqualTo(1)); + Assert.That(cookies1.ElementAt(0).Name, Is.EqualTo("isolatecookie")); + Assert.That(cookies1.ElementAt(0).Value, Is.EqualTo("page1value")); + Assert.That(cookies2.ElementAt(0).Name, Is.EqualTo("isolatecookie")); + Assert.That(cookies2.ElementAt(0).Value, Is.EqualTo("page2value")); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should isolate session cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIsolateSessionCookies() { Server.SetRoute("/setcookie.html", context => @@ -132,11 +124,11 @@ public async Task ShouldIsolateSessionCookies() page = await context2.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); var cookies = await context2.GetCookiesAsync(); - Assert.Empty(cookies); + Assert.That(cookies, Is.Empty); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should isolate persistent cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIsolatePersistentCookies() { Server.SetRoute("/setcookie.html", context => @@ -155,14 +147,14 @@ await TaskUtils.WhenAll( page2.GoToAsync(TestConstants.EmptyPage)); var (cookies1, cookies2) = await TaskUtils.WhenAll(Context.GetCookiesAsync(), context2.GetCookiesAsync()); - Assert.Single(cookies1); - Assert.Equal("persistent", cookies1.First().Name); - Assert.Equal("persistent-value", cookies1.First().Value); - Assert.Empty(cookies2); + Assert.That(cookies1, Has.Count.EqualTo(1)); + Assert.That(cookies1.First().Name, Is.EqualTo("persistent")); + Assert.That(cookies1.First().Value, Is.EqualTo("persistent-value")); + Assert.That(cookies2, Is.Empty); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should isolate send cookie header")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIsolateSendCookieHeader() { string cookie = string.Empty; @@ -181,16 +173,16 @@ await Context.AddCookiesAsync(new Cookie var page = await Context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/empty.html"); - Assert.Equal("sendcookie=value", cookie); + Assert.That(cookie, Is.EqualTo("sendcookie=value")); var context = await Browser.NewContextAsync(); page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Empty(cookie); + Assert.That(cookie, Is.Empty); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should isolate cookies between launches")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIsolateCookiesBetweenLaunches() { await using (var browser1 = await Playwright[TestConstants.Product].LaunchDefaultAsync()) @@ -210,12 +202,12 @@ await Context.AddCookiesAsync(new Cookie { var context1 = await Browser.NewContextAsync(); var cookies = await context1.GetCookiesAsync(); - Assert.Empty(cookies); + Assert.That(cookies, Is.Empty); } } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should set multiple cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSetMultipleCookies() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -235,21 +227,18 @@ await Context.AddCookiesAsync( } ); - Assert.Equal( - new[] + Assert.That(await Page.EvaluateAsync(@"() => { + const cookies = document.cookie.split(';'); + return cookies.map(cookie => cookie.trim()).sort(); + }"), Is.EqualTo(new[] { "multiple-1=123456", "multiple-2=bar" - }, - await Page.EvaluateAsync(@"() => { - const cookies = document.cookie.split(';'); - return cookies.map(cookie => cookie.trim()).sort(); - }") - ); + })); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should have |expires| set to |-1| for session cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveExpiresSetToMinus1ForSessionCookies() { await Context.AddCookiesAsync(new Cookie @@ -261,11 +250,11 @@ await Context.AddCookiesAsync(new Cookie var cookies = await Context.GetCookiesAsync(); - Assert.Equal(-1, cookies.ElementAt(0).Expires); + Assert.That(cookies.ElementAt(0).Expires, Is.EqualTo(-1)); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should set cookie with reasonable defaults")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSetCookieWithReasonableDefaults() { await Context.AddCookiesAsync(new Cookie @@ -275,19 +264,20 @@ await Context.AddCookiesAsync(new Cookie Value = "123456" }); - var cookie = Assert.Single(await Context.GetCookiesAsync()); - Assert.Equal("defaults", cookie.Name); - Assert.Equal("123456", cookie.Value); - Assert.Equal("localhost", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(-1, cookie.Expires); - Assert.False(cookie.HttpOnly); - Assert.False(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(await Context.GetCookiesAsync(), Has.Count.EqualTo(1)); + var cookie = (await Context.GetCookiesAsync()).Single(); + Assert.That(cookie.Name, Is.EqualTo("defaults")); + Assert.That(cookie.Value, Is.EqualTo("123456")); + Assert.That(cookie.Domain, Is.EqualTo("localhost")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(cookie.Expires, Is.EqualTo(-1)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should set a cookie with a path")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSetACookieWithAPath() { await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); @@ -298,30 +288,31 @@ await Context.AddCookiesAsync(new Cookie Name = "gridcookie", Value = "GRID" }); - var cookie = Assert.Single(await Context.GetCookiesAsync()); - Assert.Equal("gridcookie", cookie.Name); - Assert.Equal("GRID", cookie.Value); - Assert.Equal("localhost", cookie.Domain); - Assert.Equal("/grid.html", cookie.Path); - Assert.Equal(cookie.Expires, -1); - Assert.False(cookie.HttpOnly); - Assert.False(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); - - Assert.Equal("gridcookie=GRID", await Page.EvaluateAsync("document.cookie")); + Assert.That(await Context.GetCookiesAsync(), Has.Count.EqualTo(1)); + var cookie = (await Context.GetCookiesAsync()).Single(); + Assert.That(cookie.Name, Is.EqualTo("gridcookie")); + Assert.That(cookie.Value, Is.EqualTo("GRID")); + Assert.That(cookie.Domain, Is.EqualTo("localhost")); + Assert.That(cookie.Path, Is.EqualTo("/grid.html")); + Assert.That(-1, Is.EqualTo(cookie.Expires)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); + + Assert.That(await Page.EvaluateAsync("document.cookie"), Is.EqualTo("gridcookie=GRID")); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Empty(await Page.EvaluateAsync("document.cookie")); + Assert.That(await Page.EvaluateAsync("document.cookie"), Is.Empty); await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); - Assert.Equal("gridcookie=GRID", await Page.EvaluateAsync("document.cookie")); + Assert.That(await Page.EvaluateAsync("document.cookie"), Is.EqualTo("gridcookie=GRID")); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should not set a cookie with blank page URL")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotSetACookieWithBlankPageURL() { await Page.GoToAsync(TestConstants.AboutBlank); - var exception = await Assert.ThrowsAsync(async () + var exception = Assert.ThrowsAsync(async () => await Context.AddCookiesAsync( new Cookie { @@ -335,15 +326,15 @@ public async Task ShouldNotSetACookieWithBlankPageURL() Name = "example-cookie-blank", Value = "best" })); - Assert.Equal("Blank page can not have cookie \"example-cookie-blank\"", exception.Message); + Assert.That(exception.Message, Is.EqualTo("Blank page can not have cookie \"example-cookie-blank\"")); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should not set a cookie on a data URL page")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotSetACookieOnADataURLPage() { await Page.GoToAsync("data:,Hello%2C%20World!"); - var exception = await Assert.ThrowsAnyAsync(async () + var exception = Assert.CatchAsync(async () => await Context.AddCookiesAsync( new Cookie { @@ -352,11 +343,11 @@ public async Task ShouldNotSetACookieOnADataURLPage() Value = "best" })); - Assert.Equal("Data URL page can not have cookie \"example-cookie\"", exception.Message); + Assert.That(exception.Message, Is.EqualTo("Data URL page can not have cookie \"example-cookie\"")); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should default to setting secure cookie for HTTPS websites")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDefaultToSettingSecureCookieForHttpsWebsites() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -368,12 +359,13 @@ await Context.AddCookiesAsync(new Cookie Name = "foo", Value = "bar" }); - var cookie = Assert.Single(await Context.GetCookiesAsync(secureUrl)); - Assert.True(cookie.Secure); + Assert.That(await Context.GetCookiesAsync(secureUrl), Has.Count.EqualTo(1)); + var cookie = (await Context.GetCookiesAsync(secureUrl)).Single(); + Assert.That(cookie.Secure, Is.True); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should be able to set unsecure cookie for HTTP website")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToSetUnsecureCookieForHttpWebSite() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -385,30 +377,32 @@ await Context.AddCookiesAsync(new Cookie Name = "foo", Value = "bar" }); - var cookie = Assert.Single(await Context.GetCookiesAsync(SecureUrl)); - Assert.False(cookie.Secure); + Assert.That(await Context.GetCookiesAsync(SecureUrl), Has.Count.EqualTo(1)); + var cookie = (await Context.GetCookiesAsync(SecureUrl)).Single(); + Assert.That(cookie.Secure, Is.False); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should set a cookie on a different domain")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSetACookieOnADifferentDomain() { await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); await Context.AddCookiesAsync(new Cookie { Name = "example-cookie", Value = "best", Url = "https://www.example.com" }); - Assert.Equal(string.Empty, await Page.EvaluateAsync("document.cookie")); - var cookie = Assert.Single(await Context.GetCookiesAsync("https://www.example.com")); - Assert.Equal("example-cookie", cookie.Name); - Assert.Equal("best", cookie.Value); - Assert.Equal("www.example.com", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(cookie.Expires, -1); - Assert.False(cookie.HttpOnly); - Assert.True(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(await Page.EvaluateAsync("document.cookie"), Is.EqualTo(string.Empty)); + Assert.That(await Context.GetCookiesAsync("https://www.example.com"), Has.Count.EqualTo(1)); + var cookie = (await Context.GetCookiesAsync("https://www.example.com")).Single(); + Assert.That(cookie.Name, Is.EqualTo("example-cookie")); + Assert.That(cookie.Value, Is.EqualTo("best")); + Assert.That(cookie.Domain, Is.EqualTo("www.example.com")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(-1, Is.EqualTo(cookie.Expires)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.True); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should set cookies for a frame")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSetCookiesForAFrame() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -430,11 +424,11 @@ await Page.EvaluateAsync(@"src => { return promise; }", TestConstants.ServerUrl + "/grid.html"); - Assert.Equal("frame-cookie=value", await Page.FirstChildFrame().EvaluateAsync("document.cookie")); + Assert.That(await Page.FirstChildFrame().EvaluateAsync("document.cookie"), Is.EqualTo("frame-cookie=value")); } [PlaywrightTest("browsercontext-add-cookies.spec.ts", "should(not) block third party cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotBlockThirdPartyCookies() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -456,20 +450,20 @@ await Page.EvaluateAsync(@"src => { if (allowsThirdPart) { - Assert.Single(cookies); + Assert.That(cookies, Has.Count.EqualTo(1)); var cookie = cookies.First(); - Assert.Equal("127.0.0.1", cookie.Domain); - Assert.Equal(cookie.Expires, -1); - Assert.False(cookie.HttpOnly); - Assert.Equal("username", cookie.Name); - Assert.Equal("/", cookie.Path); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); - Assert.False(cookie.Secure); - Assert.Equal("John Doe", cookie.Value); + Assert.That(cookie.Domain, Is.EqualTo("127.0.0.1")); + Assert.That(-1, Is.EqualTo(cookie.Expires)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Name, Is.EqualTo("username")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.Value, Is.EqualTo("John Doe")); } else { - Assert.Empty(cookies); + Assert.That(cookies, Is.Empty); } } } diff --git a/src/Playwright.Tests/BrowserContextBasicTests.cs b/src/Playwright.Tests/BrowserContextBasicTests.cs index b5baf835d7..a7e757b671 100644 --- a/src/Playwright.Tests/BrowserContextBasicTests.cs +++ b/src/Playwright.Tests/BrowserContextBasicTests.cs @@ -3,39 +3,31 @@ using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextBasicTests : PlaywrightSharpBrowserBaseTest - { - /// - public BrowserContextBasicTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-basic.spec.ts", "should create new context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-basic.spec.ts", "should create new context")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCreateNewContext() { await using var browser = await BrowserType.LaunchDefaultAsync(); - Assert.Empty(browser.Contexts); + Assert.That(browser.Contexts, Is.Empty); await using var context = await browser.NewContextAsync(); - Assert.Single(browser.Contexts); - Assert.Contains(context, browser.Contexts); - Assert.Same(browser, context.Browser); + Assert.That(browser.Contexts, Has.Count.EqualTo(1)); + Assert.That(browser.Contexts, Does.Contain(context)); + Assert.That(context.Browser, Is.SameAs(browser)); await context.CloseAsync(); - Assert.Empty(browser.Contexts); - Assert.Same(browser, context.Browser); + Assert.That(browser.Contexts, Is.Empty); + Assert.That(context.Browser, Is.SameAs(browser)); } [PlaywrightTest("browsercontext-basic.spec.ts", "window.open should use parent tab context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task WindowOpenShouldUseParentTabContext() { await using var context = await Browser.NewContextAsync(); @@ -49,20 +41,20 @@ public async Task WindowOpenShouldUseParentTabContext() page.EvaluateAsync("url => window.open(url)", TestConstants.EmptyPage) ); - Assert.Same(context, popupTarget.Context); + Assert.That(popupTarget.Context, Is.SameAs(context)); await context.CloseAsync(); } [PlaywrightTest("browsercontext-basic.spec.ts", "should isolate localStorage and cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIsolateLocalStorageAndCookies() { // Create two incognito contexts. await using var browser = await BrowserType.LaunchDefaultAsync(); var context1 = await browser.NewContextAsync(); var context2 = await browser.NewContextAsync(); - Assert.Empty(context1.Pages); - Assert.Empty(context2.Pages); + Assert.That(context1.Pages, Is.Empty); + Assert.That(context2.Pages, Is.Empty); // Create a page in first incognito context. var page1 = await context1.NewPageAsync(); @@ -72,8 +64,8 @@ await page1.EvaluateAsync(@"() => { document.cookie = 'name=page1'; }"); - Assert.Single(context1.Pages); - Assert.Empty(context2.Pages); + Assert.That(context1.Pages, Has.Count.EqualTo(1)); + Assert.That(context2.Pages, Is.Empty); // Create a page in second incognito context. var page2 = await context2.NewPageAsync(); @@ -83,24 +75,24 @@ await page2.EvaluateAsync(@"() => { document.cookie = 'name=page2'; }"); - Assert.Single(context1.Pages); - Assert.Equal(page1, context1.Pages.FirstOrDefault()); - Assert.Single(context2.Pages); - Assert.Equal(page2, context2.Pages.FirstOrDefault()); + Assert.That(context1.Pages, Has.Count.EqualTo(1)); + Assert.That(context1.Pages.FirstOrDefault(), Is.EqualTo(page1)); + Assert.That(context2.Pages, Has.Count.EqualTo(1)); + Assert.That(context2.Pages.FirstOrDefault(), Is.EqualTo(page2)); // Make sure pages don't share localstorage or cookies. - Assert.Equal("page1", await page1.EvaluateAsync("() => localStorage.getItem('name')")); - Assert.Equal("name=page1", await page1.EvaluateAsync("() => document.cookie")); - Assert.Equal("page2", await page2.EvaluateAsync("() => localStorage.getItem('name')")); - Assert.Equal("name=page2", await page2.EvaluateAsync("() => document.cookie")); + Assert.That(await page1.EvaluateAsync("() => localStorage.getItem('name')"), Is.EqualTo("page1")); + Assert.That(await page1.EvaluateAsync("() => document.cookie"), Is.EqualTo("name=page1")); + Assert.That(await page2.EvaluateAsync("() => localStorage.getItem('name')"), Is.EqualTo("page2")); + Assert.That(await page2.EvaluateAsync("() => document.cookie"), Is.EqualTo("name=page2")); // Cleanup contexts. await TaskUtils.WhenAll(context1.CloseAsync(), context2.CloseAsync()); - Assert.Empty(browser.Contexts); + Assert.That(browser.Contexts, Is.Empty); } [PlaywrightTest("browsercontext-basic.spec.ts", "should propagate default viewport to the page")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPropagateDefaultViewportToThePage() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -117,7 +109,7 @@ public async Task ShouldPropagateDefaultViewportToThePage() } [PlaywrightTest("browsercontext-basic.spec.ts", "should make a copy of default viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldMakeACopyOfDefaultViewport() { var viewport = new ViewportSize @@ -136,7 +128,7 @@ public async Task ShouldMakeACopyOfDefaultViewport() } [PlaywrightTest("browsercontext-basic.spec.ts", "should respect deviceScaleFactor")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectDeviceScaleFactor() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -145,35 +137,35 @@ public async Task ShouldRespectDeviceScaleFactor() }); var page = await context.NewPageAsync(); - Assert.Equal(3, await page.EvaluateAsync("window.devicePixelRatio")); + Assert.That(await page.EvaluateAsync("window.devicePixelRatio"), Is.EqualTo(3)); } [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow deviceScaleFactor with null viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotAllowDeviceScaleFactorWithViewportDisabled() { - var exception = await Assert.ThrowsAsync(() => Browser.NewContextAsync(new BrowserContextOptions + var exception = Assert.ThrowsAsync(() => Browser.NewContextAsync(new BrowserContextOptions { Viewport = ViewportSize.NoViewport, DeviceScaleFactor = 3, })); - Assert.Equal("\"deviceScaleFactor\" option is not supported with null \"viewport\"", exception.Message); + Assert.That(exception.Message, Is.EqualTo("\"deviceScaleFactor\" option is not supported with null \"viewport\"")); } [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow isMobile with null viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotAllowIsMobileWithViewportDisabled() { - var exception = await Assert.ThrowsAsync(() => Browser.NewContextAsync(new BrowserContextOptions + var exception = Assert.ThrowsAsync(() => Browser.NewContextAsync(new BrowserContextOptions { Viewport = ViewportSize.NoViewport, IsMobile = true, })); - Assert.Equal("\"isMobile\" option is not supported with null \"viewport\"", exception.Message); + Assert.That(exception.Message, Is.EqualTo("\"isMobile\" option is not supported with null \"viewport\"")); } [PlaywrightTest("browsercontext-basic.spec.ts", "close() should work for empty context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task CloseShouldWorkForEmptyContext() { var context = await Browser.NewContextAsync(); @@ -181,18 +173,18 @@ public async Task CloseShouldWorkForEmptyContext() } [PlaywrightTest("browsercontext-basic.spec.ts", "close() should abort waitForEvent")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task CloseShouldAbortWaitForEvent() { var context = await Browser.NewContextAsync(); var waitTask = context.WaitForEventAsync(ContextEvent.Page); await context.CloseAsync(); - var exception = await Assert.ThrowsAsync(() => waitTask); - Assert.Equal("Context closed", exception.Message); + var exception = Assert.ThrowsAsync(() => waitTask); + Assert.That(exception.Message, Is.EqualTo("Context closed")); } [PlaywrightTest("browsercontext-basic.spec.ts", "should not report frameless pages on error")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotReportFramelessPagesOnError() { var context = await Browser.NewContextAsync(); @@ -211,13 +203,13 @@ public async Task ShouldNotReportFramelessPagesOnError() if (popup != null) { - Assert.True(popup.IsClosed); - Assert.NotNull(popup.MainFrame); + Assert.That(popup.IsClosed, Is.True); + Assert.That(popup.MainFrame, Is.Not.Null); } } [PlaywrightTest("browsercontext-basic.spec.ts", "close() should be callable twice")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task CloseShouldBeCallableTwice() { var context = await Browser.NewContextAsync(); @@ -226,34 +218,34 @@ public async Task CloseShouldBeCallableTwice() } [PlaywrightTest("browsercontext-basic.spec.ts", "should return all of the pages")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnAllOfThePages() { await using var context = await Browser.NewContextAsync(); var page = await context.NewPageAsync(); var second = await context.NewPageAsync(); - Assert.Equal(2, context.Pages.Count); - Assert.Contains(page, context.Pages); - Assert.Contains(second, context.Pages); + Assert.That(context.Pages.Count, Is.EqualTo(2)); + Assert.That(context.Pages, Does.Contain(page)); + Assert.That(context.Pages, Does.Contain(second)); } [PlaywrightTest("browsercontext-basic.spec.ts", "BrowserContext.pages()", "should close all belonging pages once closing context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCloseAllBelongingPagesOnceClosingContext() { await using var context = await Browser.NewContextAsync(); await context.NewPageAsync(); - Assert.Single(context.Pages); + Assert.That(context.Pages, Has.Count.EqualTo(1)); await context.CloseAsync(); - Assert.Empty(context.Pages); + Assert.That(context.Pages, Is.Empty); } [PlaywrightTest("browsercontext-basic.spec.ts", "should disable javascript")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDisableJavascript() { await using (var context = await Browser.NewContextAsync(javaScriptEnabled: false)) @@ -261,23 +253,21 @@ public async Task ShouldDisableJavascript() var page = await context.NewPageAsync(); await page.GoToAsync("data:text/html, "); - var exception = await Assert.ThrowsAnyAsync(async () => await page.EvaluateAsync("something")); + var exception = Assert.CatchAsync(async () => await page.EvaluateAsync("something")); - Assert.Contains( - TestConstants.IsWebKit ? "Can\'t find variable: something" : "something is not defined", - exception.Message); + Assert.That(exception.Message, Does.Contain(TestConstants.IsWebKit ? "Can\'t find variable: something" : "something is not defined")); } await using (var context = await Browser.NewContextAsync()) { var page = await context.NewPageAsync(); await page.GoToAsync("data:text/html, "); - Assert.Equal("forbidden", await page.EvaluateAsync("something")); + Assert.That(await page.EvaluateAsync("something"), Is.EqualTo("forbidden")); } } [PlaywrightTest("browsercontext-basic.spec.ts", "should be able to navigate after disabling javascript")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToNavigateAfterDisablingJavascript() { await using var context = await Browser.NewContextAsync(javaScriptEnabled: false); @@ -286,15 +276,15 @@ public async Task ShouldBeAbleToNavigateAfterDisablingJavascript() } [PlaywrightTest("browsercontext-basic.spec.ts", "should work with offline option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithOfflineOption() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions { Offline = true }); var page = await context.NewPageAsync(); - await Assert.ThrowsAsync(() => page.GoToAsync(TestConstants.EmptyPage)); + Assert.ThrowsAsync(() => page.GoToAsync(TestConstants.EmptyPage)); await context.SetOfflineAsync(false); var response = await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [PlaywrightTest("browsercontext-basic.spec.ts", "should emulate navigator.onLine")] @@ -303,11 +293,11 @@ public async Task ShouldEmulateNavigatorOnLine() { await using var context = await Browser.NewContextAsync(); var page = await context.NewPageAsync(); - Assert.True(await page.EvaluateAsync("() => window.navigator.onLine")); + Assert.That(await page.EvaluateAsync("() => window.navigator.onLine"), Is.True); await context.SetOfflineAsync(true); - Assert.False(await page.EvaluateAsync("() => window.navigator.onLine")); + Assert.That(await page.EvaluateAsync("() => window.navigator.onLine"), Is.False); await context.SetOfflineAsync(false); - Assert.True(await page.EvaluateAsync("() => window.navigator.onLine")); + Assert.That(await page.EvaluateAsync("() => window.navigator.onLine"), Is.True); } } } diff --git a/src/Playwright.Tests/BrowserContextCSPTests.cs b/src/Playwright.Tests/BrowserContextCSPTests.cs index 7d4c8de8ca..ebab151355 100644 --- a/src/Playwright.Tests/BrowserContextCSPTests.cs +++ b/src/Playwright.Tests/BrowserContextCSPTests.cs @@ -1,21 +1,13 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextCSPTests : PlaywrightSharpBrowserBaseTest - { - /// - public BrowserContextCSPTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass CSP meta tag")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass CSP meta tag")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBypassCSPMetatag() { // Make sure CSP prohibits addScriptTag. @@ -24,7 +16,7 @@ public async Task ShouldBypassCSPMetatag() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/csp.html"); await page.AddScriptTagAsync(content: "window.__injected = 42;").ContinueWith(_ => Task.CompletedTask); - Assert.Null(await page.EvaluateAsync("window.__injected")); + Assert.That(await page.EvaluateAsync("window.__injected"), Is.Null); } // By-pass CSP and try one more time. await using (var context = await Browser.NewContextAsync(bypassCSP: true)) @@ -32,12 +24,12 @@ public async Task ShouldBypassCSPMetatag() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/csp.html"); await page.AddScriptTagAsync(content: "window.__injected = 42;"); - Assert.Equal(42, await page.EvaluateAsync("window.__injected")); + Assert.That(await page.EvaluateAsync("window.__injected"), Is.EqualTo(42)); } } [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass CSP header")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBypassCSPHeader() { // Make sure CSP prohibits addScriptTag. @@ -48,7 +40,7 @@ public async Task ShouldBypassCSPHeader() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); await page.AddScriptTagAsync(content: "window.__injected = 42;").ContinueWith(_ => Task.CompletedTask); - Assert.Null(await page.EvaluateAsync("window.__injected")); + Assert.That(await page.EvaluateAsync("window.__injected"), Is.Null); } // By-pass CSP and try one more time. @@ -57,27 +49,27 @@ public async Task ShouldBypassCSPHeader() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); await page.AddScriptTagAsync(content: "window.__injected = 42;"); - Assert.Equal(42, await page.EvaluateAsync("window.__injected")); + Assert.That(await page.EvaluateAsync("window.__injected"), Is.EqualTo(42)); } } [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass after cross-process navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBypassAfterCrossProcessNavigation() { await using var context = await Browser.NewContextAsync(bypassCSP: true); var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/csp.html"); await page.AddScriptTagAsync(content: "window.__injected = 42;"); - Assert.Equal(42, await page.EvaluateAsync("window.__injected")); + Assert.That(await page.EvaluateAsync("window.__injected"), Is.EqualTo(42)); await page.GoToAsync(TestConstants.CrossProcessUrl + "/csp.html"); await page.AddScriptTagAsync(content: "window.__injected = 42;"); - Assert.Equal(42, await page.EvaluateAsync("window.__injected")); + Assert.That(await page.EvaluateAsync("window.__injected"), Is.EqualTo(42)); } [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass CSP in iframes as well")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBypassCSPInIframesAsWell() { await using (var context = await Browser.NewContextAsync()) @@ -88,7 +80,7 @@ public async Task ShouldBypassCSPInIframesAsWell() // Make sure CSP prohibits addScriptTag in an iframe. var frame = await FrameUtils.AttachFrameAsync(page, "frame1", TestConstants.ServerUrl + "/csp.html"); await frame.AddScriptTagAsync(content: "window.__injected = 42;").ContinueWith(_ => Task.CompletedTask); - Assert.Null(await frame.EvaluateAsync("() => window.__injected")); + Assert.That(await frame.EvaluateAsync("() => window.__injected"), Is.Null); } // By-pass CSP and try one more time. @@ -100,7 +92,7 @@ public async Task ShouldBypassCSPInIframesAsWell() // Make sure CSP prohibits addScriptTag in an iframe. var frame = await FrameUtils.AttachFrameAsync(page, "frame1", TestConstants.ServerUrl + "/csp.html"); await frame.AddScriptTagAsync(content: "window.__injected = 42;").ContinueWith(_ => Task.CompletedTask); - Assert.Equal(42, await frame.EvaluateAsync("() => window.__injected")); + Assert.That(await frame.EvaluateAsync("() => window.__injected"), Is.EqualTo(42)); } } diff --git a/src/Playwright.Tests/BrowserContextClearCookiesTests.cs b/src/Playwright.Tests/BrowserContextClearCookiesTests.cs index 840ae93b8f..6bbd628b55 100644 --- a/src/Playwright.Tests/BrowserContextClearCookiesTests.cs +++ b/src/Playwright.Tests/BrowserContextClearCookiesTests.cs @@ -1,21 +1,13 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextClearCookiesTests : PlaywrightSharpPageBaseTest - { - /// - public BrowserContextClearCookiesTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-clearcookies.spec.ts", "should clear cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-clearcookies.spec.ts", "should clear cookies")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClearCookes() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -25,15 +17,15 @@ await Context.AddCookiesAsync(new Cookie Name = "cookie1", Value = "1" }); - Assert.Equal("cookie1=1", await Page.EvaluateAsync("document.cookie")); + Assert.That(await Page.EvaluateAsync("document.cookie"), Is.EqualTo("cookie1=1")); await Context.ClearCookiesAsync(); - Assert.Empty(await Context.GetCookiesAsync()); + Assert.That(await Context.GetCookiesAsync(), Is.Empty); await Page.ReloadAsync(); - Assert.Empty(await Page.EvaluateAsync("document.cookie")); + Assert.That(await Page.EvaluateAsync("document.cookie"), Is.Empty); } [PlaywrightTest("browsercontext-clearcookies.spec.ts", "should isolate cookies when clearing")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIsolateWhenClearing() { await using var anotherContext = await Browser.NewContextAsync(); @@ -51,16 +43,16 @@ await anotherContext.AddCookiesAsync(new Cookie Url = TestConstants.EmptyPage }); - Assert.Single(await Context.GetCookiesAsync()); - Assert.Single(await anotherContext.GetCookiesAsync()); + Assert.That(await Context.GetCookiesAsync(), Has.Count.EqualTo(1)); + Assert.That(await anotherContext.GetCookiesAsync(), Has.Count.EqualTo(1)); await Context.ClearCookiesAsync(); - Assert.Empty((await Context.GetCookiesAsync())); - Assert.Single((await anotherContext.GetCookiesAsync())); + Assert.That((await Context.GetCookiesAsync()), Is.Empty); + Assert.That((await anotherContext.GetCookiesAsync()), Has.Count.EqualTo(1)); await anotherContext.ClearCookiesAsync(); - Assert.Empty(await Context.GetCookiesAsync()); - Assert.Empty(await anotherContext.GetCookiesAsync()); + Assert.That(await Context.GetCookiesAsync(), Is.Empty); + Assert.That(await anotherContext.GetCookiesAsync(), Is.Empty); } } } diff --git a/src/Playwright.Tests/BrowserContextCookiesTests.cs b/src/Playwright.Tests/BrowserContextCookiesTests.cs index 4567322665..4ed6e6e68a 100644 --- a/src/Playwright.Tests/BrowserContextCookiesTests.cs +++ b/src/Playwright.Tests/BrowserContextCookiesTests.cs @@ -1,73 +1,65 @@ using System; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextCookiesTests : PlaywrightSharpPageBaseTest - { - /// - public BrowserContextCookiesTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-cookies.spec.ts", "should return no cookies in pristine browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-cookies.spec.ts", "should return no cookies in pristine browser context")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNoCookiesInPristineBrowserContext() - => Assert.Empty(await Context.GetCookiesAsync()); + => Assert.That(await Context.GetCookiesAsync(), Is.Empty); [PlaywrightTest("browsercontext-cookies.spec.ts", "should get a cookie")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldGetACookie() { await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("username=John Doe", await Page.EvaluateAsync(@"() => { + Assert.That(await Page.EvaluateAsync(@"() => { document.cookie = 'username=John Doe'; return document.cookie; - }")); + }"), Is.EqualTo("username=John Doe")); var cookie = (await Page.Context.GetCookiesAsync()).Single(); - Assert.Equal("username", cookie.Name); - Assert.Equal("John Doe", cookie.Value); - Assert.Equal("localhost", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(-1, cookie.Expires); - Assert.False(cookie.HttpOnly); - Assert.False(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(cookie.Name, Is.EqualTo("username")); + Assert.That(cookie.Value, Is.EqualTo("John Doe")); + Assert.That(cookie.Domain, Is.EqualTo("localhost")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(cookie.Expires, Is.EqualTo(-1)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); } [PlaywrightTest("browsercontext-cookies.spec.ts", "should get a non-session cookie")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldGetANonSessionCookie() { await Page.GoToAsync(TestConstants.EmptyPage); var date = new DateTime(2038, 1, 1); - Assert.Equal("username=John Doe", await Page.EvaluateAsync(@"timestamp => { + Assert.That(await Page.EvaluateAsync(@"timestamp => { const date = new Date(timestamp); document.cookie = `username=John Doe;expires=${date.toUTCString()}`; return document.cookie; - }", date)); + }", date), Is.EqualTo("username=John Doe")); var cookie = (await Page.Context.GetCookiesAsync()).Single(); - Assert.Equal("username", cookie.Name); - Assert.Equal("John Doe", cookie.Value); - Assert.Equal("localhost", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(new DateTimeOffset(date).ToUnixTimeSeconds(), cookie.Expires); - Assert.False(cookie.HttpOnly); - Assert.False(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(cookie.Name, Is.EqualTo("username")); + Assert.That(cookie.Value, Is.EqualTo("John Doe")); + Assert.That(cookie.Domain, Is.EqualTo("localhost")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(cookie.Expires, Is.EqualTo(new DateTimeOffset(date).ToUnixTimeSeconds())); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); } [PlaywrightTest("browsercontext-cookies.spec.ts", "should properly report httpOnly cookie")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldProperlyReportHttpOnlyCookie() { Server.SetRoute("/empty.html", context => @@ -77,8 +69,8 @@ public async Task ShouldProperlyReportHttpOnlyCookie() }); await Page.GoToAsync(TestConstants.EmptyPage); var cookies = await Context.GetCookiesAsync(); - Assert.Single(cookies); - Assert.True(cookies.ElementAt(0).HttpOnly); + Assert.That(cookies, Has.Count.EqualTo(1)); + Assert.That(cookies.ElementAt(0).HttpOnly, Is.True); } [PlaywrightTest("browsercontext-cookies.spec.ts", @"should properly report ""Strict"" sameSite cookie")] @@ -92,8 +84,8 @@ public async Task ShouldProperlyReportStrictSameSiteCookie() }); await Page.GoToAsync(TestConstants.EmptyPage); var cookies = await Context.GetCookiesAsync(); - Assert.Single(cookies); - Assert.Equal(SameSiteAttribute.Strict, cookies.ElementAt(0).SameSite); + Assert.That(cookies, Has.Count.EqualTo(1)); + Assert.That(cookies.ElementAt(0).SameSite, Is.EqualTo(SameSiteAttribute.Strict)); } [PlaywrightTest("browsercontext-cookies.spec.ts", @"should properly report ""Lax"" sameSite cookie")] @@ -107,16 +99,16 @@ public async Task ShouldProperlyReportLaxSameSiteCookie() }); await Page.GoToAsync(TestConstants.EmptyPage); var cookies = await Context.GetCookiesAsync(); - Assert.Single(cookies); - Assert.Equal(SameSiteAttribute.Lax, cookies.ElementAt(0).SameSite); + Assert.That(cookies, Has.Count.EqualTo(1)); + Assert.That(cookies.ElementAt(0).SameSite, Is.EqualTo(SameSiteAttribute.Lax)); } [PlaywrightTest("browsercontext-cookies.spec.ts", "should get multiple cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldGetMultipleCookies() { await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Empty(await Context.GetCookiesAsync()); + Assert.That(await Context.GetCookiesAsync(), Is.Empty); string documentCookie = await Page.EvaluateAsync(@"() => { document.cookie = 'username=John Doe'; @@ -125,30 +117,30 @@ public async Task ShouldGetMultipleCookies() }"); var cookies = (await Context.GetCookiesAsync()).OrderBy(c => c.Name).ToList(); - Assert.Equal("password=1234; username=John Doe", documentCookie); + Assert.That(documentCookie, Is.EqualTo("password=1234; username=John Doe")); var cookie = cookies[0]; - Assert.Equal("password", cookie.Name); - Assert.Equal("1234", cookie.Value); - Assert.Equal("localhost", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(cookie.Expires, -1); - Assert.False(cookie.HttpOnly); - Assert.False(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(cookie.Name, Is.EqualTo("password")); + Assert.That(cookie.Value, Is.EqualTo("1234")); + Assert.That(cookie.Domain, Is.EqualTo("localhost")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(-1, Is.EqualTo(cookie.Expires)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); cookie = cookies[1]; - Assert.Equal("username", cookie.Name); - Assert.Equal("John Doe", cookie.Value); - Assert.Equal("localhost", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(cookie.Expires, -1); - Assert.False(cookie.HttpOnly); - Assert.False(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(cookie.Name, Is.EqualTo("username")); + Assert.That(cookie.Value, Is.EqualTo("John Doe")); + Assert.That(cookie.Domain, Is.EqualTo("localhost")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(-1, Is.EqualTo(cookie.Expires)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); } [PlaywrightTest("browsercontext-cookies.spec.ts", "should get cookies from multiple urls")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldGetCookiesFromMultipleUrls() { await Context.AddCookiesAsync( @@ -173,27 +165,27 @@ await Context.AddCookiesAsync( ); var cookies = (await Context.GetCookiesAsync("https://foo.com", "https://baz.com")).OrderBy(c => c.Name).ToList(); - Assert.Equal(2, cookies.Count); + Assert.That(cookies.Count, Is.EqualTo(2)); var cookie = cookies[0]; - Assert.Equal("birdo", cookie.Name); - Assert.Equal("tweets", cookie.Value); - Assert.Equal("baz.com", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(cookie.Expires, -1); - Assert.False(cookie.HttpOnly); - Assert.True(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(cookie.Name, Is.EqualTo("birdo")); + Assert.That(cookie.Value, Is.EqualTo("tweets")); + Assert.That(cookie.Domain, Is.EqualTo("baz.com")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(-1, Is.EqualTo(cookie.Expires)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.True); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); cookie = cookies[1]; - Assert.Equal("doggo", cookie.Name); - Assert.Equal("woofs", cookie.Value); - Assert.Equal("foo.com", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(cookie.Expires, -1); - Assert.False(cookie.HttpOnly); - Assert.True(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(cookie.Name, Is.EqualTo("doggo")); + Assert.That(cookie.Value, Is.EqualTo("woofs")); + Assert.That(cookie.Domain, Is.EqualTo("foo.com")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(-1, Is.EqualTo(cookie.Expires)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.True); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); } } } diff --git a/src/Playwright.Tests/BrowserContextDeviceTests.cs b/src/Playwright.Tests/BrowserContextDeviceTests.cs index 1b02c0b0e0..11146410c7 100644 --- a/src/Playwright.Tests/BrowserContextDeviceTests.cs +++ b/src/Playwright.Tests/BrowserContextDeviceTests.cs @@ -1,23 +1,14 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextDeviceTests : PlaywrightSharpBrowserBaseTest { - private readonly BrowserContextOptions _iPhone = TestConstants.iPhone6; - - /// - public BrowserContextDeviceTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-device.spec.ts", "should work")] + private readonly BrowserContextOptions _iPhone = TestConstants.iPhone6; [PlaywrightTest("browsercontext-device.spec.ts", "should work")] [SkipBrowserAndPlatformFact(skipFirefox: true)] public async Task ShouldWork() { @@ -25,8 +16,8 @@ public async Task ShouldWork() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.Equal(375, await page.EvaluateAsync("window.innerWidth")); - Assert.Contains("iPhone", await page.EvaluateAsync("navigator.userAgent")); + Assert.That(await page.EvaluateAsync("window.innerWidth"), Is.EqualTo(375)); + Assert.That(await page.EvaluateAsync("navigator.userAgent"), Does.Contain("iPhone")); } [PlaywrightTest("browsercontext-device.spec.ts", "should support clicking")] @@ -40,7 +31,7 @@ public async Task ShouldSupportClicking() var button = await page.QuerySelectorAsync("button"); await button.EvaluateAsync("button => button.style.marginTop = '200px'", button); await button.ClickAsync(); - Assert.Equal("Clicked", await page.EvaluateAsync("() => result")); + Assert.That(await page.EvaluateAsync("() => result"), Is.EqualTo("Clicked")); } [PlaywrightTest("browsercontext-device.spec.ts", "should scroll to click")] @@ -62,7 +53,7 @@ public async Task ShouldScrollToClick() await page.GoToAsync(TestConstants.ServerUrl + "/input/scrollable.html"); var element = await page.QuerySelectorAsync("#button-91"); await element.ClickAsync(); - Assert.Equal("clicked", await element.TextContentAsync()); + Assert.That(await element.TextContentAsync(), Is.EqualTo("clicked")); } } } diff --git a/src/Playwright.Tests/BrowserContextExposeFunctionTests.cs b/src/Playwright.Tests/BrowserContextExposeFunctionTests.cs index 810e7b4474..ff65677d4d 100644 --- a/src/Playwright.Tests/BrowserContextExposeFunctionTests.cs +++ b/src/Playwright.Tests/BrowserContextExposeFunctionTests.cs @@ -1,23 +1,15 @@ using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextExposeFunctionTests : PlaywrightSharpBrowserContextBaseTest - { - /// - public BrowserContextExposeFunctionTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-expose-function.spec.ts", "expose binding should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-expose-function.spec.ts", "expose binding should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ExposeBindingShouldWork() { BindingSource bindingSource = null; @@ -33,15 +25,15 @@ await Context.ExposeBindingAsync("add", (BindingSource source, int a, int b) => return await add(5, 6); }"); - Assert.Same(Context, bindingSource.Context); - Assert.Same(page, bindingSource.Page); - Assert.Same(page.MainFrame, bindingSource.Frame); + Assert.That(bindingSource.Context, Is.SameAs(Context)); + Assert.That(bindingSource.Page, Is.SameAs(page)); + Assert.That(bindingSource.Frame, Is.SameAs(page.MainFrame)); - Assert.Equal(11, result); + Assert.That(result, Is.EqualTo(11)); } [PlaywrightTest("browsercontext-expose-function.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Context.ExposeFunctionAsync("add", (int a, int b) => a + b); @@ -53,32 +45,32 @@ public async Task ShouldWork() var result = await page.EvaluateAsync(@"async function() { return { mul: await mul(9, 4), add: await add(9, 4), sub: await sub(9, 4) }; }"); - Assert.Equal(36, result.GetProperty("mul").GetInt32()); - Assert.Equal(13, result.GetProperty("add").GetInt32()); - Assert.Equal(5, result.GetProperty("sub").GetInt32()); + Assert.That(result.GetProperty("mul").GetInt32(), Is.EqualTo(36)); + Assert.That(result.GetProperty("add").GetInt32(), Is.EqualTo(13)); + Assert.That(result.GetProperty("sub").GetInt32(), Is.EqualTo(5)); } [PlaywrightTest("browsercontext-expose-function.spec.ts", "should throw for duplicate registrations")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForDuplicateRegistrations() { await Context.ExposeFunctionAsync("foo", () => { }); await Context.ExposeFunctionAsync("bar", () => { }); - var exception = await Assert.ThrowsAnyAsync(() => Context.ExposeFunctionAsync("foo", () => { })); - Assert.Equal("Function \"foo\" has been already registered", exception.Message); + var exception = Assert.CatchAsync(() => Context.ExposeFunctionAsync("foo", () => { })); + Assert.That(exception.Message, Is.EqualTo("Function \"foo\" has been already registered")); var page = await Context.NewPageAsync(); - exception = await Assert.ThrowsAnyAsync(() => page.ExposeFunctionAsync("foo", () => { })); - Assert.Equal("Function \"foo\" has been already registered in the browser context", exception.Message); + exception = Assert.CatchAsync(() => page.ExposeFunctionAsync("foo", () => { })); + Assert.That(exception.Message, Is.EqualTo("Function \"foo\" has been already registered in the browser context")); await page.ExposeFunctionAsync("baz", () => { }); - exception = await Assert.ThrowsAnyAsync(() => Context.ExposeFunctionAsync("baz", () => { })); - Assert.Equal("Function \"baz\" has been already registered in one of the pages", exception.Message); + exception = Assert.CatchAsync(() => Context.ExposeFunctionAsync("baz", () => { })); + Assert.That(exception.Message, Is.EqualTo("Function \"baz\" has been already registered in one of the pages")); } [PlaywrightTest("browsercontext-expose-function.spec.ts", "should be callable from-inside addInitScript")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeCallableFromInsideAddInitScript() { var args = new List(); @@ -91,12 +83,12 @@ public async Task ShouldBeCallableFromInsideAddInitScript() args.Clear(); await page.ReloadAsync(); - Assert.Contains("context", args); - Assert.Contains("page", args); + Assert.That(args, Does.Contain("context")); + Assert.That(args, Does.Contain("page")); } [PlaywrightTest("browsercontext-expose-function.spec.ts", "exposeBindingHandle should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ExposeBindingHandleShouldWork() { IJSHandle target = null; @@ -113,8 +105,8 @@ await Context.ExposeBindingAsync( return window['logme']({ foo: 42 }); }"); - Assert.Equal(42, await target.EvaluateAsync("x => x.foo")); - Assert.Equal(17, result); + Assert.That(await target.EvaluateAsync("x => x.foo"), Is.EqualTo(42)); + Assert.That(result, Is.EqualTo(17)); } } } diff --git a/src/Playwright.Tests/BrowserContextHttpCredentialsTests.cs b/src/Playwright.Tests/BrowserContextHttpCredentialsTests.cs index c4659faee5..c997f90ecc 100644 --- a/src/Playwright.Tests/BrowserContextHttpCredentialsTests.cs +++ b/src/Playwright.Tests/BrowserContextHttpCredentialsTests.cs @@ -1,39 +1,31 @@ using System.Net; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextCredentialsTests : PlaywrightSharpBrowserBaseTest - { - /// - public BrowserContextCredentialsTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-credentials.spec.ts", "should fail without credentials")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-credentials.spec.ts", "should fail without credentials")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWithoutCredentials() { Server.SetAuth("/empty.html", "user", "pass"); await using var context = await Browser.NewContextAsync(); var page = await context.NewPageAsync(); var response = await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); } [PlaywrightTest("browsercontext-credentials.spec.ts", "should work with setHTTPCredentials")] - [Fact(Skip = "This test is no longer applicable as the API no longer exists.")] + [Test, Ignore("This test is no longer applicable as the API no longer exists.")] public void ShouldWorkWithSetHTTPCredentials() { } [PlaywrightTest("browsercontext-credentials.spec.ts", "should work with correct credentials")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCorrectCredentials() { // Use unique user/password since Chromium caches credentials per origin. @@ -49,11 +41,11 @@ public async Task ShouldWorkWithCorrectCredentials() var page = await context.NewPageAsync(); var response = await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [PlaywrightTest("browsercontext-credentials.spec.ts", "should fail if wrong credentials")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailIfWrongCredentials() { // Use unique user/password since Chromium caches credentials per origin. @@ -69,11 +61,11 @@ public async Task ShouldFailIfWrongCredentials() var page = await context.NewPageAsync(); var response = await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); } [PlaywrightTest("browsercontext-credentials.spec.ts", "should return resource body")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnResourceBody() { Server.SetAuth("/playground.html", "user", "pass"); @@ -88,9 +80,9 @@ public async Task ShouldReturnResourceBody() var page = await context.NewPageAsync(); var response = await page.GoToAsync(TestConstants.ServerUrl + "/playground.html"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Playground", await page.TitleAsync()); - Assert.Contains("Playground", await response.GetTextAsync()); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(await page.TitleAsync(), Is.EqualTo("Playground")); + Assert.That(await response.GetTextAsync(), Does.Contain("Playground")); } } } diff --git a/src/Playwright.Tests/BrowserContextLocaleTests.cs b/src/Playwright.Tests/BrowserContextLocaleTests.cs index 5ea0d9a1cc..bdb4c4248f 100644 --- a/src/Playwright.Tests/BrowserContextLocaleTests.cs +++ b/src/Playwright.Tests/BrowserContextLocaleTests.cs @@ -1,23 +1,15 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextLocaleTests : PlaywrightSharpBrowserBaseTest - { - /// - public BrowserContextLocaleTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-locale.spec.ts", "should affect accept-language header")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-locale.spec.ts", "should affect accept-language header")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAffectAcceptLanguageHeader() { await using var context = await Browser.NewContextAsync(locale: "fr-CH"); @@ -29,11 +21,11 @@ await TaskUtils.WhenAll( requestTask, page.GoToAsync(TestConstants.EmptyPage)); - Assert.StartsWith("fr-CH", acceptLanguage); + Assert.That(acceptLanguage, Does.StartWith("fr-CH")); } [PlaywrightTest("browsercontext-locale.spec.ts", "should affect navigator.language")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAffectNavigatorLanguage() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -41,11 +33,11 @@ public async Task ShouldAffectNavigatorLanguage() Locale = "fr-CH" }); var page = await context.NewPageAsync(); - Assert.Equal("fr-CH", await page.EvaluateAsync("navigator.language")); + Assert.That(await page.EvaluateAsync("navigator.language"), Is.EqualTo("fr-CH")); } [PlaywrightTest("browsercontext-locale.spec.ts", "should format number")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFormatNumber() { await using (var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -55,7 +47,7 @@ public async Task ShouldFormatNumber() { var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("1,000,000.5", await page.EvaluateAsync("() => (1000000.50).toLocaleString()")); + Assert.That(await page.EvaluateAsync("() => (1000000.50).toLocaleString()"), Is.EqualTo("1,000,000.5")); } await using (var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -66,12 +58,12 @@ public async Task ShouldFormatNumber() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); string value = await page.EvaluateAsync("() => (1000000.50).toLocaleString().replace(/\\s/g, ' ')"); - Assert.Equal("1 000 000,5", value); + Assert.That(value, Is.EqualTo("1 000 000,5")); } } [PlaywrightTest("browsercontext-locale.spec.ts", "should format date")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFormatDate() { await using (var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -82,9 +74,7 @@ public async Task ShouldFormatDate() { var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal( - "Sat Nov 19 2016 10:12:34 GMT-0800 (Pacific Standard Time)", - await page.EvaluateAsync("() => new Date(1479579154987).toString()")); + Assert.That(await page.EvaluateAsync("() => new Date(1479579154987).toString()"), Is.EqualTo("Sat Nov 19 2016 10:12:34 GMT-0800 (Pacific Standard Time)")); } await using (var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -95,14 +85,12 @@ public async Task ShouldFormatDate() { var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal( - "Sat Nov 19 2016 19:12:34 GMT+0100 (Mitteleuropäische Normalzeit)", - await page.EvaluateAsync("() => new Date(1479579154987).toString()")); + Assert.That(await page.EvaluateAsync("() => new Date(1479579154987).toString()"), Is.EqualTo("Sat Nov 19 2016 19:12:34 GMT+0100 (Mitteleuropäische Normalzeit)")); } } [PlaywrightTest("browsercontext-locale.spec.ts", "should format number in popups")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFormatNumberInPopups() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -120,11 +108,11 @@ await TaskUtils.WhenAll( var popup = popupTask.Result; await popup.WaitForLoadStateAsync(LoadState.DOMContentLoaded); - Assert.Equal("1 000 000,5", await popup.EvaluateAsync("() => window.result")); + Assert.That(await popup.EvaluateAsync("() => window.result"), Is.EqualTo("1 000 000,5")); } [PlaywrightTest("browsercontext-locale.spec.ts", "should affect navigator.language in popups")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAffectNavigatorLanguageInPopups() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -142,7 +130,7 @@ await TaskUtils.WhenAll( var popup = popupTask.Result; await popup.WaitForLoadStateAsync(LoadState.DOMContentLoaded); - Assert.Equal("fr-CH", await popup.EvaluateAsync("() => window.initialNavigatorLanguage")); + Assert.That(await popup.EvaluateAsync("() => window.initialNavigatorLanguage"), Is.EqualTo("fr-CH")); } } } diff --git a/src/Playwright.Tests/BrowserContextPageEventTests.cs b/src/Playwright.Tests/BrowserContextPageEventTests.cs index 1f049a85fb..94d779bcbb 100644 --- a/src/Playwright.Tests/BrowserContextPageEventTests.cs +++ b/src/Playwright.Tests/BrowserContextPageEventTests.cs @@ -1,24 +1,16 @@ using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextPageEventTests : PlaywrightSharpBrowserBaseTest - { - /// - public BrowserContextPageEventTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-page-event.spec.ts", "should have url")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-page-event.spec.ts", "should have url")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveUrl() { await using var context = await Browser.NewContextAsync(); @@ -28,11 +20,11 @@ public async Task ShouldHaveUrl() context.WaitForEventAsync(ContextEvent.Page), page.EvaluateAsync("url => window.open(url)", TestConstants.EmptyPage)); - Assert.Equal(TestConstants.EmptyPage, otherPage.Url); + Assert.That(otherPage.Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("browsercontext-page-event.spec.ts", "should have url after domcontentloaded")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveUrlAfterDomcontentloaded() { await using var context = await Browser.NewContextAsync(); @@ -43,11 +35,11 @@ public async Task ShouldHaveUrlAfterDomcontentloaded() page.EvaluateAsync("url => window.open(url)", TestConstants.EmptyPage)); await otherPage.WaitForLoadStateAsync(LoadState.DOMContentLoaded); - Assert.Equal(TestConstants.EmptyPage, otherPage.Url); + Assert.That(otherPage.Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("browsercontext-page-event.spec.ts", "should have about:blank url with domcontentloaded")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveAboutBlankUrlWithDomcontentloaded() { await using var context = await Browser.NewContextAsync(); @@ -58,11 +50,11 @@ public async Task ShouldHaveAboutBlankUrlWithDomcontentloaded() page.EvaluateAsync("url => window.open(url)", "about:blank")); await otherPage.WaitForLoadStateAsync(LoadState.DOMContentLoaded); - Assert.Equal("about:blank", otherPage.Url); + Assert.That(otherPage.Url, Is.EqualTo("about:blank")); } [PlaywrightTest("browsercontext-page-event.spec.ts", "should have about:blank for empty url with domcontentloaded")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveAboutBlankUrlForEmptyUrlWithDomcontentloaded() { await using var context = await Browser.NewContextAsync(); @@ -73,11 +65,11 @@ public async Task ShouldHaveAboutBlankUrlForEmptyUrlWithDomcontentloaded() page.EvaluateAsync("() => window.open()")); await otherPage.WaitForLoadStateAsync(LoadState.DOMContentLoaded); - Assert.Equal("about:blank", otherPage.Url); + Assert.That(otherPage.Url, Is.EqualTo("about:blank")); } [PlaywrightTest("browsercontext-page-event.spec.ts", "should report when a new page is created and closed")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportWhenANewPageIsCreatedAndClosed() { await using var context = await Browser.NewContextAsync(); @@ -88,14 +80,14 @@ public async Task ShouldReportWhenANewPageIsCreatedAndClosed() page.EvaluateAsync("url => window.open(url)", TestConstants.CrossProcessUrl + "/empty.html")); var otherPage = otherPageEvent; - Assert.Contains(TestConstants.CrossProcessUrl, otherPage.Url); - Assert.Equal("Hello world", await otherPage.EvaluateAsync("() => ['Hello', 'world'].join(' ')")); - Assert.NotNull(await otherPage.QuerySelectorAsync("body")); + Assert.That(otherPage.Url, Does.Contain(TestConstants.CrossProcessUrl)); + Assert.That(await otherPage.EvaluateAsync("() => ['Hello', 'world'].join(' ')"), Is.EqualTo("Hello world")); + Assert.That(await otherPage.QuerySelectorAsync("body"), Is.Not.Null); var allPages = context.Pages; - Assert.Contains(page, allPages); - Assert.Contains(otherPage, allPages); + Assert.That(allPages, Does.Contain(page)); + Assert.That(allPages, Does.Contain(otherPage)); var closeEventReceived = new TaskCompletionSource(); otherPage.Close += (_, _) => closeEventReceived.TrySetResult(true); @@ -104,29 +96,29 @@ public async Task ShouldReportWhenANewPageIsCreatedAndClosed() await closeEventReceived.Task.WithTimeout(TestConstants.DefaultTaskTimeout); allPages = context.Pages; - Assert.Contains(page, allPages); - Assert.DoesNotContain(otherPage, allPages); + Assert.That(allPages, Does.Contain(page)); + Assert.That(allPages, Does.Not.Contain(otherPage)); } [PlaywrightTest("browsercontext-page-event.spec.ts", "should report initialized pages")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportInitializedPages() { await using var context = await Browser.NewContextAsync(); var pageTask = context.WaitForEventAsync(ContextEvent.Page); _ = context.NewPageAsync(); var newPage = await pageTask; - Assert.Equal("about:blank", newPage.Url); + Assert.That(newPage.Url, Is.EqualTo("about:blank")); var popupTask = context.WaitForEventAsync(ContextEvent.Page); var evaluateTask = newPage.EvaluateAsync("() => window.open('about:blank')"); var popup = await popupTask; - Assert.Equal("about:blank", popup.Url); + Assert.That(popup.Url, Is.EqualTo("about:blank")); await evaluateTask; } [PlaywrightTest("browsercontext-page-event.spec.ts", "should not crash while redirecting of original request was missed")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotCrashWhileRedirectingOfOriginalRequestWasMissed() { await using var context = await Browser.NewContextAsync(); @@ -148,11 +140,11 @@ await TaskUtils.WhenAll( var newPage = pageCreatedTask.Result; await newPage.WaitForLoadStateAsync(LoadState.DOMContentLoaded); - Assert.Equal(TestConstants.ServerUrl + "/one-style.html", newPage.Url); + Assert.That(newPage.Url, Is.EqualTo(TestConstants.ServerUrl + "/one-style.html")); } [PlaywrightTest("browsercontext-page-event.spec.ts", "should have an opener")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveAnOpener() { await using var context = await Browser.NewContextAsync(); @@ -164,13 +156,13 @@ public async Task ShouldHaveAnOpener() page.GoToAsync(TestConstants.ServerUrl + "/popup/window-open.html")); var popup = popupEvent; - Assert.Equal(TestConstants.ServerUrl + "/popup/popup.html", popup.Url); - Assert.Same(page, await popup.OpenerAsync()); - Assert.Null(await page.OpenerAsync()); + Assert.That(popup.Url, Is.EqualTo(TestConstants.ServerUrl + "/popup/popup.html")); + Assert.That(await popup.OpenerAsync(), Is.SameAs(page)); + Assert.That(await page.OpenerAsync(), Is.Null); } [PlaywrightTest("browsercontext-page-event.spec.ts", "should fire page lifecycle events")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFirePageLoadStates() { await using var context = await Browser.NewContextAsync(); @@ -185,13 +177,11 @@ public async Task ShouldFirePageLoadStates() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); await page.CloseAsync(); - Assert.Equal( - new List() + Assert.That(events, Is.EqualTo(new List() { "CREATED: about:blank", $"DESTROYED: {TestConstants.EmptyPage}" - }, - events); + })); } [PlaywrightTest("browsercontext-page-event.spec.ts", "should work with Shift-clicking")] @@ -209,7 +199,7 @@ await TaskUtils.WhenAll( popupEventTask, page.ClickAsync("a", modifiers: new[] { KeyboardModifier.Shift })); - Assert.Null(await popupEventTask.Result.OpenerAsync()); + Assert.That(await popupEventTask.Result.OpenerAsync(), Is.Null); } [PlaywrightTest("browsercontext-page-event.spec.ts", "should report when a new page is created and closed")] @@ -228,7 +218,7 @@ await TaskUtils.WhenAll( popupEventTask, page.ClickAsync("a", modifiers: new[] { TestConstants.IsMacOSX ? KeyboardModifier.Meta : KeyboardModifier.Control })); - Assert.Null(await popupEventTask.Result.OpenerAsync()); + Assert.That(await popupEventTask.Result.OpenerAsync(), Is.Null); } } } diff --git a/src/Playwright.Tests/BrowserContextRouteTests.cs b/src/Playwright.Tests/BrowserContextRouteTests.cs index aed1100c1d..3c7e5bf3d7 100644 --- a/src/Playwright.Tests/BrowserContextRouteTests.cs +++ b/src/Playwright.Tests/BrowserContextRouteTests.cs @@ -4,23 +4,15 @@ using System.Net.Http; using System.Threading.Tasks; using Microsoft.Playwright.Contracts.Constants; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextRouteTests : PlaywrightSharpBrowserBaseTest - { - /// - public BrowserContextRouteTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-route.spec.ts", "should intercept")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-route.spec.ts", "should intercept")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIntercept() { bool intercepted = false; @@ -32,26 +24,26 @@ await context.RouteAsync("**/empty.html", (route) => { intercepted = true; - Assert.Contains("empty.html", route.Request.Url); - Assert.False(string.IsNullOrEmpty(route.Request.GetHeaderValue("user-agent"))); - Assert.Equal(HttpMethod.Get.Method, route.Request.Method); - Assert.Null(route.Request.PostData); - Assert.True(route.Request.IsNavigationRequest); - Assert.Equal(ResourceTypes.Document, route.Request.ResourceType, false); - Assert.Same(page.MainFrame, route.Request.Frame); - Assert.Equal("about:blank", page.MainFrame.Url); + Assert.That(route.Request.Url, Does.Contain("empty.html")); + Assert.That(string.IsNullOrEmpty(route.Request.GetHeaderValue("user-agent")), Is.False); + Assert.That(route.Request.Method, Is.EqualTo(HttpMethod.Get.Method)); + Assert.That(route.Request.PostData, Is.Null); + Assert.That(route.Request.IsNavigationRequest, Is.True); + Assert.That(route.Request.ResourceType, Is.EqualTo(ResourceTypes.Document)); + Assert.That(route.Request.Frame, Is.SameAs(page.MainFrame)); + Assert.That(page.MainFrame.Url, Is.EqualTo("about:blank")); route.ResumeAsync(); }); page = await context.NewPageAsync(); var response = await page.GoToAsync(TestConstants.EmptyPage); - Assert.True(response.Ok); - Assert.True(intercepted); + Assert.That(response.Ok, Is.True); + Assert.That(intercepted, Is.True); } [PlaywrightTest("browsercontext-route.spec.ts", "should unroute")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUnroute() { await using var context = await Browser.NewContextAsync(); @@ -84,21 +76,21 @@ await context.RouteAsync("**/*", (route) => }); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(new List() { 1 }, intercepted); + Assert.That(intercepted, Is.EqualTo(new List() { 1 })); intercepted.Clear(); await context.UnrouteAsync("**/empty.html", handler1); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(new List() { 2 }, intercepted); + Assert.That(intercepted, Is.EqualTo(new List() { 2 })); intercepted.Clear(); await context.UnrouteAsync("**/empty.html"); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(new List() { 4 }, intercepted); + Assert.That(intercepted, Is.EqualTo(new List() { 4 })); } [PlaywrightTest("browsercontext-route.spec.ts", "should yield to page.route")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldYieldToPageRoute() { await using var context = await Browser.NewContextAsync(); @@ -114,11 +106,11 @@ await page.RouteAsync("**/empty.html", (route) => }); var response = await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("page", await response.GetTextAsync()); + Assert.That(await response.GetTextAsync(), Is.EqualTo("page")); } [PlaywrightTest("browsercontext-route.spec.ts", "should fall back to context.route")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFallBackToContextRoute() { await using var context = await Browser.NewContextAsync(); @@ -134,7 +126,7 @@ await page.RouteAsync("**/non-empty.html", (route) => }); var response = await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("context", await response.GetTextAsync()); + Assert.That(await response.GetTextAsync(), Is.EqualTo("context")); } } } diff --git a/src/Playwright.Tests/BrowserContextStorageStateTests.cs b/src/Playwright.Tests/BrowserContextStorageStateTests.cs index 938927c55d..793ef8fef0 100644 --- a/src/Playwright.Tests/BrowserContextStorageStateTests.cs +++ b/src/Playwright.Tests/BrowserContextStorageStateTests.cs @@ -3,24 +3,16 @@ using System.Text.Json; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.Helpers; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public sealed class BrowsercontextStorageStateTests : PlaywrightSharpPageBaseTest - { - /// - public BrowsercontextStorageStateTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-storage-state.spec.ts", "should capture local storage")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-storage-state.spec.ts", "should capture local storage")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCaptureLocalStorage() { var page1 = await Context.NewPageAsync(); @@ -44,17 +36,17 @@ await page1.EvaluateAsync(@"() => // TODO: think about IVT-in the StorageState and serializing string expected = @"{""cookies"":[],""origins"":[{""origin"":""https://www.example.com"",""localStorage"":[{""name"":""name1"",""value"":""value1""}]},{""origin"":""https://www.domain.com"",""localStorage"":[{""name"":""name2"",""value"":""value2""}]}]}"; - Assert.Equal(storage, expected); + Assert.That(expected, Is.EqualTo(storage)); } [PlaywrightTest("browsercontext-storage-state.spec.ts", "should set local storage")] - [Fact(Timeout = TestConstants.DefaultTestTimeout, Skip = "Needs to be implemented.")] + [Test, Ignore("Needs to be implemented.")] public void ShouldSetLocalStorage() { } [PlaywrightTest("browsercontext-storage-state.spec.ts", "should round-trip through the file")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRoundTripThroughTheFile() { var page1 = await Context.NewPageAsync(); @@ -72,7 +64,7 @@ await page1.EvaluateAsync(@"() => using var tempDir = new TempDirectory(); string path = Path.Combine(tempDir.Path, "storage-state.json"); string storage = await Context.StorageStateAsync(path); - Assert.Equal(storage, File.ReadAllText(path)); + Assert.That(File.ReadAllText(path), Is.EqualTo(storage)); await using var context = await Browser.NewContextAsync(storageStatePath: path); var page2 = await context.NewPageAsync(); @@ -82,8 +74,8 @@ await page1.RouteAsync("**/*", (route) => }); await page1.GoToAsync("https://www.example.com"); - Assert.Equal("value1", await page1.EvaluateAsync("localStorage['name1']")); - Assert.Equal("username=John Doe", await page1.EvaluateAsync("document.cookie")); + Assert.That(await page1.EvaluateAsync("localStorage['name1']"), Is.EqualTo("value1")); + Assert.That(await page1.EvaluateAsync("document.cookie"), Is.EqualTo("username=John Doe")); } } } diff --git a/src/Playwright.Tests/BrowserContextTimezoneIdTests.cs b/src/Playwright.Tests/BrowserContextTimezoneIdTests.cs index f05231a428..5f9d393a4e 100644 --- a/src/Playwright.Tests/BrowserContextTimezoneIdTests.cs +++ b/src/Playwright.Tests/BrowserContextTimezoneIdTests.cs @@ -1,22 +1,14 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextTimezoneIdTests : PlaywrightSharpBrowserBaseTest - { - /// - public BrowserContextTimezoneIdTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-timezone-id.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-timezone-id.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await using var browser = await Playwright[TestConstants.Product].LaunchDefaultAsync(); @@ -26,55 +18,47 @@ public async Task ShouldWork() { var page = await context.NewPageAsync(); string result = await page.EvaluateAsync(func); - Assert.Equal( - "Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)", - result); + Assert.That(result, Is.EqualTo("Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)")); } await using (var context = await browser.NewContextAsync(new BrowserContextOptions { TimezoneId = "Pacific/Honolulu" })) { var page = await context.NewPageAsync(); - Assert.Equal( - "Sat Nov 19 2016 08:12:34 GMT-1000 (Hawaii-Aleutian Standard Time)", - await page.EvaluateAsync(func)); + Assert.That(await page.EvaluateAsync(func), Is.EqualTo("Sat Nov 19 2016 08:12:34 GMT-1000 (Hawaii-Aleutian Standard Time)")); } await using (var context = await browser.NewContextAsync(new BrowserContextOptions { TimezoneId = "America/Buenos_Aires" })) { var page = await context.NewPageAsync(); - Assert.Equal( - "Sat Nov 19 2016 15:12:34 GMT-0300 (Argentina Standard Time)", - await page.EvaluateAsync(func)); + Assert.That(await page.EvaluateAsync(func), Is.EqualTo("Sat Nov 19 2016 15:12:34 GMT-0300 (Argentina Standard Time)")); } await using (var context = await browser.NewContextAsync(new BrowserContextOptions { TimezoneId = "Europe/Berlin" })) { var page = await context.NewPageAsync(); - Assert.Equal( - "Sat Nov 19 2016 19:12:34 GMT+0100 (Central European Standard Time)", - await page.EvaluateAsync(func)); + Assert.That(await page.EvaluateAsync(func), Is.EqualTo("Sat Nov 19 2016 19:12:34 GMT+0100 (Central European Standard Time)")); } } [PlaywrightTest("browsercontext-timezone-id.spec.ts", "should throw for invalid timezone IDs")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForInvalidTimezoneId() { await using (var context = await Browser.NewContextAsync(new BrowserContextOptions { TimezoneId = "Foo/Bar" })) { - var exception = await Assert.ThrowsAnyAsync(() => context.NewPageAsync()); - Assert.Contains("Invalid timezone ID: Foo/Bar", exception.Message); + var exception = Assert.CatchAsync(() => context.NewPageAsync()); + Assert.That(exception.Message, Does.Contain("Invalid timezone ID: Foo/Bar")); } await using (var context = await Browser.NewContextAsync(new BrowserContextOptions { TimezoneId = "Baz/Qux" })) { - var exception = await Assert.ThrowsAnyAsync(() => context.NewPageAsync()); - Assert.Contains("Invalid timezone ID: Baz/Qux", exception.Message); + var exception = Assert.CatchAsync(() => context.NewPageAsync()); + Assert.That(exception.Message, Does.Contain("Invalid timezone ID: Baz/Qux")); } } [PlaywrightTest("browsercontext-timezone-id.spec.ts", "should work for multiple pages sharing same process")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForMultiplePagesSharingSameProcess() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions { TimezoneId = "Europe/Moscow" }); diff --git a/src/Playwright.Tests/BrowserContextUserAgentTests.cs b/src/Playwright.Tests/BrowserContextUserAgentTests.cs index 83f2e1fe39..91849ca5fc 100644 --- a/src/Playwright.Tests/BrowserContextUserAgentTests.cs +++ b/src/Playwright.Tests/BrowserContextUserAgentTests.cs @@ -1,27 +1,19 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextUserAgentTests : PlaywrightSharpBrowserBaseTest - { - /// - public BrowserContextUserAgentTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-user-agent.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-user-agent.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await using (var context = await Browser.NewContextAsync()) { var page = await context.NewPageAsync(); - Assert.Contains("Mozilla", await page.EvaluateAsync("() => navigator.userAgent")); + Assert.That(await page.EvaluateAsync("() => navigator.userAgent"), Does.Contain("Mozilla")); } await using (var context = await Browser.NewContextAsync(new BrowserContextOptions { UserAgent = "foobar" })) @@ -32,18 +24,18 @@ public async Task ShouldWork() Server.WaitForRequest("/empty.html", request => request.Headers["User-Agent"].ToString()), page.GoToAsync(TestConstants.EmptyPage) ); - Assert.Equal("foobar", userAgent); + Assert.That(userAgent, Is.EqualTo("foobar")); } } [PlaywrightTest("browsercontext-user-agent.spec.ts", "should work for subframes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForSubframes() { await using (var context = await Browser.NewContextAsync()) { var page = await context.NewPageAsync(); - Assert.Contains("Mozilla", await page.EvaluateAsync("navigator.userAgent")); + Assert.That(await page.EvaluateAsync("navigator.userAgent"), Does.Contain("Mozilla")); } await using (var context = await Browser.NewContextAsync(new BrowserContextOptions { UserAgent = "foobar" })) @@ -54,31 +46,31 @@ public async Task ShouldWorkForSubframes() Server.WaitForRequest("/empty.html", (request) => request.Headers["user-agent"]), FrameUtils.AttachFrameAsync(page, "frame1", TestConstants.EmptyPage)); - Assert.Equal("foobar", userAgent); + Assert.That(userAgent, Is.EqualTo("foobar")); } } [PlaywrightTest("browsercontext-user-agent.spec.ts", "should emulate device user-agent")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmulateDeviceUserAgent() { await using (var context = await Browser.NewContextAsync()) { var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.DoesNotContain("iPhone", await page.EvaluateAsync("navigator.userAgent")); + Assert.That(await page.EvaluateAsync("navigator.userAgent"), Does.Not.Contain("iPhone")); } await using (var context = await Browser.NewContextAsync(new BrowserContextOptions { UserAgent = "iPhone" })) { var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.Contains("iPhone", await page.EvaluateAsync("navigator.userAgent")); + Assert.That(await page.EvaluateAsync("navigator.userAgent"), Does.Contain("iPhone")); } } [PlaywrightTest("browsercontext-user-agent.spec.ts", "should make a copy of default options")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldMakeACopyOfDefaultOptions() { var options = new BrowserContextOptions @@ -94,7 +86,7 @@ public async Task ShouldMakeACopyOfDefaultOptions() Server.WaitForRequest("/empty.html", request => request.Headers["User-Agent"].ToString()), page.GoToAsync(TestConstants.EmptyPage) ); - Assert.Equal("foobar", userAgent); + Assert.That(userAgent, Is.EqualTo("foobar")); } } } diff --git a/src/Playwright.Tests/BrowserContextViewportMobileTests.cs b/src/Playwright.Tests/BrowserContextViewportMobileTests.cs index e84521975c..5efff4dd24 100644 --- a/src/Playwright.Tests/BrowserContextViewportMobileTests.cs +++ b/src/Playwright.Tests/BrowserContextViewportMobileTests.cs @@ -1,24 +1,15 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextViewportMobileTests : PlaywrightSharpBrowserBaseTest { private readonly BrowserContextOptions _iPhone = TestConstants.iPhone6; - private readonly BrowserContextOptions _iPhoneLandscape = TestConstants.iPhone6Landscape; - - /// - public BrowserContextViewportMobileTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "should support mobile emulation")] + private readonly BrowserContextOptions _iPhoneLandscape = TestConstants.iPhone6Landscape; [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "should support mobile emulation")] [SkipBrowserAndPlatformFact(skipFirefox: true)] public async Task ShouldSupportMobileEmulation() { @@ -26,9 +17,9 @@ public async Task ShouldSupportMobileEmulation() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.Equal(375, await page.EvaluateAsync("window.innerWidth")); + Assert.That(await page.EvaluateAsync("window.innerWidth"), Is.EqualTo(375)); await page.SetViewportSizeAsync(400, 300); - Assert.Equal(400, await page.EvaluateAsync("window.innerWidth")); + Assert.That(await page.EvaluateAsync("window.innerWidth"), Is.EqualTo(400)); } [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "should support touch emulation")] @@ -52,8 +43,8 @@ function dispatchTouch() { await using var context = await Browser.NewContextAsync(_iPhone); var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.True(await page.EvaluateAsync("'ontouchstart' in window")); - Assert.Equal("Received touch", await page.EvaluateAsync(dispatchTouch)); + Assert.That(await page.EvaluateAsync("'ontouchstart' in window"), Is.True); + Assert.That(await page.EvaluateAsync(dispatchTouch), Is.EqualTo("Received touch")); } [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "should be detectable by Modernizr")] @@ -63,7 +54,7 @@ public async Task ShouldBeDetectableByModernizr() await using var context = await Browser.NewContextAsync(_iPhone); var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/detect-touch.html"); - Assert.Equal("YES", await page.EvaluateAsync("document.body.textContent.trim()")); + Assert.That(await page.EvaluateAsync("document.body.textContent.trim()"), Is.EqualTo("YES")); } [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "should detect touch when applying viewport with touches")] @@ -83,7 +74,7 @@ public async Task ShouldDetectTouchWhenApplyingViewportWithTouches() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); await page.AddScriptTagAsync(url: TestConstants.ServerUrl + "/modernizr.js"); - Assert.True(await page.EvaluateAsync("() => Modernizr.touchevents")); + Assert.That(await page.EvaluateAsync("() => Modernizr.touchevents"), Is.True); } [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "should support landscape emulation")] @@ -93,12 +84,12 @@ public async Task ShouldSupportLandscapeEmulation() await using var context1 = await Browser.NewContextAsync(_iPhone); var page1 = await context1.NewPageAsync(); await page1.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.False(await page1.EvaluateAsync("() => matchMedia('(orientation: landscape)').matches")); + Assert.That(await page1.EvaluateAsync("() => matchMedia('(orientation: landscape)').matches"), Is.False); await using var context2 = await Browser.NewContextAsync(_iPhoneLandscape); var page2 = await context2.NewPageAsync(); await page2.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.True(await page2.EvaluateAsync("() => matchMedia('(orientation: landscape)').matches")); + Assert.That(await page2.EvaluateAsync("() => matchMedia('(orientation: landscape)').matches"), Is.True); } [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "should support window.orientation emulation")] @@ -116,10 +107,10 @@ public async Task ShouldSupportWindowOrientationEmulation() }); var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.Equal(0, await page.EvaluateAsync("() => window.orientation")); + Assert.That(await page.EvaluateAsync("() => window.orientation"), Is.EqualTo(0)); await page.SetViewportSizeAsync(400, 300); - Assert.Equal(90, await page.EvaluateAsync("() => window.orientation")); + Assert.That(await page.EvaluateAsync("() => window.orientation"), Is.EqualTo(90)); } [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "should fire orientationchange event")] @@ -145,12 +136,12 @@ await page.EvaluateAsync(@"() => { var event1Task = page.WaitForEventAsync(PageEvent.Console); await page.SetViewportSizeAsync(400, 300); var event1 = await event1Task; - Assert.Equal("1", event1.Text); + Assert.That(event1.Text, Is.EqualTo("1")); var event2Task = page.WaitForEventAsync(PageEvent.Console); await page.SetViewportSizeAsync(300, 400); var event2 = await event2Task; - Assert.Equal("2", event2.Text); + Assert.That(event2.Text, Is.EqualTo("2")); } [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "default mobile viewports to 980 width")] @@ -169,7 +160,7 @@ public async Task DefaultMobileViewportsTo980Width() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(980, await page.EvaluateAsync("() => window.innerWidth")); + Assert.That(await page.EvaluateAsync("() => window.innerWidth"), Is.EqualTo(980)); } [PlaywrightTest("browsercontext-viewport-mobile.spec.ts", "respect meta viewport tag")] @@ -187,7 +178,7 @@ public async Task RespectMetaViewportTag() }); var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.Equal(320, await page.EvaluateAsync("() => window.innerWidth")); + Assert.That(await page.EvaluateAsync("() => window.innerWidth"), Is.EqualTo(320)); } } } diff --git a/src/Playwright.Tests/BrowserContextViewportTests.cs b/src/Playwright.Tests/BrowserContextViewportTests.cs index b524fb05a5..43eeab6e78 100644 --- a/src/Playwright.Tests/BrowserContextViewportTests.cs +++ b/src/Playwright.Tests/BrowserContextViewportTests.cs @@ -1,27 +1,19 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserContextViewportTests : PlaywrightSharpPageBaseTest - { - /// - public BrowserContextViewportTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsercontext-viewport.spec.ts", "should get the proper default viewport size")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsercontext-viewport.spec.ts", "should get the proper default viewport size")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public Task ShouldGetTheProperDefaultViewPortSize() => TestUtils.VerifyViewportAsync(Page, 1280, 720); [PlaywrightTest("browsercontext-viewport.spec.ts", "should set the proper viewport size")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSetTheProperViewportSize() { await TestUtils.VerifyViewportAsync(Page, 1280, 720); @@ -30,67 +22,67 @@ public async Task ShouldSetTheProperViewportSize() } [PlaywrightTest("browsercontext-viewport.spec.ts", "should emulate device width")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmulateDeviceWidth() { await TestUtils.VerifyViewportAsync(Page, 1280, 720); await Page.SetViewportSizeAsync(200, 200); - Assert.Equal(200, await Page.EvaluateAsync("window.innerWidth")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(min-device-width: 100px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(min-device-width: 300px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(max-device-width: 100px)').matches")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(max-device-width: 300px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(device-width: 500px)').matches")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(device-width: 200px)').matches")); + Assert.That(await Page.EvaluateAsync("window.innerWidth"), Is.EqualTo(200)); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(min-device-width: 100px)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(min-device-width: 300px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(max-device-width: 100px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(max-device-width: 300px)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(device-width: 500px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(device-width: 200px)').matches"), Is.True); await Page.SetViewportSizeAsync(500, 500); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(min-device-width: 400px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(min-device-width: 600px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(max-device-width: 400px)').matches")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(max-device-width: 600px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(device-width: 200px)').matches")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(device-width: 500px)').matches")); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(min-device-width: 400px)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(min-device-width: 600px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(max-device-width: 400px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(max-device-width: 600px)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(device-width: 200px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(device-width: 500px)').matches"), Is.True); } [PlaywrightTest("browsercontext-viewport.spec.ts", "should emulate device height")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmulateDeviceHeight() { await TestUtils.VerifyViewportAsync(Page, 1280, 720); await Page.SetViewportSizeAsync(200, 200); - Assert.Equal(200, await Page.EvaluateAsync("window.innerWidth")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(min-device-height: 100px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(min-device-height: 300px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(max-device-height: 100px)').matches")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(max-device-height: 300px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(device-height: 500px)').matches")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(device-height: 200px)').matches")); + Assert.That(await Page.EvaluateAsync("window.innerWidth"), Is.EqualTo(200)); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(min-device-height: 100px)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(min-device-height: 300px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(max-device-height: 100px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(max-device-height: 300px)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(device-height: 500px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(device-height: 200px)').matches"), Is.True); await Page.SetViewportSizeAsync(500, 500); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(min-device-height: 400px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(min-device-height: 600px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(max-device-height: 400px)').matches")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(max-device-height: 600px)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(device-height: 200px)').matches")); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(device-height: 500px)').matches")); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(min-device-height: 400px)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(min-device-height: 600px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(max-device-height: 400px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(max-device-height: 600px)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(device-height: 200px)').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(device-height: 500px)').matches"), Is.True); } [PlaywrightTest("browsercontext-viewport.spec.ts", "should not have touch by default")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotHaveTouchByDefault() { await Page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.False(await Page.EvaluateAsync("'ontouchstart' in window")); + Assert.That(await Page.EvaluateAsync("'ontouchstart' in window"), Is.False); await Page.GoToAsync(TestConstants.ServerUrl + "/detect-touch.html"); - Assert.Equal("NO", await Page.EvaluateAsync("document.body.textContent.trim()")); + Assert.That(await Page.EvaluateAsync("document.body.textContent.trim()"), Is.EqualTo("NO")); } [PlaywrightTest("browsercontext-viewport.spec.ts", "should support touch with null viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportTouchWithNullViewport() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions { Viewport = null, HasTouch = true }); var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.True(await page.EvaluateAsync("'ontouchstart' in window")); + Assert.That(await page.EvaluateAsync("'ontouchstart' in window"), Is.True); } } } diff --git a/src/Playwright.Tests/BrowserTests.cs b/src/Playwright.Tests/BrowserTests.cs index b00b5182a7..2d9bfaa526 100644 --- a/src/Playwright.Tests/BrowserTests.cs +++ b/src/Playwright.Tests/BrowserTests.cs @@ -1,61 +1,53 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///browser.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserTests : PlaywrightSharpBrowserBaseTest - { - /// - public BrowserTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browser.spec.ts", "should create new page")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browser.spec.ts", "should create new page")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCreateNewPage() { var browser = await Playwright[TestConstants.Product].LaunchDefaultAsync(); var page1 = await browser.NewPageAsync(); - Assert.Single(browser.Contexts); + Assert.That(browser.Contexts, Has.Count.EqualTo(1)); var page2 = await browser.NewPageAsync(); - Assert.Equal(2, browser.Contexts.Count); + Assert.That(browser.Contexts.Count, Is.EqualTo(2)); await page1.CloseAsync(); - Assert.Single(browser.Contexts); + Assert.That(browser.Contexts, Has.Count.EqualTo(1)); await page2.CloseAsync(); } [PlaywrightTest("browser.spec.ts", "should throw upon second create new page")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowUponSecondCreateNewPage() { var page = await Browser.NewPageAsync(); - var ex = await Assert.ThrowsAsync(() => page.Context.NewPageAsync()); + var ex = Assert.ThrowsAsync(() => page.Context.NewPageAsync()); await page.CloseAsync(); - Assert.Contains("Please use Browser.NewContextAsync()", ex.Message); + Assert.That(ex.Message, Does.Contain("Please use Browser.NewContextAsync()")); } [PlaywrightTest("browser.spec.ts", "version should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public void VersionShouldWork() { string version = Browser.Version; if (TestConstants.IsChromium) { - Assert.Matches(new Regex("\\d+\\.\\d+\\.\\d+\\.\\d+"), version); + Assert.That(version, Does.Match(new Regex("\\d+\\.\\d+\\.\\d+\\.\\d+"))); } else { - Assert.Matches(new Regex("\\d+\\.\\d+"), version); + Assert.That(version, Does.Match(new Regex("\\d+\\.\\d+"))); } } } diff --git a/src/Playwright.Tests/BrowserTypeBasicTests.cs b/src/Playwright.Tests/BrowserTypeBasicTests.cs index 0ba98c46dd..70451ca5bf 100644 --- a/src/Playwright.Tests/BrowserTypeBasicTests.cs +++ b/src/Playwright.Tests/BrowserTypeBasicTests.cs @@ -1,34 +1,27 @@ using System.IO; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserTypeBasicTests : PlaywrightSharpBaseTest { - /// - public BrowserTypeBasicTests(ITestOutputHelper output) : base(output) - { - } - [PlaywrightTest("browsertype-basic.spec.ts", "browserType.executablePath should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] - public void BrowserTypeExecutablePathShouldWork() => Assert.True(File.Exists(BrowserType.ExecutablePath)); + [Test, Timeout(TestConstants.DefaultTestTimeout)] + public void BrowserTypeExecutablePathShouldWork() => Assert.That(File.Exists(BrowserType.ExecutablePath), Is.True); [PlaywrightTest("browsertype-basic.spec.ts", "browserType.name should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public void BrowserTypeNameShouldWork() - => Assert.Equal( - TestConstants.Product switch + => Assert.That( + BrowserType.Name, + Is.EqualTo(TestConstants.Product switch { TestConstants.WebkitProduct => "webkit", TestConstants.FirefoxProduct => "firefox", TestConstants.ChromiumProduct => "chromium", _ => null - }, - BrowserType.Name); + })); } } diff --git a/src/Playwright.Tests/BrowserTypeConnectTests.cs b/src/Playwright.Tests/BrowserTypeConnectTests.cs index 0dc30a1e88..385c1ce6df 100644 --- a/src/Playwright.Tests/BrowserTypeConnectTests.cs +++ b/src/Playwright.Tests/BrowserTypeConnectTests.cs @@ -1,21 +1,13 @@ -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///browsertype-connect.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserTypeConnectTests : PlaywrightSharpBaseTest - { - /// - public BrowserTypeConnectTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsertype-connect.spec.ts", "should be able to reconnect to a browser")] - [Fact(Skip = "SKIP WIRE")] + { [PlaywrightTest("browsertype-connect.spec.ts", "should be able to reconnect to a browser")] + [Test, Ignore("SKIP WIRE")] public void ShouldBeAbleToReconnectToABrowser() { /* @@ -38,61 +30,61 @@ public void ShouldBeAbleToReconnectToABrowser() } [PlaywrightTest("browsertype-connect.spec.ts", "should be able to connect two browsers at the same time")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldBeAbleToConnectTwoBrowsersAtTheSameTime() { } [PlaywrightTest("browsertype-connect.spec.ts", "disconnected event should be emitted when browser is closed or server is closed")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void DisconnectedEventShouldBeEmittedWhenBrowserIsClosedOrServerIsClosed() { } [PlaywrightTest("browsertype-connect.spec.ts", "should handle exceptions during connect")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldHandleExceptionsDuringConnect() { } [PlaywrightTest("browsertype-connect.spec.ts", "should set the browser connected state")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldSetTheBrowserConnectedState() { } [PlaywrightTest("browsertype-connect.spec.ts", "should throw when used after isConnected returns false")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldThrowWhenUsedAfterIsConnectedReturnsFalse() { } [PlaywrightTest("browsertype-connect.spec.ts", "should reject navigation when browser closes")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldRejectNavigationWhenBrowserCloses() { } [PlaywrightTest("browsertype-connect.spec.ts", "should reject waitForSelector when browser closes")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldRejectWaitForSelectorWhenBrowserCloses() { } [PlaywrightTest("browsertype-connect.spec.ts", "should emit close events on pages and contexts")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldEmitCloseEventsOnPagesAndContexts() { } [PlaywrightTest("browsertype-connect.spec.ts", "should terminate network waiters")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldTerminateNetworkWaiters() { } [PlaywrightTest("browsertype-connect.spec.ts", "should respect selectors")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldRespectSelectors() { } diff --git a/src/Playwright.Tests/BrowserTypeLaunchTests.cs b/src/Playwright.Tests/BrowserTypeLaunchTests.cs index cf9a0f30f7..81d11b0d29 100644 --- a/src/Playwright.Tests/BrowserTypeLaunchTests.cs +++ b/src/Playwright.Tests/BrowserTypeLaunchTests.cs @@ -3,51 +3,43 @@ using System.IO; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Transport; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///browsertype-launch.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class BrowserTypeLaunchTests : PlaywrightSharpBaseTest - { - /// - public BrowserTypeLaunchTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("browsertype-launch.spec.ts", "should reject all promises when browser is closed")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("browsertype-launch.spec.ts", "should reject all promises when browser is closed")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRejectAllPromisesWhenBrowserIsClosed() { await using var browser = await BrowserType.LaunchDefaultAsync(); var page = await (await browser.NewContextAsync()).NewPageAsync(); var neverResolves = page.EvaluateHandleAsync("() => new Promise(r => {})"); await browser.CloseAsync(); - var exception = await Assert.ThrowsAsync(() => neverResolves); - Assert.Contains("Protocol error", exception.Message); + var exception = Assert.ThrowsAsync(() => neverResolves); + Assert.That(exception.Message, Does.Contain("Protocol error")); } [PlaywrightTest("browsertype-launch.spec.ts", "should throw if port option is passed")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldThrowIfPortOptionIsPassed() { } [PlaywrightTest("browsertype-launch.spec.ts", "should throw if userDataDir option is passed")] - [Fact(Skip = "This isn't supported in our language port.")] + [Test, Ignore("This isn't supported in our language port.")] public void ShouldThrowIfUserDataDirOptionIsPassed() { } [PlaywrightTest("browsertype-launch.spec.ts", "should throw if port option is passed for persistent context")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldThrowIfPortOptionIsPassedForPersistenContext() { } @@ -56,11 +48,11 @@ public void ShouldThrowIfPortOptionIsPassedForPersistenContext() [SkipBrowserAndPlatformFact(skipFirefox: true)] public async Task ShouldThrowIfPageArgumentIsPassed() { - await Assert.ThrowsAnyAsync(() => BrowserType.LaunchDefaultAsync(args: new[] { TestConstants.EmptyPage })); + Assert.CatchAsync(() => BrowserType.LaunchDefaultAsync(args: new[] { TestConstants.EmptyPage })); } [PlaywrightTest("browsertype-launch.spec.ts", "should reject if launched browser fails immediately")] - [Fact(Skip = "Skipped in playwright")] + [Test, Ignore("Skipped in playwright")] public void ShouldRejectIfLaunchedBrowserFailsImmediately() { } @@ -69,48 +61,48 @@ public void ShouldRejectIfLaunchedBrowserFailsImmediately() /// Should curante the message coming from Playwright /// /// - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCurateTheLaunchError() { // Set an invalid location using var playwright = await Microsoft.Playwright.Playwright.CreateAsync(browsersPath: Path.Combine(typeof(Microsoft.Playwright.Playwright).Assembly.Location)); - var exception = await Assert.ThrowsAsync(() => playwright[TestConstants.Product].LaunchAsync()); + var exception = Assert.ThrowsAsync(() => playwright[TestConstants.Product].LaunchAsync()); - Assert.Contains("Failed to launch", exception.Message); - Assert.Contains("Try re-installing the browsers running `playwright.cmd install` in windows or `./playwright.sh install` in MacOS or Linux.", exception.Message); - Assert.DoesNotContain("npm install playwright", exception.Message); + Assert.That(exception.Message, Does.Contain("Failed to launch")); + Assert.That(exception.Message, Does.Contain("Try re-installing the browsers running `playwright.cmd install` in windows or `./playwright.sh install` in MacOS or Linux.")); + Assert.That(exception.Message, Does.Not.Contain("npm install playwright")); Environment.SetEnvironmentVariable(EnvironmentVariables.BrowsersPathEnvironmentVariable, null); } [PlaywrightTest("browsertype-launch.spec.ts", "should reject if executable path is invalid")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRejectIfExecutablePathIsInvalid() { - var exception = await Assert.ThrowsAsync(() => BrowserType.LaunchAsync(executablePath: "random-invalid-path")); + var exception = Assert.ThrowsAsync(() => BrowserType.LaunchAsync(executablePath: "random-invalid-path")); - Assert.Contains("Failed to launch", exception.Message); + Assert.That(exception.Message, Does.Contain("Failed to launch")); } [PlaywrightTest("browsertype-launch.spec.ts", "should handle timeout")] - [Fact(Skip = "We ignore hook tests")] + [Test, Ignore("We ignore hook tests")] public void ShouldHandleTimeout() { } [PlaywrightTest("browsertype-launch.spec.ts", "should report launch log")] - [Fact(Skip = "We ignore hook tests")] + [Test, Ignore("We ignore hook tests")] public void ShouldReportLaunchLog() { } [PlaywrightTest("browsertype-launch.spec.ts", "should accept objects as options")] - [Fact(Skip = "We don't need to test this")] + [Test, Ignore("We don't need to test this")] public void ShouldAcceptObjectsAsOptions() { } [PlaywrightTest("browsertype-launch.spec.ts", "should fire close event for all contexts")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFireCloseEventForAllContexts() { await using var browser = await BrowserType.LaunchDefaultAsync(); @@ -123,7 +115,7 @@ public async Task ShouldFireCloseEventForAllContexts() } [PlaywrightTest("browsertype-launch.spec.ts", "should be callable twice")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeCallableTwice() { await using var browser = await BrowserType.LaunchDefaultAsync(); @@ -134,7 +126,7 @@ public async Task ShouldBeCallableTwice() /// /// PuppeteerSharp test. It's not in upstream /// - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithEnvironmentVariables() { var env = new Dictionary diff --git a/src/Playwright.Tests/CapabilitiesTests.cs b/src/Playwright.Tests/CapabilitiesTests.cs index c3af56ec7e..a6a0909d2a 100644 --- a/src/Playwright.Tests/CapabilitiesTests.cs +++ b/src/Playwright.Tests/CapabilitiesTests.cs @@ -1,28 +1,20 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///capabilities.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class CapabilitiesTests : PlaywrightSharpPageBaseTest - { - /// - public CapabilitiesTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("capabilities.spec.ts", "Web Assembly should work")] + { [PlaywrightTest("capabilities.spec.ts", "Web Assembly should work")] [SkipBrowserAndPlatformFact(skipWebkit: true, skipWindows: true)] public async Task WebAssemblyShouldWork() { await Page.GoToAsync(TestConstants.ServerUrl + "/wasm/table2.html"); - Assert.Equal("42, 83", await Page.EvaluateAsync("() => loadTable()")); + Assert.That(await Page.EvaluateAsync("() => loadTable()"), Is.EqualTo("42, 83")); } #if NETCOREAPP @@ -40,12 +32,12 @@ public async Task WebSocketShouldWork() return result; }}", TestConstants.Port); - Assert.Equal("incoming", value); + Assert.That(value, Is.EqualTo("incoming")); } #endif [PlaywrightTest("capabilities.spec.ts", "should respect CSP")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectCSP() { Server.SetRoute("/empty.html", context => @@ -63,7 +55,7 @@ public async Task ShouldRespectCSP() }); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("SUCCESS", await Page.EvaluateAsync("() => window.testStatus")); + Assert.That(await Page.EvaluateAsync("() => window.testStatus"), Is.EqualTo("SUCCESS")); } [PlaywrightTest("capabilities.spec.ts", "should play video")] diff --git a/src/Playwright.Tests/ChromiumCSSCoverageTests.cs b/src/Playwright.Tests/ChromiumCSSCoverageTests.cs index 784268d622..ac11c9d3b7 100644 --- a/src/Playwright.Tests/ChromiumCSSCoverageTests.cs +++ b/src/Playwright.Tests/ChromiumCSSCoverageTests.cs @@ -1,113 +1,105 @@ using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; using Newtonsoft.Json; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ChromiumCSSCoverageTests : PlaywrightSharpPageBaseTest - { - /// - public ChromiumCSSCoverageTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should work")] - [Fact(Skip = "We won't support coverage")] + { [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should work")] + [Test, Ignore("We won't support coverage")] public void ShouldWork() { /* await Page.Coverage.StartCSSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/simple.html"); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Single(coverage); - Assert.Contains("/csscoverage/simple.html", coverage[0].Url); - Assert.Equal(new[] + Assert.That(coverage, Has.Count.EqualTo(1)); + Assert.That(coverage[0].Url, Does.Contain("/csscoverage/simple.html")); + Assert.That(coverage[0].Ranges, Is.EqualTo(new[] { new CSSCoverageEntryRange { Start = 1, End = 22 } - }, coverage[0].Ranges); + })); var range = coverage[0].Ranges[0]; - Assert.Equal("div { color: green; }", coverage[0].Text.Substring(range.Start, range.End - range.Start)); + Assert.That(coverage[0].Text.Substring(range.Start, range.End - range.Start), Is.EqualTo("div { color: green; }")); */ } [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should report sourceURLs")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldReportSourceUrls() { /* await Page.Coverage.StartCSSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/sourceurl.html"); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Single(coverage); - Assert.Equal("nicename.css", coverage[0].Url); + Assert.That(coverage, Has.Count.EqualTo(1)); + Assert.That(coverage[0].Url, Is.EqualTo("nicename.css")); */ } [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should report multiple stylesheets")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldReportMultipleStylesheets() { /* await Page.Coverage.StartCSSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/multiple.html"); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Equal(2, coverage.Length); + Assert.That(coverage.Length, Is.EqualTo(2)); var orderedList = coverage.OrderBy(c => c.Url).ToArray(); - Assert.Contains("/csscoverage/stylesheet1.css", orderedList[0].Url); - Assert.Contains("/csscoverage/stylesheet2.css", orderedList[1].Url); + Assert.That(orderedList[0].Url, Does.Contain("/csscoverage/stylesheet1.css")); + Assert.That(orderedList[1].Url, Does.Contain("/csscoverage/stylesheet2.css")); */ } [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should report stylesheets that have no coverage")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldReportStylesheetsThatHaveNoCoverage() { /* await Page.Coverage.StartCSSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/unused.html"); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Single(coverage); + Assert.That(coverage, Has.Count.EqualTo(1)); var entry = coverage[0]; - Assert.Contains("unused.css", entry.Url); - Assert.Empty(entry.Ranges); + Assert.That(entry.Url, Does.Contain("unused.css")); + Assert.That(entry.Ranges, Is.Empty); */ } [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should work with media queries")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldWorkWithMediaQueries() { /* await Page.Coverage.StartCSSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/media.html"); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Single(coverage); + Assert.That(coverage, Has.Count.EqualTo(1)); var entry = coverage[0]; - Assert.Contains("/csscoverage/media.html", entry.Url); - Assert.Equal(new[] + Assert.That(entry.Url, Does.Contain("/csscoverage/media.html")); + Assert.That(coverage[0].Ranges, Is.EqualTo(new[] { new CSSCoverageEntryRange { Start = 17, End = 38 } - }, coverage[0].Ranges); + })); */ } [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should work with complicated usecases")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldWorkWithComplicatedUseCases() { /* @@ -130,14 +122,12 @@ public void ShouldWorkWithComplicatedUseCases() await Page.Coverage.StartCSSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/involved.html"); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Equal( - TestUtils.CompressText(involved), - Regex.Replace(TestUtils.CompressText(JsonConvert.SerializeObject(coverage)), @":\d{4}\/", ":/")); + Assert.That(Regex.Replace(TestUtils.CompressText(JsonConvert.SerializeObject(coverage)), @":\d{4}\/", ":/"), Is.EqualTo(TestUtils.CompressText(involved))); */ } [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should ignore injected stylesheets")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldIgnoreInjectedStylesheets() { /* @@ -145,14 +135,14 @@ public void ShouldIgnoreInjectedStylesheets() await Page.AddStyleTagAsync(content: "body { margin: 10px;}"); // trigger style recalc string margin = await Page.EvaluateAsync("window.getComputedStyle(document.body).margin"); - Assert.Equal("10px", margin); + Assert.That(margin, Is.EqualTo("10px")); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Empty(coverage); + Assert.That(coverage, Is.Empty); */ } [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should report stylesheets across navigations")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldReportStylesheetsAcrossNavigations() { /* @@ -160,12 +150,12 @@ public void ShouldReportStylesheetsAcrossNavigations() await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/multiple.html"); await Page.GoToAsync(TestConstants.EmptyPage); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Equal(2, coverage.Length); + Assert.That(coverage.Length, Is.EqualTo(2)); */ } [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should NOT report stylesheets across navigations")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldNotReportScriptsAcrossNavigations() { /* @@ -173,12 +163,12 @@ public void ShouldNotReportScriptsAcrossNavigations() await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/multiple.html"); await Page.GoToAsync(TestConstants.EmptyPage); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Empty(coverage); + Assert.That(coverage, Is.Empty); */ } [PlaywrightTest("chromium-css-coverage.spec.ts", "CSS Coverage", "should work with a recently loaded stylesheet")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldWorkWithArRecentlyLoadedStylesheet() { /* @@ -194,7 +184,7 @@ await Page.EvaluateAsync(@"async url => { await new Promise(f => requestAnimationFrame(f)); }", TestConstants.ServerUrl + "/csscoverage/stylesheet1.css"); var coverage = await Page.Coverage.StopCSSCoverageAsync(); - Assert.Single(coverage); + Assert.That(coverage, Has.Count.EqualTo(1)); */ } } diff --git a/src/Playwright.Tests/ChromiumJSCoverageTests.cs b/src/Playwright.Tests/ChromiumJSCoverageTests.cs index f9e9f9439e..644f492b27 100644 --- a/src/Playwright.Tests/ChromiumJSCoverageTests.cs +++ b/src/Playwright.Tests/ChromiumJSCoverageTests.cs @@ -1,90 +1,82 @@ using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ChromiumJSCoverageTests : PlaywrightSharpPageBaseTest - { - /// - public ChromiumJSCoverageTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("chromium-js-coverage.spec.ts", "JS Coverage", "should work")] - [Fact(Skip = "We won't support coverage")] + { [PlaywrightTest("chromium-js-coverage.spec.ts", "JS Coverage", "should work")] + [Test, Ignore("We won't support coverage")] public void ShouldWork() { /* await Page.Coverage.StartJSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/jscoverage/simple.html", LoadState.NetworkIdle); var coverage = await Page.Coverage.StopJSCoverageAsync(); - Assert.Single(coverage); - Assert.Contains("/jscoverage/simple.html", coverage[0].Url); - Assert.Equal(1, coverage[0].Functions.Single(f => f.FunctionName == "foo").Ranges[0].Count); + Assert.That(coverage, Has.Count.EqualTo(1)); + Assert.That(coverage[0].Url, Does.Contain("/jscoverage/simple.html")); + Assert.That(coverage[0].Functions.Single(f => f.FunctionName == "foo").Ranges[0].Count, Is.EqualTo(1)); */ } [PlaywrightTest("chromium-js-coverage.spec.ts", "JS Coverage", "should report sourceURLs")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldReportSourceUrls() { /* await Page.Coverage.StartJSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/jscoverage/sourceurl.html"); var coverage = await Page.Coverage.StopJSCoverageAsync(); - Assert.Single(coverage); - Assert.Equal("nicename.js", coverage[0].Url); + Assert.That(coverage, Has.Count.EqualTo(1)); + Assert.That(coverage[0].Url, Is.EqualTo("nicename.js")); */ } [PlaywrightTest("chromium-js-coverage.spec.ts", "JS Coverage", "should ignore eval() scripts by default")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldIgnoreEvalScriptsByDefault() { /* await Page.Coverage.StartJSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/jscoverage/eval.html"); var coverage = await Page.Coverage.StopJSCoverageAsync(); - Assert.Single(coverage); + Assert.That(coverage, Has.Count.EqualTo(1)); */ } [PlaywrightTest("chromium-js-coverage.spec.ts", "JS Coverage", "shouldn't ignore eval() scripts if reportAnonymousScripts is true")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldNotIgnoreEvalScriptsIfReportAnonymousScriptsIsTrue() { /* await Page.Coverage.StartJSCoverageAsync(reportAnonymousScripts: true); await Page.GoToAsync(TestConstants.ServerUrl + "/jscoverage/eval.html"); var coverage = await Page.Coverage.StopJSCoverageAsync(); - Assert.Equal("console.log(\"foo\")", coverage.Single(entry => entry.Url == string.Empty).Source); - Assert.Equal(2, coverage.Length); + Assert.That(coverage.Single(entry => entry.Url == string.Empty).Source, Is.EqualTo("console.log(\"foo\")")); + Assert.That(coverage.Length, Is.EqualTo(2)); */ } [PlaywrightTest("chromium-js-coverage.spec.ts", "JS Coverage", "should report multiple scripts")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldReportMultipleScripts() { /* await Page.Coverage.StartJSCoverageAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/jscoverage/multiple.html"); var coverage = await Page.Coverage.StopJSCoverageAsync(); - Assert.Equal(2, coverage.Length); + Assert.That(coverage.Length, Is.EqualTo(2)); var orderedList = coverage.OrderBy(c => c.Url).ToArray(); - Assert.Contains("/jscoverage/script1.js", orderedList[0].Url); - Assert.Contains("/jscoverage/script2.js", orderedList[1].Url); + Assert.That(orderedList[0].Url, Does.Contain("/jscoverage/script1.js")); + Assert.That(orderedList[1].Url, Does.Contain("/jscoverage/script2.js")); */ } [PlaywrightTest("chromium-js-coverage.spec.ts", "JS Coverage", "should report scripts across navigations when disabled")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldReportScriptsAcrossNavigationsWhenDisabled() { /* @@ -92,12 +84,12 @@ public void ShouldReportScriptsAcrossNavigationsWhenDisabled() await Page.GoToAsync(TestConstants.ServerUrl + "/jscoverage/multiple.html"); await Page.GoToAsync(TestConstants.EmptyPage); var coverage = await Page.Coverage.StopJSCoverageAsync(); - Assert.Equal(2, coverage.Length); + Assert.That(coverage.Length, Is.EqualTo(2)); */ } [PlaywrightTest("chromium-js-coverage.spec.ts", "JS Coverage", "should NOT report scripts across navigations when enabled")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldNotReportScriptsAcrossNavigationsWhenEnabled() { /* @@ -105,12 +97,12 @@ public void ShouldNotReportScriptsAcrossNavigationsWhenEnabled() await Page.GoToAsync(TestConstants.ServerUrl + "/jscoverage/multiple.html"); await Page.GoToAsync(TestConstants.EmptyPage); var coverage = await Page.Coverage.StopJSCoverageAsync(); - Assert.Empty(coverage); + Assert.That(coverage, Is.Empty); */ } [PlaywrightTest("chromium-js-coverage.spec.ts", "JS Coverage", "should not hang when there is a debugger statement")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void ShouldNotHangWhenThereIsADebuggerStatement() { /* diff --git a/src/Playwright.Tests/DefaultBrowserContext1Tests.cs b/src/Playwright.Tests/DefaultBrowserContext1Tests.cs index d9eceb55fd..5931c9e8b9 100644 --- a/src/Playwright.Tests/DefaultBrowserContext1Tests.cs +++ b/src/Playwright.Tests/DefaultBrowserContext1Tests.cs @@ -1,24 +1,16 @@ using System.Linq; using System.Net; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.Helpers; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class DefaultBrowserContext1Tests : PlaywrightSharpBaseTest - { - /// - public DefaultBrowserContext1Tests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "context.cookies() should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "context.cookies() should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ContextCookiesShouldWork() { var (tmp, context, page) = await LaunchAsync(); @@ -30,23 +22,23 @@ public async Task ContextCookiesShouldWork() return document.cookie; }"); - Assert.Equal("username=John Doe", documentCookie); + Assert.That(documentCookie, Is.EqualTo("username=John Doe")); var cookie = (await page.Context.GetCookiesAsync()).Single(); - Assert.Equal("username", cookie.Name); - Assert.Equal("John Doe", cookie.Value); - Assert.Equal("localhost", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(-1, cookie.Expires); - Assert.False(cookie.HttpOnly); - Assert.False(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(cookie.Name, Is.EqualTo("username")); + Assert.That(cookie.Value, Is.EqualTo("John Doe")); + Assert.That(cookie.Domain, Is.EqualTo("localhost")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(cookie.Expires, Is.EqualTo(-1)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "context.addCookies() should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ContextAddCookiesShouldWork() { var (tmp, context, page) = await LaunchAsync(); @@ -59,24 +51,24 @@ await context.AddCookiesAsync(new Cookie Value = "John Doe", }); - Assert.Equal("username=John Doe", await page.EvaluateAsync(@"() => document.cookie")); + Assert.That(await page.EvaluateAsync(@"() => document.cookie"), Is.EqualTo("username=John Doe")); var cookie = (await page.Context.GetCookiesAsync()).Single(); - Assert.Equal("username", cookie.Name); - Assert.Equal("John Doe", cookie.Value); - Assert.Equal("localhost", cookie.Domain); - Assert.Equal("/", cookie.Path); - Assert.Equal(-1, cookie.Expires); - Assert.False(cookie.HttpOnly); - Assert.False(cookie.Secure); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); + Assert.That(cookie.Name, Is.EqualTo("username")); + Assert.That(cookie.Value, Is.EqualTo("John Doe")); + Assert.That(cookie.Domain, Is.EqualTo("localhost")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(cookie.Expires, Is.EqualTo(-1)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "context.clearCookies() should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ContextClearCookiesShouldWork() { var (tmp, context, page) = await LaunchAsync(); @@ -96,19 +88,19 @@ await context.AddCookiesAsync( Value = "2", }); - Assert.Equal("cookie1=1; cookie2=2", await page.EvaluateAsync(@"() => document.cookie")); + Assert.That(await page.EvaluateAsync(@"() => document.cookie"), Is.EqualTo("cookie1=1; cookie2=2")); await context.ClearCookiesAsync(); await page.ReloadAsync(); - Assert.Empty(await page.Context.GetCookiesAsync()); - Assert.Empty(await page.EvaluateAsync(@"() => document.cookie")); + Assert.That(await page.Context.GetCookiesAsync(), Is.Empty); + Assert.That(await page.EvaluateAsync(@"() => document.cookie"), Is.Empty); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should(not) block third party cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotBlockThirdPartyCookies() { var (tmp, context, page) = await LaunchAsync(); @@ -131,20 +123,20 @@ await page.EvaluateAsync(@"src => { if (allowsThirdPart) { - Assert.Single(cookies); + Assert.That(cookies, Has.Count.EqualTo(1)); var cookie = cookies.First(); - Assert.Equal("127.0.0.1", cookie.Domain); - Assert.Equal(cookie.Expires, -1); - Assert.False(cookie.HttpOnly); - Assert.Equal("username", cookie.Name); - Assert.Equal("/", cookie.Path); - Assert.Equal(SameSiteAttribute.None, cookie.SameSite); - Assert.False(cookie.Secure); - Assert.Equal("John Doe", cookie.Value); + Assert.That(cookie.Domain, Is.EqualTo("127.0.0.1")); + Assert.That(-1, Is.EqualTo(cookie.Expires)); + Assert.That(cookie.HttpOnly, Is.False); + Assert.That(cookie.Name, Is.EqualTo("username")); + Assert.That(cookie.Path, Is.EqualTo("/")); + Assert.That(cookie.SameSite, Is.EqualTo(SameSiteAttribute.None)); + Assert.That(cookie.Secure, Is.False); + Assert.That(cookie.Value, Is.EqualTo("John Doe")); } else { - Assert.Empty(cookies); + Assert.That(cookies, Is.Empty); } tmp.Dispose(); @@ -152,7 +144,7 @@ await page.EvaluateAsync(@"src => { } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support viewport option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportViewportOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -173,7 +165,7 @@ public async Task ShouldSupportViewportOption() } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support deviceScaleFactor option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportDeviceScaleFactorOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -181,14 +173,14 @@ public async Task ShouldSupportDeviceScaleFactorOption() DeviceScaleFactor = 3 }); - Assert.Equal(3, await page.EvaluateAsync("window.devicePixelRatio")); + Assert.That(await page.EvaluateAsync("window.devicePixelRatio"), Is.EqualTo(3)); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support userAgent option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportUserAgentOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -202,14 +194,14 @@ await TaskUtils.WhenAll( Server.WaitForRequest("/empty.html", r => userAgent = r.Headers["user-agent"]), page.GoToAsync(TestConstants.EmptyPage)); - Assert.Equal("foobar", userAgent); + Assert.That(userAgent, Is.EqualTo("foobar")); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support bypassCSP option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportBypassCSPOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -219,14 +211,14 @@ public async Task ShouldSupportBypassCSPOption() await page.GoToAsync(TestConstants.ServerUrl + "/csp.html"); await page.AddScriptTagAsync(content: "window.__injected = 42;"); - Assert.Equal(42, await page.EvaluateAsync("window.__injected")); + Assert.That(await page.EvaluateAsync("window.__injected"), Is.EqualTo(42)); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support javascriptEnabled option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportJavascriptEnabledOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -235,15 +227,15 @@ public async Task ShouldSupportJavascriptEnabledOption() }); await page.GoToAsync("data:text/html, "); - var exception = await Assert.ThrowsAnyAsync(() => page.EvaluateAsync("something")); + var exception = Assert.CatchAsync(() => page.EvaluateAsync("something")); if (TestConstants.IsWebKit) { - Assert.Contains("Can't find variable: something", exception.Message); + Assert.That(exception.Message, Does.Contain("Can't find variable: something")); } else { - Assert.Contains("something is not defined", exception.Message); + Assert.That(exception.Message, Does.Contain("something is not defined")); } tmp.Dispose(); @@ -251,7 +243,7 @@ public async Task ShouldSupportJavascriptEnabledOption() } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support httpCredentials option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRupportHttpCredentialsOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -265,14 +257,14 @@ public async Task ShouldRupportHttpCredentialsOption() Server.SetAuth("/playground.html", "user", "pass"); var response = await page.GoToAsync(TestConstants.ServerUrl + "/playground.html"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support offline option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportOfflineOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -280,14 +272,14 @@ public async Task ShouldSupportOfflineOption() Offline = true }); - await Assert.ThrowsAnyAsync(() => page.GoToAsync(TestConstants.EmptyPage)); + Assert.CatchAsync(() => page.GoToAsync(TestConstants.EmptyPage)); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support acceptDownloads option")] - [Fact(Skip = "Skipped on playwright")] + [Test, Ignore("Skipped on playwright")] public void ShouldSupportAcceptDownloadsOption() { } diff --git a/src/Playwright.Tests/DefaultBrowsercontext2Tests.cs b/src/Playwright.Tests/DefaultBrowsercontext2Tests.cs index 2f24c5c7b5..2b404c4b10 100644 --- a/src/Playwright.Tests/DefaultBrowsercontext2Tests.cs +++ b/src/Playwright.Tests/DefaultBrowsercontext2Tests.cs @@ -3,26 +3,18 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.Helpers; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { /// defaultbrowsercontext-2.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class DefaultBrowsercontext2Tests : PlaywrightSharpBaseTest - { - /// - public DefaultBrowsercontext2Tests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support hasTouch option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support hasTouch option")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportHasTouchOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -31,7 +23,7 @@ public async Task ShouldSupportHasTouchOption() }); await page.GoToAsync(TestConstants.ServerUrl + "/mobile.html"); - Assert.True(await page.EvaluateAsync("() => 'ontouchstart' in window")); + Assert.That(await page.EvaluateAsync("() => 'ontouchstart' in window"), Is.True); tmp.Dispose(); await context.DisposeAsync(); @@ -52,14 +44,14 @@ public async Task ShouldWorkInPersistentContext() }); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(980, await page.EvaluateAsync("() => window.innerWidth")); + Assert.That(await page.EvaluateAsync("() => window.innerWidth"), Is.EqualTo(980)); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support colorScheme option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportColorSchemeOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -67,15 +59,15 @@ public async Task ShouldSupportColorSchemeOption() ColorScheme = ColorScheme.Dark, }); - Assert.False(await page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches")); - Assert.True(await page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); + Assert.That(await page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches"), Is.False); + Assert.That(await page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.True); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support timezoneId option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportTimezoneIdOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -83,14 +75,14 @@ public async Task ShouldSupportTimezoneIdOption() TimezoneId = "America/Jamaica", }); - Assert.Equal("Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)", await page.EvaluateAsync("() => new Date(1479579154987).toString()")); + Assert.That(await page.EvaluateAsync("() => new Date(1479579154987).toString()"), Is.EqualTo("Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)")); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support locale option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportLocaleOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -98,14 +90,14 @@ public async Task ShouldSupportLocaleOption() Locale = "fr-CH", }); - Assert.Equal("fr-CH", await page.EvaluateAsync("() => navigator.language")); + Assert.That(await page.EvaluateAsync("() => navigator.language"), Is.EqualTo("fr-CH")); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support geolocation and permissions options")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportGeolocationAndPermissionsOptions() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -122,16 +114,16 @@ public async Task ShouldSupportGeolocationAndPermissionsOptions() var geolocation = await page.EvaluateAsync(@"() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => { resolve({latitude: position.coords.latitude, longitude: position.coords.longitude}); }))"); - Assert.Equal(10, geolocation.Latitude); - Assert.Equal(10, geolocation.Longitude); + Assert.That(geolocation.Latitude, Is.EqualTo(10)); + Assert.That(geolocation.Longitude, Is.EqualTo(10)); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support ignoreHTTPSErrors option")] - // [Fact(Timeout = TestConstants.DefaultTestTimeout)] - [Fact(Skip = "Fix me #1058")] + // [Test, Timeout(TestConstants.DefaultTestTimeout)] + [Test, Ignore("Fix me #1058")] public async Task ShouldSupportIgnoreHTTPSErrorsOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -140,14 +132,14 @@ public async Task ShouldSupportIgnoreHTTPSErrorsOption() }); var response = await page.GoToAsync(TestConstants.HttpsPrefix + "/empty.html"); - Assert.True(response.Ok); + Assert.That(response.Ok, Is.True); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support extraHTTPHeaders option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportExtraHTTPHeadersOption() { var (tmp, context, page) = await LaunchAsync(new BrowserContextOptions @@ -164,26 +156,26 @@ await TaskUtils.WhenAll( Server.WaitForRequest("/empty.html", r => fooHeader = r.Headers["foo"]), page.GoToAsync(TestConstants.EmptyPage)); - Assert.Equal("bar", fooHeader); + Assert.That(fooHeader, Is.EqualTo("bar")); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should accept userDataDir")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptUserDataDir() { var (tmp, context, _) = await LaunchAsync(); - Assert.NotEmpty(new DirectoryInfo(tmp.Path).GetDirectories()); + Assert.That(new DirectoryInfo(tmp.Path).GetDirectories(), Is.Not.Empty); await context.CloseAsync(); - Assert.NotEmpty(new DirectoryInfo(tmp.Path).GetDirectories()); + Assert.That(new DirectoryInfo(tmp.Path).GetDirectories(), Is.Not.Empty); tmp.Dispose(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should restore state from userDataDir")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRestoreStateFromUserDataDir() { using var userDataDir = new TempDirectory(); @@ -200,7 +192,7 @@ public async Task ShouldRestoreStateFromUserDataDir() { var page = await browserContext2.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("hello", await page.EvaluateAsync("() => localStorage.hey")); + Assert.That(await page.EvaluateAsync("() => localStorage.hey"), Is.EqualTo("hello")); } using var userDataDir2 = new TempDirectory(); @@ -208,7 +200,7 @@ public async Task ShouldRestoreStateFromUserDataDir() { var page = await browserContext2.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.NotEqual("hello", await page.EvaluateAsync("() => localStorage.hey")); + Assert.That(await page.EvaluateAsync("() => localStorage.hey"), Is.Not.EqualTo("hello")); } userDataDir2.Dispose(); @@ -230,14 +222,14 @@ public async Task ShouldRestoreCookiesFromUserDataDir() return document.cookie; }"); - Assert.Equal("doSomethingOnlyOnce=true", documentCookie); + Assert.That(documentCookie, Is.EqualTo("doSomethingOnlyOnce=true")); } await using (var browserContext2 = await BrowserType.LaunchDefaultPersistentContext(userDataDir.Path)) { var page = await browserContext2.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("doSomethingOnlyOnce=true", await page.EvaluateAsync("() => document.cookie")); + Assert.That(await page.EvaluateAsync("() => document.cookie"), Is.EqualTo("doSomethingOnlyOnce=true")); } var userDataDir2 = new TempDirectory(); @@ -245,7 +237,7 @@ public async Task ShouldRestoreCookiesFromUserDataDir() { var page = await browserContext2.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.NotEqual("doSomethingOnlyOnce=true", await page.EvaluateAsync("() => document.cookie")); + Assert.That(await page.EvaluateAsync("() => document.cookie"), Is.Not.EqualTo("doSomethingOnlyOnce=true")); } userDataDir2.Dispose(); @@ -253,13 +245,13 @@ public async Task ShouldRestoreCookiesFromUserDataDir() } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should have default URL when launching browser")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveDefaultURLWhenLaunchingBrowser() { var (tmp, context, page) = await LaunchAsync(); string[] urls = context.Pages.Select(p => p.Url).ToArray(); - Assert.Equal(new[] { "about:blank" }, urls); + Assert.That(urls, Is.EqualTo(new[] { "about:blank" })); tmp.Dispose(); await context.DisposeAsync(); @@ -270,32 +262,32 @@ public async Task ShouldHaveDefaultURLWhenLaunchingBrowser() public async Task ShouldThrowIfPageArgumentIsPassed() { var tmp = new TempDirectory(); - await Assert.ThrowsAnyAsync(() => + Assert.CatchAsync(() => BrowserType.LaunchDefaultPersistentContext(tmp.Path, new[] { TestConstants.EmptyPage })); tmp.Dispose(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should have passed URL when launching with ignoreDefaultArgs: true")] - [Fact(Skip = "Skip USES_HOOKS")] + [Test, Ignore("Skip USES_HOOKS")] public void ShouldHavePassedURLWhenLaunchingWithIgnoreDefaultArgsTrue() { } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should handle timeout")] - [Fact(Skip = "Skip USES_HOOKS")] + [Test, Ignore("Skip USES_HOOKS")] public void ShouldHandleTimeout() { } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should handle exception")] - [Fact(Skip = "Skip USES_HOOKS")] + [Test, Ignore("Skip USES_HOOKS")] public void ShouldHandleException() { } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should fire close event for a persistent context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFireCloseEventForAPersistentContext() { var (tmp, context, _) = await LaunchAsync(); @@ -303,14 +295,14 @@ public async Task ShouldFireCloseEventForAPersistentContext() context.Close += (_, _) => closed = true; await context.CloseAsync(); - Assert.True(closed); + Assert.That(closed, Is.True); tmp.Dispose(); await context.DisposeAsync(); } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "coverage should work")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void CoverageShouldWork() { /* @@ -319,9 +311,9 @@ public void CoverageShouldWork() await page.Coverage.StartJSCoverageAsync(); await page.GoToAsync(TestConstants.ServerUrl + "/jscoverage/simple.html", LoadState.NetworkIdle); var coverage = await page.Coverage.StopJSCoverageAsync(); - Assert.Single(coverage); - Assert.Contains("/jscoverage/simple.html", coverage[0].Url); - Assert.Equal(1, coverage[0].Functions.Single(f => f.FunctionName == "foo").Ranges[0].Count); + Assert.That(coverage, Has.Count.EqualTo(1)); + Assert.That(coverage[0].Url, Does.Contain("/jscoverage/simple.html")); + Assert.That(coverage[0].Functions.Single(f => f.FunctionName == "foo").Ranges[0].Count, Is.EqualTo(1)); tmp.Dispose(); await context.DisposeAsync(); @@ -329,19 +321,19 @@ public void CoverageShouldWork() } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "coverage should be missing")] - [Fact(Skip = "We won't support coverage")] + [Test, Ignore("We won't support coverage")] public void CoverageShouldBeMissing() { /* var (tmp, context, page) = await LaunchAsync(); - Assert.Null(page.Coverage); + Assert.That(page.Coverage, Is.Null); tmp.Dispose(); await context.DisposeAsync(); */ } [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should respect selectors")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectSelectors() { var (tmp, context, page) = await LaunchAsync(); @@ -357,8 +349,8 @@ public async Task ShouldRespectSelectors() await TestUtils.RegisterEngineAsync(Playwright, "defaultContextCSS", defaultContextCSS); await page.SetContentAsync("
hello
"); - Assert.Equal("hello", await page.InnerHTMLAsync("css=div")); - Assert.Equal("hello", await page.InnerHTMLAsync("defaultContextCSS=div")); + Assert.That(await page.InnerHTMLAsync("css=div"), Is.EqualTo("hello")); + Assert.That(await page.InnerHTMLAsync("defaultContextCSS=div"), Is.EqualTo("hello")); tmp.Dispose(); await context.DisposeAsync(); diff --git a/src/Playwright.Tests/DownloadTests.cs b/src/Playwright.Tests/DownloadTests.cs index 7e938e314d..85bbd473ca 100644 --- a/src/Playwright.Tests/DownloadTests.cs +++ b/src/Playwright.Tests/DownloadTests.cs @@ -1,21 +1,19 @@ using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.Helpers; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///download.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class DownloadTests : PlaywrightSharpPageBaseTest { - /// - public DownloadTests(ITestOutputHelper output) : base(output) + [SetUp] + public void DownloadTestsSetUp() { Server.SetRoute("/download", context => { @@ -33,7 +31,7 @@ public DownloadTests(ITestOutputHelper output) : base(output) } [PlaywrightTest("download.spec.ts", "should report downloads with acceptDownloads: false")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportDownloadsWithAcceptDownloadsFalse() { await Page.SetContentAsync($"download"); @@ -44,16 +42,16 @@ await TaskUtils.WhenAll( Page.ClickAsync("a")); var download = downloadTask.Result; - Assert.Equal($"{TestConstants.ServerUrl}/downloadWithFilename", download.Url); - Assert.Equal("file.txt", download.SuggestedFilename); + Assert.That(download.Url, Is.EqualTo($"{TestConstants.ServerUrl}/downloadWithFilename")); + Assert.That(download.SuggestedFilename, Is.EqualTo("file.txt")); - var exception = await Assert.ThrowsAnyAsync(() => download.PathAsync()); - Assert.Contains("acceptDownloads", await download.FailureAsync()); - Assert.Contains("acceptDownloads: true", exception.Message); + var exception = Assert.CatchAsync(() => download.PathAsync()); + Assert.That(await download.FailureAsync(), Does.Contain("acceptDownloads")); + Assert.That(exception.Message, Does.Contain("acceptDownloads: true")); } [PlaywrightTest("download.spec.ts", "should report downloads with acceptDownloads: true")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportDownloadsWithAcceptDownloadsTrue() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -67,12 +65,12 @@ await TaskUtils.WhenAll( var download = downloadTask.Result; string path = await download.PathAsync(); - Assert.True(new FileInfo(path).Exists); - Assert.Equal("Hello world", File.ReadAllText(path)); + Assert.That(new FileInfo(path).Exists, Is.True); + Assert.That(File.ReadAllText(path), Is.EqualTo("Hello world")); } [PlaywrightTest("download.spec.ts", "should save to user-specified path")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSaveToUserSpecifiedPath() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -88,13 +86,13 @@ await TaskUtils.WhenAll( var download = downloadTask.Result; await download.SaveAsAsync(userPath); - Assert.True(new FileInfo(userPath).Exists); - Assert.Equal("Hello world", File.ReadAllText(userPath)); + Assert.That(new FileInfo(userPath).Exists, Is.True); + Assert.That(File.ReadAllText(userPath), Is.EqualTo("Hello world")); await page.CloseAsync(); } [PlaywrightTest("download.spec.ts", "should save to user-specified path without updating original path")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSaveToUserSpecifiedPathWithoutUpdatingOriginalPath() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -110,18 +108,18 @@ await TaskUtils.WhenAll( var download = downloadTask.Result; await download.SaveAsAsync(userPath); - Assert.True(new FileInfo(userPath).Exists); - Assert.Equal("Hello world", File.ReadAllText(userPath)); + Assert.That(new FileInfo(userPath).Exists, Is.True); + Assert.That(File.ReadAllText(userPath), Is.EqualTo("Hello world")); string originalPath = await download.PathAsync(); - Assert.True(new FileInfo(originalPath).Exists); - Assert.Equal("Hello world", File.ReadAllText(originalPath)); + Assert.That(new FileInfo(originalPath).Exists, Is.True); + Assert.That(File.ReadAllText(originalPath), Is.EqualTo("Hello world")); await page.CloseAsync(); } [PlaywrightTest("download.spec.ts", "should save to two different paths with multiple saveAs calls")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSaveToTwoDifferentPathsWithMultipleSaveAsCalls() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -136,19 +134,19 @@ await TaskUtils.WhenAll( string userPath = Path.Combine(tmpDir.Path, "download.txt"); var download = downloadTask.Result; await download.SaveAsAsync(userPath); - Assert.True(new FileInfo(userPath).Exists); - Assert.Equal("Hello world", File.ReadAllText(userPath)); + Assert.That(new FileInfo(userPath).Exists, Is.True); + Assert.That(File.ReadAllText(userPath), Is.EqualTo("Hello world")); string anotherUserPath = Path.Combine(tmpDir.Path, "download (2).txt"); await download.SaveAsAsync(anotherUserPath); - Assert.True(new FileInfo(anotherUserPath).Exists); - Assert.Equal("Hello world", File.ReadAllText(anotherUserPath)); + Assert.That(new FileInfo(anotherUserPath).Exists, Is.True); + Assert.That(File.ReadAllText(anotherUserPath), Is.EqualTo("Hello world")); await page.CloseAsync(); } [PlaywrightTest("download.spec.ts", "should save to overwritten filepath")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSaveToOverwrittenFilepath() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -163,15 +161,15 @@ await TaskUtils.WhenAll( string userPath = Path.Combine(tmpDir.Path, "download.txt"); var download = downloadTask.Result; await download.SaveAsAsync(userPath); - Assert.Single(new DirectoryInfo(tmpDir.Path).GetFiles()); + Assert.That(new DirectoryInfo(tmpDir.Path).GetFiles(), Has.Count.EqualTo(1)); await download.SaveAsAsync(userPath); - Assert.Single(new DirectoryInfo(tmpDir.Path).GetFiles()); + Assert.That(new DirectoryInfo(tmpDir.Path).GetFiles(), Has.Count.EqualTo(1)); await page.CloseAsync(); } [PlaywrightTest("download.spec.ts", "should create subdirectories when saving to non-existent user-specified path")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCreateSubdirectoriesWhenSavingToNonExistentUserSpecifiedPath() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -186,20 +184,20 @@ await TaskUtils.WhenAll( string userPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "download.txt"); var download = downloadTask.Result; await download.SaveAsAsync(userPath); - Assert.True(new FileInfo(userPath).Exists); - Assert.Equal("Hello world", File.ReadAllText(userPath)); + Assert.That(new FileInfo(userPath).Exists, Is.True); + Assert.That(File.ReadAllText(userPath), Is.EqualTo("Hello world")); await page.CloseAsync(); } [PlaywrightTest("download.spec.ts", "should save when connected remotely")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldSaveWhenConnectedRemotely() { } [PlaywrightTest("download.spec.ts", "should error when saving with downloads disabled")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldErrorWhenSavingWithDownloadsDisabled() { var page = await Browser.NewPageAsync(acceptDownloads: false); @@ -214,12 +212,12 @@ await TaskUtils.WhenAll( string userPath = Path.Combine(tmpDir.Path, "download.txt"); var download = downloadTask.Result; - var exception = await Assert.ThrowsAnyAsync(() => download.SaveAsAsync(userPath)); - Assert.Contains("Pass { acceptDownloads: true } when you are creating your browser context", exception.Message); + var exception = Assert.CatchAsync(() => download.SaveAsAsync(userPath)); + Assert.That(exception.Message, Does.Contain("Pass { acceptDownloads: true } when you are creating your browser context")); } [PlaywrightTest("download.spec.ts", "should error when saving after deletion")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldErrorWhenSavingAfterDeletion() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -234,18 +232,18 @@ await TaskUtils.WhenAll( string userPath = Path.Combine(tmpDir.Path, "download.txt"); var download = downloadTask.Result; await download.DeleteAsync(); - var exception = await Assert.ThrowsAnyAsync(() => download.SaveAsAsync(userPath)); - Assert.Contains("Download already deleted. Save before deleting.", exception.Message); + var exception = Assert.CatchAsync(() => download.SaveAsAsync(userPath)); + Assert.That(exception.Message, Does.Contain("Download already deleted. Save before deleting.")); } [PlaywrightTest("download.spec.ts", "should error when saving after deletion when connected remotely")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public void ShouldErrorWhenSavingAfterDeletionWhenConnectedRemotely() { } [PlaywrightTest("download.spec.ts", "should report non-navigation downloads")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportNonNavigationDownloads() { Server.SetRoute("/download", context => @@ -264,16 +262,16 @@ await TaskUtils.WhenAll( page.ClickAsync("a")); var download = downloadTask.Result; - Assert.Equal("file.txt", download.SuggestedFilename); + Assert.That(download.SuggestedFilename, Is.EqualTo("file.txt")); string path = await download.PathAsync(); - Assert.True(new FileInfo(path).Exists); - Assert.Equal("Hello world", File.ReadAllText(path)); + Assert.That(new FileInfo(path).Exists, Is.True); + Assert.That(File.ReadAllText(path), Is.EqualTo("Hello world")); await page.CloseAsync(); } [PlaywrightTest("download.spec.ts", "should report download path within page.on('download', …) handler for Files")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForFiles() { var downloadPathTcs = new TaskCompletionSource(); @@ -287,12 +285,12 @@ public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForFiles() await page.ClickAsync("a"); string path = await downloadPathTcs.Task; - Assert.Equal("Hello world", File.ReadAllText(path)); + Assert.That(File.ReadAllText(path), Is.EqualTo("Hello world")); await page.CloseAsync(); } [PlaywrightTest("download.spec.ts", "should report download path within page.on('download', …) handler for Blobs")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForBlobs() { var downloadPathTcs = new TaskCompletionSource(); @@ -306,7 +304,7 @@ public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForBlobs() await page.ClickAsync("a"); string path = await downloadPathTcs.Task; - Assert.Equal("Hello world", File.ReadAllText(path)); + Assert.That(File.ReadAllText(path), Is.EqualTo("Hello world")); await page.CloseAsync(); } @@ -331,12 +329,12 @@ await TaskUtils.WhenAll( var download = downloadTask.Result; string path = await download.PathAsync(); - Assert.True(new FileInfo(path).Exists); - Assert.Equal("Hello world", File.ReadAllText(path)); + Assert.That(new FileInfo(path).Exists, Is.True); + Assert.That(File.ReadAllText(path), Is.EqualTo("Hello world")); } [PlaywrightTest("download.spec.ts", "should report new window downloads")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportNewWindowDownloads() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -350,12 +348,12 @@ await TaskUtils.WhenAll( var download = downloadTask.Result; string path = await download.PathAsync(); - Assert.True(new FileInfo(path).Exists); - Assert.Equal("Hello world", File.ReadAllText(path)); + Assert.That(new FileInfo(path).Exists, Is.True); + Assert.That(File.ReadAllText(path), Is.EqualTo("Hello world")); } [PlaywrightTest("download.spec.ts", "should delete file")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDeleteFile() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -369,14 +367,14 @@ await TaskUtils.WhenAll( var download = downloadTask.Result; string path = await download.PathAsync(); - Assert.True(new FileInfo(path).Exists); + Assert.That(new FileInfo(path).Exists, Is.True); await download.DeleteAsync(); - Assert.False(new FileInfo(path).Exists); + Assert.That(new FileInfo(path).Exists, Is.False); await page.CloseAsync(); } [PlaywrightTest("download.spec.ts", "should expose stream")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldExposeStream() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -389,13 +387,13 @@ await TaskUtils.WhenAll( var download = downloadTask.Result; using var stream = await download.CreateReadStreamAsync(); - Assert.Equal("Hello world", await new StreamReader(stream).ReadToEndAsync()); + Assert.That(await new StreamReader(stream).ReadToEndAsync(), Is.EqualTo("Hello world")); await page.CloseAsync(); } [PlaywrightTest("download.spec.ts", "should delete downloads on context destruction")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDeleteDownloadsOnContextDestruction() { var page = await Browser.NewPageAsync(acceptDownloads: true); @@ -414,15 +412,15 @@ await TaskUtils.WhenAll( string path1 = await download1Task.Result.PathAsync(); string path2 = await download2Task.Result.PathAsync(); - Assert.True(new FileInfo(path1).Exists); - Assert.True(new FileInfo(path2).Exists); + Assert.That(new FileInfo(path1).Exists, Is.True); + Assert.That(new FileInfo(path2).Exists, Is.True); await page.Context.CloseAsync(); - Assert.False(new FileInfo(path1).Exists); - Assert.False(new FileInfo(path2).Exists); + Assert.That(new FileInfo(path1).Exists, Is.False); + Assert.That(new FileInfo(path2).Exists, Is.False); } [PlaywrightTest("download.spec.ts", "should delete downloads on browser gone")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDeleteDownloadsOnBrowserGone() { var browser = await BrowserType.LaunchDefaultAsync(); @@ -442,12 +440,12 @@ await TaskUtils.WhenAll( string path1 = await download1Task.Result.PathAsync(); string path2 = await download2Task.Result.PathAsync(); - Assert.True(new FileInfo(path1).Exists); - Assert.True(new FileInfo(path2).Exists); + Assert.That(new FileInfo(path1).Exists, Is.True); + Assert.That(new FileInfo(path2).Exists, Is.True); await browser.CloseAsync(); - Assert.False(new FileInfo(path1).Exists); - Assert.False(new FileInfo(path2).Exists); - Assert.False(new FileInfo(Path.Combine(path1, "..")).Exists); + Assert.That(new FileInfo(path1).Exists, Is.False); + Assert.That(new FileInfo(path2).Exists, Is.False); + Assert.That(new FileInfo(Path.Combine(path1, "..")).Exists, Is.False); } } } diff --git a/src/Playwright.Tests/DownloadsPathTests.cs b/src/Playwright.Tests/DownloadsPathTests.cs index 68b77ba34c..7c03d49401 100644 --- a/src/Playwright.Tests/DownloadsPathTests.cs +++ b/src/Playwright.Tests/DownloadsPathTests.cs @@ -1,27 +1,41 @@ using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.Helpers; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] - public class DownloadsPathTests : PlaywrightSharpBaseTest, IAsyncLifetime + public class DownloadsPathTests : PlaywrightSharpBaseTest { private IBrowser _browser { get; set; } private TempDirectory _tmp = null; - /// - public DownloadsPathTests(ITestOutputHelper output) : base(output) + [SetUp] + public async Task DownloadsPathSetUp() { + Server.SetRoute("/download", context => + { + context.Response.Headers["Content-Type"] = "application/octet-stream"; + context.Response.Headers["Content-Disposition"] = "attachment; filename=file.txt"; + return context.Response.WriteAsync("Hello world"); + }); + + _tmp = new TempDirectory(); + _browser = await Playwright[TestConstants.Product].LaunchDefaultAsync(downloadsPath: _tmp.Path); + } + + [TearDown] + public async Task DownloadsPathTearDown() + { + _tmp?.Dispose(); + await _browser.CloseAsync(); } [PlaywrightTest("downloads-path.spec.ts", "should keep downloadsPath folder")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldKeepDownloadsPathFolder() { var page = await _browser.NewPageAsync(); @@ -33,18 +47,18 @@ await TaskUtils.WhenAll( page.ClickAsync("a")); var download = downloadTask.Result; - Assert.Equal($"{TestConstants.ServerUrl}/download", download.Url); - Assert.Equal("file.txt", download.SuggestedFilename); + Assert.That(download.Url, Is.EqualTo($"{TestConstants.ServerUrl}/download")); + Assert.That(download.SuggestedFilename, Is.EqualTo("file.txt")); - var exception = await Assert.ThrowsAnyAsync(() => download.PathAsync()); + var exception = Assert.CatchAsync(() => download.PathAsync()); await page.CloseAsync(); await _browser.CloseAsync(); - Assert.True(new DirectoryInfo(_tmp.Path).Exists); + Assert.That(new DirectoryInfo(_tmp.Path).Exists, Is.True); } [PlaywrightTest("downloads-path.spec.ts", "should delete downloads when context closes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDeleteDownloadsWhenContextCloses() { var page = await _browser.NewPageAsync(acceptDownloads: true); @@ -57,13 +71,13 @@ await TaskUtils.WhenAll( var download = downloadTask.Result; string path = await download.PathAsync(); - Assert.True(new FileInfo(path).Exists); + Assert.That(new FileInfo(path).Exists, Is.True); await page.CloseAsync(); - Assert.False(new FileInfo(path).Exists); + Assert.That(new FileInfo(path).Exists, Is.False); } [PlaywrightTest("downloads-path.spec.ts", "should report downloads in downloadsPath folder")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportDownloadsInDownloadsPathFolder() { var page = await _browser.NewPageAsync(acceptDownloads: true); @@ -76,29 +90,8 @@ await TaskUtils.WhenAll( var download = downloadTask.Result; string path = await download.PathAsync(); - Assert.StartsWith(_tmp.Path, path); + Assert.That(path, Does.StartWith(_tmp.Path)); await page.CloseAsync(); } - - /// - public async Task InitializeAsync() - { - Server.SetRoute("/download", context => - { - context.Response.Headers["Content-Type"] = "application/octet-stream"; - context.Response.Headers["Content-Disposition"] = "attachment; filename=file.txt"; - return context.Response.WriteAsync("Hello world"); - }); - - _tmp = new TempDirectory(); - _browser = await Playwright[TestConstants.Product].LaunchDefaultAsync(downloadsPath: _tmp.Path); - } - - /// - public async Task DisposeAsync() - { - _tmp?.Dispose(); - await _browser.CloseAsync(); - } } } diff --git a/src/Playwright.Tests/ElementHandleBoundingBoxTests.cs b/src/Playwright.Tests/ElementHandleBoundingBoxTests.cs index 24ce86d282..8a904d33aa 100644 --- a/src/Playwright.Tests/ElementHandleBoundingBoxTests.cs +++ b/src/Playwright.Tests/ElementHandleBoundingBoxTests.cs @@ -1,35 +1,27 @@ using System; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleBoundingBoxTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleBoundingBoxTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-bounding-box.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-bounding-box.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.SetViewportSizeAsync(500, 500); await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(13)"); var box = await elementHandle.BoundingBoxAsync(); - Assert.Equal(new ElementHandleBoundingBoxResult(x: 100, y: 50, width: 50, height: 50), box); + Assert.That(box, Is.EqualTo(new ElementHandleBoundingBoxResult(x: 100, y: 50, width: 50, height: 50))); } [PlaywrightTest("elementhandle-bounding-box.spec.ts", "should handle nested frames")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHandleNestedFrames() { await Page.SetViewportSizeAsync(500, 500); @@ -37,20 +29,20 @@ public async Task ShouldHandleNestedFrames() var nestedFrame = Page.Frames.First(frame => frame.Name == "dos"); var elementHandle = await nestedFrame.QuerySelectorAsync("div"); var box = await elementHandle.BoundingBoxAsync(); - Assert.Equal(new ElementHandleBoundingBoxResult(x: 24, y: 224, width: 268, height: 18), box); + Assert.That(box, Is.EqualTo(new ElementHandleBoundingBoxResult(x: 24, y: 224, width: 268, height: 18))); } [PlaywrightTest("elementhandle-bounding-box.spec.ts", "should return null for invisible elements")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNullForInvisibleElements() { await Page.SetContentAsync("
hi
"); var element = await Page.QuerySelectorAsync("div"); - Assert.Null(await element.BoundingBoxAsync()); + Assert.That(await element.BoundingBoxAsync(), Is.Null); } [PlaywrightTest("elementhandle-bounding-box.spec.ts", "should force a layout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldForceALayout() { await Page.SetViewportSizeAsync(500, 500); @@ -58,11 +50,11 @@ public async Task ShouldForceALayout() var elementHandle = await Page.QuerySelectorAsync("div"); await Page.EvaluateAsync("element => element.style.height = '200px'", elementHandle); var box = await elementHandle.BoundingBoxAsync(); - Assert.Equal(new ElementHandleBoundingBoxResult(x: 8, y: 8, width: 100, height: 200), box); + Assert.That(box, Is.EqualTo(new ElementHandleBoundingBoxResult(x: 8, y: 8, width: 100, height: 200))); } [PlaywrightTest("elementhandle-bounding-box.spec.ts", "should work with SVG nodes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithSVGNodes() { await Page.SetContentAsync(@" @@ -75,7 +67,7 @@ await Page.SetContentAsync(@" const rect = e.getBoundingClientRect(); return { x: rect.x, y: rect.y, width: rect.width, height: rect.height}; }", element); - Assert.Equal(webBoundingBox, pwBoundingBox); + Assert.That(pwBoundingBox, Is.EqualTo(webBoundingBox)); } [PlaywrightTest("elementhandle-bounding-box.spec.ts", "should work with page scale")] @@ -105,14 +97,14 @@ await button.EvaluateAsync(@"button => { }"); var box = await button.BoundingBoxAsync(); - Assert.Equal(17 * 100, Math.Round(box.X * 100)); - Assert.Equal(23 * 100, Math.Round(box.Y * 100)); - Assert.Equal(200 * 100, Math.Round(box.Width * 100)); - Assert.Equal(20 * 100, Math.Round(box.Height * 100)); + Assert.That(Math.Round(box.X * 100), Is.EqualTo(17 * 100)); + Assert.That(Math.Round(box.Y * 100), Is.EqualTo(23 * 100)); + Assert.That(Math.Round(box.Width * 100), Is.EqualTo(200 * 100)); + Assert.That(Math.Round(box.Height * 100), Is.EqualTo(20 * 100)); } [PlaywrightTest("elementhandle-bounding-box.spec.ts", "should work when inline box child is outside of viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenInlineBoxChildIsOutsideOfViewport() { await Page.SetContentAsync(@" @@ -135,10 +127,10 @@ await Page.SetContentAsync(@" return { x: rect.x, y: rect.y, width: rect.width, height: rect.height}; }", handle); - Assert.Equal(Math.Round(webBoundingBox.X * 100), Math.Round(box.X * 100)); - Assert.Equal(Math.Round(webBoundingBox.Y * 100), Math.Round(box.Y * 100)); - Assert.Equal(Math.Round(webBoundingBox.Width * 100), Math.Round(box.Width * 100)); - Assert.Equal(Math.Round(webBoundingBox.Height * 100), Math.Round(box.Height * 100)); + Assert.That(Math.Round(box.X * 100), Is.EqualTo(Math.Round(webBoundingBox.X * 100))); + Assert.That(Math.Round(box.Y * 100), Is.EqualTo(Math.Round(webBoundingBox.Y * 100))); + Assert.That(Math.Round(box.Width * 100), Is.EqualTo(Math.Round(webBoundingBox.Width * 100))); + Assert.That(Math.Round(box.Height * 100), Is.EqualTo(Math.Round(webBoundingBox.Height * 100))); } } } diff --git a/src/Playwright.Tests/ElementHandleClickTests.cs b/src/Playwright.Tests/ElementHandleClickTests.cs index 1740ce39a1..790ec01092 100644 --- a/src/Playwright.Tests/ElementHandleClickTests.cs +++ b/src/Playwright.Tests/ElementHandleClickTests.cs @@ -1,105 +1,97 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleClickTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleClickTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-click.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-click.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); var button = await Page.QuerySelectorAsync("button"); await button.ClickAsync(); - Assert.Equal("Clicked", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("Clicked")); } [PlaywrightTest("elementhandle-click.spec.ts", "should work with Node removed")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNodeRemoved() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.EvaluateAsync("() => delete window['Node']"); var button = await Page.QuerySelectorAsync("button"); await button.ClickAsync(); - Assert.Equal("Clicked", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("Clicked")); } [PlaywrightTest("elementhandle-click.spec.ts", "should work for Shadow DOM v1")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForShadowDOMV1() { await Page.GoToAsync(TestConstants.ServerUrl + "/shadow.html"); var buttonHandle = (IElementHandle)await Page.EvaluateHandleAsync("() => button"); await buttonHandle.ClickAsync(); - Assert.True(await Page.EvaluateAsync("() => clicked")); + Assert.That(await Page.EvaluateAsync("() => clicked"), Is.True); } [PlaywrightTest("elementhandle-click.spec.ts", "should work for TextNodes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForTextNodes() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); var buttonTextNode = (IElementHandle)await Page.EvaluateHandleAsync("() => document.querySelector('button').firstChild"); await buttonTextNode.ClickAsync(); - Assert.Equal("Clicked", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("Clicked")); } [PlaywrightTest("elementhandle-click.spec.ts", "should throw for detached nodes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForDetachedNodes() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); var button = await Page.QuerySelectorAsync("button"); await Page.EvaluateAsync("button => button.remove()", button); - var exception = await Assert.ThrowsAsync(() => button.ClickAsync()); - Assert.Contains("Element is not attached to the DOM", exception.Message); + var exception = Assert.ThrowsAsync(() => button.ClickAsync()); + Assert.That(exception.Message, Does.Contain("Element is not attached to the DOM")); } [PlaywrightTest("elementhandle-click.spec.ts", "should throw for hidden nodes with force")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForHiddenNodesWithForce() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); var button = await Page.QuerySelectorAsync("button"); await Page.EvaluateAsync("button => button.style.display = 'none'", button); - var exception = await Assert.ThrowsAsync(() => button.ClickAsync(force: true)); - Assert.Contains("Element is not visible", exception.Message); + var exception = Assert.ThrowsAsync(() => button.ClickAsync(force: true)); + Assert.That(exception.Message, Does.Contain("Element is not visible")); } [PlaywrightTest("elementhandle-click.spec.ts", "should throw for recursively hidden nodes with force")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForRecursivelyHiddenNodesWithForce() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); var button = await Page.QuerySelectorAsync("button"); await Page.EvaluateAsync("button => button.parentElement.style.display = 'none'", button); - var exception = await Assert.ThrowsAsync(() => button.ClickAsync(force: true)); - Assert.Contains("Element is not visible", exception.Message); + var exception = Assert.ThrowsAsync(() => button.ClickAsync(force: true)); + Assert.That(exception.Message, Does.Contain("Element is not visible")); } [PlaywrightTest("elementhandle-click.spec.ts", "should throw for <br> elements with force")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForBrElementsWithforce() { await Page.SetContentAsync("hello
goodbye"); var br = await Page.QuerySelectorAsync("br"); - var exception = await Assert.ThrowsAsync(() => br.ClickAsync(force: true)); - Assert.Contains("Element is outside of the viewport", exception.Message); + var exception = Assert.ThrowsAsync(() => br.ClickAsync(force: true)); + Assert.That(exception.Message, Does.Contain("Element is outside of the viewport")); } [PlaywrightTest("elementhandle-click.spec.ts", "should double click the button")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDoubleClickTheButton() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -114,8 +106,8 @@ await Page.EvaluateAsync(@"() => { var button = await Page.QuerySelectorAsync("button"); await button.DblClickAsync(); - Assert.True(await Page.EvaluateAsync("double")); - Assert.Equal("Clicked", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("double"), Is.True); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("Clicked")); } } } diff --git a/src/Playwright.Tests/ElementHandleContentFrameTests.cs b/src/Playwright.Tests/ElementHandleContentFrameTests.cs index 3800d4b8fd..736143505a 100644 --- a/src/Playwright.Tests/ElementHandleContentFrameTests.cs +++ b/src/Playwright.Tests/ElementHandleContentFrameTests.cs @@ -1,73 +1,65 @@ using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleContentFrameTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleContentFrameTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-content-frame.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-content-frame.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); var elementHandle = await Page.QuerySelectorAsync("#frame1"); var frame = await elementHandle.ContentFrameAsync(); - Assert.Equal(Page.Frames.ElementAt(1), frame); + Assert.That(frame, Is.EqualTo(Page.Frames.ElementAt(1))); } [PlaywrightTest("elementhandle-content-frame.spec.ts", "should work for cross-process iframes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForCrossProcessIframes() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.CrossProcessUrl + "/empty.html"); var elementHandle = await Page.QuerySelectorAsync("#frame1"); var frame = await elementHandle.ContentFrameAsync(); - Assert.Equal(Page.Frames.ElementAt(1), frame); + Assert.That(frame, Is.EqualTo(Page.Frames.ElementAt(1))); } [PlaywrightTest("elementhandle-content-frame.spec.ts", "should work for cross-frame evaluations")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForCrossFrameEvaluations() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); var frame = Page.Frames.ElementAt(1); var elementHandle = (IElementHandle)await frame.EvaluateHandleAsync("() => window.top.document.querySelector('#frame1')"); - Assert.Equal(frame, await elementHandle.ContentFrameAsync()); + Assert.That(await elementHandle.ContentFrameAsync(), Is.EqualTo(frame)); } [PlaywrightTest("elementhandle-content-frame.spec.ts", "should return null for non-iframes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNullForNonIframes() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); var frame = Page.Frames.ElementAt(1); var elementHandle = (IElementHandle)await frame.EvaluateHandleAsync("() => document.body"); - Assert.Null(await elementHandle.ContentFrameAsync()); + Assert.That(await elementHandle.ContentFrameAsync(), Is.Null); } [PlaywrightTest("elementhandle-content-frame.spec.ts", "should return null for document.documentElement")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNullForDocumentDocumentElement() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); var frame = Page.Frames.ElementAt(1); var elementHandle = (IElementHandle)await frame.EvaluateHandleAsync("() => document.documentElement"); - Assert.Null(await elementHandle.ContentFrameAsync()); + Assert.That(await elementHandle.ContentFrameAsync(), Is.Null); } } } diff --git a/src/Playwright.Tests/ElementHandleConvenienceTests.cs b/src/Playwright.Tests/ElementHandleConvenienceTests.cs index 69c95f205d..b30262ae4f 100644 --- a/src/Playwright.Tests/ElementHandleConvenienceTests.cs +++ b/src/Playwright.Tests/ElementHandleConvenienceTests.cs @@ -1,22 +1,14 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///elementhandle-convenience.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleConvenienceTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleConvenienceTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-convenience.spec.ts", "should have a nice preview")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-convenience.spec.ts", "should have a nice preview")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveANicePreview() { await Page.GoToAsync(TestConstants.ServerUrl + "/dom.html"); @@ -25,71 +17,71 @@ public async Task ShouldHaveANicePreview() var check = await Page.QuerySelectorAsync("#check"); var text = await inner.EvaluateHandleAsync("e => e.firstChild"); await Page.EvaluateAsync("() => 1"); // Give them a chance to calculate the preview. - Assert.Equal("JSHandle@
", outer.ToString()); - Assert.Equal("JSHandle@
Text,↵more text
", inner.ToString()); - Assert.Equal("JSHandle@#text=Text,↵more text", text.ToString()); - Assert.Equal("JSHandle@", check.ToString()); + Assert.That(outer.ToString(), Is.EqualTo("JSHandle@
")); + Assert.That(inner.ToString(), Is.EqualTo("JSHandle@
Text,↵more text
")); + Assert.That(text.ToString(), Is.EqualTo("JSHandle@#text=Text,↵more text")); + Assert.That(check.ToString(), Is.EqualTo("JSHandle@")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "getAttribute should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task GetAttributeShouldWork() { await Page.GoToAsync(TestConstants.ServerUrl + "/dom.html"); var handle = await Page.QuerySelectorAsync("#outer"); - Assert.Equal("value", await handle.GetAttributeAsync("name")); - Assert.Equal("value", await Page.GetAttributeAsync("#outer", "name")); + Assert.That(await handle.GetAttributeAsync("name"), Is.EqualTo("value")); + Assert.That(await Page.GetAttributeAsync("#outer", "name"), Is.EqualTo("value")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "innerHTML should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task InnerHTMLShouldWork() { await Page.GoToAsync(TestConstants.ServerUrl + "/dom.html"); var handle = await Page.QuerySelectorAsync("#outer"); - Assert.Equal("
Text,\nmore text
", await handle.InnerHTMLAsync()); - Assert.Equal("
Text,\nmore text
", await Page.InnerHTMLAsync("#outer")); + Assert.That(await handle.InnerHTMLAsync(), Is.EqualTo("
Text,\nmore text
")); + Assert.That(await Page.InnerHTMLAsync("#outer"), Is.EqualTo("
Text,\nmore text
")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "innerText should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task InnerTextShouldWork() { await Page.GoToAsync(TestConstants.ServerUrl + "/dom.html"); var handle = await Page.QuerySelectorAsync("#inner"); - Assert.Equal("Text, more text", await handle.InnerTextAsync()); - Assert.Equal("Text, more text", await Page.InnerTextAsync("#inner")); + Assert.That(await handle.InnerTextAsync(), Is.EqualTo("Text, more text")); + Assert.That(await Page.InnerTextAsync("#inner"), Is.EqualTo("Text, more text")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "'innerText should throw")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task InnerTextShouldThrow() { await Page.SetContentAsync("text"); - var exception1 = await Assert.ThrowsAnyAsync(() => Page.InnerTextAsync("svg")); - Assert.Contains("Not an HTMLElement", exception1.Message); + var exception1 = Assert.CatchAsync(() => Page.InnerTextAsync("svg")); + Assert.That(exception1.Message, Does.Contain("Not an HTMLElement")); var handle = await Page.QuerySelectorAsync("svg"); - var exception2 = await Assert.ThrowsAnyAsync(() => handle.InnerTextAsync()); - Assert.Contains("Not an HTMLElement", exception1.Message); + var exception2 = Assert.CatchAsync(() => handle.InnerTextAsync()); + Assert.That(exception1.Message, Does.Contain("Not an HTMLElement")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "textContent should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task TextContentShouldWork() { await Page.GoToAsync(TestConstants.ServerUrl + "/dom.html"); var handle = await Page.QuerySelectorAsync("#outer"); - Assert.Equal("Text,\nmore text", await handle.TextContentAsync()); - Assert.Equal("Text,\nmore text", await Page.TextContentAsync("#outer")); + Assert.That(await handle.TextContentAsync(), Is.EqualTo("Text,\nmore text")); + Assert.That(await Page.TextContentAsync("#outer"), Is.EqualTo("Text,\nmore text")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "Page.dispatchEvent(click)", "textContent should be atomic")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task TextContentShouldBeAtomic() { const string createDummySelector = @"({ @@ -111,12 +103,12 @@ public async Task TextContentShouldBeAtomic() await TestUtils.RegisterEngineAsync(Playwright, "textContent", createDummySelector); await Page.SetContentAsync("
Hello
"); string tc = await Page.TextContentAsync("textContent=div"); - Assert.Equal("Hello", tc); - Assert.Equal("modified", await Page.EvaluateAsync("() => document.querySelector('div').textContent")); + Assert.That(tc, Is.EqualTo("Hello")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('div').textContent"), Is.EqualTo("modified")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "Page.dispatchEvent(click)", "innerText should be atomic")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task InnerTextShouldBeAtomic() { const string createDummySelector = @"({ @@ -138,12 +130,12 @@ public async Task InnerTextShouldBeAtomic() await TestUtils.RegisterEngineAsync(Playwright, "innerText", createDummySelector); await Page.SetContentAsync("
Hello
"); string tc = await Page.InnerTextAsync("innerText=div"); - Assert.Equal("Hello", tc); - Assert.Equal("modified", await Page.EvaluateAsync("() => document.querySelector('div').textContent")); + Assert.That(tc, Is.EqualTo("Hello")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('div').textContent"), Is.EqualTo("modified")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "Page.dispatchEvent(click)", "innerHTML should be atomic")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task InnerHtmlShouldBeAtomic() { const string createDummySelector = @"({ @@ -165,12 +157,12 @@ public async Task InnerHtmlShouldBeAtomic() await TestUtils.RegisterEngineAsync(Playwright, "innerHtml", createDummySelector); await Page.SetContentAsync("
Hello
"); string tc = await Page.InnerHTMLAsync("innerHtml=div"); - Assert.Equal("Hello", tc); - Assert.Equal("modified", await Page.EvaluateAsync("() => document.querySelector('div').textContent")); + Assert.That(tc, Is.EqualTo("Hello")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('div').textContent"), Is.EqualTo("modified")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "Page.dispatchEvent(click)", "getAttribute should be atomic")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task GetAttributeShouldBeAtomic() { const string createDummySelector = @"({ @@ -192,29 +184,29 @@ public async Task GetAttributeShouldBeAtomic() await TestUtils.RegisterEngineAsync(Playwright, "getAttribute", createDummySelector); await Page.SetContentAsync("
"); string tc = await Page.GetAttributeAsync("getAttribute=div", "foo"); - Assert.Equal("Hello", tc); - Assert.Equal("modified", await Page.EvaluateAsync("() => document.querySelector('div').getAttribute('foo')")); + Assert.That(tc, Is.EqualTo("Hello")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('div').getAttribute('foo')"), Is.EqualTo("modified")); } [PlaywrightTest("elementhandle-convenience.spec.ts", "isVisible and isHidden should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task IsVisibleAndIsHiddenShouldWork() { await Page.SetContentAsync("
Hi
"); var div = await Page.QuerySelectorAsync("div"); - Assert.True(await div.IsVisibleAsync()); - Assert.False(await div.IsHiddenAsync()); - Assert.True(await Page.IsVisibleAsync("div")); - Assert.False(await Page.IsHiddenAsync("div")); + Assert.That(await div.IsVisibleAsync(), Is.True); + Assert.That(await div.IsHiddenAsync(), Is.False); + Assert.That(await Page.IsVisibleAsync("div"), Is.True); + Assert.That(await Page.IsHiddenAsync("div"), Is.False); var span = await Page.QuerySelectorAsync("span"); - Assert.False(await span.IsVisibleAsync()); - Assert.True(await span.IsHiddenAsync()); - Assert.False(await Page.IsVisibleAsync("span")); - Assert.True(await Page.IsHiddenAsync("span")); + Assert.That(await span.IsVisibleAsync(), Is.False); + Assert.That(await span.IsHiddenAsync(), Is.True); + Assert.That(await Page.IsVisibleAsync("span"), Is.False); + Assert.That(await Page.IsHiddenAsync("span"), Is.True); } [PlaywrightTest("elementhandle-convenience.spec.ts", "isEnabled and isDisabled should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task IsEnabledAndIsDisabledShouldWork() { await Page.SetContentAsync(@" @@ -222,52 +214,52 @@ await Page.SetContentAsync(@"
div
"); var div = await Page.QuerySelectorAsync("div"); - Assert.True(await div.IsEnabledAsync()); - Assert.False(await div.IsDisabledAsync()); - Assert.True(await Page.IsEnabledAsync("div")); - Assert.False(await Page.IsDisabledAsync("div")); + Assert.That(await div.IsEnabledAsync(), Is.True); + Assert.That(await div.IsDisabledAsync(), Is.False); + Assert.That(await Page.IsEnabledAsync("div"), Is.True); + Assert.That(await Page.IsDisabledAsync("div"), Is.False); var button1 = await Page.QuerySelectorAsync(":text('button1')"); - Assert.False(await button1.IsEnabledAsync()); - Assert.True(await button1.IsDisabledAsync()); - Assert.False(await Page.IsEnabledAsync(":text('button1')")); - Assert.True(await Page.IsDisabledAsync(":text('button1')")); + Assert.That(await button1.IsEnabledAsync(), Is.False); + Assert.That(await button1.IsDisabledAsync(), Is.True); + Assert.That(await Page.IsEnabledAsync(":text('button1')"), Is.False); + Assert.That(await Page.IsDisabledAsync(":text('button1')"), Is.True); var button2 = await Page.QuerySelectorAsync(":text('button2')"); - Assert.True(await button2.IsEnabledAsync()); - Assert.False(await button2.IsDisabledAsync()); - Assert.True(await Page.IsEnabledAsync(":text('button2')")); - Assert.False(await Page.IsDisabledAsync(":text('button2')")); + Assert.That(await button2.IsEnabledAsync(), Is.True); + Assert.That(await button2.IsDisabledAsync(), Is.False); + Assert.That(await Page.IsEnabledAsync(":text('button2')"), Is.True); + Assert.That(await Page.IsDisabledAsync(":text('button2')"), Is.False); } [PlaywrightTest("elementhandle-convenience.spec.ts", "isEditable should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task IsEditableShouldWork() { await Page.SetContentAsync(@""); await Page.EvalOnSelectorAsync("textarea", "t => t.readOnly = true"); var input1 = await Page.QuerySelectorAsync("#input1"); - Assert.False(await input1.IsEditableAsync()); - Assert.False(await Page.IsEditableAsync("#input1")); + Assert.That(await input1.IsEditableAsync(), Is.False); + Assert.That(await Page.IsEditableAsync("#input1"), Is.False); var input2 = await Page.QuerySelectorAsync("#input2"); - Assert.True(await input2.IsEditableAsync()); - Assert.True(await Page.IsEditableAsync("#input2")); + Assert.That(await input2.IsEditableAsync(), Is.True); + Assert.That(await Page.IsEditableAsync("#input2"), Is.True); var textarea = await Page.QuerySelectorAsync("textarea"); - Assert.False(await textarea.IsEditableAsync()); - Assert.False(await Page.IsEditableAsync("textarea")); + Assert.That(await textarea.IsEditableAsync(), Is.False); + Assert.That(await Page.IsEditableAsync("textarea"), Is.False); } [PlaywrightTest("elementhandle-convenience.spec.ts", "isChecked should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task IsCheckedShouldWork() { await Page.SetContentAsync(@"
Not a checkbox
"); var handle = await Page.QuerySelectorAsync("input"); - Assert.True(await handle.IsCheckedAsync()); - Assert.True(await Page.IsCheckedAsync("input")); + Assert.That(await handle.IsCheckedAsync(), Is.True); + Assert.That(await Page.IsCheckedAsync("input"), Is.True); await handle.EvaluateAsync("input => input.checked = false"); - Assert.False(await handle.IsCheckedAsync()); - Assert.False(await Page.IsCheckedAsync("input")); - var exception = await Assert.ThrowsAnyAsync(() => Page.IsCheckedAsync("div")); - Assert.Contains("Not a checkbox or radio button", exception.Message); + Assert.That(await handle.IsCheckedAsync(), Is.False); + Assert.That(await Page.IsCheckedAsync("input"), Is.False); + var exception = Assert.CatchAsync(() => Page.IsCheckedAsync("div")); + Assert.That(exception.Message, Does.Contain("Not a checkbox or radio button")); } } } diff --git a/src/Playwright.Tests/ElementHandleEvalOnSelectorTests.cs b/src/Playwright.Tests/ElementHandleEvalOnSelectorTests.cs index fccc84f35a..d578902094 100644 --- a/src/Playwright.Tests/ElementHandleEvalOnSelectorTests.cs +++ b/src/Playwright.Tests/ElementHandleEvalOnSelectorTests.cs @@ -1,81 +1,73 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleEvalOnSelectorTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleEvalOnSelectorTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-eval-on-selector.spec.ts", "should work for all")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-eval-on-selector.spec.ts", "should work for all")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForAll() { await Page.SetContentAsync("
100
10
"); var tweet = await Page.QuerySelectorAsync(".tweet"); string[] content = await tweet.EvalOnSelectorAllAsync(".like", "nodes => nodes.map(n => n.innerText)"); - Assert.Equal(new[] { "100", "10" }, content); + Assert.That(content, Is.EqualTo(new[] { "100", "10" })); } [PlaywrightTest("elementhandle-eval-on-selector.spec.ts", "should retrieve content from subtree for all")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRetrieveContentFromSubtreeForAll() { string htmlContent = "
not-a-child-div
a1-child-div
a2-child-div
"; await Page.SetContentAsync(htmlContent); var elementHandle = await Page.QuerySelectorAsync("#myId"); string[] content = await elementHandle.EvalOnSelectorAllAsync(".a", "nodes => nodes.map(n => n.innerText)"); - Assert.Equal(new[] { "a1-child-div", "a2-child-div" }, content); + Assert.That(content, Is.EqualTo(new[] { "a1-child-div", "a2-child-div" })); } [PlaywrightTest("elementhandle-eval-on-selector.spec.ts", "should not throw in case of missing selector for all")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotThrowInCaseOfMissingSelectorForAll() { string htmlContent = "
not-a-child-div
"; await Page.SetContentAsync(htmlContent); var elementHandle = await Page.QuerySelectorAsync("#myId"); int nodesLength = await elementHandle.EvalOnSelectorAllAsync(".a", "nodes => nodes.length"); - Assert.Equal(0, nodesLength); + Assert.That(nodesLength, Is.EqualTo(0)); } [PlaywrightTest("elementhandle-eval-on-selector.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.SetContentAsync("
100
10
"); var tweet = await Page.QuerySelectorAsync(".tweet"); string content = await tweet.EvalOnSelectorAsync(".like", "node => node.innerText"); - Assert.Equal("100", content); + Assert.That(content, Is.EqualTo("100")); } [PlaywrightTest("elementhandle-eval-on-selector.spec.ts", "should retrieve content from subtree")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRetrieveContentFromSubtree() { string htmlContent = "
not-a-child-div
a-child-div
"; await Page.SetContentAsync(htmlContent); var elementHandle = await Page.QuerySelectorAsync("#myId"); string content = await elementHandle.EvalOnSelectorAsync(".a", "node => node.innerText"); - Assert.Equal("a-child-div", content); + Assert.That(content, Is.EqualTo("a-child-div")); } [PlaywrightTest("elementhandle-eval-on-selector.spec.ts", "should throw in case of missing selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowInCaseOfMissingSelector() { string htmlContent = "
not-a-child-div
"; await Page.SetContentAsync(htmlContent); var elementHandle = await Page.QuerySelectorAsync("#myId"); - var exception = await Assert.ThrowsAsync(() => elementHandle.EvalOnSelectorAsync(".a", "node => node.innerText")); - Assert.Contains("failed to find element matching selector \".a\"", exception.Message); + var exception = Assert.ThrowsAsync(() => elementHandle.EvalOnSelectorAsync(".a", "node => node.innerText")); + Assert.That(exception.Message, Does.Contain("failed to find element matching selector \".a\"")); } } } diff --git a/src/Playwright.Tests/ElementHandleMiscTests.cs b/src/Playwright.Tests/ElementHandleMiscTests.cs index 3e302a224e..76b77fca6e 100644 --- a/src/Playwright.Tests/ElementHandleMiscTests.cs +++ b/src/Playwright.Tests/ElementHandleMiscTests.cs @@ -1,103 +1,95 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleMiscTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleMiscTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-misc.spec.ts", "should hover")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-misc.spec.ts", "should hover")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHover() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/scrollable.html"); var button = await Page.QuerySelectorAsync("#button-6"); await button.HoverAsync(); - Assert.Equal("button-6", await Page.EvaluateAsync("() => document.querySelector('button:hover').id")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('button:hover').id"), Is.EqualTo("button-6")); } [PlaywrightTest("elementhandle-misc.spec.ts", "should hover when Node is removed")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHoverWhenNodeIsRemoved() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/scrollable.html"); await Page.EvaluateAsync("() => delete window['Node']"); var button = await Page.QuerySelectorAsync("#button-6"); await button.HoverAsync(); - Assert.Equal("button-6", await Page.EvaluateAsync("() => document.querySelector('button:hover').id")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('button:hover').id"), Is.EqualTo("button-6")); } [PlaywrightTest("elementhandle-misc.spec.ts", "should fill input")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillInput() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); var handle = await Page.QuerySelectorAsync("input"); await handle.FillAsync("some value"); - Assert.Equal("some value", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("some value")); } [PlaywrightTest("elementhandle-misc.spec.ts", "should fill input when Node is removed")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillInputWhenNodeIsRemoved() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.EvaluateAsync("() => delete window['Node']"); var handle = await Page.QuerySelectorAsync("input"); await handle.FillAsync("some value"); - Assert.Equal("some value", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("some value")); } [PlaywrightTest("elementhandle-misc.spec.ts", "should check the box")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCheckTheBox() { await Page.SetContentAsync(""); var input = await Page.QuerySelectorAsync("input"); await input.CheckAsync(); - Assert.True(await Page.EvaluateAsync("() => checkbox.checked")); + Assert.That(await Page.EvaluateAsync("() => checkbox.checked"), Is.True); } [PlaywrightTest("elementhandle-misc.spec.ts", "should uncheck the box")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUncheckTheBox() { await Page.SetContentAsync(""); var input = await Page.QuerySelectorAsync("input"); await input.UncheckAsync(); - Assert.False(await Page.EvaluateAsync("() => checkbox.checked")); + Assert.That(await Page.EvaluateAsync("() => checkbox.checked"), Is.False); } [PlaywrightTest("elementhandle-misc.spec.ts", "should focus a button")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFocusAButton() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); var button = await Page.QuerySelectorAsync("button"); - Assert.False(await button.EvaluateAsync("button => document.activeElement === button")); + Assert.That(await button.EvaluateAsync("button => document.activeElement === button"), Is.False); await button.FocusAsync(); - Assert.True(await button.EvaluateAsync("button => document.activeElement === button")); + Assert.That(await button.EvaluateAsync("button => document.activeElement === button"), Is.True); } [PlaywrightTest("elementhandle-misc.spec.ts", "should select single option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectSingleOption() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); var select = await Page.QuerySelectorAsync("select"); await select.SelectOptionAsync("blue"); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "blue" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "blue" })); } } } diff --git a/src/Playwright.Tests/ElementHandleOwnerFrameTests.cs b/src/Playwright.Tests/ElementHandleOwnerFrameTests.cs index cb1950ffd5..d8acf8b15f 100644 --- a/src/Playwright.Tests/ElementHandleOwnerFrameTests.cs +++ b/src/Playwright.Tests/ElementHandleOwnerFrameTests.cs @@ -1,78 +1,70 @@ using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleOwnerFrameTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleOwnerFrameTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-owner-frame.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-owner-frame.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); var frame = Page.Frames.ElementAt(1); var elementHandle = (IElementHandle)await frame.EvaluateHandleAsync("() => document.body"); - Assert.Equal(frame, await elementHandle.OwnerFrameAsync()); + Assert.That(await elementHandle.OwnerFrameAsync(), Is.EqualTo(frame)); } [PlaywrightTest("elementhandle-owner-frame.spec.ts", "should work for cross-process iframes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForCrossProcessIframes() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.CrossProcessUrl + "/empty.html"); var frame = Page.Frames.ElementAt(1); var elementHandle = (IElementHandle)await frame.EvaluateHandleAsync("() => document.body"); - Assert.Equal(frame, await elementHandle.OwnerFrameAsync()); + Assert.That(await elementHandle.OwnerFrameAsync(), Is.EqualTo(frame)); } [PlaywrightTest("elementhandle-owner-frame.spec.ts", "should work for document")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForDocument() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); var frame = Page.Frames.ElementAt(1); var elementHandle = (IElementHandle)await frame.EvaluateHandleAsync("() => document"); - Assert.Equal(frame, await elementHandle.OwnerFrameAsync()); + Assert.That(await elementHandle.OwnerFrameAsync(), Is.EqualTo(frame)); } [PlaywrightTest("elementhandle-owner-frame.spec.ts", "should work for iframe elements")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForIframeElements() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); var frame = Page.MainFrame; var elementHandle = (IElementHandle)await frame.EvaluateHandleAsync("() => document.querySelector('#frame1')"); - Assert.Equal(frame, await elementHandle.OwnerFrameAsync()); + Assert.That(await elementHandle.OwnerFrameAsync(), Is.EqualTo(frame)); } [PlaywrightTest("elementhandle-owner-frame.spec.ts", "should work for cross-frame evaluations")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForCrossFrameEvaluations() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); var frame = Page.MainFrame; var elementHandle = (IElementHandle)await frame.EvaluateHandleAsync("() => document.querySelector('#frame1').contentWindow.document.body"); - Assert.Equal(frame.ChildFrames.First(), await elementHandle.OwnerFrameAsync()); + Assert.That(await elementHandle.OwnerFrameAsync(), Is.EqualTo(frame.ChildFrames.First())); } [PlaywrightTest("elementhandle-owner-frame.spec.ts", "should work for detached elements")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForDetachedElements() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -81,12 +73,12 @@ public async Task ShouldWorkForDetachedElements() document.body.appendChild(div); return div; }"); - Assert.Equal(Page.MainFrame, await divHandle.OwnerFrameAsync()); + Assert.That(await divHandle.OwnerFrameAsync(), Is.EqualTo(Page.MainFrame)); await Page.EvaluateAsync(@"() => { var div = document.querySelector('div'); document.body.removeChild(div); }"); - Assert.Equal(Page.MainFrame, await divHandle.OwnerFrameAsync()); + Assert.That(await divHandle.OwnerFrameAsync(), Is.EqualTo(Page.MainFrame)); } [PlaywrightTest("elementhandle-owner-frame.spec.ts", "should work for adopted elements")] @@ -104,13 +96,13 @@ await TaskUtils.WhenAll( document.body.appendChild(div); return div; }"); - Assert.Equal(Page.MainFrame, await divHandle.OwnerFrameAsync()); + Assert.That(await divHandle.OwnerFrameAsync(), Is.EqualTo(Page.MainFrame)); await popup.WaitForLoadStateAsync(LoadState.DOMContentLoaded); await Page.EvaluateAsync(@"() => { var div = document.querySelector('div'); window.__popup.document.body.appendChild(div); }"); - Assert.Same(popup.MainFrame, await divHandle.OwnerFrameAsync()); + Assert.That(await divHandle.OwnerFrameAsync(), Is.SameAs(popup.MainFrame)); } } } diff --git a/src/Playwright.Tests/ElementHandleQuerySelectorTests.cs b/src/Playwright.Tests/ElementHandleQuerySelectorTests.cs index ab376671f8..53b4dac53c 100644 --- a/src/Playwright.Tests/ElementHandleQuerySelectorTests.cs +++ b/src/Playwright.Tests/ElementHandleQuerySelectorTests.cs @@ -1,22 +1,14 @@ using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleQuerySelectorTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleQuerySelectorTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-query-selector.spec.ts", "should query existing element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-query-selector.spec.ts", "should query existing element")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldQueryExistingElement() { await Page.GoToAsync(TestConstants.ServerUrl + "/playground.html"); @@ -25,21 +17,21 @@ public async Task ShouldQueryExistingElement() var second = await html.QuerySelectorAsync(".second"); var inner = await second.QuerySelectorAsync(".inner"); string content = await Page.EvaluateAsync("e => e.textContent", inner); - Assert.Equal("A", content); + Assert.That(content, Is.EqualTo("A")); } [PlaywrightTest("elementhandle-query-selector.spec.ts", "should return null for non-existing element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNullForNonExistingElement() { await Page.SetContentAsync("
B
"); var html = await Page.QuerySelectorAsync("html"); var second = await html.QuerySelectorAsync(".third"); - Assert.Null(second); + Assert.That(second, Is.Null); } [PlaywrightTest("elementhandle-query-selector.spec.ts", "should work for adopted elements")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForAdoptedElements() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -57,8 +49,8 @@ public async Task ShouldWorkForAdoptedElements() return div; }") as IElementHandle; - Assert.NotNull(divHandle); - Assert.Equal("hello", await divHandle.EvalOnSelectorAsync("span", "e => e.textContent")); + Assert.That(divHandle, Is.Not.Null); + Assert.That(await divHandle.EvalOnSelectorAsync("span", "e => e.textContent"), Is.EqualTo("hello")); await popup.WaitForLoadStateAsync(LoadState.DOMContentLoaded); await Page.EvaluateAsync(@"() => { @@ -66,34 +58,34 @@ await Page.EvaluateAsync(@"() => { window.__popup.document.body.appendChild(div); }"); - Assert.NotNull(await divHandle.QuerySelectorAsync("span")); - Assert.Equal("hello", await divHandle.EvalOnSelectorAsync("span", "e => e.textContent")); + Assert.That(await divHandle.QuerySelectorAsync("span"), Is.Not.Null); + Assert.That(await divHandle.EvalOnSelectorAsync("span", "e => e.textContent"), Is.EqualTo("hello")); } [PlaywrightTest("elementhandle-query-selector.spec.ts", "should query existing elements")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldQueryExistingElements() { await Page.SetContentAsync("
A

B
"); var html = await Page.QuerySelectorAsync("html"); var elements = await html.QuerySelectorAllAsync("div"); - Assert.Equal(2, elements.Count()); + Assert.That(elements.Count(), Is.EqualTo(2)); var tasks = elements.Select(element => Page.EvaluateAsync("e => e.textContent", element)); - Assert.Equal(new[] { "A", "B" }, await TaskUtils.WhenAll(tasks)); + Assert.That(await TaskUtils.WhenAll(tasks), Is.EqualTo(new[] { "A", "B" })); } [PlaywrightTest("elementhandle-query-selector.spec.ts", "should return empty array for non-existing elements")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnEmptyArrayForNonExistingElements() { await Page.SetContentAsync("A
B"); var html = await Page.QuerySelectorAsync("html"); var elements = await html.QuerySelectorAllAsync("div"); - Assert.Empty(elements); + Assert.That(elements, Is.Empty); } [PlaywrightTest("elementhandle-query-selector.spec.ts", "xpath should query existing element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task XPathShouldQueryExistingElement() { await Page.GoToAsync(TestConstants.ServerUrl + "/playground.html"); @@ -102,17 +94,17 @@ public async Task XPathShouldQueryExistingElement() var second = await html.QuerySelectorAllAsync("xpath=./body/div[contains(@class, 'second')]"); var inner = await second.First().QuerySelectorAllAsync("xpath=./div[contains(@class, 'inner')]"); string content = await Page.EvaluateAsync("e => e.textContent", inner.First()); - Assert.Equal("A", content); + Assert.That(content, Is.EqualTo("A")); } [PlaywrightTest("elementhandle-query-selector.spec.ts", "xpath should return null for non-existing element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task XPathShouldReturnNullForNonExistingElement() { await Page.SetContentAsync("
B
"); var html = await Page.QuerySelectorAsync("html"); var second = await html.QuerySelectorAllAsync("xpath=/div[contains(@class, 'third')]"); - Assert.Empty(second); + Assert.That(second, Is.Empty); } } } diff --git a/src/Playwright.Tests/ElementHandleScreenshotTests.cs b/src/Playwright.Tests/ElementHandleScreenshotTests.cs index e2ec00331b..6690923087 100644 --- a/src/Playwright.Tests/ElementHandleScreenshotTests.cs +++ b/src/Playwright.Tests/ElementHandleScreenshotTests.cs @@ -3,27 +3,19 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.Helpers; using SixLabors.ImageSharp; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///elementhandle-screenshot.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleScreenshotTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleScreenshotTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.SetViewportSizeAsync(500, 500); @@ -31,11 +23,11 @@ public async Task ShouldWork() await Page.EvaluateAsync("window.scrollBy(50, 100)"); var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take into account padding and border")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTakeIntoAccountPaddingAndBorder() { await Page.SetViewportSizeAsync(500, 500); @@ -51,11 +43,11 @@ await Page.SetContentAsync(@"
"); var elementHandle = await Page.QuerySelectorAsync("div#d"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-padding-border.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-padding-border.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should capture full element when larger than viewport in parallel")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCaptureFullElementWhenLargerThanViewportInParallel() { await Page.SetViewportSizeAsync(500, 500); @@ -80,11 +72,11 @@ await Page.SetContentAsync(@" var screenshotTasks = elementHandles.Select(e => e.ScreenshotAsync()).ToArray(); await TaskUtils.WhenAll(screenshotTasks); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshotTasks.ElementAt(2).Result)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshotTasks.ElementAt(2).Result), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should capture full element when larger than viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCaptureFullElementWhenLargerThanViewport() { await Page.SetViewportSizeAsync(500, 500); @@ -107,12 +99,12 @@ await Page.SetContentAsync(@" var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshot), Is.True); await TestUtils.VerifyViewportAsync(Page, 500, 500); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should scroll element into view")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldScrollElementIntoView() { await Page.SetViewportSizeAsync(500, 500); @@ -134,11 +126,11 @@ await Page.SetContentAsync(@"
"); var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should scroll 15000px into view")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldScroll15000pxIntoView() { await Page.SetViewportSizeAsync(500, 500); @@ -160,11 +152,11 @@ await Page.SetContentAsync(@"
"); var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with a rotated element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithARotatedElement() { await Page.SetViewportSizeAsync(500, 500); @@ -179,34 +171,34 @@ await Page.SetContentAsync(@" "); var elementHandle = await Page.QuerySelectorAsync("div"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-rotate.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-rotate.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should fail to screenshot a detached element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailToScreenshotADetachedElement() { await Page.SetContentAsync("

remove this

"); var elementHandle = await Page.QuerySelectorAsync("h1"); await Page.EvaluateAsync("element => element.remove()", elementHandle); - var exception = await Assert.ThrowsAsync(() => elementHandle.ScreenshotAsync()); - Assert.Contains("Element is not attached to the DOM", exception.Message); + var exception = Assert.ThrowsAsync(() => elementHandle.ScreenshotAsync()); + Assert.That(exception.Message, Does.Contain("Element is not attached to the DOM")); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should timeout waiting for visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWaitingForVisible() { await Page.SetContentAsync(@"
"); var elementHandle = await Page.QuerySelectorAsync("div"); - var exception = await Assert.ThrowsAsync(() => elementHandle.ScreenshotAsync(timeout: 3000)); - Assert.Contains("Timeout 3000ms exceeded", exception.Message); - Assert.Contains("element is not visible", exception.Message); + var exception = Assert.ThrowsAsync(() => elementHandle.ScreenshotAsync(timeout: 3000)); + Assert.That(exception.Message, Does.Contain("Timeout 3000ms exceeded")); + Assert.That(exception.Message, Does.Contain("element is not visible")); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should wait for visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForVisible() { await Page.SetViewportSizeAsync(500, 500); @@ -220,21 +212,21 @@ public async Task ShouldWaitForVisible() { await Page.EvaluateAsync("() => new Promise(f => requestAnimationFrame(f))"); } - Assert.False(task.IsCompleted); + Assert.That(task.IsCompleted, Is.False); await elementHandle.EvaluateAsync("e => e.style.visibility = 'visible'"); byte[] screenshot = await task; - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work for an element with fractional dimensions")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForAnElementWithFractionalDimensions() { await Page.SetContentAsync("
"); var elementHandle = await Page.QuerySelectorAsync("div"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-fractional.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-fractional.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with a mobile viewport")] @@ -256,7 +248,7 @@ public async Task ShouldWorkWithAMobileViewport() var elementHandle = await page.QuerySelectorAsync(".box:nth-of-type(3)"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-mobile.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-mobile.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with device scale factor")] @@ -278,21 +270,21 @@ public async Task ShouldWorkWithDeviceScaleFactor() var elementHandle = await page.QuerySelectorAsync(".box:nth-of-type(3)"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-mobile-dsf.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-mobile-dsf.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work for an element with an offset")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForAnElementWithAnOffset() { await Page.SetContentAsync("
"); var elementHandle = await Page.QuerySelectorAsync("div"); byte[] screenshot = await elementHandle.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-fractional-offset.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-fractional-offset.png", screenshot), Is.True); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take screenshots when default viewport is null")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTakeScreenshotsWhenDefaultViewportIsNull() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -305,18 +297,18 @@ public async Task ShouldTakeScreenshotsWhenDefaultViewportIsNull() var sizeBefore = await page.EvaluateAsync("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })"); byte[] screenshot = await page.ScreenshotAsync(); - Assert.NotNull(screenshot); - Assert.NotEmpty(screenshot); + Assert.That(screenshot, Is.Not.Null); + Assert.That(screenshot, Is.Not.Empty); var decoded = Image.Load(screenshot); - Assert.Equal(windowSize.Width, decoded.Width); - Assert.Equal(windowSize.Height, decoded.Height); + Assert.That(decoded.Width, Is.EqualTo(windowSize.Width)); + Assert.That(decoded.Height, Is.EqualTo(windowSize.Height)); var sizeAfter = await page.EvaluateAsync("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })"); - Assert.Equal(sizeBefore, sizeAfter); + Assert.That(sizeAfter, Is.EqualTo(sizeBefore)); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take fullPage screenshots when default viewport is null")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTakeFullPageScreenshotsWhenDefaultViewportIsNull() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -328,15 +320,15 @@ public async Task ShouldTakeFullPageScreenshotsWhenDefaultViewportIsNull() var sizeBefore = await page.EvaluateAsync("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })"); byte[] screenshot = await page.ScreenshotAsync(fullPage: true); - Assert.NotNull(screenshot); - Assert.NotEmpty(screenshot); + Assert.That(screenshot, Is.Not.Null); + Assert.That(screenshot, Is.Not.Empty); var sizeAfter = await page.EvaluateAsync("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })"); - Assert.Equal(sizeBefore, sizeAfter); + Assert.That(sizeAfter, Is.EqualTo(sizeBefore)); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should restore default viewport after fullPage screenshot")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRestoreDefaultViewportAfterFullPageScreenshot() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -346,27 +338,27 @@ public async Task ShouldRestoreDefaultViewportAfterFullPageScreenshot() var page = await context.NewPageAsync(); await TestUtils.VerifyViewportAsync(page, 456, 789); byte[] screenshot = await page.ScreenshotAsync(fullPage: true); - Assert.NotNull(screenshot); - Assert.NotEmpty(screenshot); + Assert.That(screenshot, Is.Not.Null); + Assert.That(screenshot, Is.Not.Empty); await TestUtils.VerifyViewportAsync(page, 456, 789); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should restore viewport after page screenshot and exception")] - [Fact(Skip = "Skip USES_HOOKS")] + [Test, Ignore("Skip USES_HOOKS")] public void ShouldRestoreViewportAfterPageScreenshotAndException() { } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should restore viewport after page screenshot and timeout")] - [Fact(Skip = "Skip USES_HOOKS")] + [Test, Ignore("Skip USES_HOOKS")] public void ShouldRestoreViewportAfterPageScreenshotAndTimeout() { } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take element screenshot when default viewport is null and restore back")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTakeElementScreenshotWhenDefaultViewportIsNullAndRestoreBack() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -395,33 +387,33 @@ await Page.SetContentAsync(@" var sizeBefore = await page.EvaluateAsync("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })"); var elementHandle = await page.QuerySelectorAsync("div.to-screenshot"); byte[] screenshot = await page.ScreenshotAsync(); - Assert.NotNull(screenshot); - Assert.NotEmpty(screenshot); + Assert.That(screenshot, Is.Not.Null); + Assert.That(screenshot, Is.Not.Empty); var sizeAfter = await page.EvaluateAsync("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })"); - Assert.Equal(sizeBefore, sizeAfter); + Assert.That(sizeAfter, Is.EqualTo(sizeBefore)); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should restore viewport after element screenshot and exception")] - [Fact(Skip = "Skip USES_HOOKS")] + [Test, Ignore("Skip USES_HOOKS")] public void ShouldRestoreViewportAfterElementScreenshotAndException() { } [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take screenshot of disabled button")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTakeScreenshotOfDisabledButton() { await Page.SetViewportSizeAsync(500, 500); await Page.SetContentAsync(""); var button = await Page.QuerySelectorAsync("button"); byte[] screenshot = await button.ScreenshotAsync(); - Assert.NotNull(screenshot); - Assert.NotEmpty(screenshot); + Assert.That(screenshot, Is.Not.Null); + Assert.That(screenshot, Is.Not.Empty); } [PlaywrightTest("elementhandle-screenshot.spec.ts", "path option should create subdirectories")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PathOptionShouldCreateSubdirectories() { await Page.SetViewportSizeAsync(500, 500); @@ -431,7 +423,7 @@ public async Task PathOptionShouldCreateSubdirectories() using var tmpDir = new TempDirectory(); string outputPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "screenshot.png"); await elementHandle.ScreenshotAsync(outputPath); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", outputPath)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", outputPath), Is.True); } } } diff --git a/src/Playwright.Tests/ElementHandleScrollIntoViewTests.cs b/src/Playwright.Tests/ElementHandleScrollIntoViewTests.cs index 6c05d6eaf1..f70cc8bf5b 100644 --- a/src/Playwright.Tests/ElementHandleScrollIntoViewTests.cs +++ b/src/Playwright.Tests/ElementHandleScrollIntoViewTests.cs @@ -1,22 +1,14 @@ using System; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleScrollIntoViewTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleScrollIntoViewTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-scroll-into-view.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-scroll-into-view.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.ServerUrl + "/offscreenbuttons.html"); @@ -26,29 +18,29 @@ public async Task ShouldWork() double before = await button.EvaluateAsync(@"button => { return button.getBoundingClientRect().right - window.innerWidth; }"); - Assert.Equal(10 * i, before); + Assert.That(before, Is.EqualTo(10 * i)); await button.ScrollIntoViewIfNeededAsync(); double after = await button.EvaluateAsync(@"button => { return button.getBoundingClientRect().right - window.innerWidth; }"); - Assert.True(after <= 0); + Assert.That(after <= 0, Is.True); await Page.EvaluateAsync("() => window.scrollTo(0, 0)"); } } [PlaywrightTest("elementhandle-scroll-into-view.spec.ts", "should throw for detached element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForDetachedElement() { await Page.SetContentAsync("
Hello
"); var div = await Page.QuerySelectorAsync("div"); await div.EvaluateAsync("div => div.remove()"); - var exception = await Assert.ThrowsAnyAsync(() => div.ScrollIntoViewIfNeededAsync()); - Assert.Contains("Element is not attached to the DOM", exception.Message); + var exception = Assert.CatchAsync(() => div.ScrollIntoViewIfNeededAsync()); + Assert.That(exception.Message, Does.Contain("Element is not attached to the DOM")); } [PlaywrightTest("elementhandle-scroll-into-view.spec.ts", "should wait for display:none to become visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForDisplayNoneToBecomeVisible() { await Page.SetContentAsync("
Hello
"); @@ -56,7 +48,7 @@ public async Task ShouldWaitForDisplayNoneToBecomeVisible() } [PlaywrightTest("elementhandle-scroll-into-view.spec.ts", "should wait for display:contents to become visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForDisplayContentsToBecomeVisible() { await Page.SetContentAsync("
Hello
"); @@ -64,7 +56,7 @@ public async Task ShouldWaitForDisplayContentsToBecomeVisible() } [PlaywrightTest("elementhandle-scroll-into-view.spec.ts", "should wait for visibility:hidden to become visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForVisibilityHiddenToBecomeVisible() { await Page.SetContentAsync("
Hello
"); @@ -72,7 +64,7 @@ public async Task ShouldWaitForVisibilityHiddenToBecomeVisible() } [PlaywrightTest("elementhandle-scroll-into-view.spec.ts", "should wait for zero-sized element to become visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForZeroSiedElementToBecomeVisible() { await Page.SetContentAsync("
Hello
"); @@ -80,7 +72,7 @@ public async Task ShouldWaitForZeroSiedElementToBecomeVisible() } [PlaywrightTest("elementhandle-scroll-into-view.spec.ts", "should wait for nested display:none to become visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForNestedDisplayNoneToBecomeVisible() { await Page.SetContentAsync("
Hello
"); @@ -88,13 +80,13 @@ public async Task ShouldWaitForNestedDisplayNoneToBecomeVisible() } [PlaywrightTest("elementhandle-scroll-into-view.spec.ts", "should timeout waiting for visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWaitingForVisible() { await Page.SetContentAsync("
Hello
"); var div = await Page.QuerySelectorAsync("div"); - var exception = await Assert.ThrowsAnyAsync(() => div.ScrollIntoViewIfNeededAsync(3000)); - Assert.Contains("element is not visible", exception.Message); + var exception = Assert.CatchAsync(() => div.ScrollIntoViewIfNeededAsync(3000)); + Assert.That(exception.Message, Does.Contain("element is not visible")); } private async Task TestWaitingAsync(IPage page, string after) @@ -102,7 +94,7 @@ private async Task TestWaitingAsync(IPage page, string after) var div = await page.QuerySelectorAsync("div"); var task = div.ScrollIntoViewIfNeededAsync(); await page.EvaluateAsync("() => new Promise(f => setTimeout(f, 1000))"); - Assert.False(task.IsCompleted); + Assert.That(task.IsCompleted, Is.False); await div.EvaluateAsync(after); await task; } diff --git a/src/Playwright.Tests/ElementHandleSelectTextTests.cs b/src/Playwright.Tests/ElementHandleSelectTextTests.cs index e7c395c387..d0298f790a 100644 --- a/src/Playwright.Tests/ElementHandleSelectTextTests.cs +++ b/src/Playwright.Tests/ElementHandleSelectTextTests.cs @@ -1,22 +1,14 @@ using System; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleSelectTextTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleSelectTextTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-select-text.spec.ts", "should select textarea")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-select-text.spec.ts", "should select textarea")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectTextarea() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -26,17 +18,17 @@ public async Task ShouldSelectTextarea() if (TestConstants.IsFirefox) { - Assert.Equal(0, await textarea.EvaluateAsync("el => el.selectionStart")); - Assert.Equal(10, await textarea.EvaluateAsync("el => el.selectionEnd")); + Assert.That(await textarea.EvaluateAsync("el => el.selectionStart"), Is.EqualTo(0)); + Assert.That(await textarea.EvaluateAsync("el => el.selectionEnd"), Is.EqualTo(10)); } else { - Assert.Equal("some value", await Page.EvaluateAsync("() => window.getSelection().toString()")); + Assert.That(await Page.EvaluateAsync("() => window.getSelection().toString()"), Is.EqualTo("some value")); } } [PlaywrightTest("elementhandle-select-text.spec.ts", "should select input")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectInput() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -46,17 +38,17 @@ public async Task ShouldSelectInput() if (TestConstants.IsFirefox) { - Assert.Equal(0, await input.EvaluateAsync("el => el.selectionStart")); - Assert.Equal(10, await input.EvaluateAsync("el => el.selectionEnd")); + Assert.That(await input.EvaluateAsync("el => el.selectionStart"), Is.EqualTo(0)); + Assert.That(await input.EvaluateAsync("el => el.selectionEnd"), Is.EqualTo(10)); } else { - Assert.Equal("some value", await Page.EvaluateAsync("() => window.getSelection().toString()")); + Assert.That(await Page.EvaluateAsync("() => window.getSelection().toString()"), Is.EqualTo("some value")); } } [PlaywrightTest("elementhandle-select-text.spec.ts", "should select plain div")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectPlainDiv() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -64,23 +56,23 @@ public async Task ShouldSelectPlainDiv() await div.EvaluateAsync("input => input.value = 'some value'"); await div.SelectTextAsync(); - Assert.Equal("Plain div", await Page.EvaluateAsync("() => window.getSelection().toString()")); + Assert.That(await Page.EvaluateAsync("() => window.getSelection().toString()"), Is.EqualTo("Plain div")); } [PlaywrightTest("elementhandle-select-text.spec.ts", "should timeout waiting for invisible element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWaitingForInvisibleElement() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); var textarea = await Page.QuerySelectorAsync("textarea"); await textarea.EvaluateAsync("e => e.style.display = 'none'"); - var exception = await Assert.ThrowsAnyAsync(() => textarea.SelectTextAsync(3000)); - Assert.Contains("element is not visible", exception.Message); + var exception = Assert.CatchAsync(() => textarea.SelectTextAsync(3000)); + Assert.That(exception.Message, Does.Contain("element is not visible")); } [PlaywrightTest("elementhandle-select-text.spec.ts", "should wait for visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForVisible() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -90,7 +82,7 @@ public async Task ShouldWaitForVisible() var task = textarea.SelectTextAsync(3000); await Page.EvaluateAsync("() => new Promise(f => setTimeout(f, 1000))"); - Assert.False(task.IsCompleted); + Assert.That(task.IsCompleted, Is.False); await textarea.EvaluateAsync("e => e.style.display = 'block'"); await task; } diff --git a/src/Playwright.Tests/ElementHandleWaitForElementStateTests.cs b/src/Playwright.Tests/ElementHandleWaitForElementStateTests.cs index 04b97a3a65..6f20c9ba19 100644 --- a/src/Playwright.Tests/ElementHandleWaitForElementStateTests.cs +++ b/src/Playwright.Tests/ElementHandleWaitForElementStateTests.cs @@ -1,37 +1,29 @@ using System; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///elementhandle-wait-for-element-state.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ElementHandleWaitForElementStateTests : PlaywrightSharpPageBaseTest - { - /// - public ElementHandleWaitForElementStateTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should wait for visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should wait for visible")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForVisible() { await Page.SetContentAsync("
content
"); var div = await Page.QuerySelectorAsync("div"); var task = div.WaitForElementStateAsync(ElementState.Visible); await GiveItAChanceToResolve(Page); - Assert.False(task.IsCompleted); + Assert.That(task.IsCompleted, Is.False); await div.EvaluateAsync("div => div.style.display = 'block'"); await task; } [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should wait for already visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForAlreadyVisible() { await Page.SetContentAsync("
content
"); @@ -40,42 +32,42 @@ public async Task ShouldWaitForAlreadyVisible() } [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should timeout waiting for visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWaitingForVisible() { await Page.SetContentAsync("
content
"); var div = await Page.QuerySelectorAsync("div"); - var exception = await Assert.ThrowsAnyAsync(() => div.WaitForElementStateAsync(ElementState.Visible, 1000)); - Assert.Contains("Timeout 1000ms exceeded", exception.Message); + var exception = Assert.CatchAsync(() => div.WaitForElementStateAsync(ElementState.Visible, 1000)); + Assert.That(exception.Message, Does.Contain("Timeout 1000ms exceeded")); } [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should throw waiting for visible when detached")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWaitingForVisibleWhenDetached() { await Page.SetContentAsync("
content
"); var div = await Page.QuerySelectorAsync("div"); var task = div.WaitForElementStateAsync(ElementState.Visible); await div.EvaluateAsync("div => div.remove()"); - var exception = await Assert.ThrowsAnyAsync(() => task); - Assert.Contains("Element is not attached to the DOM", exception.Message); + var exception = Assert.CatchAsync(() => task); + Assert.That(exception.Message, Does.Contain("Element is not attached to the DOM")); } [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should wait for hidden")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForHidden() { await Page.SetContentAsync("
content
"); var div = await Page.QuerySelectorAsync("div"); var task = div.WaitForElementStateAsync(ElementState.Hidden); await GiveItAChanceToResolve(Page); - Assert.False(task.IsCompleted); + Assert.That(task.IsCompleted, Is.False); await div.EvaluateAsync("div => div.style.display = 'none'"); await task; } [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should wait for already hidden")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForAlreadyHidden() { await Page.SetContentAsync("
"); @@ -84,52 +76,52 @@ public async Task ShouldWaitForAlreadyHidden() } [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should throw waiting for hidden when detached")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWaitingForHiddenWhenDetached() { await Page.SetContentAsync("
content
"); var div = await Page.QuerySelectorAsync("div"); var task = div.WaitForElementStateAsync(ElementState.Hidden); await GiveItAChanceToResolve(Page); - Assert.False(task.IsCompleted); + Assert.That(task.IsCompleted, Is.False); await div.EvaluateAsync("div => div.remove()"); await task; } [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should wait for enabled button")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForEnabledButton() { await Page.SetContentAsync(""); var span = await Page.QuerySelectorAsync("text=Target"); var task = span.WaitForElementStateAsync(ElementState.Enabled); await GiveItAChanceToResolve(Page); - Assert.False(task.IsCompleted); + Assert.That(task.IsCompleted, Is.False); await span.EvaluateAsync("span => span.parentElement.disabled = false"); await task; } [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should throw waiting for enabled when detached")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWaitingForEnabledWhenDetached() { await Page.SetContentAsync(""); var button = await Page.QuerySelectorAsync("button"); var task = button.WaitForElementStateAsync(ElementState.Enabled); await button.EvaluateAsync("button => button.remove()"); - var exception = await Assert.ThrowsAnyAsync(() => task); - Assert.Contains("Element is not attached to the DOM", exception.Message); + var exception = Assert.CatchAsync(() => task); + Assert.That(exception.Message, Does.Contain("Element is not attached to the DOM")); } [PlaywrightTest("elementhandle-wait-for-element-state.spec.ts", "should wait for disabled button")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForDisabledButton() { await Page.SetContentAsync(""); var span = await Page.QuerySelectorAsync("text=Target"); var task = span.WaitForElementStateAsync(ElementState.Disabled); await GiveItAChanceToResolve(Page); - Assert.False(task.IsCompleted); + Assert.That(task.IsCompleted, Is.False); await span.EvaluateAsync("span => span.parentElement.disabled = true"); await task; } @@ -147,7 +139,7 @@ await Page.EvalOnSelectorAsync("button", @"button => { var task = button.WaitForElementStateAsync(ElementState.Stable); await GiveItAChanceToResolve(Page); - Assert.False(task.IsCompleted); + Assert.That(task.IsCompleted, Is.False); await button.EvaluateAsync("button => button.style.transition = ''"); await task; } diff --git a/src/Playwright.Tests/EmulationFocusTests.cs b/src/Playwright.Tests/EmulationFocusTests.cs index 1d24af0def..dac3511d8b 100644 --- a/src/Playwright.Tests/EmulationFocusTests.cs +++ b/src/Playwright.Tests/EmulationFocusTests.cs @@ -1,37 +1,29 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class EmulationFocusTests : PlaywrightSharpPageBaseTest - { - /// - public EmulationFocusTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("emulation-focus.spec.ts", "should think that it is focused by default")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("emulation-focus.spec.ts", "should think that it is focused by default")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThinkThatItIsFocusedByDefault() { - Assert.True(await Page.EvaluateAsync("document.hasFocus()")); + Assert.That(await Page.EvaluateAsync("document.hasFocus()"), Is.True); } [PlaywrightTest("emulation-focus.spec.ts", "should think that all pages are focused")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThinkThatAllPagesAreFocused() { var page2 = await Page.Context.NewPageAsync(); - Assert.True(await Page.EvaluateAsync("document.hasFocus()")); - Assert.True(await page2.EvaluateAsync("document.hasFocus()")); + Assert.That(await Page.EvaluateAsync("document.hasFocus()"), Is.True); + Assert.That(await page2.EvaluateAsync("document.hasFocus()"), Is.True); } [PlaywrightTest("emulation-focus.spec.ts", "should focus popups by default")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFocusPopupsByDefault() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -43,12 +35,12 @@ await TaskUtils.WhenAll( var popup = popupTask.Result; - Assert.True(await Page.EvaluateAsync("document.hasFocus()")); - Assert.True(await popup.EvaluateAsync("document.hasFocus()")); + Assert.That(await Page.EvaluateAsync("document.hasFocus()"), Is.True); + Assert.That(await popup.EvaluateAsync("document.hasFocus()"), Is.True); } [PlaywrightTest("emulation-focus.spec.ts", "should provide target for keyboard events")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldProvideTargetForKeyboardEvents() { var page2 = await Page.Context.NewPageAsync(); @@ -72,12 +64,12 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("result"), page2.EvaluateAsync("result")); - Assert.Equal(text, results.Item1); - Assert.Equal(text2, results.Item2); + Assert.That(results.Item1, Is.EqualTo(text)); + Assert.That(results.Item2, Is.EqualTo(text2)); } [PlaywrightTest("emulation-focus.spec.ts", "should not affect mouse event target page")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotAffectMouseEventTargetPage() { var page2 = await Page.Context.NewPageAsync(); @@ -99,12 +91,12 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("window.clickCount"), page2.EvaluateAsync("window.clickCount")); - Assert.Equal(1, counters.Item1); - Assert.Equal(1, counters.Item2); + Assert.That(counters.Item1, Is.EqualTo(1)); + Assert.That(counters.Item2, Is.EqualTo(1)); } [PlaywrightTest("emulation-focus.spec.ts", "should change document.activeElement")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldChangeDocumentActiveElement() { var page2 = await Page.Context.NewPageAsync(); @@ -121,18 +113,18 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("document.activeElement.tagName"), page2.EvaluateAsync("document.activeElement.tagName")); - Assert.Equal("INPUT", results.Item1); - Assert.Equal("TEXTAREA", results.Item2); + Assert.That(results.Item1, Is.EqualTo("INPUT")); + Assert.That(results.Item2, Is.EqualTo("TEXTAREA")); } [PlaywrightTest("emulation-focus.spec.ts", "should not affect screenshots")] - [Fact(Skip = "We need screenshot features first")] + [Test, Ignore("We need screenshot features first")] public void ShouldNotAffectScreenshots() { } [PlaywrightTest("emulation-focus.spec.ts", "should change focused iframe")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldChangeFocusedIframe() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -155,38 +147,38 @@ await TaskUtils.WhenAll( frame1.EvaluateAsync("document.hasFocus()"), frame2.EvaluateAsync("document.hasFocus()")); - Assert.False(focused.Item1); - Assert.False(focused.Item2); + Assert.That(focused.Item1, Is.False); + Assert.That(focused.Item2, Is.False); await frame1.FocusAsync("input"); var events = await TaskUtils.WhenAll( frame1.EvaluateAsync("self._events"), frame2.EvaluateAsync("self._events")); - Assert.Equal(new[] { "focus" }, events.Item1); - Assert.Empty(events.Item2); + Assert.That(events.Item1, Is.EqualTo(new[] { "focus" })); + Assert.That(events.Item2, Is.Empty); focused = await TaskUtils.WhenAll( frame1.EvaluateAsync("document.hasFocus()"), frame2.EvaluateAsync("document.hasFocus()")); - Assert.True(focused.Item1); - Assert.False(focused.Item2); + Assert.That(focused.Item1, Is.True); + Assert.That(focused.Item2, Is.False); await frame2.FocusAsync("input"); events = await TaskUtils.WhenAll( frame1.EvaluateAsync("self._events"), frame2.EvaluateAsync("self._events")); - Assert.Equal(new[] { "focus", "blur" }, events.Item1); - Assert.Equal(new[] { "focus" }, events.Item2); + Assert.That(events.Item1, Is.EqualTo(new[] { "focus", "blur" })); + Assert.That(events.Item2, Is.EqualTo(new[] { "focus" })); focused = await TaskUtils.WhenAll( frame1.EvaluateAsync("document.hasFocus()"), frame2.EvaluateAsync("document.hasFocus()")); - Assert.False(focused.Item1); - Assert.True(focused.Item2); + Assert.That(focused.Item1, Is.False); + Assert.That(focused.Item2, Is.True); } } } diff --git a/src/Playwright.Tests/EvalOnSelectorAllTests.cs b/src/Playwright.Tests/EvalOnSelectorAllTests.cs index 0821e3881c..3b362a9636 100644 --- a/src/Playwright.Tests/EvalOnSelectorAllTests.cs +++ b/src/Playwright.Tests/EvalOnSelectorAllTests.cs @@ -1,91 +1,83 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class EvalOnSelectorAllTests : PlaywrightSharpPageBaseTest - { - /// - public EvalOnSelectorAllTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("eval-on-selector-all.spec.ts", "should work with css selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("eval-on-selector-all.spec.ts", "should work with css selector")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCssSelector() { await Page.SetContentAsync("
hello
beautiful
world!
"); int divsCount = await Page.EvalOnSelectorAllAsync("css=div", "divs => divs.length"); - Assert.Equal(3, divsCount); + Assert.That(divsCount, Is.EqualTo(3)); } [PlaywrightTest("eval-on-selector-all.spec.ts", "should work with text selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithTextSelector() { await Page.SetContentAsync("
hello
beautiful
beautiful
world!
"); int divsCount = await Page.EvalOnSelectorAllAsync("text=beautiful", "divs => divs.length"); - Assert.Equal(2, divsCount); + Assert.That(divsCount, Is.EqualTo(2)); } [PlaywrightTest("eval-on-selector-all.spec.ts", "should work with xpath selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithXpathSelector() { await Page.SetContentAsync("
hello
beautiful
world!
"); int divsCount = await Page.EvalOnSelectorAllAsync("xpath=/html/body/div", "divs => divs.length"); - Assert.Equal(3, divsCount); + Assert.That(divsCount, Is.EqualTo(3)); } [PlaywrightTest("eval-on-selector-all.spec.ts", "should auto-detect css selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAutoDetectCssSelector() { await Page.SetContentAsync("
hello
beautiful
world!
"); int divsCount = await Page.EvalOnSelectorAllAsync("div", "divs => divs.length"); - Assert.Equal(3, divsCount); + Assert.That(divsCount, Is.EqualTo(3)); } [PlaywrightTest("eval-on-selector-all.spec.ts", "should support >> syntax")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportDoubleGreaterThanSyntax() { await Page.SetContentAsync("
hello
beautiful
world!
Not this one"); int spansCount = await Page.EvalOnSelectorAllAsync("css=div >> css=span", "spans => spans.length"); - Assert.Equal(3, spansCount); + Assert.That(spansCount, Is.EqualTo(3)); } [PlaywrightTest("eval-on-selector-all.spec.ts", "should should support * capture")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportStarCapture() { await Page.SetContentAsync("
a
b
"); - Assert.Equal(1, await Page.EvalOnSelectorAllAsync("*css=div >> \"b\"", "divs => divs.length")); - Assert.Equal(1, await Page.EvalOnSelectorAllAsync("section >> *css=div >> \"b\"", "divs => divs.length")); - Assert.Equal(4, await Page.EvalOnSelectorAllAsync("section >> *", "divs => divs.length")); + Assert.That(await Page.EvalOnSelectorAllAsync("*css=div >> \"b\"", "divs => divs.length"), Is.EqualTo(1)); + Assert.That(await Page.EvalOnSelectorAllAsync("section >> *css=div >> \"b\"", "divs => divs.length"), Is.EqualTo(1)); + Assert.That(await Page.EvalOnSelectorAllAsync("section >> *", "divs => divs.length"), Is.EqualTo(4)); await Page.SetContentAsync("
aa
"); - Assert.Equal(1, await Page.EvalOnSelectorAllAsync("*css=div >> \"a\"", "divs => divs.length")); - Assert.Equal(1, await Page.EvalOnSelectorAllAsync("section >> *css=div >> \"a\"", "divs => divs.length")); + Assert.That(await Page.EvalOnSelectorAllAsync("*css=div >> \"a\"", "divs => divs.length"), Is.EqualTo(1)); + Assert.That(await Page.EvalOnSelectorAllAsync("section >> *css=div >> \"a\"", "divs => divs.length"), Is.EqualTo(1)); await Page.SetContentAsync("
a
a
a
"); - Assert.Equal(3, await Page.EvalOnSelectorAllAsync("*css=div >> \"a\"", "divs => divs.length")); - Assert.Equal(1, await Page.EvalOnSelectorAllAsync("section >> *css=div >> \"a\"", "divs => divs.length")); + Assert.That(await Page.EvalOnSelectorAllAsync("*css=div >> \"a\"", "divs => divs.length"), Is.EqualTo(3)); + Assert.That(await Page.EvalOnSelectorAllAsync("section >> *css=div >> \"a\"", "divs => divs.length"), Is.EqualTo(1)); } [PlaywrightTest("eval-on-selector-all.spec.ts", "should support * capture when multiple paths match")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportStarCaptureWhenMultiplePathsMatch() { await Page.SetContentAsync("
"); - Assert.Equal(2, await Page.EvalOnSelectorAllAsync("*css=div >> span", "els => els.length")); + Assert.That(await Page.EvalOnSelectorAllAsync("*css=div >> span", "els => els.length"), Is.EqualTo(2)); await Page.SetContentAsync("
"); - Assert.Equal(2, await Page.EvalOnSelectorAllAsync("*css=div >> span", "els => els.length")); + Assert.That(await Page.EvalOnSelectorAllAsync("*css=div >> span", "els => els.length"), Is.EqualTo(2)); } } } diff --git a/src/Playwright.Tests/EvalOnSelectorTests.cs b/src/Playwright.Tests/EvalOnSelectorTests.cs index 0e8c4a9a67..a080f449ae 100644 --- a/src/Playwright.Tests/EvalOnSelectorTests.cs +++ b/src/Playwright.Tests/EvalOnSelectorTests.cs @@ -1,261 +1,253 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class EvalOnSelectorTests : PlaywrightSharpPageBaseTest - { - /// - public EvalOnSelectorTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("eval-on-selector.spec.ts", "should work with css selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("eval-on-selector.spec.ts", "should work with css selector")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCssSelector() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("css=section", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with id selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithIdSelector() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("id=testAttribute", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with data-test selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithDataTestSelector() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("data-test=foo", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with data-testid selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithDataTestidSelector() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("data-testid=foo", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with data-test-id selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithDataTestIdSelector() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("data-test-id=foo", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with text selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithTextSelector() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("text=\"43543\"", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with xpath selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithXpathSelector() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("xpath=/html/body/section", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with text selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithTextSelector2() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("text=43543", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should auto-detect css selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAutoDetectCssSelector() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("section", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should auto-detect nested selectors")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAutoDetectNestedSelectors() { await Page.SetContentAsync("
43543Hello
"); string idAttribute = await Page.EvalOnSelectorAsync("div[foo=bar] > section >> \"Hello\" >> div", "e => e.id"); - Assert.Equal("target", idAttribute); + Assert.That(idAttribute, Is.EqualTo("target")); } [PlaywrightTest("eval-on-selector.spec.ts", "should auto-detect css selector with attributes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAutoDetectCssSelectorWithAttributes() { await Page.SetContentAsync("
43543
"); string idAttribute = await Page.EvalOnSelectorAsync("section[id=\"testAttribute\"]", "e => e.id"); - Assert.Equal("testAttribute", idAttribute); + Assert.That(idAttribute, Is.EqualTo("testAttribute")); } [PlaywrightTest("eval-on-selector.spec.ts", "should accept arguments")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptArguments() { await Page.SetContentAsync("
hello
"); string text = await Page.EvalOnSelectorAsync("section", "(e, suffix) => e.textContent + suffix", " world!"); - Assert.Equal("hello world!", text); + Assert.That(text, Is.EqualTo("hello world!")); } [PlaywrightTest("eval-on-selector.spec.ts", "should accept ElementHandles as arguments")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptElementHandlesAsArguments() { await Page.SetContentAsync("
hello
world
"); var divHandle = await Page.QuerySelectorAsync("div"); string text = await Page.EvalOnSelectorAsync("section", "(e, div) => e.textContent + div.textContent", divHandle); - Assert.Equal("hello world", text); + Assert.That(text, Is.EqualTo("hello world")); } [PlaywrightTest("eval-on-selector.spec.ts", "should throw error if no element is found")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowErrorIfNoElementIsFound() { - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => Page.EvalOnSelectorAsync("section", "e => e.id")); - Assert.Contains("failed to find element matching selector \"section\"", exception.Message); + Assert.That(exception.Message, Does.Contain("failed to find element matching selector \"section\"")); } [PlaywrightTest("eval-on-selector.spec.ts", "should support >> syntax")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportDoubleGreaterThanSyntax() { await Page.SetContentAsync("
hello
"); string text = await Page.EvalOnSelectorAsync("css=section >> css=div", "(e, suffix) => e.textContent + suffix", " world!"); - Assert.Equal("hello world!", text); + Assert.That(text, Is.EqualTo("hello world!")); } [PlaywrightTest("eval-on-selector.spec.ts", "should support >> syntax with different engines")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportDoubleGreaterThanSyntaxWithDifferentEngines() { await Page.SetContentAsync("
hello
"); string text = await Page.EvalOnSelectorAsync("xpath=/html/body/section >> css=div >> text=\"hello\"", "(e, suffix) => e.textContent + suffix", " world!"); - Assert.Equal("hello world!", text); + Assert.That(text, Is.EqualTo("hello world!")); } [PlaywrightTest("eval-on-selector.spec.ts", "should support spaces with >> syntax")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportSpacesWithDoubleGreaterThanSyntax() { await Page.GoToAsync(TestConstants.ServerUrl + "/deep-shadow.html"); string text = await Page.EvalOnSelectorAsync(" css = div >>css=div>>css = span ", "e => e.textContent"); - Assert.Equal("Hello from root2", text); + Assert.That(text, Is.EqualTo("Hello from root2")); } [PlaywrightTest("eval-on-selector.spec.ts", "should not stop at first failure with >> syntax")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotStopAtFirstFailureWithDoubleGraterThanSyntax() { await Page.SetContentAsync("
Next
"); string text = await Page.EvalOnSelectorAsync("button >> \"Next\"", "(e) => e.outerHTML"); - Assert.Equal("", text); + Assert.That(text, Is.EqualTo("")); } [PlaywrightTest("eval-on-selector.spec.ts", "should support * capture")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportStarCapture() { await Page.SetContentAsync("
a
b
"); - Assert.Equal("
b
", await Page.EvalOnSelectorAsync("*css=div >> \"b\"", "(e) => e.outerHTML")); - Assert.Equal("
b
", await Page.EvalOnSelectorAsync("section >> *css=div >> \"b\"", "(e) => e.outerHTML")); - Assert.Equal("b", await Page.EvalOnSelectorAsync("css=div >> *text=\"b\"", "(e) => e.outerHTML")); - Assert.NotNull(await Page.QuerySelectorAsync("*")); + Assert.That(await Page.EvalOnSelectorAsync("*css=div >> \"b\"", "(e) => e.outerHTML"), Is.EqualTo("
b
")); + Assert.That(await Page.EvalOnSelectorAsync("section >> *css=div >> \"b\"", "(e) => e.outerHTML"), Is.EqualTo("
b
")); + Assert.That(await Page.EvalOnSelectorAsync("css=div >> *text=\"b\"", "(e) => e.outerHTML"), Is.EqualTo("b")); + Assert.That(await Page.QuerySelectorAsync("*"), Is.Not.Null); } [PlaywrightTest("eval-on-selector.spec.ts", "should throw on multiple * captures")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowOnMultipleStarCaptures() { - var exception = await Assert.ThrowsAnyAsync(() => Page.EvalOnSelectorAsync("*css=div >> *css=span", "(e) => e.outerHTML")); - Assert.Equal("Only one of the selectors can capture using * modifier", exception.Message); + var exception = Assert.CatchAsync(() => Page.EvalOnSelectorAsync("*css=div >> *css=span", "(e) => e.outerHTML")); + Assert.That(exception.Message, Is.EqualTo("Only one of the selectors can capture using * modifier")); } [PlaywrightTest("eval-on-selector.spec.ts", "should throw on malformed * capture")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowOnMalformedStarCapture() { - var exception = await Assert.ThrowsAnyAsync(() => Page.EvalOnSelectorAsync("*=div", "(e) => e.outerHTML")); - Assert.Equal("Unknown engine \"\" while parsing selector *=div", exception.Message); + var exception = Assert.CatchAsync(() => Page.EvalOnSelectorAsync("*=div", "(e) => e.outerHTML")); + Assert.That(exception.Message, Is.EqualTo("Unknown engine \"\" while parsing selector *=div")); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with spaces in css attributes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithSpacesInCssAttributes() { await Page.SetContentAsync("
"); - Assert.NotNull(await Page.WaitForSelectorAsync("[placeholder = \"Select date\"]")); - Assert.NotNull(await Page.WaitForSelectorAsync("[placeholder = 'Select date']")); - Assert.NotNull(await Page.WaitForSelectorAsync("input[placeholder = \"Select date\"]")); - Assert.NotNull(await Page.WaitForSelectorAsync("input[placeholder = 'Select date']")); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = \"Select date\"]")); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = 'Select date']")); - Assert.NotNull(await Page.QuerySelectorAsync("input[placeholder = \"Select date\"]")); - Assert.NotNull(await Page.QuerySelectorAsync("input[placeholder = 'Select date']")); - Assert.Equal("", await Page.EvalOnSelectorAsync("[placeholder = \"Select date\"]", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("[placeholder = 'Select date']", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("input[placeholder = \"Select date\"]", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("input[placeholder = 'Select date']", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("css =[placeholder = \"Select date\"]", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("css =[placeholder = 'Select date']", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("css = input[placeholder = \"Select date\"]", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("css = input[placeholder = 'Select date']", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div >> [placeholder = \"Select date\"]", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div >> [placeholder = 'Select date']", "e => e.outerHTML")); + Assert.That(await Page.WaitForSelectorAsync("[placeholder = \"Select date\"]"), Is.Not.Null); + Assert.That(await Page.WaitForSelectorAsync("[placeholder = 'Select date']"), Is.Not.Null); + Assert.That(await Page.WaitForSelectorAsync("input[placeholder = \"Select date\"]"), Is.Not.Null); + Assert.That(await Page.WaitForSelectorAsync("input[placeholder = 'Select date']"), Is.Not.Null); + Assert.That(await Page.QuerySelectorAsync("[placeholder = \"Select date\"]"), Is.Not.Null); + Assert.That(await Page.QuerySelectorAsync("[placeholder = 'Select date']"), Is.Not.Null); + Assert.That(await Page.QuerySelectorAsync("input[placeholder = \"Select date\"]"), Is.Not.Null); + Assert.That(await Page.QuerySelectorAsync("input[placeholder = 'Select date']"), Is.Not.Null); + Assert.That(await Page.EvalOnSelectorAsync("[placeholder = \"Select date\"]", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("[placeholder = 'Select date']", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("input[placeholder = \"Select date\"]", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("input[placeholder = 'Select date']", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("css =[placeholder = \"Select date\"]", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("css =[placeholder = 'Select date']", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("css = input[placeholder = \"Select date\"]", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("css = input[placeholder = 'Select date']", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div >> [placeholder = \"Select date\"]", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div >> [placeholder = 'Select date']", "e => e.outerHTML"), Is.EqualTo("")); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with quotes in css attributes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWihQuotesInCssAttributes() { await Page.SetContentAsync("
"); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = \"Select\\\"date\"]")); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = 'Select\"date']")); + Assert.That(await Page.QuerySelectorAsync("[placeholder = \"Select\\\"date\"]"), Is.Not.Null); + Assert.That(await Page.QuerySelectorAsync("[placeholder = 'Select\"date']"), Is.Not.Null); await Page.SetContentAsync("
"); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = \"Select \\\" date\"]")); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = 'Select \" date']")); + Assert.That(await Page.QuerySelectorAsync("[placeholder = \"Select \\\" date\"]"), Is.Not.Null); + Assert.That(await Page.QuerySelectorAsync("[placeholder = 'Select \" date']"), Is.Not.Null); await Page.SetContentAsync("
"); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = \"Select'date\"]")); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = 'Select\\'date']")); + Assert.That(await Page.QuerySelectorAsync("[placeholder = \"Select'date\"]"), Is.Not.Null); + Assert.That(await Page.QuerySelectorAsync("[placeholder = 'Select\\'date']"), Is.Not.Null); await Page.SetContentAsync("
"); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = \"Select ' date\"]")); - Assert.NotNull(await Page.QuerySelectorAsync("[placeholder = 'Select \\' date']")); + Assert.That(await Page.QuerySelectorAsync("[placeholder = \"Select ' date\"]"), Is.Not.Null); + Assert.That(await Page.QuerySelectorAsync("[placeholder = 'Select \\' date']"), Is.Not.Null); } [PlaywrightTest("eval-on-selector.spec.ts", "should work with quotes in css attributes when missing")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWihQuotesInCssAttributesWhenMissing() { var inputTask = Page.WaitForSelectorAsync("[placeholder = \"Select\\\"date\"]"); - Assert.Null(await Page.QuerySelectorAsync("[placeholder = \"Select\\\"date\"]")); + Assert.That(await Page.QuerySelectorAsync("[placeholder = \"Select\\\"date\"]"), Is.Null); await Page.SetContentAsync("
"); await inputTask; } diff --git a/src/Playwright.Tests/Firefox/LauncherTests.cs b/src/Playwright.Tests/Firefox/LauncherTests.cs index db88d8f93e..dbc0678d1c 100644 --- a/src/Playwright.Tests/Firefox/LauncherTests.cs +++ b/src/Playwright.Tests/Firefox/LauncherTests.cs @@ -1,24 +1,16 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests.Firefox { ///firefox/launcher.spec.ts ///launcher - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class LauncherTests : PlaywrightSharpBaseTest - { - /// - public LauncherTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("firefox/launcher.spec.ts", "should pass firefox user preferences")] + { [PlaywrightTest("firefox/launcher.spec.ts", "should pass firefox user preferences")] [SkipBrowserAndPlatformFact(skipChromium: true, skipWebkit: true)] public async Task ShouldPassFirefoxUserPreferences() { @@ -31,9 +23,9 @@ public async Task ShouldPassFirefoxUserPreferences() await using var browser = await BrowserType.LaunchAsync(firefoxUserPrefs: firefoxUserPrefs); var page = await browser.NewPageAsync(); - var exception = await Assert.ThrowsAnyAsync(() => page.GoToAsync("http://example.com")); + var exception = Assert.CatchAsync(() => page.GoToAsync("http://example.com")); - Assert.Contains("NS_ERROR_PROXY_CONNECTION_REFUSED", exception.Message); + Assert.That(exception.Message, Does.Contain("NS_ERROR_PROXY_CONNECTION_REFUSED")); } } } diff --git a/src/Playwright.Tests/FixturesTests.cs b/src/Playwright.Tests/FixturesTests.cs index 72eb820547..eec0652125 100644 --- a/src/Playwright.Tests/FixturesTests.cs +++ b/src/Playwright.Tests/FixturesTests.cs @@ -1,54 +1,46 @@ -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///fixtures.spec.ts ///Fixtures - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class FixturesTests : PlaywrightSharpBaseTest - { - /// - public FixturesTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("fixtures.spec.ts", "should close the browser when the node process closes")] - [Fact(Skip = "We don't need to test process handling")] + { [PlaywrightTest("fixtures.spec.ts", "should close the browser when the node process closes")] + [Test, Ignore("We don't need to test process handling")] public void ShouldCloseTheBrowserWhenTheNodeProcessCloses() { } [PlaywrightTest("fixtures.spec.ts", "fixtures", "should report browser close signal")] - [Fact(Skip = "We don't need to test signals")] + [Test, Ignore("We don't need to test signals")] public void ShouldReportBrowserCloseSignal() { } [PlaywrightTest("fixtures.spec.ts", "fixtures", "should report browser close signal 2")] - [Fact(Skip = "We don't need to test signals")] + [Test, Ignore("We don't need to test signals")] public void ShouldReportBrowserCloseSignal2() { } [PlaywrightTest("fixtures.spec.ts", "fixtures", "should close the browser on SIGINT")] - [Fact(Skip = "We don't need to test signals")] + [Test, Ignore("We don't need to test signals")] public void ShouldCloseTheBrowserOnSIGINT() { } [PlaywrightTest("fixtures.spec.ts", "fixtures", "should close the browser on SIGTERM")] - [Fact(Skip = "We don't need to test signals")] + [Test, Ignore("We don't need to test signals")] public void ShouldCloseTheBrowserOnSIGTERM() { } [PlaywrightTest("fixtures.spec.ts", "fixtures", "should close the browser on SIGHUP")] - [Fact(Skip = "We don't need to test signals")] + [Test, Ignore("We don't need to test signals")] public void ShouldCloseTheBrowserOnSIGHUP() { } [PlaywrightTest("fixtures.spec.ts", "fixtures", "should close the browser on double SIGINT")] - [Fact(Skip = "We don't need to test signals")] + [Test, Ignore("We don't need to test signals")] public void ShouldCloseTheBrowserOnDoubleSIGINT() { } [PlaywrightTest("fixtures.spec.ts", "fixtures", "should close the browser on SIGINT + SIGERM")] - [Fact(Skip = "We don't need to test signals")] + [Test, Ignore("We don't need to test signals")] public void ShouldCloseTheBrowserOnSIGINTAndSIGTERM() { } [PlaywrightTest("fixtures.spec.ts", "should report browser close signal")] - [Fact(Skip = "We don't need to test stacktrace")] + [Test, Ignore("We don't need to test stacktrace")] public void CallerFilePath() { } } } diff --git a/src/Playwright.Tests/FrameEvaluateTests.cs b/src/Playwright.Tests/FrameEvaluateTests.cs index 28c4b47362..59e4e6f6c1 100644 --- a/src/Playwright.Tests/FrameEvaluateTests.cs +++ b/src/Playwright.Tests/FrameEvaluateTests.cs @@ -1,70 +1,62 @@ using System.Dynamic; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class FrameEvaluateTests : PlaywrightSharpPageBaseTest - { - /// - public FrameEvaluateTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("frame-evaluate.spec.ts", "should have different execution contexts")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("frame-evaluate.spec.ts", "should have different execution contexts")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveDifferentExecutionContexts() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); - Assert.Equal(2, Page.Frames.Count); + Assert.That(Page.Frames.Count, Is.EqualTo(2)); await Page.Frames.First().EvaluateAsync("() => window.FOO = 'foo'"); await Page.Frames.ElementAt(1).EvaluateAsync("() => window.FOO = 'bar'"); - Assert.Equal("foo", await Page.Frames.First().EvaluateAsync("() => window.FOO")); - Assert.Equal("bar", await Page.Frames.ElementAt(1).EvaluateAsync("() => window.FOO")); + Assert.That(await Page.Frames.First().EvaluateAsync("() => window.FOO"), Is.EqualTo("foo")); + Assert.That(await Page.Frames.ElementAt(1).EvaluateAsync("() => window.FOO"), Is.EqualTo("bar")); } [PlaywrightTest("frame-evaluate.spec.ts", "should have correct execution contexts")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveCorrectExecutionContexts() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); - Assert.Equal(2, Page.Frames.Count); - Assert.Empty(await Page.Frames.First().EvaluateAsync("() => document.body.textContent.trim()")); - Assert.Equal("Hi, I'm frame", await Page.Frames.ElementAt(1).EvaluateAsync("() => document.body.textContent.trim()")); + Assert.That(Page.Frames.Count, Is.EqualTo(2)); + Assert.That(await Page.Frames.First().EvaluateAsync("() => document.body.textContent.trim()"), Is.Empty); + Assert.That(await Page.Frames.ElementAt(1).EvaluateAsync("() => document.body.textContent.trim()"), Is.EqualTo("Hi, I'm frame")); } [PlaywrightTest("frame-evaluate.spec.ts", "should dispose context on navigation")] - [Fact(Skip = "Ignore USES_HOOKS")] + [Test, Ignore("Ignore USES_HOOKS")] public void ShouldDisposeContextOnNavigation() { } [PlaywrightTest("frame-evaluate.spec.ts", "should dispose context on cross-origin navigation")] - [Fact(Skip = "Ignore USES_HOOKS")] + [Test, Ignore("Ignore USES_HOOKS")] public void ShouldDisposeContextOnCrossOriginNavigation() { } [PlaywrightTest("frame-evaluate.spec.ts", "should execute after cross-site navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldExecuteAfterCrossSiteNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); var mainFrame = Page.MainFrame; - Assert.Contains("localhost", await mainFrame.EvaluateAsync("() => window.location.href")); + Assert.That(await mainFrame.EvaluateAsync("() => window.location.href"), Does.Contain("localhost")); await Page.GoToAsync(TestConstants.CrossProcessUrl + "/empty.html"); - Assert.Contains("127", await mainFrame.EvaluateAsync("() => window.location.href")); + Assert.That(await mainFrame.EvaluateAsync("() => window.location.href"), Does.Contain("127")); } [PlaywrightTest("frame-evaluate.spec.ts", "should allow cross-frame js handles")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAllowCrossFrameJsHandles() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); @@ -76,51 +68,51 @@ public async Task ShouldAllowCrossFrameJsHandles() }"); var childFrame = Page.MainFrame.ChildFrames.First(); dynamic childResult = await childFrame.EvaluateAsync("() => window.__foo"); - Assert.Equal("baz", childResult.bar); - var exception = await Assert.ThrowsAnyAsync(() => childFrame.EvaluateAsync("foo => foo.bar", handle)); - Assert.Equal("JSHandles can be evaluated only in the context they were created!", exception.Message); + Assert.That(childResult.bar, Is.EqualTo("baz")); + var exception = Assert.CatchAsync(() => childFrame.EvaluateAsync("foo => foo.bar", handle)); + Assert.That(exception.Message, Is.EqualTo("JSHandles can be evaluated only in the context they were created!")); } [PlaywrightTest("frame-evaluate.spec.ts", "should allow cross-frame element handles")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAllowCrossFrameElementHandles() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); var bodyHandle = await Page.MainFrame.ChildFrames.First().QuerySelectorAsync("body"); string result = await Page.EvaluateAsync("body => body.innerHTML", bodyHandle); - Assert.Equal("
Hi, I\'m frame
", result.Trim()); + Assert.That(result.Trim(), Is.EqualTo("
Hi, I\'m frame
")); } [PlaywrightTest("frame-evaluate.spec.ts", "should not allow cross-frame element handles when frames do not script each other")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotAllowCrossFrameElementHandlesWhenFramesDoNotScriptEachOther() { await Page.GoToAsync(TestConstants.EmptyPage); var frame = await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.CrossProcessUrl + "/empty.html"); var bodyHandle = await frame.QuerySelectorAsync("body"); - var exception = await Assert.ThrowsAsync(() => Page.EvaluateAsync("body => body.innerHTML", bodyHandle)); - Assert.Contains("Unable to adopt element handle from a different document", exception.Message); + var exception = Assert.ThrowsAsync(() => Page.EvaluateAsync("body => body.innerHTML", bodyHandle)); + Assert.That(exception.Message, Does.Contain("Unable to adopt element handle from a different document")); } [PlaywrightTest("frame-evaluate.spec.ts", "should throw for detached frames")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForDetachedFrames() { var frame1 = await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); await FrameUtils.DetachFrameAsync(Page, "frame1"); - var exception = await Assert.ThrowsAsync(() => frame1.EvaluateAsync("() => 7 * 8")); - Assert.Contains("Execution Context is not available in detached frame", exception.Message); + var exception = Assert.ThrowsAsync(() => frame1.EvaluateAsync("() => 7 * 8")); + Assert.That(exception.Message, Does.Contain("Execution Context is not available in detached frame")); } [PlaywrightTest("frame-evaluate.spec.ts", "should be isolated between frames")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeIsolatedBetweenFrames() { await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); - Assert.Equal(2, Page.Frames.Count); + Assert.That(Page.Frames.Count, Is.EqualTo(2)); var frames = Page.Frames; - Assert.NotSame(frames.First(), frames.ElementAt(1)); + Assert.That(frames.ElementAt(1), Is.Not.SameAs(frames.First())); await TaskUtils.WhenAll( frames.First().EvaluateAsync("() => window.a = 1"), @@ -131,8 +123,8 @@ await TaskUtils.WhenAll( frames.First().EvaluateAsync("() => window.a"), frames.ElementAt(1).EvaluateAsync("() => window.a") ); - Assert.Equal(1, result1); - Assert.Equal(2, result2); + Assert.That(result1, Is.EqualTo(1)); + Assert.That(result2, Is.EqualTo(2)); } [PlaywrightTest("frame-evaluate.spec.ts", "should work in iframes that failed initial navigation")] @@ -150,9 +142,9 @@ await Page.EvaluateAsync(@"() => { iframe.contentDocument.body.appendChild(div); }"); - Assert.Equal("about:blank", Page.Frames.ElementAt(1).Url); - Assert.Equal("about:blank", await Page.Frames.ElementAt(1).EvaluateAsync("() => window.location.href")); - Assert.NotNull(await Page.Frames.ElementAt(1).QuerySelectorAsync("DIV")); + Assert.That(Page.Frames.ElementAt(1).Url, Is.EqualTo("about:blank")); + Assert.That(await Page.Frames.ElementAt(1).EvaluateAsync("() => window.location.href"), Is.EqualTo("about:blank")); + Assert.That(await Page.Frames.ElementAt(1).QuerySelectorAsync("DIV"), Is.Not.Null); } [PlaywrightTest("frame-evaluate.spec.ts", "should work in iframes that failed initial navigation")] @@ -170,17 +162,17 @@ await Page.EvaluateAsync(@"() => { iframe.contentDocument.close(); }"); - Assert.Equal(TestConstants.EmptyPage, await Page.Frames.ElementAt(1).EvaluateAsync("() => window.location.href")); - Assert.NotNull(await Page.Frames.ElementAt(1).QuerySelectorAsync("DIV")); + Assert.That(await Page.Frames.ElementAt(1).EvaluateAsync("() => window.location.href"), Is.EqualTo(TestConstants.EmptyPage)); + Assert.That(await Page.Frames.ElementAt(1).QuerySelectorAsync("DIV"), Is.Not.Null); } [PlaywrightTest("frame-evaluate.spec.ts", "evaluateHandle should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task EvaluateHandleShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); var windowHandle = await Page.MainFrame.EvaluateHandleAsync("() => window"); - Assert.NotNull(windowHandle); + Assert.That(windowHandle, Is.Not.Null); } } } diff --git a/src/Playwright.Tests/FrameFrameElementTests.cs b/src/Playwright.Tests/FrameFrameElementTests.cs index 3d44b39e73..2d5e427ff5 100644 --- a/src/Playwright.Tests/FrameFrameElementTests.cs +++ b/src/Playwright.Tests/FrameFrameElementTests.cs @@ -1,21 +1,13 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class FrameFrameElementTests : PlaywrightSharpPageBaseTest - { - /// - public FrameFrameElementTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("frame-frame-element.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("frame-frame-element.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -28,16 +20,16 @@ public async Task ShouldWork() var frame3handle1 = await Page.QuerySelectorAsync("#frame3"); var frame3handle2 = await frame3.FrameElementAsync(); - Assert.True(await frame1handle1.EvaluateAsync("(a, b) => a === b", frame1handle2)); - Assert.True(await frame3handle1.EvaluateAsync("(a, b) => a === b", frame3handle2)); - Assert.False(await frame1handle1.EvaluateAsync("(a, b) => a === b", frame3handle2)); + Assert.That(await frame1handle1.EvaluateAsync("(a, b) => a === b", frame1handle2), Is.True); + Assert.That(await frame3handle1.EvaluateAsync("(a, b) => a === b", frame3handle2), Is.True); + Assert.That(await frame1handle1.EvaluateAsync("(a, b) => a === b", frame3handle2), Is.False); var windowHandle = await Page.MainFrame.EvaluateHandleAsync("() => window"); - Assert.NotNull(windowHandle); + Assert.That(windowHandle, Is.Not.Null); } [PlaywrightTest("frame-frame-element.spec.ts", "should work with contentFrame")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithContentFrame() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -45,20 +37,20 @@ public async Task ShouldWorkWithContentFrame() var handle = await frame.FrameElementAsync(); var contentFrame = await handle.ContentFrameAsync(); - Assert.Same(contentFrame, frame); + Assert.That(frame, Is.SameAs(contentFrame)); } [PlaywrightTest("frame-frame-element.spec.ts", "should throw when detached")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWhenDetached() { await Page.GoToAsync(TestConstants.EmptyPage); var frame1 = await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); await Page.EvalOnSelectorAsync("#frame1", "e => e.remove()"); - var exception = await Assert.ThrowsAnyAsync(() => frame1.FrameElementAsync()); + var exception = Assert.CatchAsync(() => frame1.FrameElementAsync()); - Assert.Equal("Frame has been detached.", exception.Message); + Assert.That(exception.Message, Is.EqualTo("Frame has been detached.")); } } } diff --git a/src/Playwright.Tests/FrameGoToTests.cs b/src/Playwright.Tests/FrameGoToTests.cs index 1ca58499fe..7c9009cafd 100644 --- a/src/Playwright.Tests/FrameGoToTests.cs +++ b/src/Playwright.Tests/FrameGoToTests.cs @@ -3,36 +3,28 @@ using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class FrameGoToTests : PlaywrightSharpPageBaseTest - { - /// - public FrameGoToTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("frame-goto.spec.ts", "should navigate subframes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("frame-goto.spec.ts", "should navigate subframes")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNavigateSubFrames() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); - Assert.Single(Page.Frames.Where(f => f.Url.Contains("/frames/one-frame.html"))); - Assert.Single(Page.Frames.Where(f => f.Url.Contains("/frames/frame.html"))); + Assert.That(Page.Frames.Where(f => f.Url.Contains("/frames/one-frame.html")), Has.Count.EqualTo(1)); + Assert.That(Page.Frames.Where(f => f.Url.Contains("/frames/frame.html")), Has.Count.EqualTo(1)); var childFrame = Page.FirstChildFrame(); var response = await childFrame.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Same(response.Frame, childFrame); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(childFrame, Is.SameAs(response.Frame)); } [PlaywrightTest("frame-goto.spec.ts", "should reject when frame detaches")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRejectWhenFrameDetaches() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); @@ -41,24 +33,24 @@ public async Task ShouldRejectWhenFrameDetaches() var navigationTask = Page.FirstChildFrame().GoToAsync(TestConstants.EmptyPage); await waitForRequestTask; await Page.EvalOnSelectorAsync("iframe", "frame => frame.remove()"); - var exception = await Assert.ThrowsAsync(async () => await navigationTask); - Assert.Contains("frame was detached", exception.Message); + var exception = Assert.ThrowsAsync(async () => await navigationTask); + Assert.That(exception.Message, Does.Contain("frame was detached")); } [PlaywrightTest("frame-goto.spec.ts", "should continue after client redirect")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldContinueAfterClientRedirect() { Server.SetRoute("/frames/script.js", _ => Task.Delay(10000)); string url = TestConstants.ServerUrl + "/frames/child-redirect.html"; - var exception = await Assert.ThrowsAnyAsync(() => Page.GoToAsync(url, WaitUntilState.NetworkIdle, 5000)); + var exception = Assert.CatchAsync(() => Page.GoToAsync(url, WaitUntilState.NetworkIdle, 5000)); - Assert.Contains("Timeout 5000ms", exception.Message); - Assert.Contains($"navigating to \"{url}\", waiting until \"networkidle\"", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 5000ms")); + Assert.That(exception.Message, Does.Contain($"navigating to \"{url}\", waiting until \"networkidle\"")); } [PlaywrightTest("frame-goto.spec.ts", "should return matching responses")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnMatchingResponses() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -97,8 +89,8 @@ public async Task ShouldReturnMatchingResponses() { matchingData[i].ServerResponseTcs.TrySetResult(serverResponseTexts[i]); var response = await matchingData[i].NavigationTask; - Assert.Same(matchingData[i].FrameTask.Result, response.Frame); - Assert.Equal(serverResponseTexts[i], await response.GetTextAsync()); + Assert.That(response.Frame, Is.SameAs(matchingData[i].FrameTask.Result)); + Assert.That(await response.GetTextAsync(), Is.EqualTo(serverResponseTexts[i])); } } diff --git a/src/Playwright.Tests/FrameHierarchyTests.cs b/src/Playwright.Tests/FrameHierarchyTests.cs index 24ffd7f78d..78fbc1de77 100644 --- a/src/Playwright.Tests/FrameHierarchyTests.cs +++ b/src/Playwright.Tests/FrameHierarchyTests.cs @@ -1,31 +1,23 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class FrameHierarchyTests : PlaywrightSharpPageBaseTest - { - /// - public FrameHierarchyTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("frame-hierarchy.spec.ts", "should handle nested frames")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("frame-hierarchy.spec.ts", "should handle nested frames")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHandleNestedFrames() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/nested-frames.html"); - Assert.Equal(TestConstants.NestedFramesDumpResult, FrameUtils.DumpFrames(Page.MainFrame)); + Assert.That(FrameUtils.DumpFrames(Page.MainFrame), Is.EqualTo(TestConstants.NestedFramesDumpResult)); } [PlaywrightTest("frame-hierarchy.spec.ts", "should send events when frames are manipulated dynamically")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendEventsWhenFramesAreManipulatedDynamically() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -33,8 +25,8 @@ public async Task ShouldSendEventsWhenFramesAreManipulatedDynamically() var attachedFrames = new List"); var frame = Page.Frames.Single(f => f.Name == "inner"); await frame.PressAsync("textarea", "a"); - Assert.Equal("a", await frame.EvaluateAsync("() => document.querySelector('textarea').value")); + Assert.That(await frame.EvaluateAsync("() => document.querySelector('textarea').value"), Is.EqualTo("a")); } [PlaywrightTest("page-basic.spec.ts", "page.frame should respect name")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnTheCorrectBrowserInstance() { await Page.SetContentAsync(""); - Assert.Null(Page.Frames.FirstOrDefault(f => f.Name == "bogus")); + Assert.That(Page.Frames.FirstOrDefault(f => f.Name == "bogus"), Is.Null); var frame = Page.Frames.FirstOrDefault(f => f.Name == "target"); - Assert.Same(Page.MainFrame.ChildFrames.First(), frame); + Assert.That(frame, Is.SameAs(Page.MainFrame.ChildFrames.First())); } [PlaywrightTest("page-basic.spec.ts", "page.frame should respect url")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectUrl() { await Page.SetContentAsync($""); - Assert.Null(Page.Frames.FirstOrDefault(f => f.Name == "bogus")); + Assert.That(Page.Frames.FirstOrDefault(f => f.Name == "bogus"), Is.Null); var frame = Page.Frames.FirstOrDefault(f => f.Url.Contains("empty")); - Assert.Same(Page.MainFrame.ChildFrames.First(), frame); + Assert.That(frame, Is.SameAs(Page.MainFrame.ChildFrames.First())); } [PlaywrightTest("page-basic.spec.ts", "should provide access to the opener page")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldProvideAccessToTheOpenerPage() { var (popupEvent, _) = await TaskUtils.WhenAll( @@ -89,11 +82,11 @@ public async Task ShouldProvideAccessToTheOpenerPage() Page.EvaluateAsync("() => window.open('about:blank')") ); var opener = await popupEvent.OpenerAsync(); - Assert.Equal(Page, opener); + Assert.That(opener, Is.EqualTo(Page)); } [PlaywrightTest("page-basic.spec.ts", "should return null if parent page has been closed")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNullIfParentPageHasBeenClosed() { var (popupEvent, _) = await TaskUtils.WhenAll( @@ -102,82 +95,82 @@ public async Task ShouldReturnNullIfParentPageHasBeenClosed() ); await Page.CloseAsync(); var opener = await popupEvent.OpenerAsync(); - Assert.Null(opener); + Assert.That(opener, Is.Null); } [PlaywrightTest("page-basic.spec.ts", "should return the page title")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnThePageTitle() { await Page.GoToAsync(TestConstants.ServerUrl + "/title.html"); - Assert.Equal("Woof-Woof", await Page.TitleAsync()); + Assert.That(await Page.TitleAsync(), Is.EqualTo("Woof-Woof")); } [PlaywrightTest("page-basic.spec.ts", "page.url should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageUrlShouldWork() { - Assert.Equal("about:blank", Page.Url); + Assert.That(Page.Url, Is.EqualTo("about:blank")); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(TestConstants.EmptyPage, Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("page-basic.spec.ts", "should include hashes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIncludeHashes() { await Page.GoToAsync(TestConstants.EmptyPage + "#hash"); - Assert.Equal(TestConstants.EmptyPage + "#hash", Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage + "#hash")); await Page.EvaluateAsync("() => window.location.hash = 'dynamic'"); - Assert.Equal(TestConstants.EmptyPage + "#dynamic", Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage + "#dynamic")); } [PlaywrightTest("page-basic.spec.ts", "should fail with error upon disconnect")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWithErrorUponDisconnect() { var task = Page.WaitForEventAsync(PageEvent.Download); await Page.CloseAsync(); - var exception = await Assert.ThrowsAnyAsync(() => task); - Assert.Contains("Page closed", exception.Message); + var exception = Assert.CatchAsync(() => task); + Assert.That(exception.Message, Does.Contain("Page closed")); } [PlaywrightTest("page-basic.spec.ts", "should have sane user agent")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveASaneUserAgent() { string userAgent = await Page.EvaluateAsync("() => navigator.userAgent"); var regex = new Regex("[()]"); string[] parts = Regex.Split(userAgent, "[()]").Select(t => t.Trim()).ToArray(); - Assert.Equal("Mozilla/5.0", parts[0]); + Assert.That(parts[0], Is.EqualTo("Mozilla/5.0")); if (TestConstants.IsFirefox) { string[] engineBrowser = parts[2].Split(' '); - Assert.StartsWith("Gecko", engineBrowser[0]); - Assert.StartsWith("Firefox", engineBrowser[1]); + Assert.That(engineBrowser[0], Does.StartWith("Gecko")); + Assert.That(engineBrowser[1], Does.StartWith("Firefox")); } else { - Assert.StartsWith("AppleWebKit/", parts[2]); - Assert.Equal("KHTML, like Gecko", parts[3]); + Assert.That(parts[2], Does.StartWith("AppleWebKit/")); + Assert.That(parts[3], Is.EqualTo("KHTML, like Gecko")); string[] engineBrowser = parts[4].Split(' '); - Assert.StartsWith("Safari/", engineBrowser[1]); + Assert.That(engineBrowser[1], Does.StartWith("Safari/")); if (TestConstants.IsChromium) { - Assert.Contains("Chrome/", engineBrowser[0]); + Assert.That(engineBrowser[0], Does.Contain("Chrome/")); } else { - Assert.StartsWith("Version", engineBrowser[0]); + Assert.That(engineBrowser[0], Does.StartWith("Version")); } } } [PlaywrightTest("page-basic.spec.ts", "should work with window.close")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithWindowClose() { var newPageTask = Page.WaitForEventAsync(PageEvent.Popup); @@ -190,7 +183,7 @@ public async Task ShouldWorkWithWindowClose() } [PlaywrightTest("page-basic.spec.ts", "should work with page.close")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithPageClose() { var newPage = await Context.NewPageAsync(); @@ -201,7 +194,7 @@ public async Task ShouldWorkWithPageClose() } [PlaywrightTest("page-basic.spec.ts", "should fire load when expected")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFireLoadWhenExpected() { await TaskUtils.WhenAll( @@ -211,7 +204,7 @@ await TaskUtils.WhenAll( } [PlaywrightTest("page-basic.spec.ts", "should fire domcontentloaded when expected")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFireDOMcontentloadedWhenExpected() { var task = Page.GoToAsync("about:blank"); @@ -220,21 +213,21 @@ public async Task ShouldFireDOMcontentloadedWhenExpected() } [PlaywrightTest("page-basic.spec.ts", "should set the page close state")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSetThePageCloseState() { var newPage = await Context.NewPageAsync(); - Assert.False(newPage.IsClosed); + Assert.That(newPage.IsClosed, Is.False); await newPage.CloseAsync(); - Assert.True(newPage.IsClosed); + Assert.That(newPage.IsClosed, Is.True); } [PlaywrightTest("page-basic.spec.ts", "should terminate network waiters")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTerminateNetworkWaiters() { var newPage = await Context.NewPageAsync(); - var exception = await Assert.ThrowsAsync(() => TaskUtils.WhenAll( + var exception = Assert.ThrowsAsync(() => TaskUtils.WhenAll( newPage.WaitForRequestAsync(TestConstants.EmptyPage), newPage.WaitForResponseAsync(TestConstants.EmptyPage), newPage.CloseAsync() @@ -242,13 +235,13 @@ public async Task ShouldTerminateNetworkWaiters() for (int i = 0; i < 2; i++) { string message = exception.Message; - Assert.Contains("Page closed", message); - Assert.DoesNotContain("Timeout", message); + Assert.That(message, Does.Contain("Page closed")); + Assert.That(message, Does.Not.Contain("Timeout")); } } [PlaywrightTest("page-basic.spec.ts", "should be callable twice")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeCallableTwice() { var newPage = await Context.NewPageAsync(); @@ -260,13 +253,13 @@ await TaskUtils.WhenAll( } [PlaywrightTest("page-basic.spec.ts", "should not be visible in context.pages")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotBeVisibleInContextPages() { var newPage = await Context.NewPageAsync(); - Assert.Contains(newPage, Context.Pages); + Assert.That(Context.Pages, Does.Contain(newPage)); await newPage.CloseAsync(); - Assert.DoesNotContain(newPage, Context.Pages); + Assert.That(Context.Pages, Does.Not.Contain(newPage)); } } } diff --git a/src/Playwright.Tests/PageCheckTests.cs b/src/Playwright.Tests/PageCheckTests.cs index e44dbd03f2..a32cabda19 100644 --- a/src/Playwright.Tests/PageCheckTests.cs +++ b/src/Playwright.Tests/PageCheckTests.cs @@ -1,75 +1,67 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageCheckTests : PlaywrightSharpPageBaseTest - { - /// - public PageCheckTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-check.spec.ts", "should check the box")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-check.spec.ts", "should check the box")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCheckTheBox() { await Page.SetContentAsync(""); await Page.CheckAsync("input"); - Assert.True(await Page.EvaluateAsync("checkbox.checked")); + Assert.That(await Page.EvaluateAsync("checkbox.checked"), Is.True); } [PlaywrightTest("page-check.spec.ts", "should not check the checked box")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotCheckTheCheckedBox() { await Page.SetContentAsync(""); await Page.CheckAsync("input"); - Assert.True(await Page.EvaluateAsync("checkbox.checked")); + Assert.That(await Page.EvaluateAsync("checkbox.checked"), Is.True); } [PlaywrightTest("page-check.spec.ts", "should uncheck the box")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUncheckTheBox() { await Page.SetContentAsync(""); await Page.UncheckAsync("input"); - Assert.False(await Page.EvaluateAsync("checkbox.checked")); + Assert.That(await Page.EvaluateAsync("checkbox.checked"), Is.False); } [PlaywrightTest("page-check.spec.ts", "should check the box by label")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCheckTheBoxByLabel() { await Page.SetContentAsync(""); await Page.CheckAsync("label"); - Assert.True(await Page.EvaluateAsync("checkbox.checked")); + Assert.That(await Page.EvaluateAsync("checkbox.checked"), Is.True); } [PlaywrightTest("page-check.spec.ts", "should check the box outside label")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCheckTheBoxOutsideLabel() { await Page.SetContentAsync("
"); await Page.CheckAsync("label"); - Assert.True(await Page.EvaluateAsync("checkbox.checked")); + Assert.That(await Page.EvaluateAsync("checkbox.checked"), Is.True); } [PlaywrightTest("page-check.spec.ts", "should check the box inside label w/o id")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCheckTheBoxInsideLabelWoId() { await Page.SetContentAsync(""); await Page.CheckAsync("label"); - Assert.True(await Page.EvaluateAsync("checkbox.checked")); + Assert.That(await Page.EvaluateAsync("checkbox.checked"), Is.True); } [PlaywrightTest("page-check.spec.ts", "should check radio")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCheckRadio() { await Page.SetContentAsync(@" @@ -77,11 +69,11 @@ await Page.SetContentAsync(@" two three"); await Page.CheckAsync("#two"); - Assert.True(await Page.EvaluateAsync("two.checked")); + Assert.That(await Page.EvaluateAsync("two.checked"), Is.True); } [PlaywrightTest("page-check.spec.ts", "should check the box by aria role")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCheckTheBoxByAriaRole() { await Page.SetContentAsync(@" @@ -90,7 +82,7 @@ await Page.SetContentAsync(@" checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'true')); "); await Page.CheckAsync("div"); - Assert.Equal("true", await Page.EvaluateAsync("checkbox.getAttribute('aria-checked')")); + Assert.That(await Page.EvaluateAsync("checkbox.getAttribute('aria-checked')"), Is.EqualTo("true")); } } } diff --git a/src/Playwright.Tests/PageClickReactTests.cs b/src/Playwright.Tests/PageClickReactTests.cs index 0d5a40709e..45503acced 100644 --- a/src/Playwright.Tests/PageClickReactTests.cs +++ b/src/Playwright.Tests/PageClickReactTests.cs @@ -1,60 +1,52 @@ using System; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageClickReactTests : PlaywrightSharpPageBaseTest - { - /// - public PageClickReactTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-click-react.spec.ts", "should retarget when element is recycled during hit testing")] - [Fact(Skip = " Skip USES_HOOKS")] + { [PlaywrightTest("page-click-react.spec.ts", "should retarget when element is recycled during hit testing")] + [Test, Ignore(" Skip USES_HOOKS")] public void ShouldRetargetWhenElementIsRecycledDuringHitTesting() { } [PlaywrightTest("page-click-react.spec.ts", "should report that selector does not match anymore")] - [Fact(Skip = " Skip USES_HOOKS")] + [Test, Ignore(" Skip USES_HOOKS")] public void ShouldReportThatSelectorDoesNotMatchAnymore() { } [PlaywrightTest("page-click-react.spec.ts", "should retarget when element is recycled before enabled check")] - [Fact(Skip = " Skip USES_HOOKS")] + [Test, Ignore(" Skip USES_HOOKS")] public void ShouldRetargetWhenElementIsRecycledBeforeEnabledCheck() { } [PlaywrightTest("page-click-react.spec.ts", "should not retarget the handle when element is recycled")] - [Fact(Skip = " Skip USES_HOOKS")] + [Test, Ignore(" Skip USES_HOOKS")] public void ShouldNotRetargetTheHandleWhenElementIsRecycled() { } [PlaywrightTest("page-click-react.spec.ts", "should timeout when click opens alert")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWhenClickOpensAlert() { var dialogTask = Page.WaitForEventAsync(PageEvent.Dialog); await Page.SetContentAsync("
Click me
"); - var exception = await Assert.ThrowsAsync(() => Page.ClickAsync("div", timeout: 3000)); - Assert.Contains("Timeout 3000ms exceeded", exception.Message); + var exception = Assert.ThrowsAsync(() => Page.ClickAsync("div", timeout: 3000)); + Assert.That(exception.Message, Does.Contain("Timeout 3000ms exceeded")); var dialog = await dialogTask; await dialog.DismissAsync(); } [PlaywrightTest("page-click-react.spec.ts", "should not retarget when element changes on hover")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotRetargetWhenElementChangesOnHover() { await Page.GoToAsync(TestConstants.ServerUrl + "/react.html"); @@ -63,12 +55,12 @@ await Page.EvaluateAsync(@"() => { }"); await Page.ClickAsync("text=button1"); - Assert.True(await Page.EvaluateAsync("window.button1")); - Assert.Null(await Page.EvaluateAsync("window.button2")); + Assert.That(await Page.EvaluateAsync("window.button1"), Is.True); + Assert.That(await Page.EvaluateAsync("window.button2"), Is.Null); } [PlaywrightTest("page-click-react.spec.ts", "should not retarget when element is recycled on hover")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotRetargetWhenElementIsRecycledOnHover() { await Page.GoToAsync(TestConstants.ServerUrl + "/react.html"); @@ -80,8 +72,8 @@ function shuffle() { }"); await Page.ClickAsync("text=button1"); - Assert.Null(await Page.EvaluateAsync("window.button1")); - Assert.True(await Page.EvaluateAsync("window.button2")); + Assert.That(await Page.EvaluateAsync("window.button1"), Is.Null); + Assert.That(await Page.EvaluateAsync("window.button2"), Is.True); } } diff --git a/src/Playwright.Tests/PageClickTests.cs b/src/Playwright.Tests/PageClickTests.cs index ca9655235a..375e5112f5 100644 --- a/src/Playwright.Tests/PageClickTests.cs +++ b/src/Playwright.Tests/PageClickTests.cs @@ -3,33 +3,25 @@ using System.Drawing; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageClickTests : PlaywrightSharpPageBaseTest - { - /// - public PageClickTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-click.spec.ts", "should click the button")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-click.spec.ts", "should click the button")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickTheButton() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.ClickAsync("button"); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click svg")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickSvg() { await Page.SetContentAsync($@" @@ -38,21 +30,21 @@ await Page.SetContentAsync($@" "); await Page.ClickAsync("circle"); - Assert.Equal(42, await Page.EvaluateAsync("() => window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("() => window.__CLICKED"), Is.EqualTo(42)); } [PlaywrightTest("page-click.spec.ts", "should click svg")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickTheButtonIfWindowNodeIsRemoved() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.EvaluateAsync("delete window.Node"); await Page.ClickAsync("button"); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click on a span with an inline element inside")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickOnASpanWithAnInlineElementInside() { await Page.SetContentAsync($@" @@ -64,39 +56,39 @@ await Page.SetContentAsync($@" "); await Page.ClickAsync("span"); - Assert.Equal(42, await Page.EvaluateAsync("() => window.CLICKED")); + Assert.That(await Page.EvaluateAsync("() => window.CLICKED"), Is.EqualTo(42)); } [PlaywrightTest("page-click.spec.ts", "should not throw UnhandledPromiseRejection when page closes")] - [Fact(Skip = "We don't need to test this race condition")] + [Test, Ignore("We don't need to test this race condition")] public void ShouldGracefullyFailWhenPageCloses() { } [PlaywrightTest("page-click.spec.ts", "should click the button after navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickTheButtonAfterNavigation() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.ClickAsync("button"); await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.ClickAsync("button"); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click the button after a cross origin navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickTheButtonAfterACrossOriginNavigation() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.ClickAsync("button"); await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/input/button.html"); await Page.ClickAsync("button"); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click with disabled javascript")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickWithDisabledJavascript() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions { JavaScriptEnabled = false }); @@ -106,11 +98,11 @@ await TaskUtils.WhenAll( page.ClickAsync("a"), page.WaitForNavigationAsync() ); - Assert.Equal(TestConstants.ServerUrl + "/wrappedlink.html#clicked", page.Url); + Assert.That(page.Url, Is.EqualTo(TestConstants.ServerUrl + "/wrappedlink.html#clicked")); } [PlaywrightTest("page-click.spec.ts", "should click when one of inline box children is outside of viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickWhenOneOfInlineBoxChildrenIsOutsideOfViewport() { await Page.SetContentAsync($@" @@ -124,25 +116,25 @@ await Page.SetContentAsync($@" "); await Page.ClickAsync("span"); - Assert.Equal(42, await Page.EvaluateAsync("() => window.CLICKED")); + Assert.That(await Page.EvaluateAsync("() => window.CLICKED"), Is.EqualTo(42)); } [PlaywrightTest("page-click.spec.ts", "should select the text by triple clicking")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectTheTextByTripleClicking() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); const string text = "This is the text that we are going to try to select. Let's see how it goes."; await Page.FillAsync("textarea", text); await Page.ClickAsync("textarea", clickCount: 3); - Assert.Equal(text, await Page.EvaluateAsync(@"() => { + Assert.That(await Page.EvaluateAsync(@"() => { const textarea = document.querySelector('textarea'); return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd); - }")); + }"), Is.EqualTo(text)); } [PlaywrightTest("page-click.spec.ts", "should click offscreen buttons")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickOffscreenButtons() { await Page.GoToAsync(TestConstants.ServerUrl + "/offscreenbuttons.html"); @@ -155,7 +147,7 @@ public async Task ShouldClickOffscreenButtons() await Page.EvaluateAsync("() => window.scrollTo(0, 0)"); await Page.ClickAsync($"#btn{i}"); } - Assert.Equal(new List + Assert.That(messages, Is.EqualTo(new List { "button #0 clicked", "button #1 clicked", @@ -168,34 +160,34 @@ public async Task ShouldClickOffscreenButtons() "button #8 clicked", "button #9 clicked", "button #10 clicked" - }, messages); + })); } [PlaywrightTest("page-click.spec.ts", "should waitFor visible when already visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForVisibleWhenAlreadyVisible() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.ClickAsync("button"); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should not wait with force")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotWaitWithForce() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.EvalOnSelectorAsync("button", "b => b.style.display = 'none'"); - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => Page.ClickAsync("button", force: true)); - Assert.Contains("Element is not visible", exception.Message); - Assert.Equal("Was not clicked", await Page.EvaluateAsync("result")); + Assert.That(exception.Message, Does.Contain("Element is not visible")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Was not clicked")); } [PlaywrightTest("page-click.spec.ts", "should waitFor display:none to be gone")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForDisplayNoneToBeGone() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -204,17 +196,17 @@ public async Task ShouldWaitForDisplayNoneToBeGone() await GiveItAChanceToClick(Page); - Assert.False(clickTask.IsCompleted); - Assert.Equal("Was not clicked", await Page.EvaluateAsync("result")); + Assert.That(clickTask.IsCompleted, Is.False); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Was not clicked")); await Page.EvalOnSelectorAsync("button", "b => b.style.display = 'block'"); await clickTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should waitFor visibility:hidden to be gone")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForVisibilityhiddenToBeGone() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -223,17 +215,17 @@ public async Task ShouldWaitForVisibilityhiddenToBeGone() await GiveItAChanceToClick(Page); - Assert.False(clickTask.IsCompleted); - Assert.Equal("Was not clicked", await Page.EvaluateAsync("result")); + Assert.That(clickTask.IsCompleted, Is.False); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Was not clicked")); await Page.EvalOnSelectorAsync("button", "b => b.style.visibility = 'visible'"); await clickTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should waitFor visible when parent is hidden")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForVisibleWhenParentIsHidden() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -242,33 +234,33 @@ public async Task ShouldWaitForVisibleWhenParentIsHidden() await GiveItAChanceToClick(Page); - Assert.False(clickTask.IsCompleted); - Assert.Equal("Was not clicked", await Page.EvaluateAsync("result")); + Assert.That(clickTask.IsCompleted, Is.False); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Was not clicked")); await Page.EvalOnSelectorAsync("button", "b => b.parentElement.style.display = 'block'"); await clickTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click wrapped links")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickWrappedLinks() { await Page.GoToAsync(TestConstants.ServerUrl + "/wrappedlink.html"); await Page.ClickAsync("a"); - Assert.True(await Page.EvaluateAsync("window.__clicked")); + Assert.That(await Page.EvaluateAsync("window.__clicked"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should click on checkbox input and toggle")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickOnCheckboxInputAndToggle() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/checkbox.html"); - Assert.Null(await Page.EvaluateAsync("result.check")); + Assert.That(await Page.EvaluateAsync("result.check"), Is.Null); await Page.ClickAsync("input#agree"); - Assert.True(await Page.EvaluateAsync("result.check")); - Assert.Equal(new[] { + Assert.That(await Page.EvaluateAsync("result.check"), Is.True); + Assert.That(await Page.EvaluateAsync("result.events"), Is.EqualTo(new[] { "mouseover", "mouseenter", "mousemove", @@ -277,30 +269,30 @@ public async Task ShouldClickOnCheckboxInputAndToggle() "click", "input", "change" - }, await Page.EvaluateAsync("result.events")); + })); await Page.ClickAsync("input#agree"); - Assert.False(await Page.EvaluateAsync("result.check")); + Assert.That(await Page.EvaluateAsync("result.check"), Is.False); } [PlaywrightTest("page-click.spec.ts", "should click on checkbox label and toggle")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickOnCheckboxLabelAndToggle() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/checkbox.html"); - Assert.Null(await Page.EvaluateAsync("result.check")); + Assert.That(await Page.EvaluateAsync("result.check"), Is.Null); await Page.ClickAsync("label[for=\"agree\"]"); - Assert.True(await Page.EvaluateAsync("result.check")); - Assert.Equal(new[] { + Assert.That(await Page.EvaluateAsync("result.check"), Is.True); + Assert.That(await Page.EvaluateAsync("result.events"), Is.EqualTo(new[] { "click", "input", "change" - }, await Page.EvaluateAsync("result.events")); + })); await Page.ClickAsync("label[for=\"agree\"]"); - Assert.False(await Page.EvaluateAsync("result.check")); + Assert.That(await Page.EvaluateAsync("result.check"), Is.False); } [PlaywrightTest("page-click.spec.ts", "should not hang with touch-enabled viewports")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotHangWithTouchEnabledViewports() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -316,18 +308,18 @@ public async Task ShouldNotHangWithTouchEnabledViewports() } [PlaywrightTest("page-click.spec.ts", "should scroll and click the button")] - [Fact(Skip = "Flacky")] + [Test, Ignore("Flacky")] public async Task ShouldScrollAndClickTheButton() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/scrollable.html"); await Page.ClickAsync("#button-5"); - Assert.Equal("clicked", await Page.EvaluateAsync("document.querySelector(\"#button-5\").textContent")); + Assert.That(await Page.EvaluateAsync("document.querySelector(\"#button-5\").textContent"), Is.EqualTo("clicked")); await Page.ClickAsync("#button-80"); - Assert.Equal("clicked", await Page.EvaluateAsync("document.querySelector(\"#button-80\").textContent")); + Assert.That(await Page.EvaluateAsync("document.querySelector(\"#button-80\").textContent"), Is.EqualTo("clicked")); } [PlaywrightTest("page-click.spec.ts", "should double click the button")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDoubleClickTheButton() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -340,12 +332,12 @@ await Page.EvaluateAsync(@"{ }"); var button = await Page.QuerySelectorAsync("button"); await button.DblClickAsync(); - Assert.True(await Page.EvaluateAsync("double")); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("double"), Is.True); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click a partially obscured button")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickAPartiallyObscuredButton() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -357,29 +349,29 @@ await Page.EvaluateAsync(@"{ button.style.left = '368px'; }"); await Page.ClickAsync("button"); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click a rotated button")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickARotatedButton() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/rotatedButton.html"); await Page.ClickAsync("button"); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should fire contextmenu event on right click")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFireContextmenuEventOnRightClick() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/scrollable.html"); await Page.ClickAsync("#button-8", button: MouseButton.Right); - Assert.Equal("context menu", await Page.EvaluateAsync("document.querySelector('#button-8').textContent")); + Assert.That(await Page.EvaluateAsync("document.querySelector('#button-8').textContent"), Is.EqualTo("context menu")); } [PlaywrightTest("page-click.spec.ts", "should click links which cause navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickLinksWhichCauseNavigation() { await Page.SetContentAsync($"empty.html"); @@ -388,7 +380,7 @@ public async Task ShouldClickLinksWhichCauseNavigation() } [PlaywrightTest("page-click.spec.ts", "should click the button inside an iframe")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickTheButtonInsideAnIframe() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -397,7 +389,7 @@ public async Task ShouldClickTheButtonInsideAnIframe() var frame = Page.FirstChildFrame(); var button = await frame.QuerySelectorAsync("button"); await button.ClickAsync(); - Assert.Equal("Clicked", await frame.EvaluateAsync("window.result")); + Assert.That(await frame.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click the button with fixed position inside an iframe")] @@ -411,11 +403,11 @@ public async Task ShouldClickTheButtonWithFixedPositionInsideAnIframe() var frame = Page.FirstChildFrame(); await frame.EvalOnSelectorAsync("button", "button => button.style.setProperty('position', 'fixed')"); await frame.ClickAsync("button"); - Assert.Equal("Clicked", await frame.EvaluateAsync("window.result")); + Assert.That(await frame.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click the button with deviceScaleFactor set")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickTheButtonWithDeviceScaleFactorSet() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -429,58 +421,58 @@ public async Task ShouldClickTheButtonWithDeviceScaleFactorSet() }); var page = await context.NewPageAsync(); - Assert.Equal(5, await page.EvaluateAsync("window.devicePixelRatio")); + Assert.That(await page.EvaluateAsync("window.devicePixelRatio"), Is.EqualTo(5)); await page.SetContentAsync("
spacer
"); await FrameUtils.AttachFrameAsync(page, "button-test", TestConstants.ServerUrl + "/input/button.html"); var frame = page.FirstChildFrame(); var button = await frame.QuerySelectorAsync("button"); await button.ClickAsync(); - Assert.Equal("Clicked", await frame.EvaluateAsync("window.result")); + Assert.That(await frame.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should click the button with px border with relative point")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickTheButtonWithPxBorderWithRelativePoint() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.EvalOnSelectorAsync("button", "button => button.style.borderWidth = '8px'"); await Page.ClickAsync("button", position: new Position { X = 20, Y = 10 }); - Assert.Equal("Clicked", await Page.EvaluateAsync("window.result")); + Assert.That(await Page.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); // Safari reports border-relative offsetX/offsetY. - Assert.Equal(TestConstants.IsWebKit ? 20 + 8 : 20, await Page.EvaluateAsync("offsetX")); - Assert.Equal(TestConstants.IsWebKit ? 10 + 8 : 10, await Page.EvaluateAsync("offsetY")); + Assert.That(await Page.EvaluateAsync("offsetX"), Is.EqualTo(TestConstants.IsWebKit ? 20 + 8 : 20)); + Assert.That(await Page.EvaluateAsync("offsetY"), Is.EqualTo(TestConstants.IsWebKit ? 10 + 8 : 10)); } [PlaywrightTest("page-click.spec.ts", "should click the button with em border with offset")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickTheButtonWithEmBorderWithOffset() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.EvalOnSelectorAsync("button", "button => button.style.borderWidth = '2em'"); await Page.EvalOnSelectorAsync("button", "button => button.style.fontSize = '12px'"); await Page.ClickAsync("button", position: new Position { X = 20, Y = 10 }); - Assert.Equal("Clicked", await Page.EvaluateAsync("window.result")); + Assert.That(await Page.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); // Safari reports border-relative offsetX/offsetY. - Assert.Equal(TestConstants.IsWebKit ? 12 * 2 + 20 : 20, await Page.EvaluateAsync("offsetX")); - Assert.Equal(TestConstants.IsWebKit ? 12 * 2 + 10 : 10, await Page.EvaluateAsync("offsetY")); + Assert.That(await Page.EvaluateAsync("offsetX"), Is.EqualTo(TestConstants.IsWebKit ? 12 * 2 + 20 : 20)); + Assert.That(await Page.EvaluateAsync("offsetY"), Is.EqualTo(TestConstants.IsWebKit ? 12 * 2 + 10 : 10)); } [PlaywrightTest("page-click.spec.ts", "should click a very large button with offset")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickAVeryLargeButtonWithOffset() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.EvalOnSelectorAsync("button", "button => button.style.borderWidth = '8px'"); await Page.EvalOnSelectorAsync("button", "button => button.style.height = button.style.width = '2000px'"); await Page.ClickAsync("button", position: new Position { X = 1900, Y = 1910 }); - Assert.Equal("Clicked", await Page.EvaluateAsync("window.result")); + Assert.That(await Page.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); // Safari reports border-relative offsetX/offsetY. - Assert.Equal(TestConstants.IsWebKit ? 1900 + 8 : 1900, await Page.EvaluateAsync("offsetX")); - Assert.Equal(TestConstants.IsWebKit ? 1910 + 8 : 1910, await Page.EvaluateAsync("offsetY")); + Assert.That(await Page.EvaluateAsync("offsetX"), Is.EqualTo(TestConstants.IsWebKit ? 1900 + 8 : 1900)); + Assert.That(await Page.EvaluateAsync("offsetY"), Is.EqualTo(TestConstants.IsWebKit ? 1910 + 8 : 1910)); } [PlaywrightTest("page-click.spec.ts", "should click a button in scrolling container with offset")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickAButtonInScrollingContainerWithOffset() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -497,10 +489,10 @@ await Page.EvalOnSelectorAsync("button", @"button => { }"); await Page.ClickAsync("button", position: new Position { X = 1900, Y = 1910 }); - Assert.Equal("Clicked", await Page.EvaluateAsync("window.result")); + Assert.That(await Page.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); // Safari reports border-relative offsetX/offsetY. - Assert.Equal(TestConstants.IsWebKit ? 1900 + 8 : 1900, await Page.EvaluateAsync("offsetX")); - Assert.Equal(TestConstants.IsWebKit ? 1910 + 8 : 1910, await Page.EvaluateAsync("offsetY")); + Assert.That(await Page.EvaluateAsync("offsetX"), Is.EqualTo(TestConstants.IsWebKit ? 1900 + 8 : 1900)); + Assert.That(await Page.EvaluateAsync("offsetY"), Is.EqualTo(TestConstants.IsWebKit ? 1910 + 8 : 1910)); } [PlaywrightTest("page-click.spec.ts", "should click the button with offset with page scale")] @@ -526,7 +518,7 @@ await page.EvalOnSelectorAsync("button", @"button => { }"); await page.ClickAsync("button", position: new Position { X = 20, Y = 10 }); - Assert.Equal("Clicked", await page.EvaluateAsync("window.result")); + Assert.That(await page.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); var point = TestConstants.Product switch { @@ -535,12 +527,12 @@ await page.EvalOnSelectorAsync("button", @"button => { _ => new Point(28, 18), }; - Assert.Equal(point.X, Convert.ToInt32(await page.EvaluateAsync("pageX"))); - Assert.Equal(point.Y, Convert.ToInt32(await page.EvaluateAsync("pageY"))); + Assert.That(Convert.ToInt32(await page.EvaluateAsync("pageX")), Is.EqualTo(point.X)); + Assert.That(Convert.ToInt32(await page.EvaluateAsync("pageY")), Is.EqualTo(point.Y)); } [PlaywrightTest("page-click.spec.ts", "should wait for stable position")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForStablePosition() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -557,13 +549,13 @@ await Page.EvalOnSelectorAsync("button", @"button => { }"); await Page.ClickAsync("button"); - Assert.Equal("Clicked", await Page.EvaluateAsync("window.result")); - Assert.Equal(300, await Page.EvaluateAsync("pageX")); - Assert.Equal(10, await Page.EvaluateAsync("pageY")); + Assert.That(await Page.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); + Assert.That(await Page.EvaluateAsync("pageX"), Is.EqualTo(300)); + Assert.That(await Page.EvaluateAsync("pageY"), Is.EqualTo(10)); } [PlaywrightTest("page-click.spec.ts", "should wait for becoming hit target")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForBecomingHitTarget() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -585,19 +577,19 @@ await Page.EvalOnSelectorAsync("button", @"button => { }"); var clickTask = Page.ClickAsync("button"); - Assert.False(clickTask.IsCompleted); + Assert.That(clickTask.IsCompleted, Is.False); await Page.EvalOnSelectorAsync(".flyover", "flyOver => flyOver.style.left = '0'"); await GiveItAChanceToClick(Page); - Assert.False(clickTask.IsCompleted); + Assert.That(clickTask.IsCompleted, Is.False); await Page.EvalOnSelectorAsync(".flyover", "flyOver => flyOver.style.left = '200px'"); await clickTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.Equal("Clicked", await Page.EvaluateAsync("window.result")); + Assert.That(await Page.EvaluateAsync("window.result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-click.spec.ts", "should fail when obscured and not waiting for hit target")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenObscuredAndNotWaitingForHitTarget() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -614,94 +606,94 @@ await Page.EvalOnSelectorAsync("button", @"button => { }"); await button.ClickAsync(force: true); - Assert.Equal("Was not clicked", await Page.EvaluateAsync("window.result")); + Assert.That(await Page.EvaluateAsync("window.result"), Is.EqualTo("Was not clicked")); } [PlaywrightTest("page-click.spec.ts", "should wait for button to be enabled")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForButtonToBeEnabled() { await Page.SetContentAsync(""); var clickTask = Page.ClickAsync("text=Click target"); await GiveItAChanceToClick(Page); - Assert.Null(await Page.EvaluateAsync("window.__CLICKED")); - Assert.False(clickTask.IsCompleted); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.Null); + Assert.That(clickTask.IsCompleted, Is.False); await Page.EvaluateAsync("() => document.querySelector('button').removeAttribute('disabled')"); await clickTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.True(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should wait for input to be enabled")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForInputToBeEnabled() { await Page.SetContentAsync(""); var clickTask = Page.ClickAsync("input"); await GiveItAChanceToClick(Page); - Assert.Null(await Page.EvaluateAsync("window.__CLICKED")); - Assert.False(clickTask.IsCompleted); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.Null); + Assert.That(clickTask.IsCompleted, Is.False); await Page.EvaluateAsync("() => document.querySelector('input').removeAttribute('disabled')"); await clickTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.True(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should wait for select to be enabled")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForSelectToBeEnabled() { await Page.SetContentAsync(""); var clickTask = Page.ClickAsync("select"); await GiveItAChanceToClick(Page); - Assert.Null(await Page.EvaluateAsync("window.__CLICKED")); - Assert.False(clickTask.IsCompleted); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.Null); + Assert.That(clickTask.IsCompleted, Is.False); await Page.EvaluateAsync("() => document.querySelector('select').removeAttribute('disabled')"); await clickTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.True(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should click disabled div")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickDisabledDiv() { await Page.SetContentAsync("
Click target
"); await Page.ClickAsync("text=Click target"); - Assert.True(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should climb dom for inner label with pointer-events:none")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClimbDomForInnerLabelWithPointerEventsNone() { await Page.SetContentAsync(""); await Page.ClickAsync("text=Click target"); - Assert.True(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should climb up to [role=button]")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClimbUpToRoleButton() { await Page.SetContentAsync("
Click target
"); await Page.ClickAsync("text=Click target"); - Assert.True(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should wait for BUTTON to be clickable when it has pointer-events:none")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForButtonToBeClickableWhenItHasPointerEventsNone() { await Page.SetContentAsync(""); var clickTask = Page.ClickAsync("text=Click target"); await GiveItAChanceToClick(Page); - Assert.Null(await Page.EvaluateAsync("window.__CLICKED")); - Assert.False(clickTask.IsCompleted); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.Null); + Assert.That(clickTask.IsCompleted, Is.False); await Page.EvaluateAsync("() => document.querySelector('button').style.removeProperty('pointer-events')"); await clickTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.True(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should wait for LABEL to be clickable when it has pointer-events:none")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForLabelToBeClickableWhenItHasPointerEventsNone() { await Page.SetContentAsync(""); @@ -709,41 +701,41 @@ public async Task ShouldWaitForLabelToBeClickableWhenItHasPointerEventsNone() for (int i = 0; i < 5; ++i) { - Assert.Null(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.Null); } - Assert.False(clickTask.IsCompleted); + Assert.That(clickTask.IsCompleted, Is.False); await Page.EvaluateAsync("() => document.querySelector('label').style.removeProperty('pointer-events')"); await clickTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.True(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should update modifiers correctly")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUpdateModifiersCorrectly() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.ClickAsync("button", modifiers: new[] { KeyboardModifier.Shift }); - Assert.True(await Page.EvaluateAsync("shiftKey")); + Assert.That(await Page.EvaluateAsync("shiftKey"), Is.True); await Page.ClickAsync("button", modifiers: Array.Empty()); - Assert.False(await Page.EvaluateAsync("shiftKey")); + Assert.That(await Page.EvaluateAsync("shiftKey"), Is.False); await Page.Keyboard.DownAsync("Shift"); await Page.ClickAsync("button", modifiers: Array.Empty()); - Assert.False(await Page.EvaluateAsync("shiftKey")); + Assert.That(await Page.EvaluateAsync("shiftKey"), Is.False); await Page.ClickAsync("button"); - Assert.True(await Page.EvaluateAsync("shiftKey")); + Assert.That(await Page.EvaluateAsync("shiftKey"), Is.True); await Page.Keyboard.UpAsync("Shift"); await Page.ClickAsync("button"); - Assert.False(await Page.EvaluateAsync("shiftKey")); + Assert.That(await Page.EvaluateAsync("shiftKey"), Is.False); } [PlaywrightTest("page-click.spec.ts", "should click an offscreen element when scroll-behavior is smooth")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickAnOffscreenElementWhenScrollBehaviorIsSmooth() { await Page.SetContentAsync(@$" @@ -752,11 +744,11 @@ await Page.SetContentAsync(@$"
"); await Page.ClickAsync("button"); - Assert.True(await Page.EvaluateAsync("window.clicked")); + Assert.That(await Page.EvaluateAsync("window.clicked"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should report nice error when element is detached and force-clicked")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportNiceErrorWhenElementIsDetachedAndForceClicked() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/animating-button.html"); @@ -764,13 +756,13 @@ public async Task ShouldReportNiceErrorWhenElementIsDetachedAndForceClicked() var handle = await Page.QuerySelectorAsync("button"); await Page.EvaluateAsync("() => stopButton(true)"); var clickTask = handle.ClickAsync(force: true); - var exception = await Assert.ThrowsAsync(() => clickTask); - Assert.Null(await Page.EvaluateAsync("window.clicked")); - Assert.Contains("Element is not attached to the DOM", exception.Message); + var exception = Assert.ThrowsAsync(() => clickTask); + Assert.That(await Page.EvaluateAsync("window.clicked"), Is.Null); + Assert.That(exception.Message, Does.Contain("Element is not attached to the DOM")); } [PlaywrightTest("page-click.spec.ts", "should fail when element detaches after animation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenElementDetachesAfterAnimation() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/animating-button.html"); @@ -778,35 +770,35 @@ public async Task ShouldFailWhenElementDetachesAfterAnimation() var handle = await Page.QuerySelectorAsync("button"); var clickTask = handle.ClickAsync(); await Page.EvaluateAsync("() => stopButton(true)"); - var exception = await Assert.ThrowsAsync(() => clickTask); - Assert.Null(await Page.EvaluateAsync("window.clicked")); - Assert.Contains("Element is not attached to the DOM", exception.Message); + var exception = Assert.ThrowsAsync(() => clickTask); + Assert.That(await Page.EvaluateAsync("window.clicked"), Is.Null); + Assert.That(exception.Message, Does.Contain("Element is not attached to the DOM")); } [PlaywrightTest("page-click.spec.ts", "should retry when element detaches after animation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRetryWhenElementDetachesAfterAnimation() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/animating-button.html"); await Page.EvaluateAsync("() => addButton()"); var clickTask = Page.ClickAsync("button"); - Assert.False(clickTask.IsCompleted); - Assert.Null(await Page.EvaluateAsync("window.clicked")); + Assert.That(clickTask.IsCompleted, Is.False); + Assert.That(await Page.EvaluateAsync("window.clicked"), Is.Null); await Page.EvaluateAsync("() => stopButton(true)"); await Page.EvaluateAsync("() => addButton()"); - Assert.False(clickTask.IsCompleted); - Assert.Null(await Page.EvaluateAsync("window.clicked")); + Assert.That(clickTask.IsCompleted, Is.False); + Assert.That(await Page.EvaluateAsync("window.clicked"), Is.Null); await Page.EvaluateAsync("() => stopButton(true)"); await Page.EvaluateAsync("() => addButton()"); - Assert.False(clickTask.IsCompleted); - Assert.Null(await Page.EvaluateAsync("window.clicked")); + Assert.That(clickTask.IsCompleted, Is.False); + Assert.That(await Page.EvaluateAsync("window.clicked"), Is.Null); await Page.EvaluateAsync("() => stopButton(false)"); await clickTask; - Assert.True(await Page.EvaluateAsync("window.clicked")); + Assert.That(await Page.EvaluateAsync("window.clicked"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should retry when element is animating from outside the viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRetryWhenElementIsAnimatingFromOutsideTheViewport() { await Page.SetContentAsync($@" @@ -834,11 +826,11 @@ @keyframes move {{ var clickTask = handle.ClickAsync(); await handle.EvaluateAsync("button => button.className = 'animated'"); await clickTask; - Assert.True(await Page.EvaluateAsync("window.clicked")); + Assert.That(await Page.EvaluateAsync("window.clicked"), Is.True); } [PlaywrightTest("page-click.spec.ts", "should retry when element is animating from outside the viewport with force")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRetryWhenElementIsAnimatingFromOutsideTheViewportWithForce() { await Page.SetContentAsync($@" @@ -865,13 +857,13 @@ @keyframes move {{ var handle = await Page.QuerySelectorAsync("button"); var clickTask = handle.ClickAsync(force: true); await handle.EvaluateAsync("button => button.className = 'animated'"); - var exception = await Assert.ThrowsAsync(() => clickTask); - Assert.Null(await Page.EvaluateAsync("window.clicked")); - Assert.Contains("Element is outside of the viewport", exception.Message); + var exception = Assert.ThrowsAsync(() => clickTask); + Assert.That(await Page.EvaluateAsync("window.clicked"), Is.Null); + Assert.That(exception.Message, Does.Contain("Element is outside of the viewport")); } [PlaywrightTest("page-click.spec.ts", "should dispatch microtasks in order")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDispatchMicrotasksInOrder() { await Page.SetContentAsync($@" @@ -893,18 +885,18 @@ await Page.SetContentAsync($@" "); await Page.ClickAsync("button"); - Assert.Equal(1, await Page.EvaluateAsync("window.result")); + Assert.That(await Page.EvaluateAsync("window.result"), Is.EqualTo(1)); } [PlaywrightTest("page-click.spec.ts", "should click the button when window.innerWidth is corrupted")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClickTheButtonWhenWindowInnerWidthIsCorrupted() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.EvaluateAsync(@"() => window.innerWith = 0"); await Page.ClickAsync("button"); - Assert.Equal("Clicked", await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo("Clicked")); } private async Task GiveItAChanceToClick(IPage page) diff --git a/src/Playwright.Tests/PageClickTimeout1Tests.cs b/src/Playwright.Tests/PageClickTimeout1Tests.cs index 982f952faa..1aa1282951 100644 --- a/src/Playwright.Tests/PageClickTimeout1Tests.cs +++ b/src/Playwright.Tests/PageClickTimeout1Tests.cs @@ -1,38 +1,30 @@ using System; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageClickTimeout1Tests : PlaywrightSharpPageBaseTest - { - /// - public PageClickTimeout1Tests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-click-timeout-1.spec.ts", "should avoid side effects after timeout")] - [Fact(Skip = "Ignore USES_HOOKS")] + { [PlaywrightTest("page-click-timeout-1.spec.ts", "should avoid side effects after timeout")] + [Test, Ignore("Ignore USES_HOOKS")] public void ShouldAvoidSideEffectsAfterTimeout() { } [PlaywrightTest("page-click-timeout-1.spec.ts", "should timeout waiting for button to be enabled")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWaitingForButtonToBeEnabled() { await Page.SetContentAsync(""); var clickTask = Page.ClickAsync("text=Click target", timeout: 3000); - Assert.Null(await Page.EvaluateAsync("window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("window.__CLICKED"), Is.Null); - var exception = await Assert.ThrowsAsync(() => clickTask); + var exception = Assert.ThrowsAsync(() => clickTask); - Assert.Contains("Timeout 3000ms exceeded", exception.Message); - Assert.Contains("element is not enabled - waiting", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 3000ms exceeded")); + Assert.That(exception.Message, Does.Contain("element is not enabled - waiting")); } } } diff --git a/src/Playwright.Tests/PageClickTimeout2Tests.cs b/src/Playwright.Tests/PageClickTimeout2Tests.cs index b609824aed..1c29de76fb 100644 --- a/src/Playwright.Tests/PageClickTimeout2Tests.cs +++ b/src/Playwright.Tests/PageClickTimeout2Tests.cs @@ -3,49 +3,41 @@ using System.Drawing; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageClickTimeout2Tests : PlaywrightSharpPageBaseTest - { - /// - public PageClickTimeout2Tests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-click-timeout-2.spec.ts", "should timeout waiting for display:none to be gone")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-click-timeout-2.spec.ts", "should timeout waiting for display:none to be gone")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWaitingForDisplayNoneToBeGone() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.EvalOnSelectorAsync("button", "b => b.style.display = 'none'"); - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => Page.ClickAsync("button", timeout: 5000)); - Assert.Contains("Timeout 5000ms exceeded", exception.Message); - Assert.Contains("waiting for element to be visible, enabled and stable", exception.Message); - Assert.Contains("element is not visible - waiting", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 5000ms exceeded")); + Assert.That(exception.Message, Does.Contain("waiting for element to be visible, enabled and stable")); + Assert.That(exception.Message, Does.Contain("element is not visible - waiting")); } [PlaywrightTest("page-click-timeout-2.spec.ts", "should timeout waiting for visbility:hidden to be gone")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWaitingForVisbilityHiddenToBeGone() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.EvalOnSelectorAsync("button", "b => b.style.visibility = 'hidden'"); var clickTask = Page.ClickAsync("button", timeout: 5000); - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => Page.ClickAsync("button", timeout: 5000)); - Assert.Contains("Timeout 5000ms exceeded", exception.Message); - Assert.Contains("waiting for element to be visible, enabled and stable", exception.Message); - Assert.Contains("element is not visible - waiting", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 5000ms exceeded")); + Assert.That(exception.Message, Does.Contain("waiting for element to be visible, enabled and stable")); + Assert.That(exception.Message, Does.Contain("element is not visible - waiting")); } } diff --git a/src/Playwright.Tests/PageClickTimeout3Tests.cs b/src/Playwright.Tests/PageClickTimeout3Tests.cs index 41555596bd..01a780b647 100644 --- a/src/Playwright.Tests/PageClickTimeout3Tests.cs +++ b/src/Playwright.Tests/PageClickTimeout3Tests.cs @@ -3,30 +3,22 @@ using System.Drawing; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageClickTimeout3Tests : PlaywrightSharpPageBaseTest - { - /// - public PageClickTimeout3Tests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-click-timeout-3.spec.ts", "should fail when element jumps during hit testing")] - [Fact(Skip = " Skip USES_HOOKS")] + { [PlaywrightTest("page-click-timeout-3.spec.ts", "should fail when element jumps during hit testing")] + [Test, Ignore(" Skip USES_HOOKS")] public void ShouldFailWhenElementJumpsDuringHitTesting() { } [PlaywrightTest("page-click-timeout-3.spec.ts", "should timeout waiting for hit target")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWaitingForHitTarget() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -49,10 +41,10 @@ await Page.EvalOnSelectorAsync("button", @"button => { document.body.appendChild(flyOver); }"); - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => button.ClickAsync(timeout: 5000)); - Assert.Contains("Timeout 5000ms exceeded.", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 5000ms exceeded.")); } } } diff --git a/src/Playwright.Tests/PageClickTimeout4Tests.cs b/src/Playwright.Tests/PageClickTimeout4Tests.cs index 91ab6447af..168da973f6 100644 --- a/src/Playwright.Tests/PageClickTimeout4Tests.cs +++ b/src/Playwright.Tests/PageClickTimeout4Tests.cs @@ -3,24 +3,16 @@ using System.Drawing; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageClickTimeout4Tests : PlaywrightSharpPageBaseTest - { - /// - public PageClickTimeout4Tests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-click-timeout-4.spec.ts", "should timeout waiting for stable position")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-click-timeout-4.spec.ts", "should timeout waiting for stable position")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeoutWaitingForStablePosition() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); @@ -29,12 +21,12 @@ await Page.EvalOnSelectorAsync("button", @"button => { button.style.marginLeft = '200px'; }"); - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => Page.ClickAsync("button", timeout: 3000)); - Assert.Contains("Timeout 3000ms exceeded", exception.Message); - Assert.Contains("waiting for element to be visible, enabled and stable", exception.Message); - Assert.Contains("element is not stable - waiting", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 3000ms exceeded")); + Assert.That(exception.Message, Does.Contain("waiting for element to be visible, enabled and stable")); + Assert.That(exception.Message, Does.Contain("element is not stable - waiting")); } } } diff --git a/src/Playwright.Tests/PageCloseTests.cs b/src/Playwright.Tests/PageCloseTests.cs index 9c412f6ccb..875ed4a00c 100644 --- a/src/Playwright.Tests/PageCloseTests.cs +++ b/src/Playwright.Tests/PageCloseTests.cs @@ -1,18 +1,10 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageCloseTests : PlaywrightSharpPageBaseTest - { - /// - public PageCloseTests(ITestOutputHelper output) : base(output) - { - } - - } + { } } diff --git a/src/Playwright.Tests/PageDialogTests.cs b/src/Playwright.Tests/PageDialogTests.cs index 493444de52..88fe6ec340 100644 --- a/src/Playwright.Tests/PageDialogTests.cs +++ b/src/Playwright.Tests/PageDialogTests.cs @@ -1,29 +1,21 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageDialogTests : PlaywrightSharpPageBaseTest - { - /// - public PageDialogTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-dialog.spec.ts", "should fire")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-dialog.spec.ts", "should fire")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFire() { Page.Dialog += async (_, e) => { - Assert.Equal(DialogType.Alert, e.Type); - Assert.Equal(string.Empty, e.DefaultValue); - Assert.Equal("yo", e.Message); + Assert.That(e.Type, Is.EqualTo(DialogType.Alert)); + Assert.That(e.DefaultValue, Is.EqualTo(string.Empty)); + Assert.That(e.Message, Is.EqualTo("yo")); await e.AcceptAsync(); }; @@ -32,24 +24,24 @@ public async Task ShouldFire() } [PlaywrightTest("page-dialog.spec.ts", "should allow accepting prompts")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAllowAcceptingPrompts() { Page.Dialog += async (_, e) => { - Assert.Equal(DialogType.Prompt, e.Type); - Assert.Equal("yes.", e.DefaultValue); - Assert.Equal("question?", e.Message); + Assert.That(e.Type, Is.EqualTo(DialogType.Prompt)); + Assert.That(e.DefaultValue, Is.EqualTo("yes.")); + Assert.That(e.Message, Is.EqualTo("question?")); await e.AcceptAsync("answer!"); }; string result = await Page.EvaluateAsync("prompt('question?', 'yes.')"); - Assert.Equal("answer!", result); + Assert.That(result, Is.EqualTo("answer!")); } [PlaywrightTest("page-dialog.spec.ts", "should dismiss the prompt")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDismissThePrompt() { Page.Dialog += async (_, e) => @@ -58,11 +50,11 @@ public async Task ShouldDismissThePrompt() }; string result = await Page.EvaluateAsync("prompt('question?')"); - Assert.Null(result); + Assert.That(result, Is.Null); } [PlaywrightTest("page-dialog.spec.ts", "should accept the confirm prompt")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptTheConfirmPrompts() { Page.Dialog += async (_, e) => @@ -71,11 +63,11 @@ public async Task ShouldAcceptTheConfirmPrompts() }; bool result = await Page.EvaluateAsync("confirm('boolean?')"); - Assert.True(result); + Assert.That(result, Is.True); } [PlaywrightTest("page-dialog.spec.ts", "should dismiss the confirm prompt")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDismissTheConfirmPrompt() { Page.Dialog += async (_, e) => @@ -84,11 +76,11 @@ public async Task ShouldDismissTheConfirmPrompt() }; bool result = await Page.EvaluateAsync("prompt('boolean?')"); - Assert.False(result); + Assert.That(result, Is.False); } [PlaywrightTest("page-dialog.spec.ts", "should log prompt actions")] - [Fact(Skip = "FAIL CHANNEL")] + [Test, Ignore("FAIL CHANNEL")] public async Task ShouldLogPromptActions() { Page.Dialog += async (_, e) => @@ -97,7 +89,7 @@ public async Task ShouldLogPromptActions() }; bool result = await Page.EvaluateAsync("prompt('boolean?')"); - Assert.False(result); + Assert.That(result, Is.False); } [PlaywrightTest("page-dialog.spec.ts", "should be able to close context with open alert")] diff --git a/src/Playwright.Tests/PageDispatchEventTests.cs b/src/Playwright.Tests/PageDispatchEventTests.cs index 3b664904d8..35d6a1e31b 100644 --- a/src/Playwright.Tests/PageDispatchEventTests.cs +++ b/src/Playwright.Tests/PageDispatchEventTests.cs @@ -1,43 +1,35 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///dispatchevent.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageDispatchEventTests : PlaywrightSharpPageBaseTest - { - /// - public PageDispatchEventTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-dispatchevent.spec.ts", "should dispatch click event")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-dispatchevent.spec.ts", "should dispatch click event")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDispatchClickEvent() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.DispatchEventAsync("button", "click"); - Assert.Equal("Clicked", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-dispatchevent.spec.ts", "should dispatch click event properties")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDispatchClickEventProperties() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.DispatchEventAsync("button", "click"); - Assert.True(await Page.EvaluateAsync("() => bubbles")); - Assert.True(await Page.EvaluateAsync("() => cancelable")); - Assert.True(await Page.EvaluateAsync("() => composed")); + Assert.That(await Page.EvaluateAsync("() => bubbles"), Is.True); + Assert.That(await Page.EvaluateAsync("() => cancelable"), Is.True); + Assert.That(await Page.EvaluateAsync("() => composed"), Is.True); } [PlaywrightTest("page-dispatchevent.spec.ts", "should dispatch click svg")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDispatchClickSvg() { await Page.SetContentAsync(@" @@ -46,11 +38,11 @@ await Page.SetContentAsync(@" "); await Page.DispatchEventAsync("circle", "click"); - Assert.Equal(42, await Page.EvaluateAsync("() => window.__CLICKED")); + Assert.That(await Page.EvaluateAsync("() => window.__CLICKED"), Is.EqualTo(42)); } [PlaywrightTest("page-dispatchevent.spec.ts", "should dispatch click on a span with an inline element inside")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDispatchClickOnASpanWithAnInlineElementInside() { await Page.SetContentAsync(@" @@ -62,33 +54,33 @@ await Page.SetContentAsync(@" "); await Page.DispatchEventAsync("span", "click"); - Assert.Equal(42, await Page.EvaluateAsync("() => window.CLICKED")); + Assert.That(await Page.EvaluateAsync("() => window.CLICKED"), Is.EqualTo(42)); } [PlaywrightTest("page-dispatchevent.spec.ts", "should dispatch click after navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDispatchClickAfterNavigation() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.DispatchEventAsync("button", "click"); await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.DispatchEventAsync("button", "click"); - Assert.Equal("Clicked", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-dispatchevent.spec.ts", "should dispatch click after a cross origin navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDispatchClickAfterACrossOriginNavigation() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); await Page.DispatchEventAsync("button", "click"); await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/input/button.html"); await Page.DispatchEventAsync("button", "click"); - Assert.Equal("Clicked", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("Clicked")); } [PlaywrightTest("page-dispatchevent.spec.ts", "should not fail when element is blocked on hover")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotFailWhenElementIsBlockedOnHover() { await Page.SetContentAsync(@" @@ -104,11 +96,11 @@ await Page.SetContentAsync(@" "); await Page.DispatchEventAsync("button", "click"); - Assert.True(await Page.EvaluateAsync("() => window.clicked")); + Assert.That(await Page.EvaluateAsync("() => window.clicked"), Is.True); } [PlaywrightTest("page-dispatchevent.spec.ts", "should dispatch click when node is added in shadow dom")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDispatchClickWhenNodeIsAddedInShadowDom() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -129,11 +121,11 @@ await Page.EvaluateAsync(@"() => { }"); await watchdog; - Assert.True(await Page.EvaluateAsync("() => window.clicked")); + Assert.That(await Page.EvaluateAsync("() => window.clicked"), Is.True); } [PlaywrightTest("page-dispatchevent.spec.ts", "should be atomic")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAtomic() { const string createDummySelector = @"({ @@ -155,7 +147,7 @@ public async Task ShouldBeAtomic() await TestUtils.RegisterEngineAsync(Playwright, "page-dispatchevent", createDummySelector); await Page.SetContentAsync("
Hello
"); await Page.DispatchEventAsync("page-dispatchevent=div", "click"); - Assert.True(await Page.EvaluateAsync("() => window['_clicked']")); + Assert.That(await Page.EvaluateAsync("() => window['_clicked']"), Is.True); } [PlaywrightTest("page-dispatchevent.spec.ts", "Page.dispatchEvent(drag)", "should dispatch drag drop events")] @@ -169,9 +161,9 @@ public async Task ShouldDispatchDragDropEvents() var source = await Page.QuerySelectorAsync("#source"); var target = await Page.QuerySelectorAsync("#target"); - Assert.True(await Page.EvaluateAsync(@"() => { + Assert.That(await Page.EvaluateAsync(@"() => { return source.parentElement === target; - }", new { source, target })); + }", new { source, target }), Is.True); } [PlaywrightTest("page-dispatchevent.spec.ts", "Page.dispatchEvent(drag)", "should dispatch drag drop events")] @@ -185,19 +177,19 @@ public async Task ElementHandleShouldDispatchDragDropEvents() var target = await Page.QuerySelectorAsync("#target"); await target.DispatchEventAsync("drop", new { dataTransfer }); - Assert.True(await Page.EvaluateAsync(@"() => { + Assert.That(await Page.EvaluateAsync(@"() => { return source.parentElement === target; - }", new { source, target })); + }", new { source, target }), Is.True); } [PlaywrightTest("page-dispatchevent.spec.ts", "should dispatch click event")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ElementHandleShouldDispatchClickEvent() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html"); var button = await Page.QuerySelectorAsync("button"); await button.DispatchEventAsync("click"); - Assert.Equal("Clicked", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("Clicked")); } } } diff --git a/src/Playwright.Tests/PageDragTests.cs b/src/Playwright.Tests/PageDragTests.cs index be179b3239..2feaf3339b 100644 --- a/src/Playwright.Tests/PageDragTests.cs +++ b/src/Playwright.Tests/PageDragTests.cs @@ -1,21 +1,13 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageDragTests : PlaywrightSharpPageBaseTest - { - /// - public PageDragTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-drag.spec.ts", "should work")] - [Fact(Skip = "Skipped in Playwright")] + { [PlaywrightTest("page-drag.spec.ts", "should work")] + [Test, Ignore("Skipped in Playwright")] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.ServerUrl + "/drag-n-drop.html"); @@ -24,7 +16,7 @@ public async Task ShouldWork() await Page.HoverAsync("#target"); await Page.Mouse.UpAsync(); - Assert.True(await Page.EvalOnSelectorAsync("#target", "target => target.contains(document.querySelector('#source'))")); + Assert.That(await Page.EvalOnSelectorAsync("#target", "target => target.contains(document.querySelector('#source'))"), Is.True); } } } diff --git a/src/Playwright.Tests/PageEmulateMediaTests.cs b/src/Playwright.Tests/PageEmulateMediaTests.cs index 2362702769..4790c1c71f 100644 --- a/src/Playwright.Tests/PageEmulateMediaTests.cs +++ b/src/Playwright.Tests/PageEmulateMediaTests.cs @@ -1,52 +1,44 @@ using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageEmulateMediaTests : PlaywrightSharpPageBaseTest - { - /// - public PageEmulateMediaTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-emulate-media.spec.ts", "should emulate scheme work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-emulate-media.spec.ts", "should emulate scheme work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmulateSchemeWork() { await Page.EmulateMediaAsync(ColorScheme.Light); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.False); await Page.EmulateMediaAsync(ColorScheme.Dark); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches")); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches"), Is.False); } [PlaywrightTest("page-emulate-media.spec.ts", "should default to light")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDefaultToLight() { - Assert.True(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.False); await Page.EmulateMediaAsync(ColorScheme.Dark); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches")); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches"), Is.False); await Page.EmulateMediaAsync(colorScheme: ColorScheme.Undefined); - Assert.True(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches")); - Assert.False(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.False); } [PlaywrightTest("page-emulate-media.spec.ts", "should throw in case of bad media argument")] - [Fact(Skip = "We don't need this test. Leaving for tracking purposes")] + [Test, Ignore("We don't need this test. Leaving for tracking purposes")] public void ShouldThrowInCaseOfBadMediaArgument() { } [PlaywrightTest("page-emulate-media.spec.ts", "should work during navigation")] @@ -63,11 +55,11 @@ public async Task ShouldWorkDuringNavigation() } await navigated; - Assert.True(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); + Assert.That(await Page.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.True); } [PlaywrightTest("page-emulate-media.spec.ts", "should work in popup")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkInPopup() { await using (var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -85,8 +77,8 @@ await TaskUtils.WhenAll( var popup = popupTask.Result; - Assert.True(await popup.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); - Assert.False(await popup.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches")); + Assert.That(await popup.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.True); + Assert.That(await popup.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches"), Is.False); } await using (var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -104,13 +96,13 @@ await TaskUtils.WhenAll( var popup = popupTask.Result; - Assert.False(await popup.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); - Assert.True(await popup.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches")); + Assert.That(await popup.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.False); + Assert.That(await popup.EvaluateAsync("() => matchMedia('(prefers-color-scheme: light)').matches"), Is.True); } } [PlaywrightTest("page-emulate-media.spec.ts", "should work in cross-process iframe")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkInCrossProcessIframe() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -123,28 +115,28 @@ public async Task ShouldWorkInCrossProcessIframe() await FrameUtils.AttachFrameAsync(page, "frame1", TestConstants.CrossProcessHttpPrefix + "/empty.html"); var frame = page.Frames.ElementAt(1); - Assert.True(await frame.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches")); + Assert.That(await frame.EvaluateAsync("() => matchMedia('(prefers-color-scheme: dark)').matches"), Is.True); } [PlaywrightTest("page-emulate-media.spec.ts", "should emulate type")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmulateType() { - Assert.True(await Page.EvaluateAsync("matchMedia('screen').matches")); - Assert.False(await Page.EvaluateAsync("matchMedia('print').matches")); + Assert.That(await Page.EvaluateAsync("matchMedia('screen').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("matchMedia('print').matches"), Is.False); await Page.EmulateMediaAsync(Media.Print); - Assert.False(await Page.EvaluateAsync("matchMedia('screen').matches")); - Assert.True(await Page.EvaluateAsync("matchMedia('print').matches")); + Assert.That(await Page.EvaluateAsync("matchMedia('screen').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("matchMedia('print').matches"), Is.True); await Page.EmulateMediaAsync(); - Assert.False(await Page.EvaluateAsync("matchMedia('screen').matches")); - Assert.True(await Page.EvaluateAsync("matchMedia('print').matches")); + Assert.That(await Page.EvaluateAsync("matchMedia('screen').matches"), Is.False); + Assert.That(await Page.EvaluateAsync("matchMedia('print').matches"), Is.True); await Page.EmulateMediaAsync(Media.Undefined); - Assert.True(await Page.EvaluateAsync("matchMedia('screen').matches")); - Assert.False(await Page.EvaluateAsync("matchMedia('print').matches")); + Assert.That(await Page.EvaluateAsync("matchMedia('screen').matches"), Is.True); + Assert.That(await Page.EvaluateAsync("matchMedia('print').matches"), Is.False); } [PlaywrightTest("page-emulate-media.spec.ts", "should throw in case of bad colorScheme argument")] - [Fact(Skip = "We don't need this test. Leaving for tracking purposes")] + [Test, Ignore("We don't need this test. Leaving for tracking purposes")] public void ShouldThrowInCaseOfBadColorSchemeArgument() { } } } diff --git a/src/Playwright.Tests/PageEvaluateHandleTests.cs b/src/Playwright.Tests/PageEvaluateHandleTests.cs index 05a93e5140..b1a0b83392 100644 --- a/src/Playwright.Tests/PageEvaluateHandleTests.cs +++ b/src/Playwright.Tests/PageEvaluateHandleTests.cs @@ -3,68 +3,60 @@ using System.Linq; using System.Text.Json; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageEvaluateHandleTests : PlaywrightSharpPageBaseTest - { - /// - public PageEvaluateHandleTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-evaluate-handle.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-evaluate-handle.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { var windowHandle = await Page.EvaluateHandleAsync("() => window"); - Assert.NotNull(windowHandle); + Assert.That(windowHandle, Is.Not.Null); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should accept object handle as an argument")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptObjectHandleAsAnArgument() { var navigatorHandle = await Page.EvaluateHandleAsync("() => navigator"); string text = await Page.EvaluateAsync("e => e.userAgent", navigatorHandle); - Assert.Contains("Mozilla", text); + Assert.That(text, Does.Contain("Mozilla")); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should accept object handle to primitive types")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptObjectHandleToPrimitiveTypes() { var aHandle = await Page.EvaluateHandleAsync("() => 5"); bool isFive = await Page.EvaluateAsync("e => Object.is (e, 5)", aHandle); - Assert.True(isFive); + Assert.That(isFive, Is.True); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should accept nested handle")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptNestedHandle() { var foo = await Page.EvaluateHandleAsync("() => ({x: 1, y: 'foo'})"); dynamic result = await Page.EvaluateAsync("({ foo }) => foo", new { foo }); - Assert.Equal(1, result.x); - Assert.Equal("foo", result.y); + Assert.That(result.x, Is.EqualTo(1)); + Assert.That(result.y, Is.EqualTo("foo")); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should accept nested window handle")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptNestedWindowHandle() { var foo = await Page.EvaluateHandleAsync("() => window"); - Assert.True(await Page.EvaluateAsync("({ foo }) => foo === window", new { foo })); + Assert.That(await Page.EvaluateAsync("({ foo }) => foo === window", new { foo }), Is.True); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should accept multiple nested handles")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptMultipleNestedHandles() { var foo = await Page.EvaluateHandleAsync("() => ({ x: 1, y: 'foo' })"); @@ -85,26 +77,26 @@ public async Task ShouldAcceptMultipleNestedHandles() var json = JsonDocument.Parse(result).RootElement; - Assert.Equal(1, json.GetProperty("a1").GetProperty("foo").GetProperty("x").GetInt32()); - Assert.Equal("foo", json.GetProperty("a1").GetProperty("foo").GetProperty("y").ToString()); - Assert.Equal(5, json.GetProperty("a2").GetProperty("bar").GetInt32()); - Assert.Equal("baz", json.GetProperty("a2").GetProperty("arr").EnumerateArray().First().GetProperty("baz").EnumerateArray().First().ToString()); + Assert.That(json.GetProperty("a1").GetProperty("foo").GetProperty("x").GetInt32(), Is.EqualTo(1)); + Assert.That(json.GetProperty("a1").GetProperty("foo").GetProperty("y").ToString(), Is.EqualTo("foo")); + Assert.That(json.GetProperty("a2").GetProperty("bar").GetInt32(), Is.EqualTo(5)); + Assert.That(json.GetProperty("a2").GetProperty("arr").EnumerateArray().First().GetProperty("baz").EnumerateArray().First().ToString(), Is.EqualTo("baz")); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should throw for circular objects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForCircularObjects() { dynamic a = new ExpandoObject(); a.a = 1; a.y = a; - var exception = await Assert.ThrowsAnyAsync(() => Page.EvaluateAsync("x => x", a)); - Assert.Equal("Argument is a circular structure", exception.Message); + var exception = Assert.CatchAsync(() => Page.EvaluateAsync("x => x", a)); + Assert.That(exception.Message, Is.EqualTo("Argument is a circular structure")); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should accept same nested object multiple times")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptSameNestedObjectMultipleTimes() { dynamic foo = new { x = 1 }; @@ -119,21 +111,21 @@ public async Task ShouldAcceptSameNestedObjectMultipleTimes() var json = JsonDocument.Parse(result).RootElement; - Assert.Equal(1, json.GetProperty("foo").GetProperty("x").GetInt32()); - Assert.Equal(1, json.GetProperty("bar").EnumerateArray().First().GetProperty("x").GetInt32()); - Assert.Equal(1, json.GetProperty("baz").GetProperty("foo").GetProperty("x").GetInt32()); + Assert.That(json.GetProperty("foo").GetProperty("x").GetInt32(), Is.EqualTo(1)); + Assert.That(json.GetProperty("bar").EnumerateArray().First().GetProperty("x").GetInt32(), Is.EqualTo(1)); + Assert.That(json.GetProperty("baz").GetProperty("foo").GetProperty("x").GetInt32(), Is.EqualTo(1)); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should accept object handle to unserializable value")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptObjectHandleToUnserializableValue() { var aHandle = await Page.EvaluateHandleAsync("() => Infinity"); - Assert.True(await Page.EvaluateAsync("e => Object.is(e, Infinity)", aHandle)); + Assert.That(await Page.EvaluateAsync("e => Object.is(e, Infinity)", aHandle), Is.True); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should pass configurable args")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPassConfigurableArgs() { JsonElement result = await Page.EvaluateAsync( @@ -150,18 +142,18 @@ public async Task ShouldPassConfigurableArgs() }", new { foo = 42 }); - Assert.Equal("{}", result.ToString()); + Assert.That(result.ToString(), Is.EqualTo("{}")); } [PlaywrightTest("page-evaluate-handle.spec.ts", "should work with primitives")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithPrimitives() { var aHandle = await Page.EvaluateHandleAsync(@"() => { window.FOO = 123; return window; }"); - Assert.Equal(123, await Page.EvaluateAsync("e => e.FOO", aHandle)); + Assert.That(await Page.EvaluateAsync("e => e.FOO", aHandle), Is.EqualTo(123)); } } } diff --git a/src/Playwright.Tests/PageEvaluateTests.cs b/src/Playwright.Tests/PageEvaluateTests.cs index 954b120458..fa99d2043e 100644 --- a/src/Playwright.Tests/PageEvaluateTests.cs +++ b/src/Playwright.Tests/PageEvaluateTests.cs @@ -5,64 +5,56 @@ using System.Text.Json; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageEvaluateTests : PlaywrightSharpPageBaseTest - { - /// - public PageEvaluateTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-evaluate.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-evaluate.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { int result = await Page.EvaluateAsync("() => 7 * 3"); - Assert.Equal(21, result); + Assert.That(result, Is.EqualTo(21)); } [PlaywrightTest("page-evaluate.spec.ts", "should transfer NaN")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTransferNaN() { double result = await Page.EvaluateAsync("a => a", double.NaN); - Assert.Equal(double.NaN, result); + Assert.That(result, Is.EqualTo(double.NaN)); } [PlaywrightTest("page-evaluate.spec.ts", "should transfer -0")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTransferNegative0() { double result = await Page.EvaluateAsync("a => a", -0d); - Assert.True(result.IsNegativeZero()); + Assert.That(result.IsNegativeZero(), Is.True); } [PlaywrightTest("page-evaluate.spec.ts", "should transfer Infinity")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTransferInfinity() { double result = await Page.EvaluateAsync("a => a", double.PositiveInfinity); - Assert.Equal(double.PositiveInfinity, result); + Assert.That(result, Is.EqualTo(double.PositiveInfinity)); } [PlaywrightTest("page-evaluate.spec.ts", "should transfer -Infinity")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTransferNegativeInfinity() { double result = await Page.EvaluateAsync("a => a", double.NegativeInfinity); - Assert.Equal(double.NegativeInfinity, result); + Assert.That(result, Is.EqualTo(double.NegativeInfinity)); } [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip unserializable values")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRoundtripUnserializableValues() { dynamic value = new @@ -74,31 +66,31 @@ public async Task ShouldRoundtripUnserializableValues() }; dynamic result = await Page.EvaluateAsync("value => value", value); - Assert.Equal(value.infinity, result.infinity); - Assert.Equal(value.nInfinity, result.nInfinity); - Assert.Equal(value.nZero, result.nZero); - Assert.Equal(value.nan, result.nan); + Assert.That(result.infinity, Is.EqualTo(value.infinity)); + Assert.That(result.nInfinity, Is.EqualTo(value.nInfinity)); + Assert.That(result.nZero, Is.EqualTo(value.nZero)); + Assert.That(result.nan, Is.EqualTo(value.nan)); } [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip promise to value")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRoundtripPromiseToValue() { object result = await Page.EvaluateAsync("value => Promise.resolve(value)", null); - Assert.Null(result); + Assert.That(result, Is.Null); double infitinity = await Page.EvaluateAsync("value => Promise.resolve(value)", double.PositiveInfinity); - Assert.Equal(double.PositiveInfinity, infitinity); + Assert.That(infitinity, Is.EqualTo(double.PositiveInfinity)); double ninfitinity = await Page.EvaluateAsync("value => Promise.resolve(value)", double.NegativeInfinity); - Assert.Equal(double.NegativeInfinity, ninfitinity); + Assert.That(ninfitinity, Is.EqualTo(double.NegativeInfinity)); double nzero = await Page.EvaluateAsync("value => Promise.resolve(value)", -0d); - Assert.Equal(-0, nzero); + Assert.That(nzero, Is.EqualTo(-0)); } [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip promise to unserializable values")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRoundtripPromiseToUnserializableValues() { dynamic value = new @@ -110,104 +102,104 @@ public async Task ShouldRoundtripPromiseToUnserializableValues() }; dynamic result = await Page.EvaluateAsync("value => Promise.resolve(value)", value); - Assert.Equal(value.infinity, result.infinity); - Assert.Equal(value.nInfinity, result.nInfinity); - Assert.Equal(value.nZero, result.nZero); - Assert.Equal(value.nan, result.nan); + Assert.That(result.infinity, Is.EqualTo(value.infinity)); + Assert.That(result.nInfinity, Is.EqualTo(value.nInfinity)); + Assert.That(result.nZero, Is.EqualTo(value.nZero)); + Assert.That(result.nan, Is.EqualTo(value.nan)); } [PlaywrightTest("page-evaluate.spec.ts", "should transfer arrays")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTransferArrays() { int[] result = await Page.EvaluateAsync("a => a", new[] { 1, 2, 3 }); - Assert.Equal(new[] { 1, 2, 3 }, result); + Assert.That(result, Is.EqualTo(new[] { 1, 2, 3 })); } [PlaywrightTest("page-evaluate.spec.ts", "should transfer arrays as arrays, not objects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTransferArraysAsArraysNotObjects() { bool result = await Page.EvaluateAsync("a => Array.isArray(a)", new[] { 1, 2, 3 }); - Assert.True(result); + Assert.That(result, Is.True); } [PlaywrightTest("page-evaluate.spec.ts", "should transfer maps as empty objects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTransferMapsAsEmptyObjects() { dynamic result = await Page.EvaluateAsync("a => a.x.constructor.name + ' ' + JSON.stringify(a.x), {x: new Map([[1, 2]])}"); - Assert.Empty(TypeDescriptor.GetProperties(result)); + Assert.That(TypeDescriptor.GetProperties(result), Is.Empty); } [PlaywrightTest("page-evaluate.spec.ts", "should modify global environment")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldModifyGlobalEnvironment() { await Page.EvaluateAsync("() => window.globalVar = 123"); - Assert.Equal(123, await Page.EvaluateAsync("globalVar")); + Assert.That(await Page.EvaluateAsync("globalVar"), Is.EqualTo(123)); } [PlaywrightTest("page-evaluate.spec.ts", "should evaluate in the page context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEvaluateInThePageContext() { await Page.GoToAsync(TestConstants.ServerUrl + "/global-var.html"); - Assert.Equal(123, await Page.EvaluateAsync("globalVar")); + Assert.That(await Page.EvaluateAsync("globalVar"), Is.EqualTo(123)); } [PlaywrightTest("page-evaluate.spec.ts", "should return undefined for objects with symbols")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnUndefinedForObjectsWithSymbols() { - Assert.Equal(new object[] { null }, await Page.EvaluateAsync("() => [Symbol('foo4')]")); - Assert.Equal("{}", (await Page.EvaluateAsync(@"() => { + Assert.That(await Page.EvaluateAsync("() => [Symbol('foo4')]"), Is.EqualTo(new object[] { null })); + Assert.That((await Page.EvaluateAsync(@"() => { var a = { }; a[Symbol('foo4')] = 42; return a; - }")).ToJson()); + }")).ToJson(), Is.EqualTo("{}")); dynamic element = await Page.EvaluateAsync(@"() => { return { foo: [{ a: Symbol('foo4') }] }; }"); - Assert.Null(element.foo[0].a); + Assert.That(element.foo[0].a, Is.Null); } [PlaywrightTest("page-evaluate.spec.ts", "should work with function shorthands")] - [Fact(Skip = "Not relevant for C#, js specific")] + [Test, Ignore("Not relevant for C#, js specific")] public void ShouldWorkWithFunctionShorthands() { } [PlaywrightTest("page-evaluate.spec.ts", "should work with unicode chars")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithUnicodeChars() { int result = await Page.EvaluateAsync("a => a['中文字符']", new Dictionary { ["中文字符"] = 42 }); - Assert.Equal(42, result); + Assert.That(result, Is.EqualTo(42)); } [PlaywrightTest("page-evaluate.spec.ts", "should throw when evaluation triggers reload")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWhenEvaluationTriggersReload() { - var exception = await Assert.ThrowsAsync(() => Page.EvaluateAsync(@"() => { + var exception = Assert.ThrowsAsync(() => Page.EvaluateAsync(@"() => { location.reload(); return new Promise(() => { }); }")); - Assert.Contains("navigation", exception.Message); + Assert.That(exception.Message, Does.Contain("navigation")); } [PlaywrightTest("page-evaluate.spec.ts", "should await promise")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAwaitPromise() { int result = await Page.EvaluateAsync("() => Promise.resolve(8 * 7)"); - Assert.Equal(56, result); + Assert.That(result, Is.EqualTo(56)); } [PlaywrightTest("page-evaluate.spec.ts", "should work right after framenavigated")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkRightAfterFrameNavigated() { Task frameEvaluation = null; @@ -216,11 +208,11 @@ public async Task ShouldWorkRightAfterFrameNavigated() frameEvaluation = e.EvaluateAsync("() => 6 * 7"); }; await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(42, await frameEvaluation); + Assert.That(await frameEvaluation, Is.EqualTo(42)); } [PlaywrightTest("page-evaluate.spec.ts", "should work right after a cross-origin navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkRightAfterACrossOriginNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -230,11 +222,11 @@ public async Task ShouldWorkRightAfterACrossOriginNavigation() frameEvaluation = e.EvaluateAsync("() => 6 * 7"); }; await Page.GoToAsync(TestConstants.CrossProcessUrl + "/empty.html"); - Assert.Equal(42, await frameEvaluation); + Assert.That(await frameEvaluation, Is.EqualTo(42)); } [PlaywrightTest("page-evaluate.spec.ts", "should work from-inside an exposed function")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkFromInsideAnExposedFunction() { // Setup inpage callback, which calls Page.evaluate @@ -242,73 +234,73 @@ public async Task ShouldWorkFromInsideAnExposedFunction() int result = await Page.EvaluateAsync(@"async function() { return await callController(9, 3); }"); - Assert.Equal(27, result); + Assert.That(result, Is.EqualTo(27)); } [PlaywrightTest("page-evaluate.spec.ts", "should reject promise with exception")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRejectPromiseWithException() { - var exception = await Assert.ThrowsAsync(() => Page.EvaluateAsync("() => not_existing_object.property")); - Assert.Contains("not_existing_object", exception.Message); + var exception = Assert.ThrowsAsync(() => Page.EvaluateAsync("() => not_existing_object.property")); + Assert.That(exception.Message, Does.Contain("not_existing_object")); } [PlaywrightTest("page-evaluate.spec.ts", "should support thrown strings as error messages")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportThrownStringsAsErrorMessages() { - var exception = await Assert.ThrowsAsync(() => Page.EvaluateAsync("() => { throw 'qwerty'; }")); - Assert.Contains("qwerty", exception.Message); + var exception = Assert.ThrowsAsync(() => Page.EvaluateAsync("() => { throw 'qwerty'; }")); + Assert.That(exception.Message, Does.Contain("qwerty")); } [PlaywrightTest("page-evaluate.spec.ts", "should support thrown numbers as error messages")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportThrownNumbersAsErrorMessages() { - var exception = await Assert.ThrowsAsync(() => Page.EvaluateAsync("() => { throw 100500; }")); - Assert.Contains("100500", exception.Message); + var exception = Assert.ThrowsAsync(() => Page.EvaluateAsync("() => { throw 100500; }")); + Assert.That(exception.Message, Does.Contain("100500")); } [PlaywrightTest("page-evaluate.spec.ts", "should return complex objects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnComplexObjects() { var obj = new { foo = "bar!" }; var result = await Page.EvaluateAsync("a => a", obj); - Assert.Equal("bar!", result.GetProperty("foo").GetString()); + Assert.That(result.GetProperty("foo").GetString(), Is.EqualTo("bar!")); } [PlaywrightTest("page-evaluate.spec.ts", "should return NaN")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNaN() { double result = await Page.EvaluateAsync("() => NaN"); - Assert.Equal(double.NaN, result); + Assert.That(result, Is.EqualTo(double.NaN)); } [PlaywrightTest("page-evaluate.spec.ts", "should return -0")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNegative0() - => Assert.True((await Page.EvaluateAsync("() => -0")).IsNegativeZero()); + => Assert.That((await Page.EvaluateAsync("() => -0")).IsNegativeZero(), Is.True); [PlaywrightTest("page-evaluate.spec.ts", "should return Infinity")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnInfinity() { double result = await Page.EvaluateAsync("() => Infinity"); - Assert.Equal(double.PositiveInfinity, result); + Assert.That(result, Is.EqualTo(double.PositiveInfinity)); } [PlaywrightTest("page-evaluate.spec.ts", "should return -Infinity")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNegativeInfinity() { double result = await Page.EvaluateAsync("() => -Infinity"); - Assert.Equal(double.NegativeInfinity, result); + Assert.That(result, Is.EqualTo(double.NegativeInfinity)); } [PlaywrightTest("page-evaluate.spec.ts", "should work with overwritten Promise")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithOverwrittenPromise() { await Page.EvaluateAsync(@"const originalPromise = window.Promise; @@ -343,21 +335,21 @@ static resolve(...arg) { window.Promise = Promise2; window.__Promise2 = Promise2;"); - Assert.True(await Page.EvaluateAsync(@"() => { + Assert.That(await Page.EvaluateAsync(@"() => { const p = Promise.all([Promise.race([]), new Promise(() => {}).then(() => {})]); return p instanceof window.__Promise2; - }")); - Assert.Equal(42, await Page.EvaluateAsync("() => Promise.resolve(42)")); + }"), Is.True); + Assert.That(await Page.EvaluateAsync("() => Promise.resolve(42)"), Is.EqualTo(42)); } [PlaywrightTest("page-evaluate.spec.ts", "should throw when passed more than one parameter")] - [Fact(Skip = "Not relevant for C#, js specific")] + [Test, Ignore("Not relevant for C#, js specific")] public void ShouldThrowWhenPassedMoreThanOneParameter() { } [PlaywrightTest("page-evaluate.spec.ts", @"should accept ""undefined"" as one of multiple parameters")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptUndefinedAsOneOfMultipleParameters() { //C# will send nulls @@ -366,43 +358,43 @@ public async Task ShouldAcceptUndefinedAsOneOfMultipleParameters() console.log(b); return Object.is (a, null) && Object.is (b, 'foo') }", new { a = (object)null, b = "foo" }); - Assert.True(result); + Assert.That(result, Is.True); } [PlaywrightTest("page-evaluate.spec.ts", "should properly serialize undefined arguments")] - [Fact(Skip = "Not relevant for C#, js specific")] + [Test, Ignore("Not relevant for C#, js specific")] public void ShouldProperlySerializeUndefinedArguments() { } [PlaywrightTest("page-evaluate.spec.ts", "should properly serialize undefined fields")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldProperlySerializeUndefinedFields() { dynamic result = await Page.EvaluateAsync("() => ({a: undefined})"); - Assert.Null(result.a); + Assert.That(result.a, Is.Null); } [PlaywrightTest("page-evaluate.spec.ts", "should properly serialize null arguments")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldProperlySerializeNullArguments() - => Assert.Null(await Page.EvaluateAsync("x => x", null)); + => Assert.That(await Page.EvaluateAsync("x => x", null), Is.Null); [PlaywrightTest("page-evaluate.spec.ts", "should properly serialize null fields")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldProperlySerializeNullFields() { dynamic result = await Page.EvaluateAsync("() => ({ a: null})"); - Assert.Null(result.a); + Assert.That(result.a, Is.Null); } [PlaywrightTest("page-evaluate.spec.ts", "should return undefined for non-serializable objects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnUndefinedForNonSerializableObjects() - => Assert.Null(await Page.EvaluateAsync("() => window")); + => Assert.That(await Page.EvaluateAsync("() => window"), Is.Null); [PlaywrightTest("page-evaluate.spec.ts", "should fail for circular object")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailForCircularObject() { object result = await Page.EvaluateAsync(@"() => { @@ -411,66 +403,66 @@ public async Task ShouldFailForCircularObject() a.b = b; return a; }"); - Assert.Null(result); + Assert.That(result, Is.Null); } [PlaywrightTest("page-evaluate.spec.ts", "should be able to throw a tricky error")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToThrowATrickyError() { var windowHandle = await Page.EvaluateHandleAsync("() => window"); - var exceptionText = await Assert.ThrowsAnyAsync(() => windowHandle.JsonValueAsync()); - var error = await Assert.ThrowsAnyAsync(() => Page.EvaluateAsync(@"errorText => { + var exceptionText = Assert.CatchAsync(() => windowHandle.JsonValueAsync()); + var error = Assert.CatchAsync(() => Page.EvaluateAsync(@"errorText => { throw new Error(errorText); }", exceptionText.Message)); - Assert.Contains(exceptionText.Message, error.Message); + Assert.That(error.Message, Does.Contain(exceptionText.Message)); } [PlaywrightTest("page-evaluate.spec.ts", "should accept a string")] - [Fact(Skip = "Not relevant for C#, js specific")] + [Test, Ignore("Not relevant for C#, js specific")] public void ShouldAcceptAString() { } [PlaywrightTest("page-evaluate.spec.ts", "should accept a string with semi colons")] - [Fact(Skip = "Not relevant for C#, js specific")] + [Test, Ignore("Not relevant for C#, js specific")] public void ShouldAcceptAStringWithSemiColons() { } [PlaywrightTest("page-evaluate.spec.ts", "should accept a string with comments")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptAStringWithComments() { int result = await Page.EvaluateAsync("2 + 5;\n// do some math!"); - Assert.Equal(7, result); + Assert.That(result, Is.EqualTo(7)); } [PlaywrightTest("page-evaluate.spec.ts", "should accept element handle as an argument")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptElementHandleAsAnArgument() { await Page.SetContentAsync("
42
"); var element = await Page.QuerySelectorAsync("section"); string text = await Page.EvaluateAsync("e => e.textContent", element); - Assert.Equal("42", text); + Assert.That(text, Is.EqualTo("42")); } [PlaywrightTest("page-evaluate.spec.ts", "should throw if underlying element was disposed")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowIfUnderlyingElementWasDisposed() { await Page.SetContentAsync("
39
"); var element = await Page.QuerySelectorAsync("section"); - Assert.NotNull(element); + Assert.That(element, Is.Not.Null); await element.DisposeAsync(); - var exception = await Assert.ThrowsAnyAsync(() => Page.EvaluateAsync("e => e.textContent", element)); - Assert.Contains("JSHandle is disposed", exception.Message); + var exception = Assert.CatchAsync(() => Page.EvaluateAsync("e => e.textContent", element)); + Assert.That(exception.Message, Does.Contain("JSHandle is disposed")); } [PlaywrightTest("page-evaluate.spec.ts", "should simulate a user gesture")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSimulateAUserGesture() { bool result = await Page.EvaluateAsync(@"() => { @@ -478,14 +470,14 @@ public async Task ShouldSimulateAUserGesture() document.execCommand('selectAll'); return document.execCommand('copy'); }"); - Assert.True(result); + Assert.That(result, Is.True); } [PlaywrightTest("page-evaluate.spec.ts", "should throw a nice error after a navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowANiceErrorAfterANavigation() { - var exceptionTask = Assert.ThrowsAsync(() => Page.EvaluateAsync("() => new Promise(f => window.__resolve = f)")); + var exception = Assert.ThrowsAsync(() => Page.EvaluateAsync("() => new Promise(f => window.__resolve = f)")); await TaskUtils.WhenAll( Page.WaitForNavigationAsync(), Page.EvaluateAsync(@"() => { @@ -493,12 +485,11 @@ await TaskUtils.WhenAll( setTimeout(() => window.__resolve(42), 1000); }") ); - var exception = await exceptionTask; - Assert.Contains("navigation", exception.Message); + Assert.That(exception.Message, Does.Contain("navigation")); } [PlaywrightTest("page-evaluate.spec.ts", "should not throw an error when evaluation does a navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation() { await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); @@ -506,7 +497,7 @@ public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation() window.location = '/empty.html'; return [42]; }"); - Assert.Equal(new[] { 42 }, result); + Assert.That(result, Is.EqualTo(new[] { 42 })); } [PlaywrightTest("page-evaluate.spec.ts", "should not throw an error when evaluation does a synchronous navigation and returns an object")] @@ -517,7 +508,7 @@ public async Task ShouldNotThrowAnErrorWhenEvaluationDoesASynchronousNavigationA window.location.reload(); return {a: 42}; }"); - Assert.Equal(42, result.GetProperty("a").GetInt32()); + Assert.That(result.GetProperty("a").GetInt32(), Is.EqualTo(42)); } [PlaywrightTest("page-evaluate.spec.ts", "should not throw an error when evaluation does a synchronous navigation and returns an undefined")] @@ -528,34 +519,34 @@ public async Task ShouldNotThrowAnErrorWhenEvaluationDoesASynchronousNavigationA window.location.reload(); return undefined; }"); - Assert.Null(result); + Assert.That(result, Is.Null); } [PlaywrightTest("page-evaluate.spec.ts", "should transfer 100Mb of data from page to node.js")] - [Fact(Skip = "SKIP WIRE")] + [Test, Ignore("SKIP WIRE")] public async Task ShouldTransfer100MbOfDataFromPageToNodeJs() { string a = await Page.EvaluateAsync("() => Array(100 * 1024 * 1024 + 1).join('a')"); - Assert.Equal(100 * 1024 * 1024, a.Length); + Assert.That(a.Length, Is.EqualTo(100 * 1024 * 1024)); } [PlaywrightTest("page-evaluate.spec.ts", "should throw error with detailed information on exception inside promise ")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowErrorWithDetailedInformationOnExceptionInsidePromise() { - var exception = await Assert.ThrowsAsync(() => Page.EvaluateAsync(@"() => new Promise(() => { + var exception = Assert.ThrowsAsync(() => Page.EvaluateAsync(@"() => new Promise(() => { throw new Error('Error in promise'); })")); - Assert.Contains("Error in promise", exception.Message); + Assert.That(exception.Message, Does.Contain("Error in promise")); } [PlaywrightTest("page-evaluate.spec.ts", "should work even when JSON is set to null")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkEvenWhenJSONIsSetToNull() { await Page.EvaluateAsync("() => { window.JSON.stringify = null; window.JSON = null; }"); var result = await Page.EvaluateAsync("() => ({ abc: 123})"); - Assert.Equal(123, result.GetProperty("abc").GetInt32()); + Assert.That(result.GetProperty("abc").GetInt32(), Is.EqualTo(123)); } [PlaywrightTest("page-evaluate.spec.ts", "should await promise from popup")] @@ -568,68 +559,68 @@ public async Task ShouldAwaitPromiseFromPopup() const win = window.open('about:blank'); return new win.Promise(f => f(42)); }"); - Assert.Equal(42, result); + Assert.That(result, Is.EqualTo(42)); } [PlaywrightTest("page-evaluate.spec.ts", "should work with new Function() and CSP")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNewFunctionAndCSP() { Server.SetCSP("/empty.html", "script-src" + TestConstants.ServerUrl); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.True(await Page.EvaluateAsync("() => new Function('return true')()")); + Assert.That(await Page.EvaluateAsync("() => new Function('return true')()"), Is.True); } [PlaywrightTest("page-evaluate.spec.ts", "should work with non-strict expressions")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNonStrictExpressions() { - Assert.Equal(3.14m, await Page.EvaluateAsync(@"() => { + Assert.That(await Page.EvaluateAsync(@"() => { y = 3.14; return y; - }")); + }"), Is.EqualTo(3.14m)); } [PlaywrightTest("page-evaluate.spec.ts", "should respect use strict expression")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectUseStrictExpression() { - var exception = await Assert.ThrowsAsync(() => Page.EvaluateAsync(@"() => { + var exception = Assert.ThrowsAsync(() => Page.EvaluateAsync(@"() => { ""use strict""; variableY = 3.14; return variableY; }")); - Assert.Contains("variableY", exception.Message); + Assert.That(exception.Message, Does.Contain("variableY")); } [PlaywrightTest("page-evaluate.spec.ts", "should not leak utility script")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotLeakUtilityScript() { - Assert.True(await Page.EvaluateAsync(@"() => this === window")); + Assert.That(await Page.EvaluateAsync(@"() => this === window"), Is.True); } [PlaywrightTest("page-evaluate.spec.ts", "should not leak handles")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotLeakHandles() { - var exception = await Assert.ThrowsAsync(() => Page.EvaluateAsync(@"() => handles.length")); - Assert.Contains("handles", exception.Message); + var exception = Assert.ThrowsAsync(() => Page.EvaluateAsync(@"() => handles.length")); + Assert.That(exception.Message, Does.Contain("handles")); } [PlaywrightTest("page-evaluate.spec.ts", "should work with CSP")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCSP() { Server.SetCSP("/empty.html", "script-src 'self'"); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(4, await Page.EvaluateAsync("() => 2 + 2")); + Assert.That(await Page.EvaluateAsync("() => 2 + 2"), Is.EqualTo(4)); } [PlaywrightTest("page-evaluate.spec.ts", "should evaluate exception")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEvaluateException() { string exception = await Page.EvaluateAsync(@"() => { @@ -637,66 +628,66 @@ public async Task ShouldEvaluateException() return new Error('error message'); })(); }"); - Assert.Contains("Error: error message", exception); - Assert.Contains("functionOnStack", exception); + Assert.That(exception, Does.Contain("Error: error message")); + Assert.That(exception, Does.Contain("functionOnStack")); } [PlaywrightTest("page-evaluate.spec.ts", "should evaluate exception")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEvaluateException2() { string exception = await Page.EvaluateAsync(@"() => new Error('error message')"); - Assert.Contains("Error: error message", exception); + Assert.That(exception, Does.Contain("Error: error message")); } [PlaywrightTest("page-evaluate.spec.ts", "should evaluate date")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEvaluateDate() { dynamic result = await Page.EvaluateAsync(@"() => ({ date: new Date('2020-05-27T01:31:38.506Z') })"); - Assert.Equal(new DateTime(2020, 05, 27, 1, 31, 38, 506), result.date); + Assert.That(result.date, Is.EqualTo(new DateTime(2020, 05, 27, 1, 31, 38, 506))); } [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip date")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRoundtripDate() { var date = new DateTime(2020, 05, 27, 1, 31, 38, 506, DateTimeKind.Utc); var result = await Page.EvaluateAsync(@"date => date", date); - Assert.Equal(date, result); + Assert.That(result, Is.EqualTo(date)); } - [Fact(Skip = "The driver doesn't support this yet")] + [Test, Ignore("The driver doesn't support this yet")] public async Task ShouldTreatEcma2020AsFunctions() - => Assert.Equal("dario", await Page.EvaluateAsync( + => Assert.That(await Page.EvaluateAsync( @"() => { const person = { name: 'dario' }; return person?.name; - }")); + }"), Is.EqualTo("dario")); [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip regex")] - [Fact(Skip = "Regex is not native as in javascript")] + [Test, Ignore("Regex is not native as in javascript")] public void ShouldRoundtripRegex() { } [PlaywrightTest("page-evaluate.spec.ts", "should jsonValue() date")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldJsonValueDate() { var resultHandle = await Page.EvaluateHandleAsync(@"() => ({ date: new Date('2020-05-27T01:31:38.506Z') })"); dynamic result = await resultHandle.JsonValueAsync(); - Assert.Equal(new DateTime(2020, 05, 27, 1, 31, 38, 506), result.date); + Assert.That(result.date, Is.EqualTo(new DateTime(2020, 05, 27, 1, 31, 38, 506))); } [PlaywrightTest("page-evaluate.spec.ts", "should not use toJSON when evaluating")] - [Fact(Skip = "Skip for now")] + [Test, Ignore("Skip for now")] public void ShouldNotUseToJSONWhenEvaluating() { } [PlaywrightTest("page-evaluate.spec.ts", "should not use toJSON in jsonValue")] - [Fact(Skip = "Skip for now")] + [Test, Ignore("Skip for now")] public void ShouldNotUseToJSONInJsonValue() { } diff --git a/src/Playwright.Tests/PageEventConsoleTests.cs b/src/Playwright.Tests/PageEventConsoleTests.cs index 57bf75a424..22e3b883d1 100644 --- a/src/Playwright.Tests/PageEventConsoleTests.cs +++ b/src/Playwright.Tests/PageEventConsoleTests.cs @@ -2,23 +2,15 @@ using System.Linq; using System.Text.Json; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageEventConsoleTests : PlaywrightSharpPageBaseTest - { - /// - public PageEventConsoleTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-event-console.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-event-console.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { IConsoleMessage message = null; @@ -32,15 +24,15 @@ await TaskUtils.WhenAll( Page.WaitForEventAsync(PageEvent.Console), Page.EvaluateAsync("() => console.log('hello', 5, { foo: 'bar'})")); - Assert.Equal("hello 5 JSHandle@object", message.Text); - Assert.Equal("log", message.Type); - Assert.Equal("hello", await message.Args.ElementAt(0).JsonValueAsync()); - Assert.Equal(5, await message.Args.ElementAt(1).JsonValueAsync()); - Assert.Equal("bar", (await message.Args.ElementAt(2).JsonValueAsync()).GetProperty("foo").GetString()); + Assert.That(message.Text, Is.EqualTo("hello 5 JSHandle@object")); + Assert.That(message.Type, Is.EqualTo("log")); + Assert.That(await message.Args.ElementAt(0).JsonValueAsync(), Is.EqualTo("hello")); + Assert.That(await message.Args.ElementAt(1).JsonValueAsync(), Is.EqualTo(5)); + Assert.That((await message.Args.ElementAt(2).JsonValueAsync()).GetProperty("foo").GetString(), Is.EqualTo("bar")); } [PlaywrightTest("page-event-console.spec.ts", "should emit same log twice")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmitSameLogTwice() { var messages = new List(); @@ -48,11 +40,11 @@ public async Task ShouldEmitSameLogTwice() Page.Console += (_, e) => messages.Add(e.Text); await Page.EvaluateAsync("() => { for (let i = 0; i < 2; ++i ) console.log('hello'); } "); - Assert.Equal(new[] { "hello", "hello" }, messages.ToArray()); + Assert.That(messages.ToArray(), Is.EqualTo(new[] { "hello", "hello" })); } [PlaywrightTest("page-event-console.spec.ts", "should work for different console API calls")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForDifferentConsoleAPICalls() { var messages = new List(); @@ -68,20 +60,20 @@ await Page.EvaluateAsync(@"() => { console.error('calling console.error'); console.log(Promise.resolve('should not wait until resolved!')); }"); - Assert.Equal(new[] { "timeEnd", "trace", "dir", "warning", "error", "log" }, messages.Select(msg => msg.Type)); - Assert.Contains("calling console.time", messages[0].Text); - Assert.Equal(new[] + Assert.That(messages.Select(msg => msg.Type), Is.EqualTo(new[] { "timeEnd", "trace", "dir", "warning", "error", "log" })); + Assert.That(messages[0].Text, Does.Contain("calling console.time")); + Assert.That(messages.Skip(1).Select(msg => msg.Text), Is.EqualTo(new[] { "calling console.trace", "calling console.dir", "calling console.warn", "calling console.error", "JSHandle@promise" - }, messages.Skip(1).Select(msg => msg.Text)); + })); } [PlaywrightTest("page-event-console.spec.ts", "should not fail for window object")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotFailForWindowObject() { IConsoleMessage message = null; @@ -95,11 +87,11 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("() => console.error(window)"), Page.WaitForEventAsync(PageEvent.Console) ); - Assert.Equal("JSHandle@object", message.Text); + Assert.That(message.Text, Is.EqualTo("JSHandle@object")); } [PlaywrightTest("page-event-console.spec.ts", "should trigger correct Log")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTriggerCorrectLog() { await Page.GoToAsync("about:blank"); @@ -107,12 +99,12 @@ public async Task ShouldTriggerCorrectLog() Page.WaitForEventAsync(PageEvent.Console), Page.EvaluateAsync("async url => fetch(url).catch (e => { })", TestConstants.EmptyPage) ); - Assert.Contains("Access-Control-Allow-Origin", messageEvent.Text); - Assert.Equal("error", messageEvent.Type); + Assert.That(messageEvent.Text, Does.Contain("Access-Control-Allow-Origin")); + Assert.That(messageEvent.Type, Is.EqualTo("error")); } [PlaywrightTest("page-event-console.spec.ts", "should have location for console API calls")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveLocationForConsoleAPICalls() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -120,13 +112,13 @@ public async Task ShouldHaveLocationForConsoleAPICalls() Page.WaitForEventAsync(PageEvent.Console), Page.GoToAsync(TestConstants.ServerUrl + "/consolelog.html") ); - Assert.Equal("yellow", messageEvent.Text); - Assert.Equal("log", messageEvent.Type); + Assert.That(messageEvent.Text, Is.EqualTo("yellow")); + Assert.That(messageEvent.Type, Is.EqualTo("log")); string location = messageEvent.Location; } [PlaywrightTest("page-event-console.spec.ts", "should not throw when there are console messages in detached iframes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotThrowWhenThereAreConsoleMessagesInDetachedIframes() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -148,7 +140,7 @@ public async Task ShouldNotThrowWhenThereAreConsoleMessagesInDetachedIframes() frame.remove(); }")); // 4. Connect to the popup and make sure it doesn't throw. - Assert.Equal(2, await popup.EvaluateAsync("1 + 1")); + Assert.That(await popup.EvaluateAsync("1 + 1"), Is.EqualTo(2)); } } } diff --git a/src/Playwright.Tests/PageEventCrashTests.cs b/src/Playwright.Tests/PageEventCrashTests.cs index bdd2fcf550..f6410f4a49 100644 --- a/src/Playwright.Tests/PageEventCrashTests.cs +++ b/src/Playwright.Tests/PageEventCrashTests.cs @@ -1,23 +1,15 @@ using System; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageEventCrashTests : PlaywrightSharpPageBaseTest - { - /// - public PageEventCrashTests(ITestOutputHelper output) : base(output) - { - } - - // We skip all browser because crash uses internals. + { // We skip all browser because crash uses internals. [PlaywrightTest("page-event-crash.spec.ts", "should emit crash event when page crashes")] [SkipBrowserAndPlatformFact(skipFirefox: true, skipWebkit: true)] public async Task ShouldEmitCrashEventWhenPageCrashes() @@ -37,8 +29,8 @@ public async Task ShouldThrowOnAnyActionAfterPageCrashes() var crashTask = Page.WaitForEventAsync(PageEvent.Crash); await CrashAsync(Page); await crashTask.WithTimeout(TestConstants.DefaultTaskTimeout); - var exception = await Assert.ThrowsAnyAsync(() => Page.EvaluateAsync("() => {}")); - Assert.Contains("crash", exception.Message); + var exception = Assert.CatchAsync(() => Page.EvaluateAsync("() => {}")); + Assert.That(exception.Message, Does.Contain("crash")); } // We skip all browser because crash uses internals. @@ -49,8 +41,8 @@ public async Task ShouldCancelWaitForEventWhenPageCrashes() await Page.SetContentAsync("
This page should crash
"); var responseTask = Page.WaitForEventAsync(PageEvent.Response); await CrashAsync(Page); - var exception = await Assert.ThrowsAnyAsync(() => responseTask.WithTimeout(TestConstants.DefaultTaskTimeout)); - Assert.Contains("Page crashed", exception.Message); + var exception = Assert.CatchAsync(() => responseTask.WithTimeout(TestConstants.DefaultTaskTimeout)); + Assert.That(exception.Message, Does.Contain("Page crashed")); } // We skip all browser because crash uses internals. @@ -64,8 +56,8 @@ public async Task ShouldCancelNavigationWhenPageCrashes() await Page.WaitForNavigationAsync(WaitUntilState.DOMContentLoaded); await CrashAsync(Page); - var exception = await Assert.ThrowsAnyAsync(() => task); - Assert.Contains("Navigation failed because page crashed", exception.Message); + var exception = Assert.CatchAsync(() => task); + Assert.That(exception.Message, Does.Contain("Navigation failed because page crashed")); } // We skip all browser because crash uses internals. diff --git a/src/Playwright.Tests/PageEventNetworkTests.cs b/src/Playwright.Tests/PageEventNetworkTests.cs index ac0bf2a138..b502e93035 100644 --- a/src/Playwright.Tests/PageEventNetworkTests.cs +++ b/src/Playwright.Tests/PageEventNetworkTests.cs @@ -3,54 +3,46 @@ using System.Net.Http; using System.Threading.Tasks; using Microsoft.Playwright.Contracts.Constants; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.TestServer; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageEventNetworkTests : PlaywrightSharpPageBaseTest - { - /// - public PageEventNetworkTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-event-network.spec.ts", "Page.Events.Request")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-event-network.spec.ts", "Page.Events.Request")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageEventsRequest() { var requests = new List(); Page.Request += (_, e) => requests.Add(e); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Single(requests); - Assert.Equal(TestConstants.EmptyPage, requests[0].Url); - Assert.Equal(ResourceTypes.Document, requests[0].ResourceType, true); - Assert.Equal(HttpMethod.Get.Method, requests[0].Method); - Assert.NotNull(await requests[0].GetResponseAsync()); - Assert.Equal(Page.MainFrame, requests[0].Frame); - Assert.Equal(TestConstants.EmptyPage, requests[0].Frame.Url); + Assert.That(requests, Has.Count.EqualTo(1)); + Assert.That(requests[0].Url, Is.EqualTo(TestConstants.EmptyPage)); + Assert.That(requests[0].ResourceType, Is.EqualTo(ResourceTypes.Document)); + Assert.That(requests[0].Method, Is.EqualTo(HttpMethod.Get.Method)); + Assert.That(await requests[0].GetResponseAsync(), Is.Not.Null); + Assert.That(requests[0].Frame, Is.EqualTo(Page.MainFrame)); + Assert.That(requests[0].Frame.Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("page-event-network.spec.ts", "Page.Events.Response")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageEventsResponse() { var responses = new List(); Page.Response += (_, e) => responses.Add(e); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Single(responses); - Assert.Equal(TestConstants.EmptyPage, responses[0].Url); - Assert.Equal(HttpStatusCode.OK, responses[0].StatusCode); - Assert.True(responses[0].Ok); - Assert.NotNull(responses[0].Request); + Assert.That(responses, Has.Count.EqualTo(1)); + Assert.That(responses[0].Url, Is.EqualTo(TestConstants.EmptyPage)); + Assert.That(responses[0].StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(responses[0].Ok, Is.True); + Assert.That(responses[0].Request, Is.Not.Null); } [PlaywrightTest("page-event-network.spec.ts", "Page.Events.RequestFailed")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageEventsRequestFailed() { int port = TestConstants.Port + 100; @@ -67,20 +59,20 @@ public async Task PageEventsRequestFailed() await Page.GoToAsync($"http://localhost:{port}/one-style.html"); - Assert.Single(failedRequests); - Assert.Contains("one-style.css", failedRequests[0].Url); - Assert.Null(await failedRequests[0].GetResponseAsync()); - Assert.Equal(ResourceTypes.Stylesheet, failedRequests[0].ResourceType, true); + Assert.That(failedRequests, Has.Count.EqualTo(1)); + Assert.That(failedRequests[0].Url, Does.Contain("one-style.css")); + Assert.That(await failedRequests[0].GetResponseAsync(), Is.Null); + Assert.That(failedRequests[0].ResourceType, Is.EqualTo(ResourceTypes.Stylesheet)); string error = string.Empty; //We just need to test that we had a failure. - Assert.NotNull(failedRequests[0].Failure); - Assert.NotNull(failedRequests[0].Frame); + Assert.That(failedRequests[0].Failure, Is.Not.Null); + Assert.That(failedRequests[0].Frame, Is.Not.Null); } [PlaywrightTest("page-event-network.spec.ts", "Page.Events.RequestFinished")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageEventsRequestFinished() { var (_, response) = await TaskUtils.WhenAll( @@ -88,15 +80,15 @@ public async Task PageEventsRequestFinished() Page.GoToAsync(TestConstants.EmptyPage)); var request = response.Request; - Assert.Equal(TestConstants.EmptyPage, request.Url); - Assert.NotNull(await request.GetResponseAsync()); - Assert.Equal(HttpMethod.Get.Method, request.Method); - Assert.Equal(Page.MainFrame, request.Frame); - Assert.Equal(TestConstants.EmptyPage, request.Frame.Url); + Assert.That(request.Url, Is.EqualTo(TestConstants.EmptyPage)); + Assert.That(await request.GetResponseAsync(), Is.Not.Null); + Assert.That(request.Method, Is.EqualTo(HttpMethod.Get.Method)); + Assert.That(request.Frame, Is.EqualTo(Page.MainFrame)); + Assert.That(request.Frame.Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("page-event-network.spec.ts", "should fire events in proper order")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFireEventsInProperOrder() { var events = new List(); @@ -105,11 +97,11 @@ public async Task ShouldFireEventsInProperOrder() var response = await Page.GoToAsync(TestConstants.EmptyPage); await response.GetFinishedAsync(); events.Add("requestfinished"); - Assert.Equal(new[] { "request", "response", "requestfinished" }, events); + Assert.That(events, Is.EqualTo(new[] { "request", "response", "requestfinished" })); } [PlaywrightTest("page-event-network.spec.ts", "should support redirects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportRedirects() { var events = new List(); @@ -121,21 +113,21 @@ public async Task ShouldSupportRedirects() const string FOO_URL = TestConstants.ServerUrl + "/foo.html"; var response = await Page.GoToAsync(FOO_URL); await response.GetFinishedAsync(); - Assert.Equal(new[] { + Assert.That(events, Is.EqualTo(new[] { $"GET {FOO_URL}", $"302 {FOO_URL}", $"DONE {FOO_URL}", $"GET {TestConstants.EmptyPage}", $"200 {TestConstants.EmptyPage}", $"DONE {TestConstants.EmptyPage}" - }, events); + })); // Check redirect chain var redirectedFrom = response.Request.RedirectedFrom; - Assert.Contains("/foo.html", redirectedFrom.Url); - Assert.NotNull(redirectedFrom.RedirectedTo); - Assert.Equal(response.Request, redirectedFrom.RedirectedTo); + Assert.That(redirectedFrom.Url, Does.Contain("/foo.html")); + Assert.That(redirectedFrom.RedirectedTo, Is.Not.Null); + Assert.That(redirectedFrom.RedirectedTo, Is.EqualTo(response.Request)); } } } diff --git a/src/Playwright.Tests/PageEventPageErrorTests.cs b/src/Playwright.Tests/PageEventPageErrorTests.cs index 1e5ee0b5e2..11a1281a9f 100644 --- a/src/Playwright.Tests/PageEventPageErrorTests.cs +++ b/src/Playwright.Tests/PageEventPageErrorTests.cs @@ -1,23 +1,15 @@ using System.Text.Json; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageEventPageErrorTests : PlaywrightSharpPageBaseTest - { - /// - public PageEventPageErrorTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-event-pageerror.spec.ts", "should fire")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-event-pageerror.spec.ts", "should fire")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFire() { var (error, _) = await TaskUtils.WhenAll( @@ -25,8 +17,8 @@ public async Task ShouldFire() Page.GoToAsync(TestConstants.ServerUrl + "/error.html") ); - Assert.Contains("Error", error); - Assert.Contains("Fancy error!", error); + Assert.That(error, Does.Contain("Error")); + Assert.That(error, Does.Contain("Fancy error!")); string stack = await Page.EvaluateAsync("() => window.e.stack"); if (TestConstants.IsWebKit) @@ -34,7 +26,7 @@ public async Task ShouldFire() stack = stack.Replace("14:25", "15:19"); } - Assert.Contains(stack, error); + Assert.That(error, Does.Contain(stack)); } [PlaywrightTest("page-event-pageerror.spec.ts", "should contain sourceURL")] @@ -45,11 +37,11 @@ public async Task ShouldContainSourceURL() Page.WaitForEventAsync(PageEvent.PageError), Page.GoToAsync(TestConstants.ServerUrl + "/error.html")); - Assert.Contains("myscript.js", error); + Assert.That(error, Does.Contain("myscript.js")); } [PlaywrightTest("page-event-pageerror.spec.ts", "should handle odd values")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHandleOddValues() { object[][] cases = new object[][] @@ -66,7 +58,7 @@ public async Task ShouldHandleOddValues() Page.WaitForEventAsync(PageEvent.PageError), Page.EvaluateAsync("value => setTimeout(() => { throw value; }, 0)", kv[0])); - Assert.Contains(TestConstants.IsFirefox ? "uncaught exception: " + kv[1].ToString() : kv[1].ToString(), error); + Assert.That(error, Does.Contain(TestConstants.IsFirefox ? "uncaught exception: " + kv[1].ToString() : kv[1].ToString())); } } @@ -78,7 +70,7 @@ public async Task ShouldHandleObject() Page.WaitForEventAsync(PageEvent.PageError), Page.EvaluateAsync("value => setTimeout(() => { throw {}; }, 0)", 0)); - Assert.Contains(TestConstants.IsChromium ? "Object" : "[object Object]", error); + Assert.That(error, Does.Contain(TestConstants.IsChromium ? "Object" : "[object Object]")); } [PlaywrightTest("page-event-pageerror.spec.ts", "should handle window")] @@ -89,7 +81,7 @@ public async Task ShouldHandleWindow() Page.WaitForEventAsync(PageEvent.PageError), Page.EvaluateAsync("value => setTimeout(() => { throw window ; }, 0)", 0)); - Assert.Contains(TestConstants.IsChromium ? "Window" : "[object Window]", error); + Assert.That(error, Does.Contain(TestConstants.IsChromium ? "Window" : "[object Window]")); } } } diff --git a/src/Playwright.Tests/PageEventPopupTests.cs b/src/Playwright.Tests/PageEventPopupTests.cs index c88cab3d92..980e93d023 100644 --- a/src/Playwright.Tests/PageEventPopupTests.cs +++ b/src/Playwright.Tests/PageEventPopupTests.cs @@ -1,22 +1,14 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageEventPopupTests : PlaywrightSharpPageBaseTest - { - /// - public PageEventPopupTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-event-popup.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-event-popup.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { var popupTask = Page.WaitForEventAsync(PageEvent.Popup); @@ -25,12 +17,12 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("() => window.open('about:blank')") ); var popup = popupTask.Result; - Assert.False(await Page.EvaluateAsync("() => !!window.opener")); - Assert.True(await popup.EvaluateAsync("() => !!window.opener")); + Assert.That(await Page.EvaluateAsync("() => !!window.opener"), Is.False); + Assert.That(await popup.EvaluateAsync("() => !!window.opener"), Is.True); } [PlaywrightTest("page-event-popup.spec.ts", "should work with window features")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithWindowFeatures() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -40,12 +32,12 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("() => window.open('about:blank', 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0')") ); var popup = popupTask.Result; - Assert.False(await Page.EvaluateAsync("() => !!window.opener")); - Assert.True(await popup.EvaluateAsync("() => !!window.opener")); + Assert.That(await Page.EvaluateAsync("() => !!window.opener"), Is.False); + Assert.That(await popup.EvaluateAsync("() => !!window.opener"), Is.True); } [PlaywrightTest("page-event-popup.spec.ts", "should emit for immediately closed popups")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmitForImmediatelyClosedPopups() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -57,11 +49,11 @@ await TaskUtils.WhenAll( win.close(); }") ); - Assert.NotNull(popupTask.Result); + Assert.That(popupTask.Result, Is.Not.Null); } [PlaywrightTest("page-event-popup.spec.ts", "should emit for immediately closed popups")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmitForImmediatelyClosedPopupsWithLocation() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -73,11 +65,11 @@ await TaskUtils.WhenAll( win.close(); }") ); - Assert.NotNull(popupTask.Result); + Assert.That(popupTask.Result, Is.Not.Null); } [PlaywrightTest("page-event-popup.spec.ts", "should be able to capture alert")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToCaptureAlert() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -90,13 +82,13 @@ public async Task ShouldBeAbleToCaptureAlert() var popup = await popupTask; var dialog = await popup.WaitForEventAsync(PageEvent.Dialog); - Assert.Equal("hello", dialog.Message); + Assert.That(dialog.Message, Is.EqualTo("hello")); await dialog.DismissAsync(); await evaluateTask; } [PlaywrightTest("page-event-popup.spec.ts", "should work with empty url")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithEmptyUrl() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -106,12 +98,12 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("() => window.open('')") ); var popup = popupTask.Result; - Assert.False(await Page.EvaluateAsync("() => !!window.opener")); - Assert.True(await popup.EvaluateAsync("() => !!window.opener")); + Assert.That(await Page.EvaluateAsync("() => !!window.opener"), Is.False); + Assert.That(await popup.EvaluateAsync("() => !!window.opener"), Is.True); } [PlaywrightTest("page-event-popup.spec.ts", "should work with noopener and no url")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNoopenerAndNoUrl() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -121,13 +113,13 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("() => window.open(undefined, null, 'noopener')") ); var popup = popupTask.Result; - Assert.Equal("about:blank", popup.Url.Split('#')[0]); - Assert.False(await Page.EvaluateAsync("() => !!window.opener")); - Assert.False(await popup.EvaluateAsync("() => !!window.opener")); + Assert.That(popup.Url.Split('#')[0], Is.EqualTo("about:blank")); + Assert.That(await Page.EvaluateAsync("() => !!window.opener"), Is.False); + Assert.That(await popup.EvaluateAsync("() => !!window.opener"), Is.False); } [PlaywrightTest("page-event-popup.spec.ts", "should work with noopener and about:blank")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNoopenerAndAboutBlank() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -137,12 +129,12 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("() => window.open('about:blank', null, 'noopener')") ); var popup = popupTask.Result; - Assert.False(await Page.EvaluateAsync("() => !!window.opener")); - Assert.False(await popup.EvaluateAsync("() => !!window.opener")); + Assert.That(await Page.EvaluateAsync("() => !!window.opener"), Is.False); + Assert.That(await popup.EvaluateAsync("() => !!window.opener"), Is.False); } [PlaywrightTest("page-event-popup.spec.ts", "should work with noopener and url")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNoopenerAndUrl() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -152,8 +144,8 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("url => window.open(url, null, 'noopener')", TestConstants.EmptyPage) ); var popup = popupTask.Result; - Assert.False(await Page.EvaluateAsync("() => !!window.opener")); - Assert.False(await popup.EvaluateAsync("() => !!window.opener")); + Assert.That(await Page.EvaluateAsync("() => !!window.opener"), Is.False); + Assert.That(await popup.EvaluateAsync("() => !!window.opener"), Is.False); } [PlaywrightTest("page-event-popup.spec.ts", "should work with clicking target=_blank")] @@ -174,8 +166,8 @@ await TaskUtils.WhenAll( ); var popup = await popupTask.Result; - Assert.False(await Page.EvaluateAsync("() => !!window.opener")); - Assert.True(await popup.EvaluateAsync("() => !!window.opener")); + Assert.That(await Page.EvaluateAsync("() => !!window.opener"), Is.False); + Assert.That(await popup.EvaluateAsync("() => !!window.opener"), Is.True); } [PlaywrightTest("page-event-popup.spec.ts", "should work with fake-clicking target=_blank and rel=noopener")] @@ -195,8 +187,8 @@ await TaskUtils.WhenAll( Page.EvalOnSelectorAsync("a", "a => a.click()") ); var popup = await popupTask.Result; - Assert.False(await Page.EvaluateAsync("() => !!window.opener")); - Assert.False(await popup.EvaluateAsync("() => !!window.opener")); + Assert.That(await Page.EvaluateAsync("() => !!window.opener"), Is.False); + Assert.That(await popup.EvaluateAsync("() => !!window.opener"), Is.False); } [PlaywrightTest("page-event-popup.spec.ts", "should work with clicking target=_blank and rel=noopener")] @@ -216,8 +208,8 @@ await TaskUtils.WhenAll( Page.ClickAsync("a") ); var popup = await popupTask.Result; - Assert.False(await Page.EvaluateAsync("() => !!window.opener")); - Assert.False(await popup.EvaluateAsync("() => !!window.opener")); + Assert.That(await Page.EvaluateAsync("() => !!window.opener"), Is.False); + Assert.That(await popup.EvaluateAsync("() => !!window.opener"), Is.False); } [PlaywrightTest("page-event-popup.spec.ts", "should not treat navigations as new popups")] @@ -240,7 +232,7 @@ await TaskUtils.WhenAll( bool badSecondPopup = false; Page.Popup += (_, _) => badSecondPopup = true; await popup.GoToAsync(TestConstants.CrossProcessUrl + "/empty.html"); - Assert.False(badSecondPopup); + Assert.That(badSecondPopup, Is.False); } } } diff --git a/src/Playwright.Tests/PageEventRequestTests.cs b/src/Playwright.Tests/PageEventRequestTests.cs index 56289687ce..0863bc04ba 100644 --- a/src/Playwright.Tests/PageEventRequestTests.cs +++ b/src/Playwright.Tests/PageEventRequestTests.cs @@ -1,54 +1,46 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageEventRequestTests : PlaywrightSharpPageBaseTest - { - /// - public PageEventRequestTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-event-request.spec.ts", "should fire for navigation requests")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-event-request.spec.ts", "should fire for navigation requests")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFireForNavigationRequests() { var requests = new List(); Page.Request += (_, e) => requests.Add(e); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Single(requests); + Assert.That(requests, Has.Count.EqualTo(1)); } [PlaywrightTest("page-event-request.spec.ts", "should fire for iframes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFireForIframes() { var requests = new List(); Page.Request += (_, e) => requests.Add(e); await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); - Assert.Equal(2, requests.Count); + Assert.That(requests.Count, Is.EqualTo(2)); } [PlaywrightTest("page-event-request.spec.ts", "should fire for fetches")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFireForFetches() { var requests = new List(); Page.Request += (_, e) => requests.Add(e); await Page.GoToAsync(TestConstants.EmptyPage); await Page.EvaluateAsync("fetch('/empty.html')"); - Assert.Equal(2, requests.Count); + Assert.That(requests.Count, Is.EqualTo(2)); } [PlaywrightTest("page-event-request.spec.ts", "should report requests and responses handled by service worker")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportRequestsAndResponsesHandledByServiceWorker() { await Page.GoToAsync(TestConstants.ServerUrl + "/serviceworkers/fetchdummy/sw.html"); @@ -58,11 +50,11 @@ public async Task ShouldReportRequestsAndResponsesHandledByServiceWorker() Page.WaitForEventAsync(PageEvent.Request), Page.EvaluateAsync("() => fetchDummy('foo')")); - Assert.Equal("responseFromServiceWorker:foo", swResponse); - Assert.Equal(TestConstants.ServerUrl + "/serviceworkers/fetchdummy/foo", request.Url); + Assert.That(swResponse, Is.EqualTo("responseFromServiceWorker:foo")); + Assert.That(request.Url, Is.EqualTo(TestConstants.ServerUrl + "/serviceworkers/fetchdummy/foo")); var response = await request.GetResponseAsync(); - Assert.Equal(TestConstants.ServerUrl + "/serviceworkers/fetchdummy/foo", response.Url); - Assert.Equal("responseFromServiceWorker:foo", await response.GetTextAsync()); + Assert.That(response.Url, Is.EqualTo(TestConstants.ServerUrl + "/serviceworkers/fetchdummy/foo")); + Assert.That(await response.GetTextAsync(), Is.EqualTo("responseFromServiceWorker:foo")); } } } diff --git a/src/Playwright.Tests/PageExposeFunctionTests.cs b/src/Playwright.Tests/PageExposeFunctionTests.cs index 26ba861dae..e0dd969dc6 100644 --- a/src/Playwright.Tests/PageExposeFunctionTests.cs +++ b/src/Playwright.Tests/PageExposeFunctionTests.cs @@ -1,24 +1,16 @@ using System.Linq; using System.Text.Json; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///page-expose-function.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageExposeFunctionTests : PlaywrightSharpPageBaseTest - { - /// - public PageExposeFunctionTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-expose-function.spec.ts", "exposeBinding should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-expose-function.spec.ts", "exposeBinding should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ExposeBindingShouldWork() { BindingSource bindingSource = null; @@ -31,25 +23,25 @@ await Page.ExposeBindingAsync("add", (BindingSource source, int a, int b) => int result = await Page.EvaluateAsync("async function () { return add(5, 6); }"); - Assert.Same(Context, bindingSource.Context); - Assert.Same(Page, bindingSource.Page); - Assert.Same(Page.MainFrame, bindingSource.Frame); - Assert.Equal(11, result); + Assert.That(bindingSource.Context, Is.SameAs(Context)); + Assert.That(bindingSource.Page, Is.SameAs(Page)); + Assert.That(bindingSource.Frame, Is.SameAs(Page.MainFrame)); + Assert.That(result, Is.EqualTo(11)); } [PlaywrightTest("page-expose-function.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.ExposeFunctionAsync("compute", (int a, int b) => a * b); int result = await Page.EvaluateAsync(@"async function() { return await compute(9, 4); }"); - Assert.Equal(36, result); + Assert.That(result, Is.EqualTo(36)); } [PlaywrightTest("page-expose-function.spec.ts", "should work with handles and complex objects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithHandlesAndComplexObjects() { var fooHandle = await Page.EvaluateHandleAsync(@"() => { @@ -59,15 +51,15 @@ public async Task ShouldWorkWithHandlesAndComplexObjects() await Page.ExposeFunctionAsync("handle", () => new[] { new { foo = fooHandle } }); - Assert.True(await Page.EvaluateAsync(@"async function() { + Assert.That(await Page.EvaluateAsync(@"async function() { const value = await window['handle'](); const [{ foo }] = value; return foo === window['fooValue']; - }")); + }"), Is.True); } [PlaywrightTest("page-expose-function.spec.ts", "should throw exception in page context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowExceptionInPageContext() { await Page.ExposeFunctionAsync("woof", () => @@ -84,18 +76,18 @@ await Page.ExposeFunctionAsync("woof", () => return { message: e.message, stack: e.stack}; } }"); - Assert.Equal("WOOF WOOF", result.GetProperty("message").GetString()); - Assert.Contains(nameof(PageExposeFunctionTests), result.GetProperty("stack").GetString()); + Assert.That(result.GetProperty("message").GetString(), Is.EqualTo("WOOF WOOF")); + Assert.That(result.GetProperty("stack").GetString(), Does.Contain(nameof(PageExposeFunctionTests))); } [PlaywrightTest("page-expose-function.spec.ts", @"should support throwing ""null""")] - [Fact(Skip = "Not relevant for C#, js specific")] + [Test, Ignore("Not relevant for C#, js specific")] public void ShouldSupportThrowingNull() { } [PlaywrightTest("page-expose-function.spec.ts", "should be callable from-inside addInitScript")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeCallableFromInsideAddInitScript() { bool called = false; @@ -105,11 +97,11 @@ await Page.ExposeFunctionAsync("woof", () => }); await Page.AddInitScriptAsync("() => woof()"); await Page.ReloadAsync(); - Assert.True(called); + Assert.That(called, Is.True); } [PlaywrightTest("page-expose-function.spec.ts", "should survive navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSurviveNavigation() { await Page.ExposeFunctionAsync("compute", (int a, int b) => a * b); @@ -117,22 +109,22 @@ public async Task ShouldSurviveNavigation() int result = await Page.EvaluateAsync(@"async function() { return await compute(9, 4); }"); - Assert.Equal(36, result); + Assert.That(result, Is.EqualTo(36)); } [PlaywrightTest("page-expose-function.spec.ts", "should await returned promise")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAwaitReturnedPromise() { await Page.ExposeFunctionAsync("compute", (int a, int b) => Task.FromResult(a * b)); int result = await Page.EvaluateAsync(@"async function() { return await compute(3, 5); }"); - Assert.Equal(15, result); + Assert.That(result, Is.EqualTo(15)); } [PlaywrightTest("page-expose-function.spec.ts", "should work on frames")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkOnFrames() { await Page.ExposeFunctionAsync("compute", (int a, int b) => Task.FromResult(a * b)); @@ -141,11 +133,11 @@ public async Task ShouldWorkOnFrames() int result = await frame.EvaluateAsync(@"async function() { return await compute(3, 5); }"); - Assert.Equal(15, result); + Assert.That(result, Is.EqualTo(15)); } [PlaywrightTest("page-expose-function.spec.ts", "should work on frames before navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkOnFramesBeforeNavigation() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/nested-frames.html"); @@ -154,11 +146,11 @@ public async Task ShouldWorkOnFramesBeforeNavigation() int result = await frame.EvaluateAsync(@"async function() { return await compute(3, 5); }"); - Assert.Equal(15, result); + Assert.That(result, Is.EqualTo(15)); } [PlaywrightTest("page-expose-function.spec.ts", "should work after cross origin navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkAfterCrossOriginNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -167,11 +159,11 @@ public async Task ShouldWorkAfterCrossOriginNavigation() int result = await Page.EvaluateAsync(@"async function() { return await compute(9, 4); }"); - Assert.Equal(36, result); + Assert.That(result, Is.EqualTo(36)); } [PlaywrightTest("page-expose-function.spec.ts", "should work with complex objects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithComplexObjects() { await Page.ExposeFunctionAsync("complexObject", (ComplexObject a, ComplexObject b) => @@ -179,11 +171,11 @@ await Page.ExposeFunctionAsync("complexObject", (ComplexObject a, ComplexObject return new ComplexObject { x = a.x + b.x }; }); var result = await Page.EvaluateAsync("async () => complexObject({ x: 5}, { x: 2})"); - Assert.Equal(7, result.x); + Assert.That(result.x, Is.EqualTo(7)); } [PlaywrightTest("page-expose-function.spec.ts", "exposeBindingHandle should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ExposeBindingHandleShouldWork() { IJSHandle target = null; @@ -199,12 +191,12 @@ await Page.ExposeBindingAsync( return window['logme']({ foo: 42 }); }"); - Assert.Equal(42, await target.EvaluateAsync("x => x.foo")); - Assert.Equal(17, result); + Assert.That(await target.EvaluateAsync("x => x.foo"), Is.EqualTo(42)); + Assert.That(result, Is.EqualTo(17)); } [PlaywrightTest("page-expose-function.spec.ts", "exposeBindingHandle should not throw during navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ExposeBindingHandleShouldNotThrowDuringNavigation() { IJSHandle target = null; @@ -225,16 +217,16 @@ await TaskUtils.WhenAll( } [PlaywrightTest("browsercontext-expose-function.spec.ts", "should throw for duplicate registrations")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowForDuplicateRegistrations() { await Page.ExposeFunctionAsync("foo", () => { }); - var exception = await Assert.ThrowsAnyAsync(() => Page.ExposeFunctionAsync("foo", () => { })); - Assert.Equal("Function \"foo\" has been already registered", exception.Message); + var exception = Assert.CatchAsync(() => Page.ExposeFunctionAsync("foo", () => { })); + Assert.That(exception.Message, Is.EqualTo("Function \"foo\" has been already registered")); } [PlaywrightTest("page-expose-function.spec.ts", "exposeBindingHandle should throw for multiple arguments")] - [Fact(Skip = "Not relevant for C#, js specific")] + [Test, Ignore("Not relevant for C#, js specific")] public void ExposeBindingHandleShouldThrowForMultipleArguments() { } diff --git a/src/Playwright.Tests/PageFillTests.cs b/src/Playwright.Tests/PageFillTests.cs index ba8cb72e16..41219a0395 100644 --- a/src/Playwright.Tests/PageFillTests.cs +++ b/src/Playwright.Tests/PageFillTests.cs @@ -1,53 +1,45 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageFillTests : PlaywrightSharpPageBaseTest - { - /// - public PageFillTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-fill.spec.ts", "should fill textarea")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-fill.spec.ts", "should fill textarea")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillTextarea() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.FillAsync("textarea", "some value"); - Assert.Equal("some value", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("some value")); } [PlaywrightTest("page-fill.spec.ts", "should fill input")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillInput() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.FillAsync("input", "some value"); - Assert.Equal("some value", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("some value")); } [PlaywrightTest("page-fill.spec.ts", "should throw on unsupported inputs")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowOnUnsupportedInputs() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); foreach (string type in new[] { "button", "checkbox", "file", "image", "radio", "range", "reset", "submit" }) { await Page.EvalOnSelectorAsync("input", "(input, type) => input.setAttribute('type', type)", type); - var exception = await Assert.ThrowsAsync(() => Page.FillAsync("input", string.Empty)); - Assert.Contains($"input of type \"{type}\" cannot be filled", exception.Message); + var exception = Assert.ThrowsAsync(() => Page.FillAsync("input", string.Empty)); + Assert.That(exception.Message, Does.Contain($"input of type \"{type}\" cannot be filled")); } } [PlaywrightTest("page-fill.spec.ts", "should fill different input types")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillDifferentInputTypes() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -55,18 +47,18 @@ public async Task ShouldFillDifferentInputTypes() { await Page.EvalOnSelectorAsync("input", "(input, type) => input.setAttribute('type', type)", type); await Page.FillAsync("input", "text " + type); - Assert.Equal("text " + type, await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("text " + type)); } } [PlaywrightTest("page-fill.spec.ts", "should fill date input after clicking")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillDateInputAfterClicking() { await Page.SetContentAsync(""); await Page.ClickAsync("input"); await Page.FillAsync("input", "2020-03-02"); - Assert.Equal("2020-03-02", await Page.EvalOnSelectorAsync("input", "input => input.value")); + Assert.That(await Page.EvalOnSelectorAsync("input", "input => input.value"), Is.EqualTo("2020-03-02")); } [PlaywrightTest("page-fill.spec.ts", "should throw on incorrect date")] @@ -75,18 +67,18 @@ public async Task ShouldThrowOnIncorrectDate() { await Page.SetContentAsync(""); await Page.ClickAsync("input"); - var exception = await Assert.ThrowsAnyAsync(() => Page.FillAsync("input", "2020-13-02")); - Assert.Contains("Malformed value", exception.Message); + var exception = Assert.CatchAsync(() => Page.FillAsync("input", "2020-13-02")); + Assert.That(exception.Message, Does.Contain("Malformed value")); } [PlaywrightTest("page-fill.spec.ts", "should fill time input after clicking")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillTimeInputAfterClicking() { await Page.SetContentAsync(""); await Page.ClickAsync("input"); await Page.FillAsync("input", "13:15"); - Assert.Equal("13:15", await Page.EvalOnSelectorAsync("input", "input => input.value")); + Assert.That(await Page.EvalOnSelectorAsync("input", "input => input.value"), Is.EqualTo("13:15")); } [PlaywrightTest("page-fill.spec.ts", "should throw on incorrect time")] @@ -95,18 +87,18 @@ public async Task ShouldThrowOnIncorrectTime() { await Page.SetContentAsync(""); await Page.ClickAsync("input"); - var exception = await Assert.ThrowsAnyAsync(() => Page.FillAsync("input", "25:05")); - Assert.Contains("Malformed value", exception.Message); + var exception = Assert.CatchAsync(() => Page.FillAsync("input", "25:05")); + Assert.That(exception.Message, Does.Contain("Malformed value")); } [PlaywrightTest("page-fill.spec.ts", "should fill datetime-local input")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillDatetimeLocalInput() { await Page.SetContentAsync(""); await Page.ClickAsync("input"); await Page.FillAsync("input", "2020-03-02T05:15"); - Assert.Equal("2020-03-02T05:15", await Page.EvalOnSelectorAsync("input", "input => input.value")); + Assert.That(await Page.EvalOnSelectorAsync("input", "input => input.value"), Is.EqualTo("2020-03-02T05:15")); } [PlaywrightTest("page-fill.spec.ts", "should throw on incorrect datetime-local")] @@ -115,35 +107,35 @@ public async Task ShouldThrowOnIncorrectDateTimeLocal() { await Page.SetContentAsync(""); await Page.ClickAsync("input"); - var exception = await Assert.ThrowsAnyAsync(() => Page.FillAsync("input", "abc")); - Assert.Contains("Malformed value", exception.Message); + var exception = Assert.CatchAsync(() => Page.FillAsync("input", "abc")); + Assert.That(exception.Message, Does.Contain("Malformed value")); } [PlaywrightTest("page-fill.spec.ts", "should fill contenteditable")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillContenteditable() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.FillAsync("div[contenteditable]", "some value"); - Assert.Equal("some value", await Page.EvalOnSelectorAsync("div[contenteditable]", "div => div.textContent")); + Assert.That(await Page.EvalOnSelectorAsync("div[contenteditable]", "div => div.textContent"), Is.EqualTo("some value")); } [PlaywrightTest("page-fill.spec.ts", "should fill elements with existing value and selection")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillElementsWithExistingValueAndSelection() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.EvalOnSelectorAsync("input", "input => input.value = 'value one'"); await Page.FillAsync("input", "another value"); - Assert.Equal("another value", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("another value")); await Page.EvalOnSelectorAsync("input", @"input => { input.selectionStart = 1; input.selectionEnd = 2; }"); await Page.FillAsync("input", "maybe this one"); - Assert.Equal("maybe this one", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("maybe this one")); await Page.EvalOnSelectorAsync("div[contenteditable]", @"div => { div.innerHTML = 'some text some more text and even more text'; @@ -154,26 +146,26 @@ await Page.EvalOnSelectorAsync("div[contenteditable]", @"div => { selection.addRange(range); }"); await Page.FillAsync("div[contenteditable]", "replace with this"); - Assert.Equal("replace with this", await Page.EvalOnSelectorAsync("div[contenteditable]", "div => div.textContent")); + Assert.That(await Page.EvalOnSelectorAsync("div[contenteditable]", "div => div.textContent"), Is.EqualTo("replace with this")); } [PlaywrightTest("page-fill.spec.ts", "should throw when element is not an <input>, <textarea> or [contenteditable]")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWhenElementIsNotAnInputOrTextareaOrContenteditable() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); - var exception = await Assert.ThrowsAsync(() => Page.FillAsync("body", string.Empty)); - Assert.Contains("Element is not an ", exception.Message); + var exception = Assert.ThrowsAsync(() => Page.FillAsync("body", string.Empty)); + Assert.That(exception.Message, Does.Contain("Element is not an ")); } [PlaywrightTest("page-fill.spec.ts", "should throw if passed a non-string value")] - [Fact(Skip = "Not relevant for C#, js specific")] + [Test, Ignore("Not relevant for C#, js specific")] public void ShouldThrowIfPassedANonStringValue() { } [PlaywrightTest("page-fill.spec.ts", "should retry on disabled element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRetryOnDisabledElement() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -181,32 +173,32 @@ public async Task ShouldRetryOnDisabledElement() var task = Page.FillAsync("input", "some value"); await GiveItAChanceToFillAsync(Page); - Assert.False(task.IsCompleted); - Assert.Empty(await Page.EvaluateAsync("() => result")); + Assert.That(task.IsCompleted, Is.False); + Assert.That(await Page.EvaluateAsync("() => result"), Is.Empty); await Page.EvalOnSelectorAsync("input", "i => i.disabled = false"); await task; - Assert.Equal("some value", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("some value")); } [PlaywrightTest("page-fill.spec.ts", "should retry on readonly element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRetryOnReadonlyElement() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.EvalOnSelectorAsync("textarea", "i => i.readOnly = true"); var task = Page.FillAsync("textarea", "some value"); await GiveItAChanceToFillAsync(Page); - Assert.False(task.IsCompleted); - Assert.Empty(await Page.EvaluateAsync("() => result")); + Assert.That(task.IsCompleted, Is.False); + Assert.That(await Page.EvaluateAsync("() => result"), Is.Empty); await Page.EvalOnSelectorAsync("textarea", "i => i.readOnly = false"); await task; - Assert.Equal("some value", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("some value")); } [PlaywrightTest("page-fill.spec.ts", "should retry on invisible element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRetryOnInvisibleElement() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -214,87 +206,87 @@ public async Task ShouldRetryOnInvisibleElement() var task = Page.FillAsync("input", "some value"); await GiveItAChanceToFillAsync(Page); - Assert.False(task.IsCompleted); - Assert.Empty(await Page.EvaluateAsync("() => result")); + Assert.That(task.IsCompleted, Is.False); + Assert.That(await Page.EvaluateAsync("() => result"), Is.Empty); await Page.EvalOnSelectorAsync("input", "i => i.style.display = 'inline'"); await task; - Assert.Equal("some value", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("some value")); } [PlaywrightTest("page-fill.spec.ts", "should be able to fill the body")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToFillTheBody() { await Page.SetContentAsync(""); await Page.FillAsync("body", "some value"); - Assert.Equal("some value", await Page.EvaluateAsync("() => document.body.textContent")); + Assert.That(await Page.EvaluateAsync("() => document.body.textContent"), Is.EqualTo("some value")); } [PlaywrightTest("page-fill.spec.ts", "should fill fixed position input")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFillFixedPositionInput() { await Page.SetContentAsync(""); await Page.FillAsync("input", "some value"); - Assert.Equal("some value", await Page.EvalOnSelectorAsync("input", "i => i.value")); + Assert.That(await Page.EvalOnSelectorAsync("input", "i => i.value"), Is.EqualTo("some value")); } [PlaywrightTest("page-fill.spec.ts", "should be able to fill when focus is in the wrong frame")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToFillWhenFocusIsInTheWrongFrame() { await Page.SetContentAsync("
"); await Page.FocusAsync("iframe"); await Page.FillAsync("div", "some value"); - Assert.Equal("some value", await Page.EvalOnSelectorAsync("div", "d => d.textContent")); + Assert.That(await Page.EvalOnSelectorAsync("div", "d => d.textContent"), Is.EqualTo("some value")); } [PlaywrightTest("page-fill.spec.ts", "should be able to fill the input[type=number]")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToFillTheInputTypeNumber() { await Page.SetContentAsync(""); await Page.FillAsync("input", "42"); - Assert.Equal("42", await Page.EvaluateAsync("() => input.value")); + Assert.That(await Page.EvaluateAsync("() => input.value"), Is.EqualTo("42")); } [PlaywrightTest("page-fill.spec.ts", "should be able to fill exponent into the input[type=number]")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToFillTheInputExponentIntoTypeNumber() { await Page.SetContentAsync(""); await Page.FillAsync("input", "-10e5"); - Assert.Equal("-10e5", await Page.EvaluateAsync("() => input.value")); + Assert.That(await Page.EvaluateAsync("() => input.value"), Is.EqualTo("-10e5")); } [PlaywrightTest("page-fill.spec.ts", "should be able to fill the input[type=number] with empty string")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToFillTheInputTypeNumberWithEmptyString() { await Page.SetContentAsync(""); await Page.FillAsync("input", ""); - Assert.Empty(await Page.EvaluateAsync("() => input.value")); + Assert.That(await Page.EvaluateAsync("() => input.value"), Is.Empty); } [PlaywrightTest("page-fill.spec.ts", "should not be able to fill text into the input[type=number]")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotBeAbleToFillTextIntoTheInputTypeNumber() { await Page.SetContentAsync(""); - var exception = await Assert.ThrowsAnyAsync(() => Page.FillAsync("input", "abc")); - Assert.Contains("Cannot type text into input[type=number]", exception.Message); + var exception = Assert.CatchAsync(() => Page.FillAsync("input", "abc")); + Assert.That(exception.Message, Does.Contain("Cannot type text into input[type=number]")); } [PlaywrightTest("page-fill.spec.ts", "should be able to clear")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToClear() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.FillAsync("input", "some value"); - Assert.Equal("some value", await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.EqualTo("some value")); await Page.FillAsync("input", ""); - Assert.Empty(await Page.EvaluateAsync("() => result")); + Assert.That(await Page.EvaluateAsync("() => result"), Is.Empty); } private async Task GiveItAChanceToFillAsync(IPage page) diff --git a/src/Playwright.Tests/PageFocusTests.cs b/src/Playwright.Tests/PageFocusTests.cs index 65070eed52..caf867b08e 100644 --- a/src/Playwright.Tests/PageFocusTests.cs +++ b/src/Playwright.Tests/PageFocusTests.cs @@ -1,32 +1,24 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageFocusTests : PlaywrightSharpPageBaseTest - { - /// - public PageFocusTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-focus.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-focus.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.SetContentAsync("
"); - Assert.Equal("BODY", await Page.EvaluateAsync("() => document.activeElement.nodeName")); + Assert.That(await Page.EvaluateAsync("() => document.activeElement.nodeName"), Is.EqualTo("BODY")); await Page.FocusAsync("#d1"); - Assert.Equal("d1", await Page.EvaluateAsync("() => document.activeElement.id")); + Assert.That(await Page.EvaluateAsync("() => document.activeElement.id"), Is.EqualTo("d1")); } [PlaywrightTest("page-focus.spec.ts", "should emit focus event")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmitFocusEvent() { await Page.SetContentAsync("
"); @@ -34,11 +26,11 @@ public async Task ShouldEmitFocusEvent() await Page.ExposeFunctionAsync("focusEvent", () => focused = true); await Page.EvaluateAsync("() => d1.addEventListener('focus', focusEvent)"); await Page.FocusAsync("#d1"); - Assert.True(focused); + Assert.That(focused, Is.True); } [PlaywrightTest("page-focus.spec.ts", "should emit blur event")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmitBlurEvent() { await Page.SetContentAsync("
DIV1
DIV2
"); @@ -50,8 +42,8 @@ public async Task ShouldEmitBlurEvent() await Page.EvaluateAsync("() => d1.addEventListener('blur', blurEvent)"); await Page.EvaluateAsync("() => d2.addEventListener('focus', focusEvent)"); await Page.FocusAsync("#d2"); - Assert.True(focused); - Assert.True(blurred); + Assert.That(focused, Is.True); + Assert.That(blurred, Is.True); } [PlaywrightTest("page-focus.spec.ts", "should traverse focus")] @@ -68,10 +60,10 @@ public async Task ShouldTraverseFocus() await Page.Keyboard.PressAsync("Tab"); await Page.Keyboard.TypeAsync("Last"); - Assert.True(focused); + Assert.That(focused, Is.True); - Assert.Equal("First", await Page.EvalOnSelectorAsync("#i1", "e => e.value")); - Assert.Equal("Last", await Page.EvalOnSelectorAsync("#i2", "e => e.value")); + Assert.That(await Page.EvalOnSelectorAsync("#i1", "e => e.value"), Is.EqualTo("First")); + Assert.That(await Page.EvalOnSelectorAsync("#i2", "e => e.value"), Is.EqualTo("Last")); } } } diff --git a/src/Playwright.Tests/PageGoToTests.cs b/src/Playwright.Tests/PageGoToTests.cs index d04aab4f28..6fa5c8d7d3 100644 --- a/src/Playwright.Tests/PageGoToTests.cs +++ b/src/Playwright.Tests/PageGoToTests.cs @@ -3,53 +3,45 @@ using System.IO; using System.Net; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class GoToTests : PlaywrightSharpPageBaseTest - { - /// - public GoToTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-goto.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-goto.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(TestConstants.EmptyPage, Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should work with file URL")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithFileURL() { string fileurl = new Uri(TestUtils.GetWebServerFile(Path.Combine("frames", "two-frames.html"))).AbsoluteUri; await Page.GoToAsync(fileurl); - Assert.Equal(fileurl.ToLower(), Page.Url.ToLower()); - Assert.Equal(3, Page.Frames.Count); + Assert.That(Page.Url.ToLower(), Is.EqualTo(fileurl.ToLower())); + Assert.That(Page.Frames.Count, Is.EqualTo(3)); } [PlaywrightTest("page-goto.spec.ts", "should use http for no protocol")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUseHttpForNoProtocol() { await Page.GoToAsync(TestConstants.EmptyPage.Replace("http://", string.Empty)); - Assert.Equal(TestConstants.EmptyPage, Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should work cross-process")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkCrossProcess() { await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(TestConstants.EmptyPage, Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage)); string url = TestConstants.CrossProcessHttpPrefix + "/empty.html"; IFrame requestFrame = null; @@ -62,18 +54,18 @@ public async Task ShouldWorkCrossProcess() }; var response = await Page.GoToAsync(url); - Assert.Equal(url, Page.Url); - Assert.Same(Page.MainFrame, response.Frame); - Assert.Same(Page.MainFrame, requestFrame); - Assert.Equal(url, response.Url); + Assert.That(Page.Url, Is.EqualTo(url)); + Assert.That(response.Frame, Is.SameAs(Page.MainFrame)); + Assert.That(requestFrame, Is.SameAs(Page.MainFrame)); + Assert.That(response.Url, Is.EqualTo(url)); } [PlaywrightTest("page-goto.spec.ts", "should capture iframe navigation request")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCaptureIframeNavigationRequest() { await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(TestConstants.EmptyPage, Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage)); IFrame requestFrame = null; Page.Request += (_, e) => @@ -85,20 +77,20 @@ public async Task ShouldCaptureIframeNavigationRequest() }; var response = await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); - Assert.Equal(TestConstants.ServerUrl + "/frames/one-frame.html", Page.Url); - Assert.Same(Page.MainFrame, response.Frame); - Assert.Equal(TestConstants.ServerUrl + "/frames/one-frame.html", response.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/frames/one-frame.html")); + Assert.That(response.Frame, Is.SameAs(Page.MainFrame)); + Assert.That(response.Url, Is.EqualTo(TestConstants.ServerUrl + "/frames/one-frame.html")); - Assert.Equal(2, Page.Frames.Count); - Assert.Same(Page.FirstChildFrame(), requestFrame); + Assert.That(Page.Frames.Count, Is.EqualTo(2)); + Assert.That(requestFrame, Is.SameAs(Page.FirstChildFrame())); } [PlaywrightTest("page-goto.spec.ts", "should capture cross-process iframe navigation request")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldCaptureCrossProcessIframeNavigationRequest() { await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(TestConstants.EmptyPage, Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage)); IFrame requestFrame = null; Page.Request += (_, e) => @@ -110,56 +102,56 @@ public async Task ShouldCaptureCrossProcessIframeNavigationRequest() }; var response = await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/frames/one-frame.html"); - Assert.Equal(TestConstants.CrossProcessHttpPrefix + "/frames/one-frame.html", Page.Url); - Assert.Same(Page.MainFrame, response.Frame); - Assert.Equal(TestConstants.CrossProcessHttpPrefix + "/frames/one-frame.html", response.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.CrossProcessHttpPrefix + "/frames/one-frame.html")); + Assert.That(response.Frame, Is.SameAs(Page.MainFrame)); + Assert.That(response.Url, Is.EqualTo(TestConstants.CrossProcessHttpPrefix + "/frames/one-frame.html")); - Assert.Equal(2, Page.Frames.Count); - Assert.Same(Page.FirstChildFrame(), requestFrame); + Assert.That(Page.Frames.Count, Is.EqualTo(2)); + Assert.That(requestFrame, Is.SameAs(Page.FirstChildFrame())); } [PlaywrightTest("page-goto.spec.ts", "should work with anchor navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithAnchorNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(TestConstants.EmptyPage, Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage)); await Page.GoToAsync($"{TestConstants.EmptyPage}#foo"); - Assert.Equal($"{TestConstants.EmptyPage}#foo", Page.Url); + Assert.That(Page.Url, Is.EqualTo($"{TestConstants.EmptyPage}#foo")); await Page.GoToAsync($"{TestConstants.EmptyPage}#bar"); - Assert.Equal($"{TestConstants.EmptyPage}#bar", Page.Url); + Assert.That(Page.Url, Is.EqualTo($"{TestConstants.EmptyPage}#bar")); } [PlaywrightTest("page-goto.spec.ts", "should work with redirects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithRedirects() { Server.SetRedirect("/redirect/1.html", "/redirect/2.html"); Server.SetRedirect("/redirect/2.html", "/empty.html"); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/redirect/1.html"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); await Page.GoToAsync(TestConstants.EmptyPage); } [PlaywrightTest("page-goto.spec.ts", "should navigate to about:blank")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNavigateToAboutBlank() { var response = await Page.GoToAsync(TestConstants.AboutBlank); - Assert.Null(response); + Assert.That(response, Is.Null); } [PlaywrightTest("page-goto.spec.ts", "should return response when page changes its URL after load")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnResponseWhenPageChangesItsURLAfterLoad() { var response = await Page.GoToAsync(TestConstants.ServerUrl + "/historyapi.html"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [PlaywrightTest("page-goto.spec.ts", "should work with subframes return 204")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithSubframesReturn204() { Server.SetRoute("/frames/frame.html", context => @@ -171,7 +163,7 @@ public async Task ShouldWorkWithSubframesReturn204() } [PlaywrightTest("page-goto.spec.ts", "should work with subframes return 204")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenServerReturns204() { Server.SetRoute("/empty.html", context => @@ -179,33 +171,33 @@ public async Task ShouldFailWhenServerReturns204() context.Response.StatusCode = 204; return Task.CompletedTask; }); - var exception = await Assert.ThrowsAnyAsync( + var exception = Assert.CatchAsync( () => Page.GoToAsync(TestConstants.EmptyPage)); if (TestConstants.IsChromium) { - Assert.Contains("net::ERR_ABORTED", exception.Message); + Assert.That(exception.Message, Does.Contain("net::ERR_ABORTED")); } else if (TestConstants.IsFirefox) { - Assert.Contains("NS_BINDING_ABORTED", exception.Message); + Assert.That(exception.Message, Does.Contain("NS_BINDING_ABORTED")); } else { - Assert.Contains("Aborted: 204 No Content", exception.Message); + Assert.That(exception.Message, Does.Contain("Aborted: 204 No Content")); } } [PlaywrightTest("page-goto.spec.ts", "should navigate to empty page with domcontentloaded")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNavigateToEmptyPageWithDOMContentLoaded() { var response = await Page.GoToAsync(TestConstants.EmptyPage, WaitUntilState.DOMContentLoaded); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [PlaywrightTest("page-goto.spec.ts", "should work when page calls history API in beforeunload")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenPageCallsHistoryAPIInBeforeunload() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -214,51 +206,51 @@ await Page.EvaluateAsync(@"() => window.addEventListener('beforeunload', () => history.replaceState(null, 'initial', window.location.href), false); }"); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [PlaywrightTest("page-goto.spec.ts", "should fail when navigating to bad url")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenNavigatingToBadUrl() { - var exception = await Assert.ThrowsAnyAsync(async () => await Page.GoToAsync("asdfasdf")); + var exception = Assert.CatchAsync(async () => await Page.GoToAsync("asdfasdf")); if (TestConstants.IsChromium || TestConstants.IsWebKit) { - Assert.Contains("Cannot navigate to invalid URL", exception.Message); + Assert.That(exception.Message, Does.Contain("Cannot navigate to invalid URL")); } else { - Assert.Contains("Invalid url", exception.Message); + Assert.That(exception.Message, Does.Contain("Invalid url")); } } [PlaywrightTest("page-goto.spec.ts", "should fail when navigating to bad SSL")] - // [Fact(Timeout = TestConstants.DefaultTestTimeout)] - [Fact(Skip = "Fix me #1058")] + // [Test, Timeout(TestConstants.DefaultTestTimeout)] + [Test, Ignore("Fix me #1058")] public async Task ShouldFailWhenNavigatingToBadSSL() { - Page.Request += (_, e) => Assert.NotNull(e); - Page.RequestFinished += (_, e) => Assert.NotNull(e); - Page.RequestFailed += (_, e) => Assert.NotNull(e); + Page.Request += (_, e) => Assert.That(e, Is.Not.Null); + Page.RequestFinished += (_, e) => Assert.That(e, Is.Not.Null); + Page.RequestFailed += (_, e) => Assert.That(e, Is.Not.Null); - var exception = await Assert.ThrowsAnyAsync(async () => await Page.GoToAsync(TestConstants.HttpsPrefix + "/empty.html")); + var exception = Assert.CatchAsync(async () => await Page.GoToAsync(TestConstants.HttpsPrefix + "/empty.html")); TestUtils.AssertSSLError(exception.Message); } [PlaywrightTest("page-goto.spec.ts", "should fail when navigating to bad SSL after redirects")] - // [Fact(Timeout = TestConstants.DefaultTestTimeout)] - [Fact(Skip = "Fix me #1058")] + // [Test, Timeout(TestConstants.DefaultTestTimeout)] + [Test, Ignore("Fix me #1058")] public async Task ShouldFailWhenNavigatingToBadSSLAfterRedirects() { Server.SetRedirect("/redirect/1.html", "/redirect/2.html"); Server.SetRedirect("/redirect/2.html", "/empty.html"); - var exception = await Assert.ThrowsAnyAsync(async () => await Page.GoToAsync(TestConstants.HttpsPrefix + "/redirect/1.html")); + var exception = Assert.CatchAsync(async () => await Page.GoToAsync(TestConstants.HttpsPrefix + "/redirect/1.html")); TestUtils.AssertSSLError(exception.Message); } [PlaywrightTest("page-goto.spec.ts", "should not crash when navigating to bad SSL after a cross origin navigation")] - // [Fact(Timeout = TestConstants.DefaultTestTimeout)] - [Fact(Skip = "Fix me #1058")] + // [Test, Timeout(TestConstants.DefaultTestTimeout)] + [Test, Ignore("Fix me #1058")] public async Task ShouldNotCrashWhenNavigatingToBadSSLAfterACrossOriginNavigation() { await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/empty.html"); @@ -266,111 +258,111 @@ public async Task ShouldNotCrashWhenNavigatingToBadSSLAfterACrossOriginNavigatio } [PlaywrightTest("page-goto.spec.ts", "should throw if networkidle0 is passed as an option")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldThrowIfNetworkIdle0IsPassedAsAnOption() { } [PlaywrightTest("page-goto.spec.ts", "should throw if networkidle2 is passed as an option")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldThrowIfNetworkIdle2IsPassedAsAnOption() { } [PlaywrightTest("page-goto.spec.ts", "should throw if networkidle is passed as an option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenMainResourcesFailedToLoad() { - var exception = await Assert.ThrowsAnyAsync(async () => await Page.GoToAsync("http://localhost:44123/non-existing-url")); + var exception = Assert.CatchAsync(async () => await Page.GoToAsync("http://localhost:44123/non-existing-url")); if (TestConstants.IsChromium) { - Assert.Contains("net::ERR_CONNECTION_REFUSED", exception.Message); + Assert.That(exception.Message, Does.Contain("net::ERR_CONNECTION_REFUSED")); } else if (TestConstants.IsWebKit && TestConstants.IsWindows) { - Assert.Contains("Couldn't connect to server", exception.Message); + Assert.That(exception.Message, Does.Contain("Couldn't connect to server")); } else if (TestConstants.IsWebKit) { - Assert.Contains("Could not connect", exception.Message); + Assert.That(exception.Message, Does.Contain("Could not connect")); } else { - Assert.Contains("NS_ERROR_CONNECTION_REFUSED", exception.Message); + Assert.That(exception.Message, Does.Contain("NS_ERROR_CONNECTION_REFUSED")); } } [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding maximum navigation timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenExceedingMaximumNavigationTimeout() { Server.SetRoute("/empty.html", _ => Task.Delay(-1)); - var exception = await Assert.ThrowsAsync(async () + var exception = Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage, timeout: 1)); - Assert.Contains("Timeout 1ms exceeded", exception.Message); - Assert.Contains(TestConstants.EmptyPage, exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 1ms exceeded")); + Assert.That(exception.Message, Does.Contain(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding maximum navigation timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenExceedingDefaultMaximumNavigationTimeout() { Server.SetRoute("/empty.html", _ => Task.Delay(-1)); Page.Context.DefaultNavigationTimeout = 2; Page.DefaultNavigationTimeout = 1; - var exception = await Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); - Assert.Contains("Timeout 1ms exceeded", exception.Message); - Assert.Contains(TestConstants.EmptyPage, exception.Message); + var exception = Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); + Assert.That(exception.Message, Does.Contain("Timeout 1ms exceeded")); + Assert.That(exception.Message, Does.Contain(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding browser context navigation timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenExceedingBrowserContextNavigationTimeout() { Server.SetRoute("/empty.html", _ => Task.Delay(-1)); Page.Context.DefaultNavigationTimeout = 2; - var exception = await Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); - Assert.Contains("Timeout 2ms exceeded", exception.Message); - Assert.Contains(TestConstants.EmptyPage, exception.Message); + var exception = Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); + Assert.That(exception.Message, Does.Contain("Timeout 2ms exceeded")); + Assert.That(exception.Message, Does.Contain(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding default maximum timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenExceedingDefaultMaximumTimeout() { Server.SetRoute("/empty.html", _ => Task.Delay(-1)); Page.Context.DefaultTimeout = 2; Page.DefaultTimeout = 1; - var exception = await Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); - Assert.Contains("Timeout 1ms exceeded", exception.Message); - Assert.Contains(TestConstants.EmptyPage, exception.Message); + var exception = Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); + Assert.That(exception.Message, Does.Contain("Timeout 1ms exceeded")); + Assert.That(exception.Message, Does.Contain(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding browser context timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenExceedingBrowserContextTimeout() { Server.SetRoute("/empty.html", _ => Task.Delay(-1)); Page.Context.DefaultTimeout = 2; - var exception = await Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); - Assert.Contains("Timeout 2ms exceeded", exception.Message); - Assert.Contains(TestConstants.EmptyPage, exception.Message); + var exception = Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); + Assert.That(exception.Message, Does.Contain("Timeout 2ms exceeded")); + Assert.That(exception.Message, Does.Contain(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should prioritize default navigation timeout over default timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPrioritizeDefaultNavigationTimeoutOverDefaultTimeout() { // Hang for request to the empty.html Server.SetRoute("/empty.html", _ => Task.Delay(-1)); Page.DefaultTimeout = 0; Page.DefaultNavigationTimeout = 1; - var exception = await Assert.ThrowsAnyAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); - Assert.Contains("Timeout 1ms exceeded", exception.Message); - Assert.Contains(TestConstants.EmptyPage, exception.Message); + var exception = Assert.CatchAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); + Assert.That(exception.Message, Does.Contain("Timeout 1ms exceeded")); + Assert.That(exception.Message, Does.Contain(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should disable timeout when its set to 0")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDisableTimeoutWhenItsSetTo0() { bool loaded = false; @@ -382,11 +374,11 @@ void OnLoad(object sender, IPage e) Page.Load += OnLoad; await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html", WaitUntilState.Load, 0); - Assert.True(loaded); + Assert.That(loaded, Is.True); } [PlaywrightTest("page-goto.spec.ts", "should fail when replaced by another navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenReplacedByAnotherNavigation() { Task anotherTask = null; @@ -398,49 +390,49 @@ public async Task ShouldFailWhenReplacedByAnotherNavigation() return Task.Delay(-1); }); - var exception = await Assert.ThrowsAnyAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); + var exception = Assert.CatchAsync(async () => await Page.GoToAsync(TestConstants.EmptyPage)); await anotherTask; if (TestConstants.IsChromium) { - Assert.Contains("net::ERR_ABORTED", exception.Message); + Assert.That(exception.Message, Does.Contain("net::ERR_ABORTED")); } else if (TestConstants.IsWebKit) { - Assert.Contains("cancelled", exception.Message); + Assert.That(exception.Message, Does.Contain("cancelled")); } else { - Assert.Contains("NS_BINDING_ABORTED", exception.Message); + Assert.That(exception.Message, Does.Contain("NS_BINDING_ABORTED")); } } [PlaywrightTest("page-goto.spec.ts", "should work when navigating to valid url")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenNavigatingToValidUrl() { var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [PlaywrightTest("page-goto.spec.ts", "should work when navigating to data url")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenNavigatingToDataUrl() { var response = await Page.GoToAsync("data:text/html,hello"); - Assert.Null(response); + Assert.That(response, Is.Null); } [PlaywrightTest("page-goto.spec.ts", "should work when navigating to 404")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenNavigatingTo404() { var response = await Page.GoToAsync(TestConstants.ServerUrl + "/not-found"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); } [PlaywrightTest("page-goto.spec.ts", "should return last response in redirect chain")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnLastResponseInRedirectChain() { Server.SetRedirect("/redirect/1.html", "/redirect/2.html"); @@ -448,27 +440,27 @@ public async Task ShouldReturnLastResponseInRedirectChain() Server.SetRedirect("/redirect/3.html", TestConstants.EmptyPage); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/redirect/1.html"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(TestConstants.EmptyPage, response.Url); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(response.Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should not leak listeners during navigation")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldNotLeakListenersDuringNavigation() { } [PlaywrightTest("page-goto.spec.ts", "should not leak listeners during bad navigation")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldNotLeakListenersDuringBadNavigation() { } [PlaywrightTest("page-goto.spec.ts", "should not leak listeners during navigation of 11 pages")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldNotLeakListenersDuringNavigationOf11Pages() { } [PlaywrightTest("page-goto.spec.ts", "should navigate to dataURL and not fire dataURL requests")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNavigateToDataURLAndNotFireDataURLRequests() { var requests = new List(); @@ -476,45 +468,45 @@ public async Task ShouldNavigateToDataURLAndNotFireDataURLRequests() string dataUrl = "data:text/html,
yo
"; var response = await Page.GoToAsync(dataUrl); - Assert.Null(response); - Assert.Empty(requests); + Assert.That(response, Is.Null); + Assert.That(requests, Is.Empty); } [PlaywrightTest("page-goto.spec.ts", "should navigate to URL with hash and fire requests without hash")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNavigateToURLWithHashAndFireRequestsWithoutHash() { var requests = new List(); Page.Request += (_, e) => requests.Add(e); var response = await Page.GoToAsync(TestConstants.EmptyPage + "#hash"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(TestConstants.EmptyPage, response.Url); - Assert.Single(requests); - Assert.Equal(TestConstants.EmptyPage, requests[0].Url); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(response.Url, Is.EqualTo(TestConstants.EmptyPage)); + Assert.That(requests, Has.Count.EqualTo(1)); + Assert.That(requests[0].Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("page-goto.spec.ts", "should work with self requesting page")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithSelfRequestingPage() { var response = await Page.GoToAsync(TestConstants.ServerUrl + "/self-request.html"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("self-request.html", response.Url); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(response.Url, Does.Contain("self-request.html")); } [PlaywrightTest("page-goto.spec.ts", "should fail when navigating and show the url at the error message")] - // [Fact(Timeout = TestConstants.DefaultTestTimeout)] - [Fact(Skip = "Fix me #1058")] + // [Test, Timeout(TestConstants.DefaultTestTimeout)] + [Test, Ignore("Fix me #1058")] public async Task ShouldFailWhenNavigatingAndShowTheUrlAtTheErrorMessage() { const string url = TestConstants.HttpsPrefix + "/redirect/1.html"; - var exception = await Assert.ThrowsAnyAsync(async () => await Page.GoToAsync(url)); - Assert.Contains(url, exception.Message); + var exception = Assert.CatchAsync(async () => await Page.GoToAsync(url)); + Assert.That(exception.Message, Does.Contain(url)); } [PlaywrightTest("page-goto.spec.ts", "should be able to navigate to a page controlled by service worker")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToNavigateToAPageControlledByServiceWorker() { await Page.GoToAsync(TestConstants.ServerUrl + "/serviceworkers/fetch/sw.html"); @@ -523,7 +515,7 @@ public async Task ShouldBeAbleToNavigateToAPageControlledByServiceWorker() } [PlaywrightTest("page-goto.spec.ts", "should send referer")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendReferer() { string referer1 = null; @@ -535,14 +527,14 @@ await TaskUtils.WhenAll( Page.GoToAsync(TestConstants.ServerUrl + "/grid.html", referer: "http://google.com/") ); - Assert.Equal("http://google.com/", referer1); + Assert.That(referer1, Is.EqualTo("http://google.com/")); // Make sure subresources do not inherit referer. - Assert.Equal(TestConstants.ServerUrl + "/grid.html", referer2); - Assert.Equal(TestConstants.ServerUrl + "/grid.html", Page.Url); + Assert.That(referer2, Is.EqualTo(TestConstants.ServerUrl + "/grid.html")); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/grid.html")); } [PlaywrightTest("page-goto.spec.ts", "should reject referer option when setExtraHTTPHeaders provides referer")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRejectRefererOptionWhenSetExtraHTTPHeadersProvidesReferer() { await Page.SetExtraHttpHeadersAsync(new Dictionary @@ -550,15 +542,15 @@ await Page.SetExtraHttpHeadersAsync(new Dictionary ["referer"] = "http://microsoft.com/" }); - var exception = await Assert.ThrowsAsync(async () => + var exception = Assert.ThrowsAsync(async () => await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html", referer: "http://google.com/")); - Assert.Contains("\"referer\" is already specified as extra HTTP header", exception.Message); - Assert.Contains(TestConstants.ServerUrl + "/grid.html", exception.Message); + Assert.That(exception.Message, Does.Contain("\"referer\" is already specified as extra HTTP header")); + Assert.That(exception.Message, Does.Contain(TestConstants.ServerUrl + "/grid.html")); } [PlaywrightTest("page-goto.spec.ts", "should override referrer-policy")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldOverrideReferrerPolicy() { Server.Subscribe("/grid.html", context => @@ -576,14 +568,14 @@ await TaskUtils.WhenAll( reqTask2, Page.GoToAsync(TestConstants.ServerUrl + "/grid.html", referer: "http://microsoft.com/")); - Assert.Equal("http://microsoft.com/", referer1); + Assert.That(referer1, Is.EqualTo("http://microsoft.com/")); // Make sure subresources do not inherit referer. - Assert.Null(referer2); - Assert.Equal(TestConstants.ServerUrl + "/grid.html", Page.Url); + Assert.That(referer2, Is.Null); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/grid.html")); } [PlaywrightTest("page-goto.spec.ts", "should fail when canceled by another navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenCanceledByAnotherNavigation() { Server.SetRoute("/one-style.html", _ => Task.Delay(10_000)); @@ -592,11 +584,11 @@ public async Task ShouldFailWhenCanceledByAnotherNavigation() await request; await Page.GoToAsync(TestConstants.EmptyPage); - await Assert.ThrowsAnyAsync(async () => await failed); + Assert.CatchAsync(async () => await failed); } [PlaywrightTest("page-goto.spec.ts", "extraHTTPHeaders should be pushed to provisional page")] - [Fact(Skip = "Skipped in Playwright")] + [Test, Ignore("Skipped in Playwright")] public void ExtraHTTPHeadersShouldBePushedToProvisionalPage() { } diff --git a/src/Playwright.Tests/PageHistoryTests.cs b/src/Playwright.Tests/PageHistoryTests.cs index 6b2a7d3219..b6de4caf86 100644 --- a/src/Playwright.Tests/PageHistoryTests.cs +++ b/src/Playwright.Tests/PageHistoryTests.cs @@ -1,40 +1,32 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageHistoryTests : PlaywrightSharpPageBaseTest - { - /// - public PageHistoryTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-history.spec.ts", "page.goBack should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-history.spec.ts", "page.goBack should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageGobackShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); var response = await Page.GoBackAsync(); - Assert.True(response.Ok); - Assert.Contains(TestConstants.EmptyPage, response.Url); + Assert.That(response.Ok, Is.True); + Assert.That(response.Url, Does.Contain(TestConstants.EmptyPage)); response = await Page.GoForwardAsync(); - Assert.True(response.Ok); - Assert.Contains("/grid.html", response.Url); + Assert.That(response.Ok, Is.True); + Assert.That(response.Url, Does.Contain("/grid.html")); response = await Page.GoForwardAsync(); - Assert.Null(response); + Assert.That(response, Is.Null); } [PlaywrightTest("page-history.spec.ts", "page.goBack should work with HistoryAPI")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageGoBackShouldWorkWithHistoryAPI() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -42,31 +34,31 @@ await Page.EvaluateAsync(@" history.pushState({ }, '', '/first.html'); history.pushState({ }, '', '/second.html'); "); - Assert.Equal(TestConstants.ServerUrl + "/second.html", Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/second.html")); await Page.GoBackAsync(); - Assert.Equal(TestConstants.ServerUrl + "/first.html", Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/first.html")); await Page.GoBackAsync(); - Assert.Equal(TestConstants.EmptyPage, Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage)); await Page.GoForwardAsync(); - Assert.Equal(TestConstants.ServerUrl + "/first.html", Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/first.html")); } [PlaywrightTest("page-history.spec.ts", "should work for file urls")] - [Fact(Skip = "We need screenshots for this")] + [Test, Ignore("We need screenshots for this")] public void ShouldWorkForFileUrls() { } [PlaywrightTest("page-history.spec.ts", "page.reload should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageReloadShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); await Page.EvaluateAsync("() => window._foo = 10"); await Page.ReloadAsync(); - Assert.Null(await Page.EvaluateAsync("() => window._foo")); + Assert.That(await Page.EvaluateAsync("() => window._foo"), Is.Null); } } } diff --git a/src/Playwright.Tests/PageKeyboardTests.cs b/src/Playwright.Tests/PageKeyboardTests.cs index 5295ca72fb..5c91e469d7 100644 --- a/src/Playwright.Tests/PageKeyboardTests.cs +++ b/src/Playwright.Tests/PageKeyboardTests.cs @@ -3,24 +3,16 @@ using System.Dynamic; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageKeyboardTests : PlaywrightSharpPageBaseTest - { - /// - public PageKeyboardTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-keyboard.spec.ts", "should type into a textarea")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-keyboard.spec.ts", "should type into a textarea")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTypeIntoATextarea() { await Page.EvaluateAsync(@"() => { @@ -30,11 +22,11 @@ await Page.EvaluateAsync(@"() => { }"); string text = "Hello world. I am the text that was typed!"; await Page.Keyboard.TypeAsync(text); - Assert.Equal(text, await Page.EvaluateAsync("() => document.querySelector('textarea').value")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('textarea').value"), Is.EqualTo(text)); } [PlaywrightTest("page-keyboard.spec.ts", "should press the metaKey")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPressTheMetaKey1() { await Page.GoToAsync(TestConstants.ServerUrl + "/empty.html"); @@ -42,22 +34,22 @@ await Page.EvaluateAsync(@"() => { window.keyPromise = new Promise(resolve => document.addEventListener('keydown', event => resolve(event.key))); }"); await Page.Keyboard.PressAsync("Meta"); - Assert.Equal(TestConstants.IsFirefox && !TestConstants.IsMacOSX ? "OS" : "Meta", await Page.EvaluateAsync("keyPromise")); + Assert.That(await Page.EvaluateAsync("keyPromise"), Is.EqualTo(TestConstants.IsFirefox && !TestConstants.IsMacOSX ? "OS" : "Meta")); } [PlaywrightTest("page-keyboard.spec.ts", "should move with the arrow keys")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldMoveWithTheArrowKeys() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.TypeAsync("textarea", "Hello World!"); - Assert.Equal("Hello World!", await Page.EvaluateAsync("() => document.querySelector('textarea').value")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('textarea').value"), Is.EqualTo("Hello World!")); for (int i = 0; i < "World!".Length; i++) { _ = Page.Keyboard.PressAsync("ArrowLeft"); } await Page.Keyboard.TypeAsync("inserted "); - Assert.Equal("Hello inserted World!", await Page.EvaluateAsync("() => document.querySelector('textarea').value")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('textarea').value"), Is.EqualTo("Hello inserted World!")); _ = Page.Keyboard.DownAsync("Shift"); for (int i = 0; i < "inserted ".Length; i++) { @@ -65,39 +57,39 @@ public async Task ShouldMoveWithTheArrowKeys() } _ = Page.Keyboard.UpAsync("Shift"); await Page.Keyboard.PressAsync("Backspace"); - Assert.Equal("Hello World!", await Page.EvaluateAsync("() => document.querySelector('textarea').value")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('textarea').value"), Is.EqualTo("Hello World!")); } [PlaywrightTest("page-keyboard.spec.ts", "should send a character with ElementHandle.press")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendACharacterWithElementHandlePress() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); var textarea = await Page.QuerySelectorAsync("textarea"); await textarea.PressAsync("a"); - Assert.Equal("a", await Page.EvaluateAsync("() => document.querySelector('textarea').value")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('textarea').value"), Is.EqualTo("a")); await Page.EvaluateAsync("() => window.addEventListener('keydown', e => e.preventDefault(), true)"); await textarea.PressAsync("b"); - Assert.Equal("a", await Page.EvaluateAsync("() => document.querySelector('textarea').value")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('textarea').value"), Is.EqualTo("a")); } [PlaywrightTest("page-keyboard.spec.ts", "should send a character with sendCharacter")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendACharacterWithSendCharacter() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.FocusAsync("textarea"); await Page.Keyboard.InsertTextAsync("嗨"); - Assert.Equal("嗨", await Page.EvaluateAsync("() => document.querySelector('textarea').value")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('textarea').value"), Is.EqualTo("嗨")); await Page.EvaluateAsync("() => window.addEventListener('keydown', e => e.preventDefault(), true)"); await Page.Keyboard.InsertTextAsync("a"); - Assert.Equal("嗨a", await Page.EvaluateAsync("() => document.querySelector('textarea').value")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('textarea').value"), Is.EqualTo("嗨a")); } [PlaywrightTest("page-keyboard.spec.ts", "insertText should only emit input event")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task InsertTextShouldOnlyEmitInputEvent() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -113,7 +105,7 @@ public async Task InsertTextShouldOnlyEmitInputEvent() }"); await Page.Keyboard.InsertTextAsync("hello world"); - Assert.Equal(new[] { "input" }, await events.JsonValueAsync()); + Assert.That(await events.JsonValueAsync(), Is.EqualTo(new[] { "input" })); } [PlaywrightTest("page-keyboard.spec.ts", "should report shiftKey")] @@ -127,80 +119,80 @@ public async Task ShouldReportShiftKey() { int modifierValue = codeForKey[modifierKey]; await keyboard.DownAsync(modifierKey); - Assert.Equal($"Keydown: {modifierKey} {modifierKey}Left {modifierValue} [{modifierKey}]", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo($"Keydown: {modifierKey} {modifierKey}Left {modifierValue} [{modifierKey}]")); await keyboard.DownAsync("!"); // Shift+! will generate a keypress if (modifierKey == "Shift") { - Assert.Equal($"Keydown: ! Digit1 49 [{modifierKey}]\nKeypress: ! Digit1 33 33 [{modifierKey}]", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo($"Keydown: ! Digit1 49 [{modifierKey}]\nKeypress: ! Digit1 33 33 [{modifierKey}]")); } else { - Assert.Equal($"Keydown: ! Digit1 49 [{modifierKey}]", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo($"Keydown: ! Digit1 49 [{modifierKey}]")); } await keyboard.UpAsync("!"); - Assert.Equal($"Keyup: ! Digit1 49 [{modifierKey}]", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo($"Keyup: ! Digit1 49 [{modifierKey}]")); await keyboard.UpAsync(modifierKey); - Assert.Equal($"Keyup: {modifierKey} {modifierKey}Left {modifierValue} []", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo($"Keyup: {modifierKey} {modifierKey}Left {modifierValue} []")); } } [PlaywrightTest("page-keyboard.spec.ts", "should report multiple modifiers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportMultipleModifiers() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html"); var keyboard = Page.Keyboard; await keyboard.DownAsync("Control"); - Assert.Equal("Keydown: Control ControlLeft 17 [Control]", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo("Keydown: Control ControlLeft 17 [Control]")); await keyboard.DownAsync("Alt"); - Assert.Equal("Keydown: Alt AltLeft 18 [Alt Control]", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo("Keydown: Alt AltLeft 18 [Alt Control]")); await keyboard.DownAsync(";"); - Assert.Equal("Keydown: ; Semicolon 186 [Alt Control]", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo("Keydown: ; Semicolon 186 [Alt Control]")); await keyboard.UpAsync(";"); - Assert.Equal("Keyup: ; Semicolon 186 [Alt Control]", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo("Keyup: ; Semicolon 186 [Alt Control]")); await keyboard.UpAsync("Control"); - Assert.Equal("Keyup: Control ControlLeft 17 [Alt]", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo("Keyup: Control ControlLeft 17 [Alt]")); await keyboard.UpAsync("Alt"); - Assert.Equal("Keyup: Alt AltLeft 18 []", await Page.EvaluateAsync("() => getResult()")); + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo("Keyup: Alt AltLeft 18 []")); } [PlaywrightTest("page-keyboard.spec.ts", "should send proper codes while typing")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendProperCodesWhileTyping() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html"); await Page.Keyboard.TypeAsync("!"); - Assert.Equal(string.Join("\n", + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo(string.Join("\n", "Keydown: ! Digit1 49 []", "Keypress: ! Digit1 33 33 []", - "Keyup: ! Digit1 49 []"), await Page.EvaluateAsync("() => getResult()")); + "Keyup: ! Digit1 49 []"))); await Page.Keyboard.TypeAsync("^"); - Assert.Equal(string.Join("\n", + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo(string.Join("\n", "Keydown: ^ Digit6 54 []", "Keypress: ^ Digit6 94 94 []", - "Keyup: ^ Digit6 54 []"), await Page.EvaluateAsync("() => getResult()")); + "Keyup: ^ Digit6 54 []"))); } [PlaywrightTest("page-keyboard.spec.ts", "should send proper codes while typing with shift")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendProperCodesWhileTypingWithShift() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html"); var keyboard = Page.Keyboard; await keyboard.DownAsync("Shift"); await Page.Keyboard.TypeAsync("~"); - Assert.Equal(string.Join("\n", + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo(string.Join("\n", "Keydown: Shift ShiftLeft 16 [Shift]", "Keydown: ~ Backquote 192 [Shift]", // 192 is ` keyCode "Keypress: ~ Backquote 126 126 [Shift]", // 126 is ~ charCode - "Keyup: ~ Backquote 192 [Shift]"), await Page.EvaluateAsync("() => getResult()")); + "Keyup: ~ Backquote 192 [Shift]"))); await keyboard.UpAsync("Shift"); } [PlaywrightTest("page-keyboard.spec.ts", "should not type canceled events")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotTypeCanceledEvents() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -216,35 +208,32 @@ await Page.EvaluateAsync(@"() =>{ }, false); }"); await Page.Keyboard.TypeAsync("Hello World!"); - Assert.Equal("He Wrd!", await Page.EvaluateAsync("() => textarea.value")); + Assert.That(await Page.EvaluateAsync("() => textarea.value"), Is.EqualTo("He Wrd!")); } [PlaywrightTest("page-keyboard.spec.ts", "should press plus")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPressPlus() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html"); await Page.Keyboard.PressAsync("+"); - Assert.Equal( - string.Join( + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo(string.Join( "\n", new[] { "Keydown: + Equal 187 []", // 192 is ` keyCode "Keypress: + Equal 43 43 []", // 126 is ~ charCode "Keyup: + Equal 187 []" - }), - await Page.EvaluateAsync("() => getResult()")); + }))); } [PlaywrightTest("page-keyboard.spec.ts", "should press shift plus")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPressShiftPlus() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html"); await Page.Keyboard.PressAsync("Shift++"); - Assert.Equal( - string.Join( + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo(string.Join( "\n", new[] { @@ -253,18 +242,16 @@ public async Task ShouldPressShiftPlus() "Keypress: + Equal 43 43 [Shift]", // 126 is ~ charCode "Keyup: + Equal 187 [Shift]", "Keyup: Shift ShiftLeft 16 []" - }), - await Page.EvaluateAsync("() => getResult()")); + }))); } [PlaywrightTest("page-keyboard.spec.ts", "should support plus-separated modifiers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportPlusSeparatedModifiers() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html"); await Page.Keyboard.PressAsync("Shift+~"); - Assert.Equal( - string.Join( + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo(string.Join( "\n", new[] { @@ -273,18 +260,16 @@ public async Task ShouldSupportPlusSeparatedModifiers() "Keypress: ~ Backquote 126 126 [Shift]", // 126 is ~ charCode "Keyup: ~ Backquote 192 [Shift]", "Keyup: Shift ShiftLeft 16 []" - }), - await Page.EvaluateAsync("() => getResult()")); + }))); } [PlaywrightTest("page-keyboard.spec.ts", "should support multiple plus-separated modifiers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportMultiplePlusSeparatedModifiers() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html"); await Page.Keyboard.PressAsync("Control+Shift+~"); - Assert.Equal( - string.Join( + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo(string.Join( "\n", new[] { @@ -294,18 +279,16 @@ public async Task ShouldSupportMultiplePlusSeparatedModifiers() "Keyup: ~ Backquote 192 [Control Shift]", "Keyup: Shift ShiftLeft 16 [Control]", "Keyup: Control ControlLeft 17 []" - }), - await Page.EvaluateAsync("() => getResult()")); + }))); } [PlaywrightTest("page-keyboard.spec.ts", "should shift raw codes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldShiftRawCodes() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html"); await Page.Keyboard.PressAsync("Shift+Digit3"); - Assert.Equal( - string.Join( + Assert.That(await Page.EvaluateAsync("() => getResult()"), Is.EqualTo(string.Join( "\n", new[] { @@ -314,12 +297,11 @@ public async Task ShouldShiftRawCodes() "Keypress: # Digit3 35 35 [Shift]", // 35 is # charCode "Keyup: # Digit3 51 [Shift]", "Keyup: Shift ShiftLeft 16 []" - }), - await Page.EvaluateAsync("() => getResult()")); + }))); } [PlaywrightTest("page-keyboard.spec.ts", "should specify repeat property")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSpecifyRepeatProperty() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -327,33 +309,33 @@ public async Task ShouldSpecifyRepeatProperty() var lastEvent = await CaptureLastKeydownAsync(Page); await Page.EvaluateAsync("() => document.querySelector('textarea').addEventListener('keydown', e => window.lastEvent = e, true)"); await Page.Keyboard.DownAsync("a"); - Assert.False(await lastEvent.EvaluateAsync("e => e.repeat")); + Assert.That(await lastEvent.EvaluateAsync("e => e.repeat"), Is.False); await Page.Keyboard.PressAsync("a"); - Assert.True(await lastEvent.EvaluateAsync("e => e.repeat")); + Assert.That(await lastEvent.EvaluateAsync("e => e.repeat"), Is.True); await Page.Keyboard.DownAsync("b"); - Assert.False(await lastEvent.EvaluateAsync("e => e.repeat")); + Assert.That(await lastEvent.EvaluateAsync("e => e.repeat"), Is.False); await Page.Keyboard.DownAsync("b"); - Assert.True(await lastEvent.EvaluateAsync("e => e.repeat")); + Assert.That(await lastEvent.EvaluateAsync("e => e.repeat"), Is.True); await Page.Keyboard.UpAsync("a"); await Page.Keyboard.DownAsync("a"); - Assert.False(await lastEvent.EvaluateAsync("e => e.repeat")); + Assert.That(await lastEvent.EvaluateAsync("e => e.repeat"), Is.False); } [PlaywrightTest("page-keyboard.spec.ts", "should type all kinds of characters")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTypeAllKindsOfCharacters() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.FocusAsync("textarea"); string text = "This text goes onto two lines.\nThis character is 嗨."; await Page.Keyboard.TypeAsync(text); - Assert.Equal(text, await Page.EvaluateAsync("result")); + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo(text)); } [PlaywrightTest("page-keyboard.spec.ts", "should specify location")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSpecifyLocation() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -361,20 +343,20 @@ public async Task ShouldSpecifyLocation() var textarea = await Page.QuerySelectorAsync("textarea"); await textarea.PressAsync("Digit5"); - Assert.Equal(0, await lastEventHandle.EvaluateAsync("e => e.location")); + Assert.That(await lastEventHandle.EvaluateAsync("e => e.location"), Is.EqualTo(0)); await textarea.PressAsync("ControlLeft"); - Assert.Equal(1, await lastEventHandle.EvaluateAsync("e => e.location")); + Assert.That(await lastEventHandle.EvaluateAsync("e => e.location"), Is.EqualTo(1)); await textarea.PressAsync("ControlRight"); - Assert.Equal(2, await lastEventHandle.EvaluateAsync("e => e.location")); + Assert.That(await lastEventHandle.EvaluateAsync("e => e.location"), Is.EqualTo(2)); await textarea.PressAsync("NumpadSubtract"); - Assert.Equal(3, await lastEventHandle.EvaluateAsync("e => e.location")); + Assert.That(await lastEventHandle.EvaluateAsync("e => e.location"), Is.EqualTo(3)); } [PlaywrightTest("page-keyboard.spec.ts", "should press Enter")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPressEnter() { await Page.SetContentAsync(""); @@ -390,40 +372,40 @@ async Task TestEnterKeyAsync(string key, string expectedKey, string expectedCode { await Page.Keyboard.PressAsync(key); dynamic lastEvent = await lastEventHandle.JsonValueAsync(); - Assert.Equal(expectedKey, lastEvent.key); - Assert.Equal(expectedCode, lastEvent.code); + Assert.That(lastEvent.key, Is.EqualTo(expectedKey)); + Assert.That(lastEvent.code, Is.EqualTo(expectedCode)); string value = await Page.EvalOnSelectorAsync("textarea", "t => t.value"); - Assert.Equal("\n", value); + Assert.That(value, Is.EqualTo("\n")); await Page.EvalOnSelectorAsync("textarea", "t => t.value = ''"); } } [PlaywrightTest("page-keyboard.spec.ts", "should throw on unknown keys")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowOnUnknownKeys() { - var exception = await Assert.ThrowsAsync(() => Page.Keyboard.PressAsync("NotARealKey")); - Assert.Equal("Unknown key: \"NotARealKey\"", exception.Message); + var exception = Assert.ThrowsAsync(() => Page.Keyboard.PressAsync("NotARealKey")); + Assert.That(exception.Message, Is.EqualTo("Unknown key: \"NotARealKey\"")); - exception = await Assert.ThrowsAsync(() => Page.Keyboard.PressAsync("ё")); - Assert.Equal("Unknown key: \"ё\"", exception.Message); + exception = Assert.ThrowsAsync(() => Page.Keyboard.PressAsync("ё")); + Assert.That(exception.Message, Is.EqualTo("Unknown key: \"ё\"")); - exception = await Assert.ThrowsAsync(() => Page.Keyboard.PressAsync("😊")); - Assert.Equal("Unknown key: \"😊\"", exception.Message); + exception = Assert.ThrowsAsync(() => Page.Keyboard.PressAsync("😊")); + Assert.That(exception.Message, Is.EqualTo("Unknown key: \"😊\"")); } [PlaywrightTest("page-keyboard.spec.ts", "should type emoji")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTypeEmoji() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); await Page.TypeAsync("textarea", "👹 Tokyo street Japan 🇯🇵"); - Assert.Equal("👹 Tokyo street Japan 🇯🇵", await Page.EvalOnSelectorAsync("textarea", "textarea => textarea.value")); + Assert.That(await Page.EvalOnSelectorAsync("textarea", "textarea => textarea.value"), Is.EqualTo("👹 Tokyo street Japan 🇯🇵")); } [PlaywrightTest("page-keyboard.spec.ts", "should type emoji into an iframe")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTypeEmojiIntoAnIframe() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -431,7 +413,7 @@ public async Task ShouldTypeEmojiIntoAnIframe() var frame = Page.Frames.ElementAt(1); var textarea = await frame.QuerySelectorAsync("textarea"); await textarea.TypeAsync("👹 Tokyo street Japan 🇯🇵"); - Assert.Equal("👹 Tokyo street Japan 🇯🇵", await frame.EvalOnSelectorAsync("textarea", "textarea => textarea.value")); + Assert.That(await frame.EvalOnSelectorAsync("textarea", "textarea => textarea.value"), Is.EqualTo("👹 Tokyo street Japan 🇯🇵")); } [PlaywrightTest("page-keyboard.spec.ts", "should handle selectAll")] @@ -446,7 +428,7 @@ public async Task ShouldHandleSelectAll() await Page.Keyboard.PressAsync("a"); await Page.Keyboard.UpAsync(modifier); await Page.Keyboard.PressAsync("Backspace"); - Assert.Empty(await Page.EvalOnSelectorAsync("textarea", "textarea => textarea.value")); + Assert.That(await Page.EvalOnSelectorAsync("textarea", "textarea => textarea.value"), Is.Empty); } [PlaywrightTest("page-keyboard.spec.ts", "should be able to prevent selectAll")] @@ -467,11 +449,11 @@ await Page.EvalOnSelectorAsync("textarea", @"textarea => { await Page.Keyboard.PressAsync("a"); await Page.Keyboard.UpAsync(modifier); await Page.Keyboard.PressAsync("Backspace"); - Assert.Equal("some tex", await Page.EvalOnSelectorAsync("textarea", "textarea => textarea.value")); + Assert.That(await Page.EvalOnSelectorAsync("textarea", "textarea => textarea.value"), Is.EqualTo("some tex")); } [PlaywrightTest("page-keyboard.spec.ts", "should press the meta key")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPressTheMetaKey2() { var lastEventHandle = await CaptureLastKeydownAsync(Page); @@ -483,34 +465,34 @@ public async Task ShouldPressTheMetaKey2() if (TestConstants.IsFirefox && !TestConstants.IsMacOSX) { - Assert.Equal("OS", key); + Assert.That(key, Is.EqualTo("OS")); } else { - Assert.Equal("Meta", key); + Assert.That(key, Is.EqualTo("Meta")); } if (TestConstants.IsFirefox) { - Assert.Equal("OSLeft", code); + Assert.That(code, Is.EqualTo("OSLeft")); } else { - Assert.Equal("MetaLeft", code); + Assert.That(code, Is.EqualTo("MetaLeft")); } if (TestConstants.IsFirefox && !TestConstants.IsMacOSX) { - Assert.False(metaKey); + Assert.That(metaKey, Is.False); } else { - Assert.True(metaKey); + Assert.That(metaKey, Is.True); } } [PlaywrightTest("page-keyboard.spec.ts", "should work after a cross origin navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkAfterACrossOriginNavigation() { await Page.GoToAsync(TestConstants.ServerUrl + "/empty.html"); @@ -518,7 +500,7 @@ public async Task ShouldWorkAfterACrossOriginNavigation() var lastEventHandle = await CaptureLastKeydownAsync(Page); await Page.Keyboard.PressAsync("a"); dynamic result = await lastEventHandle.JsonValueAsync(); - Assert.Equal("a", result.key); + Assert.That(result.key, Is.EqualTo("a")); } [PlaywrightTest("page-keyboard.spec.ts", "should expose keyIdentifier in webkit")] @@ -543,12 +525,12 @@ public async Task ShouldExposeKeyIdentifierInWebkit() foreach (var kv in keyMap) { await Page.Keyboard.PressAsync(kv.Key); - Assert.Equal(kv.Value, await lastEventHandle.EvaluateAsync("e => e.keyIdentifier")); + Assert.That(await lastEventHandle.EvaluateAsync("e => e.keyIdentifier"), Is.EqualTo(kv.Value)); } } [PlaywrightTest("page-keyboard.spec.ts", "should scroll with PageDown")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldScrollWithPageDown() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/scrollable.html"); diff --git a/src/Playwright.Tests/PageMouseTests.cs b/src/Playwright.Tests/PageMouseTests.cs index 782e258a3f..7e609ce01d 100644 --- a/src/Playwright.Tests/PageMouseTests.cs +++ b/src/Playwright.Tests/PageMouseTests.cs @@ -1,23 +1,15 @@ using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageMouseTests : PlaywrightSharpPageBaseTest - { - /// - public PageMouseTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-mouse.spec.ts", "should click the document")] + { [PlaywrightTest("page-mouse.spec.ts", "should click the document")] [SkipBrowserAndPlatformFact(skipFirefox: true, skipWindows: true)] public async Task ShouldClickTheDocument() { @@ -37,16 +29,16 @@ await Page.EvaluateAsync(@"() => { }"); await Page.Mouse.ClickAsync(50, 60); var clickEvent = await Page.EvaluateAsync("() => window.clickPromise"); - Assert.Equal("click", clickEvent.GetProperty("type").GetString()); - Assert.Equal(1, clickEvent.GetProperty("detail").GetInt32()); - Assert.Equal(50, clickEvent.GetProperty("clientX").GetInt32()); - Assert.Equal(60, clickEvent.GetProperty("clientY").GetInt32()); - Assert.True(clickEvent.GetProperty("isTrusted").GetBoolean()); - Assert.Equal(0, clickEvent.GetProperty("button").GetInt32()); + Assert.That(clickEvent.GetProperty("type").GetString(), Is.EqualTo("click")); + Assert.That(clickEvent.GetProperty("detail").GetInt32(), Is.EqualTo(1)); + Assert.That(clickEvent.GetProperty("clientX").GetInt32(), Is.EqualTo(50)); + Assert.That(clickEvent.GetProperty("clientY").GetInt32(), Is.EqualTo(60)); + Assert.That(clickEvent.GetProperty("isTrusted").GetBoolean(), Is.True); + Assert.That(clickEvent.GetProperty("button").GetInt32(), Is.EqualTo(0)); } [PlaywrightTest("page-mouse.spec.ts", "should select the text with mouse")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectTheTextWithMouse() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html"); @@ -71,37 +63,37 @@ public async Task ShouldSelectTheTextWithMouse() await Page.Mouse.DownAsync(); await Page.Mouse.MoveAsync(200, 200); await Page.Mouse.UpAsync(); - Assert.Equal(text, await Page.EvaluateAsync(@"() => { + Assert.That(await Page.EvaluateAsync(@"() => { const textarea = document.querySelector('textarea'); return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd); - }")); + }"), Is.EqualTo(text)); } [PlaywrightTest("page-mouse.spec.ts", "should trigger hover state")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTriggerHoverState() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/scrollable.html"); await Page.HoverAsync("#button-6"); - Assert.Equal("button-6", await Page.EvaluateAsync("() => document.querySelector('button:hover').id")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('button:hover').id"), Is.EqualTo("button-6")); await Page.HoverAsync("#button-2"); - Assert.Equal("button-2", await Page.EvaluateAsync("() => document.querySelector('button:hover').id")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('button:hover').id"), Is.EqualTo("button-2")); await Page.HoverAsync("#button-91"); - Assert.Equal("button-91", await Page.EvaluateAsync("() => document.querySelector('button:hover').id")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('button:hover').id"), Is.EqualTo("button-91")); } [PlaywrightTest("page-mouse.spec.ts", "should trigger hover state with removed window.Node")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTriggerHoverStateWithRemovedWindowNode() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/scrollable.html"); await Page.EvaluateAsync("() => delete window.Node"); await Page.HoverAsync("#button-6"); - Assert.Equal("button-6", await Page.EvaluateAsync("() => document.querySelector('button:hover').id")); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('button:hover').id"), Is.EqualTo("button-6")); } [PlaywrightTest("page-mouse.spec.ts", "should set modifier keys on click")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSetModifierKeysOnClick() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/scrollable.html"); @@ -118,18 +110,18 @@ public async Task ShouldSetModifierKeysOnClick() string value = modifiers[key]; await Page.Keyboard.DownAsync(key); await Page.ClickAsync("#button-3"); - Assert.True(await Page.EvaluateAsync("mod => window.lastEvent[mod]", value)); + Assert.That(await Page.EvaluateAsync("mod => window.lastEvent[mod]", value), Is.True); await Page.Keyboard.UpAsync(key); } await Page.ClickAsync("#button-3"); foreach (string key in modifiers.Keys) { - Assert.False(await Page.EvaluateAsync("mod => window.lastEvent[mod]", modifiers[key])); + Assert.That(await Page.EvaluateAsync("mod => window.lastEvent[mod]", modifiers[key]), Is.False); } } [PlaywrightTest("page-mouse.spec.ts", "should tween mouse movement")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTweenMouseMovement() { // The test becomes flaky on WebKit without next line. @@ -145,16 +137,14 @@ await Page.EvaluateAsync(@"() => { }); }"); await Page.Mouse.MoveAsync(200, 300, steps: 5); - Assert.Equal( - new[] + Assert.That(await Page.EvaluateAsync("result"), Is.EqualTo(new[] { new[] { 120, 140 }, new[] { 140, 180 }, new[] { 160, 220 }, new[] { 180, 260 }, new[] { 200, 300 } - }, - await Page.EvaluateAsync("result")); + })); } [PlaywrightTest("page-mouse.spec.ts", "should work with mobile viewports and cross process navigations")] @@ -177,8 +167,8 @@ await page.EvaluateAsync(@"() => { }"); await page.Mouse.ClickAsync(30, 40); var result = await page.EvaluateAsync("result"); - Assert.Equal(30, result.GetProperty("x").GetInt32()); - Assert.Equal(40, result.GetProperty("y").GetInt32()); + Assert.That(result.GetProperty("x").GetInt32(), Is.EqualTo(30)); + Assert.That(result.GetProperty("y").GetInt32(), Is.EqualTo(40)); } } } diff --git a/src/Playwright.Tests/PageNavigationTests.cs b/src/Playwright.Tests/PageNavigationTests.cs index 494508b95e..57d89de9e5 100644 --- a/src/Playwright.Tests/PageNavigationTests.cs +++ b/src/Playwright.Tests/PageNavigationTests.cs @@ -1,22 +1,14 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ClickNavigationTests : PlaywrightSharpPageBaseTest - { - /// - public ClickNavigationTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-navigation.spec.ts", "should work with _blank target")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-navigation.spec.ts", "should work with _blank target")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithBblankTarget() { Server.SetRoute("/empty.html", ctx => @@ -26,7 +18,7 @@ public async Task ShouldWorkWithBblankTarget() } [PlaywrightTest("page-navigation.spec.ts", "should work with cross-process _blank target")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCrossProcessBlankTarget() { Server.SetRoute("/empty.html", ctx => diff --git a/src/Playwright.Tests/PageNetworkIdleTests.cs b/src/Playwright.Tests/PageNetworkIdleTests.cs index 9415d2e3c8..93324bcd4f 100644 --- a/src/Playwright.Tests/PageNetworkIdleTests.cs +++ b/src/Playwright.Tests/PageNetworkIdleTests.cs @@ -6,37 +6,29 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///page-network-idle.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageNetworkIdleTests : PlaywrightSharpPageBaseTest - { - /// - public PageNetworkIdleTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-network-idle.spec.ts", "should navigate to empty page with networkidle")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-network-idle.spec.ts", "should navigate to empty page with networkidle")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNavigateToEmptyPageWithNetworkIdle() { var response = await Page.GoToAsync(TestConstants.EmptyPage, WaitUntilState.NetworkIdle); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle to succeed navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public Task ShouldWaitForNetworkIdleToSucceedNavigation() => NetworkIdleTestAsync(Page.MainFrame, () => Page.GoToAsync(TestConstants.ServerUrl + "/networkidle.html", WaitUntilState.NetworkIdle)); [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle to succeed navigation with request from previous navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForToSucceedNavigationWithRequestFromPreviousNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -46,7 +38,7 @@ public async Task ShouldWaitForToSucceedNavigationWithRequestFromPreviousNavigat } [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in waitForNavigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public Task ShouldWaitForInWaitForNavigation() => NetworkIdleTestAsync( Page.MainFrame, @@ -58,7 +50,7 @@ public Task ShouldWaitForInWaitForNavigation() }); [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in setContent")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForInSetContent() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -69,7 +61,7 @@ await NetworkIdleTestAsync( } [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in setContent with request from previous navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForNetworkIdleInSetContentWithRequestFromPreviousNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -82,7 +74,7 @@ await NetworkIdleTestAsync( } [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle when navigating iframe")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForNetworkIdleWhenNavigatingIframe() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); @@ -93,7 +85,7 @@ await NetworkIdleTestAsync( } [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in setContent from the child frame")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForInSetContentFromTheChildFrame() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -104,14 +96,14 @@ await NetworkIdleTestAsync( } [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle from the child frame")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public Task ShouldWaitForFromTheChildFrame() => NetworkIdleTestAsync( Page.MainFrame, () => Page.GoToAsync(TestConstants.ServerUrl + "/networkidle-frame.html", WaitUntilState.NetworkIdle)); [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle from the popup")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForNetworkIdleFromThePopup() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -164,10 +156,10 @@ async Task RequestDelegate(HttpContext context) var actionTask = action(); await waitForLoadTask; - Assert.False(actionTask.IsCompleted); + Assert.That(actionTask.IsCompleted, Is.False); await firstFetchResourceRequested.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.False(actionTask.IsCompleted); + Assert.That(actionTask.IsCompleted, Is.False); await fetches["/fetch-request-a.js"].Task.WithTimeout(TestConstants.DefaultTaskTimeout); await frame.Page.EvaluateAsync("() => window['fetchSecond']()"); @@ -177,7 +169,7 @@ async Task RequestDelegate(HttpContext context) // Wait for the second round to be requested. await secondFetchResourceRequested.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.False(actionTask.IsCompleted); + Assert.That(actionTask.IsCompleted, Is.False); await fetches["/fetch-request-b.js"].Task.WithTimeout(TestConstants.DefaultTaskTimeout); responses["/fetch-request-b.js"].TrySetResult(true); @@ -195,7 +187,7 @@ async Task RequestDelegate(HttpContext context) lastResponseFinished.Stop(); if (!isSetContent) { - Assert.Equal(HttpStatusCode.OK, navigationResponse.StatusCode); + Assert.That(navigationResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } } } diff --git a/src/Playwright.Tests/PageNetworkRequestTest.cs b/src/Playwright.Tests/PageNetworkRequestTest.cs index daaf373435..cead1ad676 100644 --- a/src/Playwright.Tests/PageNetworkRequestTest.cs +++ b/src/Playwright.Tests/PageNetworkRequestTest.cs @@ -3,35 +3,27 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Playwright.Contracts.Constants; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///network-request.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageNetworkRequestTest : PlaywrightSharpPageBaseTest - { - /// - public PageNetworkRequestTest(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-network-request.spec.ts", "should work for main frame navigation request")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-network-request.spec.ts", "should work for main frame navigation request")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForMainFrameNavigationRequests() { var requests = new List(); Page.Request += (_, e) => requests.Add(e); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Single(requests); - Assert.Equal(Page.MainFrame, requests[0].Frame); + Assert.That(requests, Has.Count.EqualTo(1)); + Assert.That(requests[0].Frame, Is.EqualTo(Page.MainFrame)); } [PlaywrightTest("page-network-request.spec.ts", "should work for subframe navigation request")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForSubframeNavigationRequest() { var requests = new List(); @@ -40,24 +32,24 @@ public async Task ShouldWorkForSubframeNavigationRequest() await Page.GoToAsync(TestConstants.EmptyPage); await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); - Assert.Equal(2, requests.Count); - Assert.Equal(Page.FirstChildFrame(), requests[1].Frame); + Assert.That(requests.Count, Is.EqualTo(2)); + Assert.That(requests[1].Frame, Is.EqualTo(Page.FirstChildFrame())); } [PlaywrightTest("page-network-request.spec.ts", "should work for fetch requests")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForFetchRequests() { await Page.GoToAsync(TestConstants.EmptyPage); var requests = new List(); Page.Request += (_, e) => requests.Add(e); await Page.EvaluateAsync("fetch('/digits/1.png')"); - Assert.Single(requests.Where(r => !r.Url.Contains("favicon"))); - Assert.Equal(Page.MainFrame, requests[0].Frame); + Assert.That(requests.Where(r => !r.Url.Contains("favicon")), Has.Count.EqualTo(1)); + Assert.That(requests[0].Frame, Is.EqualTo(Page.MainFrame)); } [PlaywrightTest("page-network-request.spec.ts", "should return headers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnHeaders() { var response = await Page.GoToAsync(TestConstants.EmptyPage); @@ -70,17 +62,17 @@ public async Task ShouldReturnHeaders() _ => "None" }; - Assert.Contains(response.Request.GetHeaderValues("user-agent"), (f) => f.Contains(expected)); + Assert.That(response.Request.GetHeaderValues("user-agent"), Has.Some.Matches(f => f.Contains(expected))); } [PlaywrightTest("page-network-request.spec.ts", "Request.headers", "should get the same headers as the server")] - [Fact(Skip = "We don't need to test this")] + [Test, Ignore("We don't need to test this")] public void ShouldGetTheSameHeadersAsTheServer() { } [PlaywrightTest("page-network-request.spec.ts", "should return postData")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnPostData() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -88,12 +80,12 @@ public async Task ShouldReturnPostData() IRequest request = null; Page.Request += (_, e) => request = e; await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar'})})"); - Assert.NotNull(request); - Assert.Equal("{\"foo\":\"bar\"}", request.PostData); + Assert.That(request, Is.Not.Null); + Assert.That(request.PostData, Is.EqualTo("{\"foo\":\"bar\"}")); } [PlaywrightTest("page-network-request.spec.ts", "should work with binary post data")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithBinaryPostData() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -101,18 +93,18 @@ public async Task ShouldWorkWithBinaryPostData() IRequest request = null; Page.Request += (_, e) => request = e; await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })"); - Assert.NotNull(request); + Assert.That(request, Is.Not.Null); byte[] data = request.PostDataBuffer; - Assert.Equal(256, data.Length); + Assert.That(data.Length, Is.EqualTo(256)); for (int index = 0; index < data.Length; index++) { - Assert.Equal(index, data[index]); + Assert.That(data[index], Is.EqualTo(index)); } } [PlaywrightTest("page-network-request.spec.ts", "should work with binary post data and interception")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithBinaryPostDataAndInterception() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -121,27 +113,27 @@ public async Task ShouldWorkWithBinaryPostDataAndInterception() IRequest request = null; Page.Request += (_, e) => request = e; await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })"); - Assert.NotNull(request); + Assert.That(request, Is.Not.Null); byte[] data = request.PostDataBuffer; - Assert.Equal(256, data.Length); + Assert.That(data.Length, Is.EqualTo(256)); for (int index = 0; index < data.Length; index++) { - Assert.Equal(index, data[index]); + Assert.That(data[index], Is.EqualTo(index)); } } [PlaywrightTest("page-network-request.spec.ts", "should be |undefined| when there is no post data")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeUndefinedWhenThereIsNoPostData() { var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Null(response.Request.PostData); + Assert.That(response.Request.PostData, Is.Null); } [PlaywrightTest("page-network-request.spec.ts", "should parse the json post data")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldParseTheJsonPostData() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -149,12 +141,12 @@ public async Task ShouldParseTheJsonPostData() IRequest request = null; Page.Request += (_, e) => request = e; await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar'})})"); - Assert.NotNull(request); - Assert.Equal("bar", request.GetPayloadAsJson().RootElement.GetProperty("foo").ToString()); + Assert.That(request, Is.Not.Null); + Assert.That(request.GetPayloadAsJson().RootElement.GetProperty("foo").ToString(), Is.EqualTo("bar")); } [PlaywrightTest("page-network-request.spec.ts", "should parse the data if content-type is application/x-www-form-urlencoded")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldParseTheDataIfContentTypeIsApplicationXWwwFormUrlencoded() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -164,22 +156,22 @@ public async Task ShouldParseTheDataIfContentTypeIsApplicationXWwwFormUrlencoded await Page.SetContentAsync("
"); await Page.ClickAsync("input[type=submit]"); - Assert.NotNull(request); + Assert.That(request, Is.Not.Null); var element = request.GetPayloadAsJson().RootElement; - Assert.Equal("bar", element.GetProperty("foo").ToString()); - Assert.Equal("123", element.GetProperty("baz").ToString()); + Assert.That(element.GetProperty("foo").ToString(), Is.EqualTo("bar")); + Assert.That(element.GetProperty("baz").ToString(), Is.EqualTo("123")); } [PlaywrightTest("page-network-request.spec.ts", "should be |undefined| when there is no post data")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeUndefinedWhenThereIsNoPostData2() { var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Null(response.Request.GetPayloadAsJson()); + Assert.That(response.Request.GetPayloadAsJson(), Is.Null); } [PlaywrightTest("page-network-request.spec.ts", "should return event source")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnEventSource() { const string sseMessage = "{\"foo\": \"bar\"}"; @@ -199,39 +191,39 @@ public async Task ShouldReturnEventSource() var requests = new List(); Page.Request += (_, e) => requests.Add(e); - Assert.Equal(sseMessage, await Page.EvaluateAsync(@"() => { + Assert.That(await Page.EvaluateAsync(@"() => { const eventSource = new EventSource('/sse'); return new Promise(resolve => { eventSource.onmessage = e => resolve(e.data); }); - }")); + }"), Is.EqualTo(sseMessage)); - Assert.Equal(ResourceTypes.EventSource, requests[0].ResourceType); + Assert.That(requests[0].ResourceType, Is.EqualTo(ResourceTypes.EventSource)); } [PlaywrightTest("page-network-request.spec.ts", "should return navigation bit")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNavigationBit() { var requests = new Dictionary(); Page.Request += (_, e) => requests[e.Url.Split('/').Last()] = e; Server.SetRedirect("/rrredirect", "/frames/one-frame.html"); await Page.GoToAsync(TestConstants.ServerUrl + "/rrredirect"); - Assert.True(requests["rrredirect"].IsNavigationRequest); - Assert.True(requests["one-frame.html"].IsNavigationRequest); - Assert.True(requests["frame.html"].IsNavigationRequest); - Assert.False(requests["script.js"].IsNavigationRequest); - Assert.False(requests["style.css"].IsNavigationRequest); + Assert.That(requests["rrredirect"].IsNavigationRequest, Is.True); + Assert.That(requests["one-frame.html"].IsNavigationRequest, Is.True); + Assert.That(requests["frame.html"].IsNavigationRequest, Is.True); + Assert.That(requests["script.js"].IsNavigationRequest, Is.False); + Assert.That(requests["style.css"].IsNavigationRequest, Is.False); } [PlaywrightTest("page-network-request.spec.ts", "Request.isNavigationRequest", "should return navigation bit when navigating to image")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNavigationBitWhenNavigatingToImage() { var requests = new List(); Page.Request += (_, e) => requests.Add(e); await Page.GoToAsync(TestConstants.ServerUrl + "/pptr.png"); - Assert.True(requests[0].IsNavigationRequest); + Assert.That(requests[0].IsNavigationRequest, Is.True); } } } diff --git a/src/Playwright.Tests/PageNetworkResponseTests.cs b/src/Playwright.Tests/PageNetworkResponseTests.cs index 1a7c219213..ddf7597565 100644 --- a/src/Playwright.Tests/PageNetworkResponseTests.cs +++ b/src/Playwright.Tests/PageNetworkResponseTests.cs @@ -3,42 +3,34 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageNetworkResponseTests : PlaywrightSharpPageBaseTest - { - /// - public PageNetworkResponseTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-network-response.spec.ts", "should return body")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-network-response.spec.ts", "should return body")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnBody() { var response = await Page.GoToAsync(TestConstants.ServerUrl + "/pptr.png"); byte[] imageBuffer = File.ReadAllBytes(TestUtils.GetWebServerFile("pptr.png")); - Assert.Equal(imageBuffer, await response.GetBodyAsync()); + Assert.That(await response.GetBodyAsync(), Is.EqualTo(imageBuffer)); } [PlaywrightTest("page-network-response.spec.ts", "should return body with compression")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnBodyWithCompression() { Server.EnableGzip("/pptr.png"); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/pptr.png"); byte[] imageBuffer = File.ReadAllBytes(TestUtils.GetWebServerFile("pptr.png")); - Assert.Equal(imageBuffer, await response.GetBodyAsync()); + Assert.That(await response.GetBodyAsync(), Is.EqualTo(imageBuffer)); } [PlaywrightTest("page-network-response.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { Server.SetRoute("/empty.html", (context) => @@ -48,26 +40,26 @@ public async Task ShouldWork() }); var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Contains("bar", response.GetHeaderValues("foo")); + Assert.That(response.GetHeaderValues("foo"), Does.Contain("bar")); } [PlaywrightTest("page-network-response.spec.ts", "should return json")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnJson() { var response = await Page.GoToAsync(TestConstants.ServerUrl + "/simple.json"); - Assert.Equal("{\"foo\": \"bar\"}", (await response.GetJsonAsync()).RootElement.GetRawText()); + Assert.That((await response.GetJsonAsync()).RootElement.GetRawText(), Is.EqualTo("{\"foo\": \"bar\"}")); } - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithGenerics() { var response = await Page.GoToAsync(TestConstants.ServerUrl + "/simple.json"); - Assert.Equal("bar", (await response.GetJsonAsync()).Foo); + Assert.That((await response.GetJsonAsync()).Foo, Is.EqualTo("bar")); } [PlaywrightTest("page-network-response.spec.ts", "should return status text")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnStatusText() { Server.SetRoute("/cool", (context) => @@ -81,44 +73,44 @@ public async Task ShouldReturnStatusText() return Task.CompletedTask; }); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/cool"); - Assert.Equal("cool!", response.StatusText); + Assert.That(response.StatusText, Is.EqualTo("cool!")); } [PlaywrightTest("page-network-response.spec.ts", "should return text")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnText() { var response = await Page.GoToAsync(TestConstants.ServerUrl + "/simple.json"); - Assert.Equal("{\"foo\": \"bar\"}", (await response.GetTextAsync()).Trim()); + Assert.That((await response.GetTextAsync()).Trim(), Is.EqualTo("{\"foo\": \"bar\"}")); } [PlaywrightTest("page-network-response.spec.ts", "should return uncompressed text")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnUncompressedText() { Server.EnableGzip("/simple.json"); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/simple.json"); - Assert.Equal("gzip", response.GetHeaderValue("content-encoding")); - Assert.Equal("{\"foo\": \"bar\"}", (await response.GetTextAsync()).Trim()); + Assert.That(response.GetHeaderValue("content-encoding"), Is.EqualTo("gzip")); + Assert.That((await response.GetTextAsync()).Trim(), Is.EqualTo("{\"foo\": \"bar\"}")); } [PlaywrightTest("page-network-response.spec.ts", "should throw when requesting body of redirected response")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWhenRequestingBodyOfRedirectedResponse() { Server.SetRedirect("/foo.html", "/empty.html"); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/foo.html"); var redirectedFrom = response.Request.RedirectedFrom; - Assert.NotNull(redirectedFrom); + Assert.That(redirectedFrom, Is.Not.Null); var redirected = await redirectedFrom.GetResponseAsync(); - Assert.Equal(HttpStatusCode.Redirect, redirected.StatusCode); + Assert.That(redirected.StatusCode, Is.EqualTo(HttpStatusCode.Redirect)); - var exception = await Assert.ThrowsAsync(async () => await redirected.GetTextAsync()); - Assert.Contains("Response body is unavailable for redirect responses", exception.Message); + var exception = Assert.ThrowsAsync(async () => await redirected.GetTextAsync()); + Assert.That(exception.Message, Does.Contain("Response body is unavailable for redirect responses")); } [PlaywrightTest("page-network-response.spec.ts", "should wait until response completes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitUntilResponseCompletes() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -143,10 +135,10 @@ public async Task ShouldWaitUntilResponseCompletes() Server.WaitForRequest("/get") ); - Assert.NotNull(serverResponse); - Assert.NotNull(pageResponse); - Assert.Equal(HttpStatusCode.OK, pageResponse.StatusCode); - Assert.False(requestFinished); + Assert.That(serverResponse, Is.Not.Null); + Assert.That(pageResponse, Is.Not.Null); + Assert.That(pageResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(requestFinished, Is.False); var responseText = pageResponse.GetTextAsync(); // Write part of the response and wait for it to be flushed. @@ -154,7 +146,7 @@ public async Task ShouldWaitUntilResponseCompletes() // Finish response. await serverResponse.WriteAsync("ld!"); serverResponseCompletion.SetResult(true); - Assert.Equal("hello world!", await responseText); + Assert.That(await responseText, Is.EqualTo("hello world!")); } class TestClass diff --git a/src/Playwright.Tests/PageRequestContinueTests.cs b/src/Playwright.Tests/PageRequestContinueTests.cs index a1066910af..5d8c4658a9 100644 --- a/src/Playwright.Tests/PageRequestContinueTests.cs +++ b/src/Playwright.Tests/PageRequestContinueTests.cs @@ -5,23 +5,15 @@ using System.Net.Http; using System.Text; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageRequestContinueTests : PlaywrightSharpPageBaseTest - { - /// - public PageRequestContinueTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-request-continue.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-request-continue.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.RouteAsync("**/*", (route) => route.ResumeAsync()); @@ -29,7 +21,7 @@ public async Task ShouldWork() } [PlaywrightTest("page-request-continue.spec.ts", "should amend HTTP headers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAmendHTTPHeaders() { await Page.RouteAsync("**/*", (route) => @@ -43,21 +35,21 @@ await TaskUtils.WhenAll( requestTask, Page.EvaluateAsync("() => fetch('/sleep.zzz')") ); - Assert.Equal("bar", requestTask.Result); + Assert.That(requestTask.Result, Is.EqualTo("bar")); } [PlaywrightTest("page-request-continue.spec.ts", "should amend method on main request")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAmendMethodOnMainRequest() { var methodTask = Server.WaitForRequest("/empty.html", r => r.Method); await Page.RouteAsync("**/*", (route) => route.ResumeAsync(method: HttpMethod.Post.Method)); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("POST", await methodTask); + Assert.That(await methodTask, Is.EqualTo("POST")); } [PlaywrightTest("page-request-continue.spec.ts", "should amend post data")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAmendPostData() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -75,7 +67,7 @@ await TaskUtils.WhenAll( requestTask, Page.EvaluateAsync("() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })") ); - Assert.Equal("doggo", requestTask.Result); + Assert.That(requestTask.Result, Is.EqualTo("doggo")); } } } diff --git a/src/Playwright.Tests/PageRequestFulfillTests.cs b/src/Playwright.Tests/PageRequestFulfillTests.cs index ebeb7e9cf7..875d3499f5 100644 --- a/src/Playwright.Tests/PageRequestFulfillTests.cs +++ b/src/Playwright.Tests/PageRequestFulfillTests.cs @@ -4,24 +4,16 @@ using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.Helpers; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class RequestFulfillTests : PlaywrightSharpPageBaseTest - { - /// - public RequestFulfillTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-request-fulfill.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-request-fulfill.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.RouteAsync("**/*", (route) => @@ -36,9 +28,9 @@ await Page.RouteAsync("**/*", (route) => body: "Yo, page!"); }); var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(HttpStatusCode.Created, response.StatusCode); - Assert.Equal("bar", response.GetHeaderValue("foo")); - Assert.Equal("Yo, page!", await Page.EvaluateAsync("() => document.body.textContent")); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created)); + Assert.That(response.GetHeaderValue("foo"), Is.EqualTo("bar")); + Assert.That(await Page.EvaluateAsync("() => document.body.textContent"), Is.EqualTo("Yo, page!")); } /// @@ -47,7 +39,7 @@ await Page.RouteAsync("**/*", (route) => /// As the goal here is testing HTTP codes that are not in Chromium (see https://cs.chromium.org/chromium/src/net/http/http_status_code_list.h?sq=package:chromium) we will use code 426: Upgrade Required /// [PlaywrightTest("page-request-fulfill.spec.ts", "should work with status code 422")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithStatusCode422() { await Page.RouteAsync("**/*", (route) => @@ -55,13 +47,13 @@ await Page.RouteAsync("**/*", (route) => route.FulfillAsync(HttpStatusCode.UpgradeRequired, "Yo, page!"); }); var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(HttpStatusCode.UpgradeRequired, response.StatusCode); - Assert.Equal("Upgrade Required", response.StatusText); - Assert.Equal("Yo, page!", await Page.EvaluateAsync("() => document.body.textContent")); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.UpgradeRequired)); + Assert.That(response.StatusText, Is.EqualTo("Upgrade Required")); + Assert.That(await Page.EvaluateAsync("() => document.body.textContent"), Is.EqualTo("Yo, page!")); } [PlaywrightTest("page-request-fulfill.spec.ts", "should allow mocking binary responses")] - [Fact(Skip = "We need screenshots for this")] + [Test, Ignore("We need screenshots for this")] public async Task ShouldAllowMockingBinaryResponses() { await Page.RouteAsync("**/*", (route) => @@ -78,17 +70,17 @@ await Page.EvaluateAsync(@"PREFIX => { return new Promise(fulfill => img.onload = fulfill); }", TestConstants.ServerUrl); var img = await Page.QuerySelectorAsync("img"); - Assert.True(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync())); + Assert.That(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync()), Is.True); } [PlaywrightTest("page-request-fulfill.spec.ts", "should allow mocking svg with charset")] - [Fact(Skip = "We need screenshots for this")] + [Test, Ignore("We need screenshots for this")] public void ShouldAllowMockingSvgWithCharset() { } [PlaywrightTest("page-request-fulfill.spec.ts", "should work with file path")] - [Fact(Skip = "We need screenshots for this")] + [Test, Ignore("We need screenshots for this")] public async Task ShouldWorkWithFilePath() { await Page.RouteAsync("**/*", (route) => @@ -105,11 +97,11 @@ await Page.EvaluateAsync(@"PREFIX => { return new Promise(fulfill => img.onload = fulfill); }", TestConstants.ServerUrl); var img = await Page.QuerySelectorAsync("img"); - Assert.True(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync())); + Assert.That(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync()), Is.True); } [PlaywrightTest("page-request-fulfill.spec.ts", "should stringify intercepted request response headers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldStringifyInterceptedRequestResponseHeaders() { await Page.RouteAsync("**/*", (route) => @@ -124,13 +116,13 @@ await Page.RouteAsync("**/*", (route) => }); var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("true", response.GetHeaderValue("foo")); - Assert.Equal("Yo, page!", await Page.EvaluateAsync("() => document.body.textContent")); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(response.GetHeaderValue("foo"), Is.EqualTo("true")); + Assert.That(await Page.EvaluateAsync("() => document.body.textContent"), Is.EqualTo("Yo, page!")); } [PlaywrightTest("page-request-fulfill.spec.ts", "should not modify the headers sent to the server")] - [Fact(Skip = "Flacky with the ASP.NET server")] + [Test, Ignore("Flacky with the ASP.NET server")] public async Task ShouldNotModifyTheHeadersSentToTheServer() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -150,7 +142,7 @@ public async Task ShouldNotModifyTheHeadersSentToTheServer() return data.text(); }", TestConstants.CrossProcessUrl + "/something"); - Assert.Equal("done", text); + Assert.That(text, Is.EqualTo("done")); IRequest playwrightRequest = null; @@ -165,14 +157,14 @@ await Page.RouteAsync(TestConstants.CrossProcessUrl + "/something", (route) => return data.text(); }", TestConstants.CrossProcessUrl + "/something"); - Assert.Equal("done", textAfterRoute); + Assert.That(textAfterRoute, Is.EqualTo("done")); - Assert.Equal(2, interceptedRequests.Count); - Assert.Equal(interceptedRequests[1].OrderBy(kv => kv.Key), interceptedRequests[0].OrderBy(kv => kv.Key)); + Assert.That(interceptedRequests.Count, Is.EqualTo(2)); + Assert.That(interceptedRequests[0].OrderBy(kv => kv.Key), Is.EqualTo(interceptedRequests[1].OrderBy(kv => kv.Key))); } [PlaywrightTest("page-request-fulfill.spec.ts", "should include the origin header")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIncludeTheOriginHeader() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -192,8 +184,8 @@ await Page.RouteAsync(TestConstants.CrossProcessUrl + "/something", (route) => return data.text(); }", TestConstants.CrossProcessUrl + "/something"); - Assert.Equal("done", text); - Assert.Equal(TestConstants.ServerUrl, interceptedRequest.GetHeaderValue("origin")); + Assert.That(text, Is.EqualTo("done")); + Assert.That(interceptedRequest.GetHeaderValue("origin"), Is.EqualTo(TestConstants.ServerUrl)); } } } diff --git a/src/Playwright.Tests/PageRouteTests.cs b/src/Playwright.Tests/PageRouteTests.cs index 34fd3190bf..e2b2f2e576 100644 --- a/src/Playwright.Tests/PageRouteTests.cs +++ b/src/Playwright.Tests/PageRouteTests.cs @@ -8,48 +8,40 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using Microsoft.Playwright.Contracts.Constants; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageRouteTests : PlaywrightSharpPageBaseTest - { - /// - public PageRouteTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-route.spec.ts", "should intercept")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-route.spec.ts", "should intercept")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldIntercept() { bool intercepted = false; await Page.RouteAsync("**/empty.html", (route) => { - Assert.Contains("empty.html", route.Request.Url); - Assert.Contains(route.Request.Headers, x => string.Equals(x.Key, "user-agent", StringComparison.OrdinalIgnoreCase)); - Assert.Equal(HttpMethod.Get.Method, route.Request.Method); - Assert.Null(route.Request.PostData); - Assert.True(route.Request.IsNavigationRequest); - Assert.Equal(ResourceTypes.Document, route.Request.ResourceType, true); - Assert.Same(route.Request.Frame, Page.MainFrame); - Assert.Equal("about:blank", route.Request.Frame.Url); + Assert.That(route.Request.Url, Does.Contain("empty.html")); + Assert.That(route.Request.Headers, Has.Some.Matches>(x => string.Equals(x.Key, "user-agent", StringComparison.OrdinalIgnoreCase))); + Assert.That(route.Request.Method, Is.EqualTo(HttpMethod.Get.Method)); + Assert.That(route.Request.PostData, Is.Null); + Assert.That(route.Request.IsNavigationRequest, Is.True); + Assert.That(route.Request.ResourceType, Is.EqualTo(ResourceTypes.Document)); + Assert.That(Page.MainFrame, Is.SameAs(route.Request.Frame)); + Assert.That(route.Request.Frame.Url, Is.EqualTo("about:blank")); route.ResumeAsync(); intercepted = true; }); var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.True(response.Ok); - Assert.True(intercepted); + Assert.That(response.Ok, Is.True); + Assert.That(intercepted, Is.True); } [PlaywrightTest("page-route.spec.ts", "should unroute")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUnroute() { var intercepted = new List(); @@ -79,21 +71,21 @@ await Page.RouteAsync("**/*", (route) => }); var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(new[] { 1 }, intercepted.ToArray()); + Assert.That(intercepted.ToArray(), Is.EqualTo(new[] { 1 })); intercepted.Clear(); await Page.UnrouteAsync("**/empty.html", handler1); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(new[] { 2 }, intercepted.ToArray()); + Assert.That(intercepted.ToArray(), Is.EqualTo(new[] { 2 })); intercepted.Clear(); await Page.UnrouteAsync("**/empty.html"); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(new[] { 4 }, intercepted.ToArray()); + Assert.That(intercepted.ToArray(), Is.EqualTo(new[] { 4 })); } [PlaywrightTest("page-route.spec.ts", "should work when POST is redirected with 302")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenPostIsRedirectedWith302() { Server.SetRedirect("/rredirect", "/empty.html"); @@ -110,7 +102,7 @@ await TaskUtils.WhenAll( } [PlaywrightTest("page-route.spec.ts", "should work when header manipulation headers with redirect")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenHeaderManipulationHeadersWithRedirect() { Server.SetRedirect("/rrredirect", "/empty.html"); @@ -123,7 +115,7 @@ await Page.RouteAsync("**/*", (route) => } [PlaywrightTest("page-route.spec.ts", "should be able to remove headers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToRemoveHeaders() { await Page.RouteAsync("**/*", (route) => @@ -138,11 +130,11 @@ await TaskUtils.WhenAll( originRequestHeader, Page.GoToAsync(TestConstants.EmptyPage) ); - Assert.Equal(StringValues.Empty, originRequestHeader.Result); + Assert.That(originRequestHeader.Result, Is.EqualTo(StringValues.Empty)); } [PlaywrightTest("page-route.spec.ts", "should contain referer header")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldContainRefererHeader() { var requests = new List(); @@ -152,12 +144,12 @@ await Page.RouteAsync("**/*", (route) => route.ResumeAsync(); }); await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); - Assert.Contains("/one-style.css", requests[1].Url); - Assert.Contains("/one-style.html", requests[1].GetHeaderValue("referer")); + Assert.That(requests[1].Url, Does.Contain("/one-style.css")); + Assert.That(requests[1].GetHeaderValue("referer"), Does.Contain("/one-style.html")); } [PlaywrightTest("page-route.spec.ts", "should properly return navigation response when URL has cookies")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldProperlyReturnNavigationResponseWhenURLHasCookies() { // Setup cookie. @@ -172,11 +164,11 @@ await Context.AddCookiesAsync(new Cookie // Setup request interception. await Page.RouteAsync("**/*", (route) => route.ResumeAsync()); var response = await Page.ReloadAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [PlaywrightTest("page-route.spec.ts", "should show custom HTTP headers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldShowCustomHTTPHeaders() { await Page.SetExtraHttpHeadersAsync(new Dictionary @@ -185,15 +177,15 @@ await Page.SetExtraHttpHeadersAsync(new Dictionary }); await Page.RouteAsync("**/*", (route) => { - Assert.Equal("bar", route.Request.GetHeaderValue("foo")); + Assert.That(route.Request.GetHeaderValue("foo"), Is.EqualTo("bar")); route.ResumeAsync(); }); var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.True(response.Ok); + Assert.That(response.Ok, Is.True); } [PlaywrightTest("page-route.spec.ts", "should work with redirect inside sync XHR")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithRedirectInsideSyncXHR() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -205,25 +197,25 @@ public async Task ShouldWorkWithRedirectInsideSyncXHR() request.send(null); return request.status; }"); - Assert.Equal(200, status); + Assert.That(status, Is.EqualTo(200)); } [PlaywrightTest("page-route.spec.ts", "should work with custom referer headers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCustomRefererHeaders() { await Page.SetExtraHttpHeadersAsync(new Dictionary { ["referer"] = TestConstants.EmptyPage }); await Page.RouteAsync("**/*", (route) => { - Assert.Equal(TestConstants.EmptyPage, route.Request.GetHeaderValue("referer")); + Assert.That(route.Request.GetHeaderValue("referer"), Is.EqualTo(TestConstants.EmptyPage)); route.ResumeAsync(); }); var response = await Page.GoToAsync(TestConstants.EmptyPage); - Assert.True(response.Ok); + Assert.That(response.Ok, Is.True); } [PlaywrightTest("page-route.spec.ts", "should be abortable")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbortable() { await Page.RouteAsync(new Regex("\\.css"), (route) => route.AbortAsync()); @@ -231,13 +223,13 @@ public async Task ShouldBeAbortable() int failedRequests = 0; Page.RequestFailed += (_, _) => ++failedRequests; var response = await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); - Assert.True(response.Ok); - Assert.Null(response.Request.Failure); - Assert.Equal(1, failedRequests); + Assert.That(response.Ok, Is.True); + Assert.That(response.Request.Failure, Is.Null); + Assert.That(failedRequests, Is.EqualTo(1)); } [PlaywrightTest("page-route.spec.ts", "should be abortable with custom error codes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbortableWithCustomErrorCodes() { await Page.RouteAsync("**/*", (route) => @@ -248,23 +240,23 @@ await Page.RouteAsync("**/*", (route) => IRequest failedRequest = null; Page.RequestFailed += (_, e) => failedRequest = e; await Page.GoToAsync(TestConstants.EmptyPage).ContinueWith(_ => { }); - Assert.NotNull(failedRequest); + Assert.That(failedRequest, Is.Not.Null); if (TestConstants.IsWebKit) { - Assert.Equal("Request intercepted", failedRequest.Failure); + Assert.That(failedRequest.Failure, Is.EqualTo("Request intercepted")); } else if (TestConstants.IsFirefox) { - Assert.Equal("NS_ERROR_OFFLINE", failedRequest.Failure); + Assert.That(failedRequest.Failure, Is.EqualTo("NS_ERROR_OFFLINE")); } else { - Assert.Equal("net::ERR_INTERNET_DISCONNECTED", failedRequest.Failure); + Assert.That(failedRequest.Failure, Is.EqualTo("net::ERR_INTERNET_DISCONNECTED")); } } [PlaywrightTest("page-route.spec.ts", "should send referer")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendReferer() { await Page.SetExtraHttpHeadersAsync(new Dictionary { ["referer"] = "http://google.com/" }); @@ -274,32 +266,32 @@ await TaskUtils.WhenAll( requestTask, Page.GoToAsync(TestConstants.ServerUrl + "/grid.html") ); - Assert.Equal("http://google.com/", requestTask.Result); + Assert.That(requestTask.Result, Is.EqualTo("http://google.com/")); } [PlaywrightTest("page-route.spec.ts", "should fail navigation when aborting main resource")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailNavigationWhenAbortingMainResource() { await Page.RouteAsync("**/*", (route) => route.AbortAsync()); - var exception = await Assert.ThrowsAnyAsync(() => Page.GoToAsync(TestConstants.EmptyPage)); - Assert.NotNull(exception); + var exception = Assert.CatchAsync(() => Page.GoToAsync(TestConstants.EmptyPage)); + Assert.That(exception, Is.Not.Null); if (TestConstants.IsWebKit) { - Assert.Contains("Request intercepted", exception.Message); + Assert.That(exception.Message, Does.Contain("Request intercepted")); } else if (TestConstants.IsFirefox) { - Assert.Contains("NS_ERROR_FAILURE", exception.Message); + Assert.That(exception.Message, Does.Contain("NS_ERROR_FAILURE")); } else { - Assert.Contains("net::ERR_FAILED", exception.Message); + Assert.That(exception.Message, Does.Contain("net::ERR_FAILED")); } } [PlaywrightTest("page-route.spec.ts", "should not work with redirects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotWorkWithRedirects() { var requests = new List(); @@ -314,36 +306,36 @@ await Page.RouteAsync("**/*", (route) => Server.SetRedirect("/non-existing-page-4.html", "/empty.html"); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/non-existing-page.html"); - Assert.Contains("non-existing-page.html", requests[0].Url); - Assert.Single(requests); - Assert.Equal(ResourceTypes.Document, requests[0].ResourceType, true); - Assert.True(requests[0].IsNavigationRequest); + Assert.That(requests[0].Url, Does.Contain("non-existing-page.html")); + Assert.That(requests, Has.Count.EqualTo(1)); + Assert.That(requests[0].ResourceType, Is.EqualTo(ResourceTypes.Document)); + Assert.That(requests[0].IsNavigationRequest, Is.True); var chain = new List(); for (var request = response.Request; request != null; request = request.RedirectedFrom) { chain.Add(request); - Assert.True(request.IsNavigationRequest); + Assert.That(request.IsNavigationRequest, Is.True); } - Assert.Equal(5, chain.Count); - Assert.Contains("/empty.html", chain[0].Url); - Assert.Contains("/non-existing-page-4.html", chain[1].Url); - Assert.Contains("/non-existing-page-3.html", chain[2].Url); - Assert.Contains("/non-existing-page-2.html", chain[3].Url); - Assert.Contains("/non-existing-page.html", chain[4].Url); + Assert.That(chain.Count, Is.EqualTo(5)); + Assert.That(chain[0].Url, Does.Contain("/empty.html")); + Assert.That(chain[1].Url, Does.Contain("/non-existing-page-4.html")); + Assert.That(chain[2].Url, Does.Contain("/non-existing-page-3.html")); + Assert.That(chain[3].Url, Does.Contain("/non-existing-page-2.html")); + Assert.That(chain[4].Url, Does.Contain("/non-existing-page.html")); for (int i = 0; i < chain.Count; ++i) { var request = chain[i]; - Assert.True(request.IsNavigationRequest); - Assert.Equal(i > 0 ? chain[i - 1] : null, chain[i].RedirectedTo); + Assert.That(request.IsNavigationRequest, Is.True); + Assert.That(chain[i].RedirectedTo, Is.EqualTo(i > 0 ? chain[i - 1] : null)); } } [PlaywrightTest("page-route.spec.ts", "should work with redirects for subresources")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithRedirectsForSubresources() { var requests = new List(); @@ -358,26 +350,26 @@ await Page.RouteAsync("**/*", (route) => Server.SetRoute("/four-style.css", context => context.Response.WriteAsync("body {box-sizing: border-box; }")); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("one-style.html", response.Url); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(response.Url, Does.Contain("one-style.html")); - Assert.Equal(2, requests.Count); - Assert.Equal(ResourceTypes.Document, requests[0].ResourceType, true); - Assert.Contains("one-style.html", requests[0].Url); + Assert.That(requests.Count, Is.EqualTo(2)); + Assert.That(requests[0].ResourceType, Is.EqualTo(ResourceTypes.Document)); + Assert.That(requests[0].Url, Does.Contain("one-style.html")); var request = requests[1]; foreach (string url in new[] { "/one-style.css", "/two-style.css", "/three-style.css", "/four-style.css" }) { - Assert.Equal(ResourceTypes.Stylesheet, request.ResourceType, true); - Assert.Contains(url, request.Url); + Assert.That(request.ResourceType, Is.EqualTo(ResourceTypes.Stylesheet)); + Assert.That(request.Url, Does.Contain(url)); request = request.RedirectedTo; } - Assert.Null(request); + Assert.That(request, Is.Null); } [PlaywrightTest("page-route.spec.ts", "should work with equal requests")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithEqualRequests() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -405,11 +397,11 @@ await Page.RouteAsync("**/*", (route) => results.Add(await Page.EvaluateAsync("fetch('/zzz').then(response => response.text()).catch (e => 'FAILED')")); } - Assert.Equal(new[] { "11", "FAILED", "22" }, results); + Assert.That(results, Is.EqualTo(new[] { "11", "FAILED", "22" })); } [PlaywrightTest("page-route.spec.ts", "should navigate to dataURL and not fire dataURL requests")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNavigateToDataURLAndNotFireDataURLRequests() { var requests = new List(); @@ -420,12 +412,12 @@ await Page.RouteAsync("**/*", (route) => }); string dataURL = "data:text/html,
yo
"; var response = await Page.GoToAsync(dataURL); - Assert.Null(response); - Assert.Empty(requests); + Assert.That(response, Is.Null); + Assert.That(requests, Is.Empty); } [PlaywrightTest("page-route.spec.ts", "should be able to fetch dataURL and not fire dataURL requests")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToFetchDataURLAndNotFireDataURLRequests() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -438,12 +430,12 @@ await Page.RouteAsync("**/*", (route) => }); string dataURL = "data:text/html,
yo
"; string text = await Page.EvaluateAsync("url => fetch(url).then(r => r.text())", dataURL); - Assert.Equal("
yo
", text); - Assert.Empty(requests); + Assert.That(text, Is.EqualTo("
yo
")); + Assert.That(requests, Is.Empty); } [PlaywrightTest("page-route.spec.ts", "should navigate to URL with hash and and fire requests without hash")] - [Fact(Skip = "Not implemented")] + [Test, Ignore("Not implemented")] public async Task ShouldNavigateToURLWithHashAndAndFireRequestsWithoutHash() { var requests = new List(); @@ -453,35 +445,35 @@ await Page.RouteAsync("**/*", (route) => route.ResumeAsync(); }); var response = await Page.GoToAsync(TestConstants.EmptyPage + "#hash"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(TestConstants.EmptyPage, response.Url); - Assert.Single(requests); - Assert.Equal(TestConstants.EmptyPage, requests[0].Url); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(response.Url, Is.EqualTo(TestConstants.EmptyPage)); + Assert.That(requests, Has.Count.EqualTo(1)); + Assert.That(requests[0].Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("page-route.spec.ts", "should work with encoded server")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithEncodedServer() { // The requestWillBeSent will report encoded URL, whereas interception will // report URL as-is. @see crbug.com/759388 await Page.RouteAsync("**/*", (route) => route.ResumeAsync()); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/some nonexisting page"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); } [PlaywrightTest("page-route.spec.ts", "should work with badly encoded server")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithBadlyEncodedServer() { Server.SetRoute("/malformed?rnd=%911", _ => Task.CompletedTask); await Page.RouteAsync("**/*", (route) => route.ResumeAsync()); var response = await Page.GoToAsync(TestConstants.ServerUrl + "/malformed?rnd=%911"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [PlaywrightTest("page-route.spec.ts", "should work with encoded server - 2")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithEncodedServer2() { // The requestWillBeSent will report URL as-is, whereas interception will @@ -493,13 +485,13 @@ await Page.RouteAsync("**/*", (route) => requests.Add(route.Request); }); var response = await Page.GoToAsync($"data:text/html,"); - Assert.Null(response); - Assert.Single(requests); - Assert.Equal(HttpStatusCode.NotFound, (await requests[0].GetResponseAsync()).StatusCode); + Assert.That(response, Is.Null); + Assert.That(requests, Has.Count.EqualTo(1)); + Assert.That((await requests[0].GetResponseAsync()).StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); } [PlaywrightTest("page-route.spec.ts", @"should not throw ""Invalid Interception Id"" if the request was cancelled")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotThrowInvalidInterceptionIdIfTheRequestWasCancelled() { await Page.SetContentAsync(""); @@ -514,7 +506,7 @@ public async Task ShouldNotThrowInvalidInterceptionIdIfTheRequestWasCancelled() } [PlaywrightTest("page-route.spec.ts", "should intercept main resource during cross-process navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldInterceptMainResourceDuringCrossProcessNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -529,8 +521,8 @@ await Page.RouteAsync(TestConstants.CrossProcessUrl + "/empty.html", (route) => route.ResumeAsync(); }); var response = await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/empty.html"); - Assert.True(response.Ok); - Assert.True(intercepted); + Assert.That(response.Ok, Is.True); + Assert.That(intercepted, Is.True); } [PlaywrightTest("page-route.spec.ts", "should fulfill with redirect status")] @@ -560,11 +552,11 @@ await Page.RouteAsync("**/*", (route) => return data.text(); }", TestConstants.ServerUrl + "/redirect_this"); - Assert.Equal("foo", text); + Assert.That(text, Is.EqualTo("foo")); } [PlaywrightTest("page-route.spec.ts", "should support cors with GET")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportCorsWithGET() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -586,18 +578,18 @@ await Page.RouteAsync("**/cars*", (route) => return response.json(); }"); - Assert.Equal(new[] { "electric", "cars" }, resp); + Assert.That(resp, Is.EqualTo(new[] { "electric", "cars" })); - var exception = await Assert.ThrowsAnyAsync(() => Page.EvaluateAsync(@"async () => { + var exception = Assert.CatchAsync(() => Page.EvaluateAsync(@"async () => { const response = await fetch('https://example.com/cars?reject', { mode: 'cors' }); return response.json(); }")); - Assert.Contains("failed", exception.Message); + Assert.That(exception.Message, Does.Contain("failed")); } [PlaywrightTest("page-route.spec.ts", "should support cors with POST")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportCorsWithPOST() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -620,11 +612,11 @@ await Page.RouteAsync("**/cars*", (route) => return response.json(); }"); - Assert.Equal(new[] { "electric", "cars" }, resp); + Assert.That(resp, Is.EqualTo(new[] { "electric", "cars" })); } [PlaywrightTest("page-route.spec.ts", "should support cors with different methods")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportCorsWithDifferentMethods() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -647,7 +639,7 @@ await Page.RouteAsync("**/cars*", (route) => return response.json(); }"); - Assert.Equal(new[] { "POST", "electric", "cars" }, resp); + Assert.That(resp, Is.EqualTo(new[] { "POST", "electric", "cars" })); resp = await Page.EvaluateAsync(@"async () => { const response = await fetch('https://example.com/cars', { @@ -659,7 +651,7 @@ await Page.RouteAsync("**/cars*", (route) => return response.json(); }"); - Assert.Equal(new[] { "DELETE", "electric", "cars" }, resp); + Assert.That(resp, Is.EqualTo(new[] { "DELETE", "electric", "cars" })); } } } diff --git a/src/Playwright.Tests/PageScreenshotTests.cs b/src/Playwright.Tests/PageScreenshotTests.cs index 57f3a2323c..1ca9bc495e 100644 --- a/src/Playwright.Tests/PageScreenshotTests.cs +++ b/src/Playwright.Tests/PageScreenshotTests.cs @@ -3,37 +3,29 @@ using System.IO; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.Helpers; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///page-screenshot.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageScreenshotTests : PlaywrightSharpPageBaseTest - { - /// - public PageScreenshotTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-screenshot.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-screenshot.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.SetViewportSizeAsync(500, 500); await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); byte[] screenshot = await Page.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should clip rect")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClipRect() { await Page.SetViewportSizeAsync(500, 500); @@ -47,11 +39,11 @@ public async Task ShouldClipRect() Height = 100 } ); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should clip rect with fullPage")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClipRectWithFullPage() { await Page.SetViewportSizeAsync(500, 500); @@ -66,11 +58,11 @@ public async Task ShouldClipRectWithFullPage() Width = 150, Height = 100, }); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should clip elements to the viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClipElementsToTheViewport() { await Page.SetViewportSizeAsync(500, 500); @@ -83,16 +75,16 @@ public async Task ShouldClipElementsToTheViewport() Width = 1000, Height = 100, }); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-offscreen-clip.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-offscreen-clip.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should throw on clip outside the viewport")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowOnClipOutsideTheViewport() { await Page.SetViewportSizeAsync(500, 500); await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); - var exception = await Assert.ThrowsAsync(() => Page.ScreenshotAsync( + var exception = Assert.ThrowsAsync(() => Page.ScreenshotAsync( clip: new Clip { X = 50, @@ -101,11 +93,11 @@ public async Task ShouldThrowOnClipOutsideTheViewport() Height = 100, })); - Assert.Contains("Clipped area is either empty or outside the resulting image", exception.Message); + Assert.That(exception.Message, Does.Contain("Clipped area is either empty or outside the resulting image")); } [PlaywrightTest("page-screenshot.spec.ts", "should run in parallel")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRunInParallel() { await Page.SetViewportSizeAsync(500, 500); @@ -125,33 +117,33 @@ public async Task ShouldRunInParallel() } await TaskUtils.WhenAll(tasks); - Assert.True(ScreenshotHelper.PixelMatch("grid-cell-1.png", tasks[0].Result)); + Assert.That(ScreenshotHelper.PixelMatch("grid-cell-1.png", tasks[0].Result), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should take fullPage screenshots")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTakeFullPageScreenshots() { await Page.SetViewportSizeAsync(500, 500); await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); byte[] screenshot = await Page.ScreenshotAsync(fullPage: true); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-grid-fullpage.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-grid-fullpage.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should restore viewport after fullPage screenshot")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRestoreViewportAfterFullPageScreenshot() { await Page.SetViewportSizeAsync(500, 500); await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); await Page.ScreenshotAsync(fullPage: true); - Assert.Equal(500, Page.ViewportSize.Width); - Assert.Equal(500, Page.ViewportSize.Height); + Assert.That(Page.ViewportSize.Width, Is.EqualTo(500)); + Assert.That(Page.ViewportSize.Height, Is.EqualTo(500)); } [PlaywrightTest("page-screenshot.spec.ts", "should run in parallel in multiple pages")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRunInParallelInMultiplePages() { int n = 5; @@ -187,7 +179,7 @@ async Task Func() for (int i = 0; i < n; i++) { - Assert.True(ScreenshotHelper.PixelMatch($"grid-cell-{i % 2}.png", screenshotTasks[i].Result)); + Assert.That(ScreenshotHelper.PixelMatch($"grid-cell-{i % 2}.png", screenshotTasks[i].Result), Is.True); } var closeTasks = new List(); @@ -207,11 +199,11 @@ public async Task ShouldAllowTransparency() await Page.GoToAsync(TestConstants.EmptyPage); byte[] screenshot = await Page.ScreenshotAsync(omitBackground: true); - Assert.True(ScreenshotHelper.PixelMatch("transparent.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("transparent.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should render white background on jpeg file")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRenderWhiteBackgroundOnJpegFile() { await Page.SetViewportSizeAsync(100, 100); @@ -219,11 +211,11 @@ public async Task ShouldRenderWhiteBackgroundOnJpegFile() byte[] screenshot = await Page.ScreenshotAsync( omitBackground: true, type: ScreenshotType.Jpeg); - Assert.True(ScreenshotHelper.PixelMatch("white.jpg", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("white.jpg", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should work with odd clip size on Retina displays")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithOddClipSizeOnRetinaDisplays() { byte[] screenshot = await Page.ScreenshotAsync( @@ -235,7 +227,7 @@ public async Task ShouldWorkWithOddClipSizeOnRetinaDisplays() Height = 11 }); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-odd-size.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-clip-odd-size.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport")] @@ -255,7 +247,7 @@ public async Task ShouldWorkWithAMobileViewport() await page.GoToAsync(TestConstants.ServerUrl + "/overflow.html"); byte[] screenshot = await page.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-mobile.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport and clip")] @@ -282,7 +274,7 @@ public async Task ShouldWorkWithAMobileViewportAndClip() Height = 150 }); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile-clip.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-mobile-clip.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport and fullPage")] @@ -302,18 +294,18 @@ public async Task ShouldWorkWithAMobileViewportAndFullPage() await page.GoToAsync(TestConstants.ServerUrl + "/overflow-large.html"); byte[] screenshot = await page.ScreenshotAsync(fullPage: true); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile-fullpage.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-mobile-fullpage.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should work for canvas")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForCanvas() { await Page.SetViewportSizeAsync(500, 500); await Page.GoToAsync(TestConstants.ServerUrl + "/screenshots/canvas.html"); byte[] screenshot = await Page.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-canvas.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-canvas.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should work for webgl")] @@ -324,22 +316,22 @@ public async Task ShouldWorkForWebgl() await Page.GoToAsync(TestConstants.ServerUrl + "/screenshots/webgl.html"); byte[] screenshot = await Page.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-webgl.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-webgl.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should work for translateZ")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForTranslateZ() { await Page.SetViewportSizeAsync(500, 500); await Page.GoToAsync(TestConstants.ServerUrl + "/screenshots/translateZ.html"); byte[] screenshot = await Page.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-translateZ.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-translateZ.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should work while navigating")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhileNavigating() { await Page.SetViewportSizeAsync(500, 500); @@ -358,7 +350,7 @@ public async Task ShouldWorkWhileNavigating() } [PlaywrightTest("page-screenshot.spec.ts", "should work with device scale factor")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithDeviceScaleFactor() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -374,11 +366,11 @@ public async Task ShouldWorkWithDeviceScaleFactor() await page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); byte[] screenshot = await page.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-device-scale-factor.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-device-scale-factor.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "should work with iframe in shadow")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithiFrameInShadow() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -393,11 +385,11 @@ public async Task ShouldWorkWithiFrameInShadow() await page.GoToAsync(TestConstants.ServerUrl + "/grid-iframe-in-shadow.html"); byte[] screenshot = await page.ScreenshotAsync(); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-iframe.png", screenshot)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-iframe.png", screenshot), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "path option should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PathOptionShouldWork() { await Page.SetViewportSizeAsync(500, 500); @@ -406,11 +398,11 @@ public async Task PathOptionShouldWork() string outputPath = Path.Combine(tmpDir.Path, "screenshot.png"); await Page.ScreenshotAsync(outputPath); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "path option should create subdirectories")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PathOptionShouldCreateSubdirectories() { await Page.SetViewportSizeAsync(500, 500); @@ -419,11 +411,11 @@ public async Task PathOptionShouldCreateSubdirectories() string outputPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "screenshot.png"); await Page.ScreenshotAsync(outputPath); - Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath)); + Assert.That(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "path option should detect joeg")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PathOptionShouldDetectJpeg() { await Page.SetViewportSizeAsync(100, 100); @@ -432,15 +424,15 @@ public async Task PathOptionShouldDetectJpeg() string outputPath = Path.Combine(tmpDir.Path, "screenshot.jpg"); await Page.ScreenshotAsync(outputPath, omitBackground: true); - Assert.True(ScreenshotHelper.PixelMatch("white.jpg", outputPath)); + Assert.That(ScreenshotHelper.PixelMatch("white.jpg", outputPath), Is.True); } [PlaywrightTest("page-screenshot.spec.ts", "path option should throw for unsupported mime type")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PathOptionShouldThrowForUnsupportedMimeType() { - var exception = await Assert.ThrowsAnyAsync(() => Page.ScreenshotAsync("file.txt")); - Assert.Contains("path: unsupported mime type \"text/plain\"", exception.Message); + var exception = Assert.CatchAsync(() => Page.ScreenshotAsync("file.txt")); + Assert.That(exception.Message, Does.Contain("path: unsupported mime type \"text/plain\"")); } } } diff --git a/src/Playwright.Tests/PageScrollTests.cs b/src/Playwright.Tests/PageScrollTests.cs index 32378973e0..ccd9134b35 100644 --- a/src/Playwright.Tests/PageScrollTests.cs +++ b/src/Playwright.Tests/PageScrollTests.cs @@ -3,20 +3,13 @@ using System.Drawing; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageScrollTests : PlaywrightSharpPageBaseTest - { - /// - public PageScrollTests(ITestOutputHelper output) : base(output) - { - } - } + { } } diff --git a/src/Playwright.Tests/PageSelectOptionTests.cs b/src/Playwright.Tests/PageSelectOptionTests.cs index c22320c6fb..6c1dabd416 100644 --- a/src/Playwright.Tests/PageSelectOptionTests.cs +++ b/src/Playwright.Tests/PageSelectOptionTests.cs @@ -1,103 +1,95 @@ using System; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageSelectOptionTests : PlaywrightSharpPageBaseTest - { - /// - public PageSelectOptionTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-select-option.spec.ts", "should select single option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-select-option.spec.ts", "should select single option")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectSingleOption() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.SelectOptionAsync("select", "blue"); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "blue" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "blue" })); } [PlaywrightTest("page-select-option.spec.ts", "should select single option by value")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectSingleOptionByValue() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.SelectOptionAsync("select", new SelectOptionValue { Value = "blue" }); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "blue" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "blue" })); } [PlaywrightTest("page-select-option.spec.ts", "should select single option by label")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectSingleOptionByLabel() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.SelectOptionAsync("select", new SelectOptionValue { Label = "Indigo" }); - Assert.Equal(new[] { "indigo" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "indigo" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "indigo" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "indigo" })); } [PlaywrightTest("page-select-option.spec.ts", "should select single option by handle")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectSingleOptionByHandle() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.SelectOptionAsync("select", await Page.QuerySelectorAsync("[id=whiteOption]")); - Assert.Equal(new[] { "white" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "white" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "white" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "white" })); } [PlaywrightTest("page-select-option.spec.ts", "should select single option by index")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectSingleOptionByIndex() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.SelectOptionAsync("select", new SelectOptionValue { Index = 2 }); - Assert.Equal(new[] { "brown" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "brown" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "brown" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "brown" })); } [PlaywrightTest("page-select-option.spec.ts", "should select single option by multiple attributes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectSingleOptionByMultipleAttributes() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.SelectOptionAsync("select", new SelectOptionValue { Value = "green", Label = "Green" }); - Assert.Equal(new[] { "green" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "green" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "green" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "green" })); } [PlaywrightTest("page-select-option.spec.ts", "should not select single option when some attributes do not match")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotSelectSingleOptionWhenSomeAttributesDoNotMatch() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.EvalOnSelectorAsync("select", "s => s.value = undefined"); - await Assert.ThrowsAsync(() => Page.SelectOptionAsync("select", new SelectOptionValue { Value = "green", Label = "Brown" })); - Assert.Empty(await Page.EvaluateAsync("() => document.querySelector('select').value")); + Assert.ThrowsAsync(() => Page.SelectOptionAsync("select", new SelectOptionValue { Value = "green", Label = "Brown" })); + Assert.That(await Page.EvaluateAsync("() => document.querySelector('select').value"), Is.Empty); } [PlaywrightTest("page-select-option.spec.ts", "should select only first option")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectOnlyFirstOption() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.SelectOptionAsync("select", "blue", "green", "red"); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "blue" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "blue" })); } [PlaywrightTest("page-select-option.spec.ts", "should not throw when select causes navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotThrowWhenSelectCausesNavigation() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); @@ -106,146 +98,146 @@ await TaskUtils.WhenAll( Page.SelectOptionAsync("select", "blue"), Page.WaitForNavigationAsync() ); - Assert.Contains("empty.html", Page.Url); + Assert.That(Page.Url, Does.Contain("empty.html")); } [PlaywrightTest("page-select-option.spec.ts", "should select multiple options")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectMultipleOptions() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.EvaluateAsync("() => makeMultiple()"); await Page.SelectOptionAsync("select", "blue", "green", "red"); - Assert.Equal(new[] { "blue", "green", "red" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "blue", "green", "red" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "blue", "green", "red" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "blue", "green", "red" })); } [PlaywrightTest("page-select-option.spec.ts", "should select multiple options with attributes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSelectMultipleOptionsWithAttributes() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.EvaluateAsync("() => makeMultiple()"); await Page.SelectOptionAsync("select", new SelectOptionValue { Value = "blue" }, new SelectOptionValue { Label = "Green" }, new SelectOptionValue { Index = 4 }); - Assert.Equal(new[] { "blue", "gray", "green" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "blue", "gray", "green" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "blue", "gray", "green" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "blue", "gray", "green" })); } [PlaywrightTest("page-select-option.spec.ts", "should respect event bubbling")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectEventBubbling() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.SelectOptionAsync("select", "blue"); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onBubblingInput")); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onBubblingChange")); + Assert.That(await Page.EvaluateAsync("() => result.onBubblingInput"), Is.EqualTo(new[] { "blue" })); + Assert.That(await Page.EvaluateAsync("() => result.onBubblingChange"), Is.EqualTo(new[] { "blue" })); } [PlaywrightTest("page-select-option.spec.ts", "should throw when element is not a <select>")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWhenElementIsNotASelect() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); - var exception = await Assert.ThrowsAsync(() => Page.SelectOptionAsync("body", string.Empty)); - Assert.Contains("Element is not a element.")); } [PlaywrightTest("page-select-option.spec.ts", "should return [] on no matched values")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnEmptyArrayOnNoMatchedValues() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); var result = await Page.SelectOptionAsync("select", Array.Empty()); - Assert.Empty(result); + Assert.That(result, Is.Empty); } [PlaywrightTest("page-select-option.spec.ts", "should return an array of matched values")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnAnArrayOfMatchedValues() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.EvaluateAsync("() => makeMultiple()"); var result = await Page.SelectOptionAsync("select", "blue", "black", "magenta"); - Assert.Equal(new[] { "blue", "black", "magenta" }.OrderBy(v => v), result.OrderBy(v => v)); + Assert.That(result.OrderBy(v => v), Is.EqualTo(new[] { "blue", "black", "magenta" }.OrderBy(v => v))); } [PlaywrightTest("page-select-option.spec.ts", "should return an array of one element when multiple is not set")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnAnArrayOfOneElementWhenMultipleIsNotSet() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); var result = await Page.SelectOptionAsync("select", "42", "blue", "black", "magenta"); - Assert.Single(result); + Assert.That(result, Has.Count.EqualTo(1)); } [PlaywrightTest("page-select-option.spec.ts", "should return [] on no values")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnEmptyArrayOnNoValues() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); var result = await Page.SelectOptionAsync("select", Array.Empty()); - Assert.Empty(result); + Assert.That(result, Is.Empty); } [PlaywrightTest("page-select-option.spec.ts", "should not allow null items")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotAllowNullItems() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.EvaluateAsync("() => makeMultiple()"); - var exception = await Assert.ThrowsAsync( + var exception = Assert.ThrowsAsync( () => Page.SelectOptionAsync("select", new[] { "blue", null, "black", "magenta" })); - Assert.Contains("got null", exception.Message); + Assert.That(exception.Message, Does.Contain("got null")); } [PlaywrightTest("page-select-option.spec.ts", "should unselect with null")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUnselectWithNull() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.EvaluateAsync("() => makeMultiple()"); var result = await Page.SelectOptionAsync("select", new[] { "blue", "black", "magenta" }); - Assert.True(result.All(r => new[] { "blue", "black", "magenta" }.Contains(r))); + Assert.That(result.All(r => new[] { "blue", "black", "magenta" }.Contains(r)), Is.True); await Page.SelectOptionAsync("select"); - Assert.True(await Page.EvalOnSelectorAsync("select", "select => Array.from(select.options).every(option => !option.selected)")); + Assert.That(await Page.EvalOnSelectorAsync("select", "select => Array.from(select.options).every(option => !option.selected)"), Is.True); } [PlaywrightTest("page-select-option.spec.ts", "should deselect all options when passed no values for a multiple select")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDeselectAllOptionsWhenPassedNoValuesForAMultipleSelect() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.EvaluateAsync("() => makeMultiple()"); await Page.SelectOptionAsync("select", "blue", "black", "magenta"); await Page.SelectOptionAsync("select"); - Assert.True(await Page.EvalOnSelectorAsync("select", "select => Array.from(select.options).every(option => !option.selected)")); + Assert.That(await Page.EvalOnSelectorAsync("select", "select => Array.from(select.options).every(option => !option.selected)"), Is.True); } [PlaywrightTest("page-select-option.spec.ts", "should deselect all options when passed no values for a select without multiple")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDeselectAllOptionsWhenPassedNoValuesForASelectWithoutMultiple() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.SelectOptionAsync("select", "blue", "black", "magenta"); await Page.SelectOptionAsync("select", Array.Empty()); - Assert.True(await Page.EvalOnSelectorAsync("select", "select => Array.from(select.options).every(option => !option.selected)")); + Assert.That(await Page.EvalOnSelectorAsync("select", "select => Array.from(select.options).every(option => !option.selected)"), Is.True); } [PlaywrightTest("page-select-option.spec.ts", "should throw if passed wrong types")] - [Fact(Skip = "Not relevant for C#, js specific")] + [Test, Ignore("Not relevant for C#, js specific")] public void ShouldThrowIfPassedWrongTypes() { } [PlaywrightTest("page-select-option.spec.ts", "should work when re-defining top-level Event class")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenReDefiningTopLevelEventClass() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/select.html"); await Page.EvaluateAsync("() => window.Event = null"); await Page.SelectOptionAsync("select", "blue"); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onInput")); - Assert.Equal(new[] { "blue" }, await Page.EvaluateAsync("() => result.onChange")); + Assert.That(await Page.EvaluateAsync("() => result.onInput"), Is.EqualTo(new[] { "blue" })); + Assert.That(await Page.EvaluateAsync("() => result.onChange"), Is.EqualTo(new[] { "blue" })); } } } diff --git a/src/Playwright.Tests/PageSetContentTests.cs b/src/Playwright.Tests/PageSetContentTests.cs index a9e5b7c21f..4017f7777d 100644 --- a/src/Playwright.Tests/PageSetContentTests.cs +++ b/src/Playwright.Tests/PageSetContentTests.cs @@ -1,90 +1,84 @@ using System; using System.Threading; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageSetContentTests : PlaywrightSharpPageBaseTest { const string _expectedOutput = "
hello
"; - /// - public PageSetContentTests(ITestOutputHelper output) : base(output) - { - } [PlaywrightTest("page-set-content.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.SetContentAsync("
hello
"); string result = await Page.ContentAsync(); - Assert.Equal(_expectedOutput, result); + Assert.That(result, Is.EqualTo(_expectedOutput)); } [PlaywrightTest("page-set-content.spec.ts", "should work with domcontentloaded")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithDomcontentloaded() { await Page.SetContentAsync("
hello
", waitUntil: WaitUntilState.DOMContentLoaded); string result = await Page.ContentAsync(); - Assert.Equal(_expectedOutput, result); + Assert.That(result, Is.EqualTo(_expectedOutput)); } [PlaywrightTest("page-set-content.spec.ts", "should work with doctype")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithDoctype() { string doctype = ""; await Page.SetContentAsync($"{doctype}
hello
"); string result = await Page.ContentAsync(); - Assert.Equal($"{doctype}{_expectedOutput}", result); + Assert.That(result, Is.EqualTo($"{doctype}{_expectedOutput}")); } [PlaywrightTest("page-set-content.spec.ts", "should work with HTML 4 doctype")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithHTML4Doctype() { string doctype = ""; await Page.SetContentAsync($"{doctype}
hello
"); string result = await Page.ContentAsync(); - Assert.Equal($"{doctype}{_expectedOutput}", result); + Assert.That(result, Is.EqualTo($"{doctype}{_expectedOutput}")); } [PlaywrightTest("page-set-content.spec.ts", "should respect timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectTimeout() { string imgPath = "/img.png"; // stall for image Server.SetRoute(imgPath, _ => Task.Delay(Timeout.Infinite)); - await Assert.ThrowsAsync(() => + Assert.ThrowsAsync(() => Page.SetContentAsync($"", timeout: 1) ); } [PlaywrightTest("page-set-content.spec.ts", "should respect default navigation timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectDefaultNavigationTimeout() { Page.DefaultNavigationTimeout = 1; string imgPath = "/img.png"; // stall for image Server.SetRoute(imgPath, _ => Task.Delay(Timeout.Infinite)); - var exception = await Assert.ThrowsAsync(() => + var exception = Assert.ThrowsAsync(() => Page.SetContentAsync($"", timeout: 1) ); - Assert.Contains("Timeout 1ms exceeded", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 1ms exceeded")); } [PlaywrightTest("page-set-content.spec.ts", "should await resources to load")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAwaitResourcesToLoad() { string imgPath = "/img.png"; @@ -93,13 +87,13 @@ public async Task ShouldAwaitResourcesToLoad() bool loaded = false; var contentTask = Page.SetContentAsync($"").ContinueWith(_ => loaded = true); await Server.WaitForRequest(imgPath); - Assert.False(loaded); + Assert.That(loaded, Is.False); imgResponse.SetResult(true); await contentTask; } [PlaywrightTest("page-set-content.spec.ts", "should work fast enough")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkFastEnough() { for (int i = 0; i < 20; ++i) @@ -109,35 +103,35 @@ public async Task ShouldWorkFastEnough() } [PlaywrightTest("page-set-content.spec.ts", "should work with tricky content")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithTrickyContent() { await Page.SetContentAsync("
hello world
" + "\x7F"); - Assert.Equal("hello world", await Page.EvalOnSelectorAsync("div", "div => div.textContent")); + Assert.That(await Page.EvalOnSelectorAsync("div", "div => div.textContent"), Is.EqualTo("hello world")); } [PlaywrightTest("page-set-content.spec.ts", "should work with accents")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithAccents() { await Page.SetContentAsync("
aberración
"); - Assert.Equal("aberración", await Page.EvalOnSelectorAsync("div", "div => div.textContent")); + Assert.That(await Page.EvalOnSelectorAsync("div", "div => div.textContent"), Is.EqualTo("aberración")); } [PlaywrightTest("page-set-content.spec.ts", "should work with emojis")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithEmojis() { await Page.SetContentAsync("
🐥
"); - Assert.Equal("🐥", await Page.EvalOnSelectorAsync("div", "div => div.textContent")); + Assert.That(await Page.EvalOnSelectorAsync("div", "div => div.textContent"), Is.EqualTo("🐥")); } [PlaywrightTest("page-set-content.spec.ts", "should work with newline")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNewline() { await Page.SetContentAsync("
\n
"); - Assert.Equal("\n", await Page.EvalOnSelectorAsync("div", "div => div.textContent")); + Assert.That(await Page.EvalOnSelectorAsync("div", "div => div.textContent"), Is.EqualTo("\n")); } } } diff --git a/src/Playwright.Tests/PageSetExtraHttpHeadersTests.cs b/src/Playwright.Tests/PageSetExtraHttpHeadersTests.cs index 74aa4d8db9..48d0f5cc66 100644 --- a/src/Playwright.Tests/PageSetExtraHttpHeadersTests.cs +++ b/src/Playwright.Tests/PageSetExtraHttpHeadersTests.cs @@ -1,22 +1,14 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageSetExtraHTTPHeadersTests : PlaywrightSharpPageBaseTest - { - /// - public PageSetExtraHTTPHeadersTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-set-extra-http-headers.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-set-extra-http-headers.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.SetExtraHttpHeadersAsync(new Dictionary @@ -27,11 +19,11 @@ await Page.SetExtraHttpHeadersAsync(new Dictionary var headerTask = Server.WaitForRequest("/empty.html", request => request.Headers["Foo"]); await TaskUtils.WhenAll(Page.GoToAsync(TestConstants.EmptyPage), headerTask); - Assert.Equal("Bar", headerTask.Result); + Assert.That(headerTask.Result, Is.EqualTo("Bar")); } [PlaywrightTest("page-set-extra-http-headers.spec.ts", "should work with redirects")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithRedirects() { Server.SetRedirect("/foo.html", "/empty.html"); @@ -43,11 +35,11 @@ await Page.SetExtraHttpHeadersAsync(new Dictionary var headerTask = Server.WaitForRequest("/empty.html", request => request.Headers["Foo"]); await TaskUtils.WhenAll(Page.GoToAsync(TestConstants.ServerUrl + "/foo.html"), headerTask); - Assert.Equal("Bar", headerTask.Result); + Assert.That(headerTask.Result, Is.EqualTo("Bar")); } [PlaywrightTest("page-set-extra-http-headers.spec.ts", "should work with extra headers from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithExtraHeadersFromBrowserContext() { await using var context = await Browser.NewContextAsync(); @@ -60,11 +52,11 @@ await context.SetExtraHttpHeadersAsync(new Dictionary var headerTask = Server.WaitForRequest("/empty.html", request => request.Headers["Foo"]); await TaskUtils.WhenAll(page.GoToAsync(TestConstants.EmptyPage), headerTask); - Assert.Equal("Bar", headerTask.Result); + Assert.That(headerTask.Result, Is.EqualTo("Bar")); } [PlaywrightTest("page-set-extra-http-headers.spec.ts", "should override extra headers from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldOverrideExtraHeadersFromBrowserContext() { await using var context = await Browser.NewContextAsync(); @@ -83,12 +75,12 @@ await page.SetExtraHttpHeadersAsync(new Dictionary var headerTask = Server.WaitForRequest("/empty.html", request => (request.Headers["Foo"], request.Headers["baR"])); await TaskUtils.WhenAll(page.GoToAsync(TestConstants.EmptyPage), headerTask); - Assert.Equal("Bar", headerTask.Result.Item1); - Assert.Equal("foO", headerTask.Result.Item2); + Assert.That(headerTask.Result.Item1, Is.EqualTo("Bar")); + Assert.That(headerTask.Result.Item2, Is.EqualTo("foO")); } [PlaywrightTest("page-set-extra-http-headers.spec.ts", "should throw for non-string header values")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldThrowForNonStringHeaderValues() { } } } diff --git a/src/Playwright.Tests/PageSetInputFilesTests.cs b/src/Playwright.Tests/PageSetInputFilesTests.cs index 2bb28286c3..1914695d8c 100644 --- a/src/Playwright.Tests/PageSetInputFilesTests.cs +++ b/src/Playwright.Tests/PageSetInputFilesTests.cs @@ -4,53 +4,45 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///page-set-input-files.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageSetInputFilesTests : PlaywrightSharpPageBaseTest - { - /// - public PageSetInputFilesTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-set-input-files.spec.ts", "should upload the file")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-set-input-files.spec.ts", "should upload the file")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUploadTheFile() { await Page.GoToAsync(TestConstants.ServerUrl + "/input/fileupload.html"); string filePath = Path.Combine(Directory.GetCurrentDirectory(), "Assets", TestConstants.FileToUpload); var input = await Page.QuerySelectorAsync("input"); await input.SetInputFilesAsync(filePath); - Assert.Equal("file-to-upload.txt", await Page.EvaluateAsync("e => e.files[0].name", input)); - Assert.Equal("contents of the file", await Page.EvaluateAsync(@"e => { + Assert.That(await Page.EvaluateAsync("e => e.files[0].name", input), Is.EqualTo("file-to-upload.txt")); + Assert.That(await Page.EvaluateAsync(@"e => { var reader = new FileReader(); var promise = new Promise(fulfill => reader.onload = fulfill); reader.readAsText(e.files[0]); return promise.then(() => reader.result); - }", input)); + }", input), Is.EqualTo("contents of the file")); } [PlaywrightTest("page-set-input-files.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.SetContentAsync(""); string filePath = Path.Combine(Directory.GetCurrentDirectory(), "Assets", TestConstants.FileToUpload); await Page.SetInputFilesAsync("input", filePath); - Assert.Equal(1, await Page.EvalOnSelectorAsync("input", "e => e.files.length")); - Assert.Equal("file-to-upload.txt", await Page.EvalOnSelectorAsync("input", "e => e.files[0].name")); + Assert.That(await Page.EvalOnSelectorAsync("input", "e => e.files.length"), Is.EqualTo(1)); + Assert.That(await Page.EvalOnSelectorAsync("input", "e => e.files[0].name"), Is.EqualTo("file-to-upload.txt")); } [PlaywrightTest("page-set-input-files.spec.ts", "should set from memory")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSetFromMemory() { await Page.SetContentAsync(""); @@ -62,12 +54,12 @@ public async Task ShouldSetFromMemory() Buffer = Encoding.UTF8.GetBytes("this is a test"), }); - Assert.Equal(1, await Page.EvalOnSelectorAsync("input", "e => e.files.length")); - Assert.Equal("test.txt", await Page.EvalOnSelectorAsync("input", "e => e.files[0].name")); + Assert.That(await Page.EvalOnSelectorAsync("input", "e => e.files.length"), Is.EqualTo(1)); + Assert.That(await Page.EvalOnSelectorAsync("input", "e => e.files[0].name"), Is.EqualTo("test.txt")); } [PlaywrightTest("page-set-input-files.spec.ts", "should emit event once")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmitEventOnce() { await Page.SetContentAsync(""); @@ -82,23 +74,23 @@ void EventHandler(object sender, IFileChooser e) chooserTsc.Task, Page.ClickAsync("input") ); - Assert.NotNull(chooser); + Assert.That(chooser, Is.Not.Null); } [PlaywrightTest("page-set-input-files.spec.ts", "should emit event on/off")] - [Fact(Skip = "We dont'need to test this")] + [Test, Ignore("We dont'need to test this")] public void ShouldEmitEventOnOff() { } [PlaywrightTest("page-set-input-files.spec.ts", "should emit addListener/removeListener")] - [Fact(Skip = "We dont'need to test this")] + [Test, Ignore("We dont'need to test this")] public void ShouldEmitEventAddListenerRemoveListener() { } [PlaywrightTest("page-set-input-files.spec.ts", "should work when file input is attached to DOM")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenFileInputIsAttachedToDOM() { await Page.SetContentAsync(""); @@ -106,11 +98,11 @@ public async Task ShouldWorkWhenFileInputIsAttachedToDOM() Page.WaitForEventAsync(PageEvent.FileChooser), Page.ClickAsync("input") ); - Assert.NotNull(chooser?.Element); + Assert.That(chooser?.Element, Is.Not.Null); } [PlaywrightTest("page-set-input-files.spec.ts", "should work when file input is not attached to DOM")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenFileInputIsNotAttachedToDOM() { var (chooser, _) = await TaskUtils.WhenAll( @@ -121,12 +113,12 @@ public async Task ShouldWorkWhenFileInputIsNotAttachedToDOM() el.click(); }") ); - Assert.NotNull(chooser?.Element); + Assert.That(chooser?.Element, Is.Not.Null); } [PlaywrightTest("page-set-input-files.spec.ts", "should work with CSP")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCSP() { Server.SetCSP("/empty.html", "default-src \"none\""); @@ -134,33 +126,35 @@ public async Task ShouldWorkWithCSP() await Page.SetContentAsync(""); await Page.SetInputFilesAsync("input", Path.Combine(Directory.GetCurrentDirectory(), "Assets", TestConstants.FileToUpload)); - Assert.Equal(1, await Page.EvalOnSelectorAsync("input", "input => input.files.length")); - Assert.Equal("file-to-upload.txt", await Page.EvalOnSelectorAsync("input", "input => input.files[0].name")); + Assert.That(await Page.EvalOnSelectorAsync("input", "input => input.files.length"), Is.EqualTo(1)); + Assert.That(await Page.EvalOnSelectorAsync("input", "input => input.files[0].name"), Is.EqualTo("file-to-upload.txt")); } [PlaywrightTest("page-set-input-files.spec.ts", "should respect timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] - public Task ShouldRespectTimeout() => Assert.ThrowsAsync(() - => Page.WaitForEventAsync(PageEvent.FileChooser, timeout: 1)); + [Test, Timeout(TestConstants.DefaultTestTimeout)] + public void ShouldRespectTimeout() + { + Assert.ThrowsAsync(() => Page.WaitForEventAsync(PageEvent.FileChooser, timeout: 1)); + } [PlaywrightTest("page-set-input-files.spec.ts", "should respect default timeout when there is no custom timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectDefaultTimeoutWhenThereIsNoCustomTimeout() { Page.DefaultTimeout = 1; - await Assert.ThrowsAsync(() => Page.WaitForEventAsync(PageEvent.FileChooser)); + Assert.ThrowsAsync(() => Page.WaitForEventAsync(PageEvent.FileChooser)); } [PlaywrightTest("page-set-input-files.spec.ts", "should prioritize exact timeout over default timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPrioritizeExactTimeoutOverDefaultTimeout() { Page.DefaultTimeout = 0; - await Assert.ThrowsAsync(() => Page.WaitForEventAsync(PageEvent.FileChooser, timeout: 1)); + Assert.ThrowsAsync(() => Page.WaitForEventAsync(PageEvent.FileChooser, timeout: 1)); } [PlaywrightTest("page-set-input-files.spec.ts", "should work with no timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNoTimeout() { var (chooser, _) = await TaskUtils.WhenAll( @@ -171,11 +165,11 @@ public async Task ShouldWorkWithNoTimeout() el.click(); }, 50)") ); - Assert.NotNull(chooser?.Element); + Assert.That(chooser?.Element, Is.Not.Null); } [PlaywrightTest("page-set-input-files.spec.ts", "should return the same file chooser when there are many watchdogs simultaneously")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnTheSameFileChooserWhenThereAreManyWatchdogsSimultaneously() { await Page.SetContentAsync(""); @@ -184,11 +178,11 @@ public async Task ShouldReturnTheSameFileChooserWhenThereAreManyWatchdogsSimulta Page.WaitForEventAsync(PageEvent.FileChooser), Page.EvalOnSelectorAsync("input", "input => input.click()") ); - Assert.Equal(fileChooser1, fileChooser2); + Assert.That(fileChooser2, Is.EqualTo(fileChooser1)); } [PlaywrightTest("page-set-input-files.spec.ts", "should accept single file")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptSingleFile() { await Page.SetContentAsync(""); @@ -197,15 +191,15 @@ public async Task ShouldAcceptSingleFile() Page.ClickAsync("input") ); - Assert.Same(Page, fileChooser.Page); - Assert.NotNull(fileChooser.Element); + Assert.That(fileChooser.Page, Is.SameAs(Page)); + Assert.That(fileChooser.Element, Is.Not.Null); await fileChooser.SetFilesAsync(TestConstants.FileToUpload); - Assert.Equal(1, await Page.EvalOnSelectorAsync("input", "input => input.files.length")); - Assert.Equal("file-to-upload.txt", await Page.EvalOnSelectorAsync("input", "input => input.files[0].name")); + Assert.That(await Page.EvalOnSelectorAsync("input", "input => input.files.length"), Is.EqualTo(1)); + Assert.That(await Page.EvalOnSelectorAsync("input", "input => input.files[0].name"), Is.EqualTo("file-to-upload.txt")); } [PlaywrightTest("page-set-input-files.spec.ts", "should detect mime type")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDetectMimeType() { var files = new List<(string name, string mime, byte[] content)>(); @@ -238,55 +232,55 @@ await TaskUtils.WhenAll( Server.WaitForRequest("/upload") ); - Assert.Equal("file-to-upload.txt", files[0].name); - Assert.Equal("text/plain", files[0].mime); - Assert.Equal(File.ReadAllBytes(TestUtils.GetWebServerFile("file-to-upload.txt")), files[0].content); + Assert.That(files[0].name, Is.EqualTo("file-to-upload.txt")); + Assert.That(files[0].mime, Is.EqualTo("text/plain")); + Assert.That(files[0].content, Is.EqualTo(File.ReadAllBytes(TestUtils.GetWebServerFile("file-to-upload.txt")))); - Assert.Equal("pptr.png", files[1].name); - Assert.Equal("image/png", files[1].mime); - Assert.Equal(File.ReadAllBytes(TestUtils.GetWebServerFile("pptr.png")), files[1].content); + Assert.That(files[1].name, Is.EqualTo("pptr.png")); + Assert.That(files[1].mime, Is.EqualTo("image/png")); + Assert.That(files[1].content, Is.EqualTo(File.ReadAllBytes(TestUtils.GetWebServerFile("pptr.png")))); } [PlaywrightTest("page-set-input-files.spec.ts", "should be able to read selected file")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToReadSelectedFile() { await Page.SetContentAsync(""); _ = Page.WaitForEventAsync(PageEvent.FileChooser) .ContinueWith(task => task.Result.SetFilesAsync(TestConstants.FileToUpload)); - Assert.Equal("contents of the file", await Page.EvalOnSelectorAsync("input", @"async picker => { + Assert.That(await Page.EvalOnSelectorAsync("input", @"async picker => { picker.click(); await new Promise(x => picker.oninput = x); const reader = new FileReader(); const promise = new Promise(fulfill => reader.onload = fulfill); reader.readAsText(picker.files[0]); return promise.then(() => reader.result); - }")); + }"), Is.EqualTo("contents of the file")); } [PlaywrightTest("page-set-input-files.spec.ts", "should be able to reset selected files with empty file list")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeAbleToResetSelectedFilesWithEmptyFileList() { await Page.SetContentAsync(""); _ = Page.WaitForEventAsync(PageEvent.FileChooser) .ContinueWith(task => task.Result.SetFilesAsync(TestConstants.FileToUpload)); - Assert.Equal(1, await Page.EvalOnSelectorAsync("input", @"async picker => { + Assert.That(await Page.EvalOnSelectorAsync("input", @"async picker => { picker.click(); await new Promise(x => picker.oninput = x); return picker.files.length; - }")); + }"), Is.EqualTo(1)); _ = Page.WaitForEventAsync(PageEvent.FileChooser) .ContinueWith(task => task.Result.Element.SetInputFilesAsync(new string[] { })); - Assert.Equal(0, await Page.EvalOnSelectorAsync("input", @"async picker => { + Assert.That(await Page.EvalOnSelectorAsync("input", @"async picker => { picker.click(); await new Promise(x => picker.oninput = x); return picker.files.length; - }")); + }"), Is.EqualTo(0)); } [PlaywrightTest("page-set-input-files.spec.ts", "should not accept multiple files for single-file input")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotAcceptMultipleFilesForSingleFileInput() { await Page.SetContentAsync(""); @@ -294,7 +288,7 @@ public async Task ShouldNotAcceptMultipleFilesForSingleFileInput() Page.WaitForEventAsync(PageEvent.FileChooser), Page.ClickAsync("input") ); - await Assert.ThrowsAsync(() => fileChooser.SetFilesAsync(new string[] + Assert.ThrowsAsync(() => fileChooser.SetFilesAsync(new string[] { TestUtils.GetWebServerFile(TestConstants.FileToUpload), TestUtils.GetWebServerFile("pptr.png"), @@ -302,7 +296,7 @@ await Assert.ThrowsAsync(() => fileChooser.SetFilesAsy } [PlaywrightTest("page-set-input-files.spec.ts", "should emit input and change events")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmitInputAndChangeEvents() { var events = new List(); @@ -317,13 +311,13 @@ await Page.SetContentAsync(@" "); await (await Page.QuerySelectorAsync("input")).SetInputFilesAsync(TestUtils.GetWebServerFile("file-to-upload.txt")); - Assert.Equal(2, events.Count); - Assert.Equal("input", events[0]); - Assert.Equal("change", events[1]); + Assert.That(events.Count, Is.EqualTo(2)); + Assert.That(events[0], Is.EqualTo("input")); + Assert.That(events[1], Is.EqualTo("change")); } [PlaywrightTest("page-set-input-files.spec.ts", "should work for single file pick")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForSingleFilePick() { await Page.SetContentAsync(""); @@ -333,11 +327,11 @@ public async Task ShouldWorkForSingleFilePick() waitTask, Page.ClickAsync("input") ); - Assert.False(fileChooser.IsMultiple); + Assert.That(fileChooser.IsMultiple, Is.False); } [PlaywrightTest("page-set-input-files.spec.ts", @"should work for ""multiple""")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForMultiple() { await Page.SetContentAsync(""); @@ -345,11 +339,11 @@ public async Task ShouldWorkForMultiple() Page.WaitForEventAsync(PageEvent.FileChooser), Page.ClickAsync("input") ); - Assert.True(fileChooser.IsMultiple); + Assert.That(fileChooser.IsMultiple, Is.True); } [PlaywrightTest("page-set-input-files.spec.ts", @"should work for ""webkitdirectory""")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForWebkitdirectory() { await Page.SetContentAsync(""); @@ -357,7 +351,7 @@ public async Task ShouldWorkForWebkitdirectory() Page.WaitForEventAsync(PageEvent.FileChooser), Page.ClickAsync("input") ); - Assert.True(fileChooser.IsMultiple); + Assert.That(fileChooser.IsMultiple, Is.True); } } } diff --git a/src/Playwright.Tests/PageWaitForFunctionTests.cs b/src/Playwright.Tests/PageWaitForFunctionTests.cs index 840db07109..d23ed78523 100644 --- a/src/Playwright.Tests/PageWaitForFunctionTests.cs +++ b/src/Playwright.Tests/PageWaitForFunctionTests.cs @@ -1,38 +1,30 @@ using System; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageWaitForFunctionTests : PlaywrightSharpPageBaseTest - { - /// - public PageWaitForFunctionTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-wait-for-function.spec.ts", "should timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-wait-for-function.spec.ts", "should timeout")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldTimeout() { var startTime = DateTime.Now; int timeout = 42; await Page.WaitForTimeoutAsync(timeout); - Assert.True((DateTime.Now - startTime).TotalMilliseconds > timeout / 2); + Assert.That((DateTime.Now - startTime).TotalMilliseconds > timeout / 2, Is.True); } [PlaywrightTest("page-wait-for-function.spec.ts", "should accept a string")] - [Fact(Skip = "We don't this test")] + [Test, Ignore("We don't this test")] public void ShouldAcceptAString() { } [PlaywrightTest("page-wait-for-function.spec.tsPageWaitForFunctionTests", "should work when resolved right before execution context disposal")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenResolvedRightBeforeExecutionContextDisposal() { await Page.AddInitScriptAsync("() => window.__RELOADED = true"); @@ -45,7 +37,7 @@ await Page.WaitForFunctionAsync(@"() => } [PlaywrightTest("page-wait-for-function.spec.ts", "should poll on interval")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPollOnInterval() { int polling = 100; @@ -58,17 +50,17 @@ public async Task ShouldPollOnInterval() }", pollingInterval: polling); int value = (await timeDelta.JsonValueAsync()); - Assert.True(value >= polling); + Assert.That(value >= polling, Is.True); } [PlaywrightTest("page-wait-for-function.spec.ts", "should avoid side effects after timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAvoidSideEffectsAfterTimeout() { int counter = 0; Page.Console += (_, _) => ++counter; - var exception = await Assert.ThrowsAnyAsync(() => Page.WaitForFunctionAsync( + var exception = Assert.CatchAsync(() => Page.WaitForFunctionAsync( @"() => { window.counter = (window.counter || 0) + 1; console.log(window.counter); @@ -79,18 +71,18 @@ public async Task ShouldAvoidSideEffectsAfterTimeout() int savedCounter = counter; await Page.WaitForTimeoutAsync(2000); - Assert.Contains("Timeout 1000ms exceeded", exception.Message); - Assert.Equal(savedCounter, counter); + Assert.That(exception.Message, Does.Contain("Timeout 1000ms exceeded")); + Assert.That(counter, Is.EqualTo(savedCounter)); } [PlaywrightTest("page-wait-for-function.spec.ts", "should throw on polling:mutation")] - [Fact(Skip = "We don't need to test this")] + [Test, Ignore("We don't need to test this")] public void ShouldThrowOnPollingMutation() { } [PlaywrightTest("page-wait-for-function.spec.ts", "should poll on raf")] - [Fact(Skip = "We don't support raf")] + [Test, Ignore("We don't support raf")] public void ShouldPollOnRaf() { /* @@ -103,36 +95,36 @@ public void ShouldPollOnRaf() } [PlaywrightTest("page-wait-for-function.spec.ts", "should fail with predicate throwing on first call")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWithPredicateThrowingOnFirstCall() { - var exception = await Assert.ThrowsAnyAsync(() => Page.WaitForFunctionAsync("() => { throw new Error('oh my'); }")); - Assert.Contains("oh my", exception.Message); + var exception = Assert.CatchAsync(() => Page.WaitForFunctionAsync("() => { throw new Error('oh my'); }")); + Assert.That(exception.Message, Does.Contain("oh my")); } [PlaywrightTest("page-wait-for-function.spec.ts", "should fail with predicate throwing sometimes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWithPredicateThrowingSometimes() { - var exception = await Assert.ThrowsAnyAsync(() => Page.WaitForFunctionAsync(@"() => { + var exception = Assert.CatchAsync(() => Page.WaitForFunctionAsync(@"() => { window.counter = (window.counter || 0) + 1; if (window.counter === 3) throw new Error('Bad counter!'); return window.counter === 5 ? 'result' : false; }")); - Assert.Contains("Bad counter!", exception.Message); + Assert.That(exception.Message, Does.Contain("Bad counter!")); } [PlaywrightTest("page-wait-for-function.spec.ts", "should fail with ReferenceError on wrong page")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWithReferenceErrorOnWrongPage() { - var exception = await Assert.ThrowsAnyAsync(() => Page.WaitForFunctionAsync("() => globalVar === 123")); - Assert.Contains("globalVar", exception.Message); + var exception = Assert.CatchAsync(() => Page.WaitForFunctionAsync("() => globalVar === 123")); + Assert.That(exception.Message, Does.Contain("globalVar")); } [PlaywrightTest("page-wait-for-function.spec.ts", "should work with strict CSP policy")] - [Fact(Skip = "We don't support raf")] + [Test, Ignore("We don't support raf")] public void ShouldWorkWithStrictCSPPolicy() { /* @@ -147,33 +139,33 @@ await TaskUtils.WhenAll( } [PlaywrightTest("page-wait-for-function.spec.ts", "should throw on bad polling value")] - [Fact(Skip = "We don't this test")] + [Test, Ignore("We don't this test")] public void ShouldThrowOnBadPollingValue() { } [PlaywrightTest("page-wait-for-function.spec.ts", "should throw negative polling interval")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowNegativePollingInterval() { - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => Page.WaitForFunctionAsync("() => !!document.body", pollingInterval: -10)); - Assert.Contains("Cannot poll with non-positive interval", exception.Message); + Assert.That(exception.Message, Does.Contain("Cannot poll with non-positive interval")); } [PlaywrightTest("page-wait-for-function.spec.ts", "should return the success value as a JSHandle")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnTheSuccessValueAsAJSHandle() - => Assert.Equal(5, await (await Page.WaitForFunctionAsync("() => 5")).JsonValueAsync()); + => Assert.That(await (await Page.WaitForFunctionAsync("() => 5")).JsonValueAsync(), Is.EqualTo(5)); [PlaywrightTest("page-wait-for-function.spec.ts", "should return the window as a success value")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnTheWindowAsASuccessValue() - => Assert.NotNull(await Page.WaitForFunctionAsync("() => window")); + => Assert.That(await Page.WaitForFunctionAsync("() => window"), Is.Not.Null); [PlaywrightTest("page-wait-for-function.spec.ts", "should accept ElementHandle arguments")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAcceptElementHandleArguments() { await Page.SetContentAsync("
"); @@ -181,34 +173,34 @@ public async Task ShouldAcceptElementHandleArguments() bool resolved = false; var waitForFunction = Page.WaitForFunctionAsync("element => !element.parentElement", div) .ContinueWith(_ => resolved = true); - Assert.False(resolved); + Assert.That(resolved, Is.False); await Page.EvaluateAsync("element => element.remove()", div); await waitForFunction; } [PlaywrightTest("page-wait-for-function.spec.ts", "should respect timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectTimeout() { - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => Page.WaitForFunctionAsync("false", timeout: 10)); - Assert.Contains("Timeout 10ms exceeded", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 10ms exceeded")); } [PlaywrightTest("page-wait-for-function.spec.ts", "should respect default timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectDefaultTimeout() { Page.DefaultTimeout = 1; - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => Page.WaitForFunctionAsync("false")); - Assert.Contains("Timeout 1ms exceeded", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 1ms exceeded")); } [PlaywrightTest("page-wait-for-function.spec.ts", "should disable timeout when its set to 0")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldDisableTimeoutWhenItsSetTo0() { var watchdog = Page.WaitForFunctionAsync( @@ -224,25 +216,25 @@ public async Task ShouldDisableTimeoutWhenItsSetTo0() } [PlaywrightTest("page-wait-for-function.spec.ts", "should survive cross-process navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSurviveCrossProcessNavigation() { bool fooFound = false; var waitForFunction = Page.WaitForFunctionAsync("window.__FOO === 1") .ContinueWith(_ => fooFound = true); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.False(fooFound); + Assert.That(fooFound, Is.False); await Page.ReloadAsync(); - Assert.False(fooFound); + Assert.That(fooFound, Is.False); await Page.GoToAsync(TestConstants.CrossProcessUrl + "/grid.html"); - Assert.False(fooFound); + Assert.That(fooFound, Is.False); await Page.EvaluateAsync("window.__FOO = 1"); await waitForFunction; - Assert.True(fooFound); + Assert.That(fooFound, Is.True); } [PlaywrightTest("page-wait-for-function.spec.ts", "should survive navigations")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSurviveNavigations() { var watchdog = Page.WaitForFunctionAsync("() => window.__done"); @@ -253,18 +245,18 @@ public async Task ShouldSurviveNavigations() } [PlaywrightTest("page-wait-for-function.spec.ts", "should work with multiline body")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithMultilineBody() { var result = await Page.WaitForFunctionAsync(@" (() => true)() "); - Assert.True(await result.JsonValueAsync()); + Assert.That(await result.JsonValueAsync(), Is.True); } [PlaywrightTest("page-wait-for-function.spec.ts", "should wait for predicate with arguments")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public Task ShouldWaitForPredicateWithArguments() => Page.WaitForFunctionAsync(@"({arg1, arg2}) => arg1 + arg2 === 3", new { arg1 = 1, arg2 = 2 }); } diff --git a/src/Playwright.Tests/PageWaitForLoadStateTests.cs b/src/Playwright.Tests/PageWaitForLoadStateTests.cs index 5a55d36592..a274faaa69 100644 --- a/src/Playwright.Tests/PageWaitForLoadStateTests.cs +++ b/src/Playwright.Tests/PageWaitForLoadStateTests.cs @@ -3,25 +3,17 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///page-wait-for-load-state.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageWaitForLoadStateTests : PlaywrightSharpPageBaseTest - { - /// - public PageWaitForLoadStateTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-wait-for-load-state.ts", "should pick up ongoing navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-wait-for-load-state.ts", "should pick up ongoing navigation")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPickUpOngoingNavigation() { var responseTask = new TaskCompletionSource(); @@ -45,17 +37,17 @@ public async Task ShouldPickUpOngoingNavigation() } [PlaywrightTest("page-wait-for-load-state.ts", "should respect timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectTimeout() { Server.SetRoute("/one-style.css", _ => Task.Delay(Timeout.Infinite)); await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html", WaitUntilState.DOMContentLoaded); - var exception = await Assert.ThrowsAnyAsync(() => Page.WaitForLoadStateAsync(LoadState.Load, 1)); - Assert.Contains("Timeout 1ms exceeded", exception.Message); + var exception = Assert.CatchAsync(() => Page.WaitForLoadStateAsync(LoadState.Load, 1)); + Assert.That(exception.Message, Does.Contain("Timeout 1ms exceeded")); } [PlaywrightTest("page-wait-for-load-state.ts", "should resolve immediately if loaded")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldResolveImmediatelyIfLoaded() { await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); @@ -63,13 +55,13 @@ public async Task ShouldResolveImmediatelyIfLoaded() } [PlaywrightTest("page-wait-for-load-state.ts", "should throw for bad state")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldTthrowForBadState() { } [PlaywrightTest("page-wait-for-load-state.ts", "should resolve immediately if load state matches")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldResolveImmediatelyIfLoadStateMatches() { var responseTask = new TaskCompletionSource(); @@ -102,22 +94,22 @@ await Page.EvaluateAsync(@"async () => { await new Promise(f => setTimeout(f, 100)); }"); var pages = Context.Pages; - Assert.Equal(2, pages.Count); + Assert.That(pages.Count, Is.EqualTo(2)); // order is not guaranteed var mainPage = pages.FirstOrDefault(p => ReferenceEquals(Page, p)); var connectedPage = pages.Single(p => !ReferenceEquals(Page, p)); - Assert.NotNull(mainPage); - Assert.Equal(TestConstants.EmptyPage, mainPage.Url); + Assert.That(mainPage, Is.Not.Null); + Assert.That(mainPage.Url, Is.EqualTo(TestConstants.EmptyPage)); - Assert.Equal(TestConstants.EmptyPage, connectedPage.Url); + Assert.That(connectedPage.Url, Is.EqualTo(TestConstants.EmptyPage)); await connectedPage.WaitForLoadStateAsync(); - Assert.Equal(TestConstants.EmptyPage, connectedPage.Url); + Assert.That(connectedPage.Url, Is.EqualTo(TestConstants.EmptyPage)); } [PlaywrightTest("page-wait-for-load-state.spec.ts", "should work for frame")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForFrame() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); @@ -137,7 +129,7 @@ await Page.RouteAsync(TestConstants.ServerUrl + "/one-style.css", async (route) await routeReachedTask.Task; var loadTask = frame.WaitForLoadStateAsync(); await Page.EvaluateAsync("1"); - Assert.False(loadTask.IsCompleted); + Assert.That(loadTask.IsCompleted, Is.False); requestTask.TrySetResult(true); await loadTask; } diff --git a/src/Playwright.Tests/PageWaitForNavigationTests.cs b/src/Playwright.Tests/PageWaitForNavigationTests.cs index 13514ae544..a62886ef21 100644 --- a/src/Playwright.Tests/PageWaitForNavigationTests.cs +++ b/src/Playwright.Tests/PageWaitForNavigationTests.cs @@ -5,23 +5,15 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageWaitForNavigationTests : PlaywrightSharpPageBaseTest - { - /// - public PageWaitForNavigationTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -31,27 +23,27 @@ await TaskUtils.WhenAll( Page.EvaluateAsync("url => window.location.href = url", TestConstants.ServerUrl + "/grid.html") ); var response = await waitForNavigationResult; - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("grid.html", response.Url); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(response.Url, Does.Contain("grid.html")); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should respect timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectTimeout() { var waitForNavigationResult = Page.WaitForNavigationAsync("**/frame.html", timeout: 5000); await Page.GoToAsync(TestConstants.EmptyPage); - var exception = await Assert.ThrowsAnyAsync(() => waitForNavigationResult); + var exception = Assert.CatchAsync(() => waitForNavigationResult); - Assert.Contains("Timeout 5000ms exceeded", exception.Message); - Assert.Contains("waiting for navigation to \"**/frame.html\" until \"Load\"", exception.Message); - Assert.Contains($"navigated to \"{TestConstants.EmptyPage}\"", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 5000ms exceeded")); + Assert.That(exception.Message, Does.Contain("waiting for navigation to \"**/frame.html\" until \"Load\"")); + Assert.That(exception.Message, Does.Contain($"navigated to \"{TestConstants.EmptyPage}\"")); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with both domcontentloaded and load")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithBothDomcontentloadedAndLoad() { var responseCompleted = new TaskCompletionSource(); @@ -68,14 +60,14 @@ public async Task ShouldWorkWithBothDomcontentloadedAndLoad() await waitForRequestTask.WithTimeout(TestConstants.DefaultTaskTimeout); await domContentLoadedTask.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.False(bothFired); + Assert.That(bothFired, Is.False); responseCompleted.SetResult(true); await bothFiredTask.WithTimeout(TestConstants.DefaultTaskTimeout); await navigationTask.WithTimeout(TestConstants.DefaultTaskTimeout); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with clicking on anchor links")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithClickingOnAnchorLinks() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -85,19 +77,19 @@ await TaskUtils.WhenAll( navigationTask, Page.ClickAsync("a") ); - Assert.Null(await navigationTask); - Assert.Equal(TestConstants.EmptyPage + "#foobar", Page.Url); + Assert.That(await navigationTask, Is.Null); + Assert.That(Page.Url, Is.EqualTo(TestConstants.EmptyPage + "#foobar")); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with clicking on links which do not commit navigation")] - // [Fact(Timeout = TestConstants.DefaultTestTimeout)] - [Fact(Skip = "Fix me #1058")] + // [Test, Timeout(TestConstants.DefaultTestTimeout)] + [Test, Ignore("Fix me #1058")] public async Task ShouldWorkWithClickingOnLinksWhichDoNotCommitNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); await Page.SetContentAsync($"foobar"); var navigationTask = Page.WaitForNavigationAsync(); - var exception = await Assert.ThrowsAnyAsync(() => TaskUtils.WhenAll( + var exception = Assert.CatchAsync(() => TaskUtils.WhenAll( navigationTask, Page.ClickAsync("a") )); @@ -105,7 +97,7 @@ public async Task ShouldWorkWithClickingOnLinksWhichDoNotCommitNavigation() } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with history.pushState()")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithHistoryPushState() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -120,12 +112,12 @@ await TaskUtils.WhenAll( navigationTask, Page.ClickAsync("a") ); - Assert.Null(await navigationTask); - Assert.Equal(TestConstants.ServerUrl + "/wow.html", Page.Url); + Assert.That(await navigationTask, Is.Null); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/wow.html")); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with history.replaceState()")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithHistoryReplaceState() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -140,12 +132,12 @@ await TaskUtils.WhenAll( navigationTask, Page.ClickAsync("a") ); - Assert.Null(await navigationTask); - Assert.Equal(TestConstants.ServerUrl + "/replaced.html", Page.Url); + Assert.That(await navigationTask, Is.Null); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/replaced.html")); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with DOM history.back()/history.forward()")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithDOMHistoryBackAndHistoryForward() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -159,25 +151,25 @@ await Page.SetContentAsync(@" history.pushState({}, '', '/second.html'); "); - Assert.Equal(TestConstants.ServerUrl + "/second.html", Page.Url); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/second.html")); var navigationTask = Page.WaitForNavigationAsync(); await TaskUtils.WhenAll( navigationTask, Page.ClickAsync("a#back") ); - Assert.Null(await navigationTask); - Assert.Equal(TestConstants.ServerUrl + "/first.html", Page.Url); + Assert.That(await navigationTask, Is.Null); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/first.html")); navigationTask = Page.WaitForNavigationAsync(); await TaskUtils.WhenAll( navigationTask, Page.ClickAsync("a#forward") ); - Assert.Null(await navigationTask); - Assert.Equal(TestConstants.ServerUrl + "/second.html", Page.Url); + Assert.That(await navigationTask, Is.Null); + Assert.That(Page.Url, Is.EqualTo(TestConstants.ServerUrl + "/second.html")); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work when subframe issues window.stop()")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenSubframeIssuesWindowStop() { //This test is slightly different from the one in PW because of .NET Threads (or thanks to .NET Threads) @@ -223,7 +215,7 @@ await TaskUtils.WhenAll( } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with url match")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithUrlMatch() { IResponse response1 = null; @@ -238,57 +230,57 @@ public async Task ShouldWorkWithUrlMatch() return query.ContainsKey("foo") && query["foo"] == "bar"; }).ContinueWith(t => response3 = t.Result); - Assert.Null(response1); - Assert.Null(response2); - Assert.Null(response3); + Assert.That(response1, Is.Null); + Assert.That(response2, Is.Null); + Assert.That(response3, Is.Null); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Null(response1); - Assert.Null(response2); - Assert.Null(response3); + Assert.That(response1, Is.Null); + Assert.That(response2, Is.Null); + Assert.That(response3, Is.Null); await Page.GoToAsync(TestConstants.ServerUrl + "/frame.html"); - Assert.Null(response1); + Assert.That(response1, Is.Null); await response2Task; - Assert.NotNull(response2); - Assert.Null(response3); + Assert.That(response2, Is.Not.Null); + Assert.That(response3, Is.Null); await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); await response1Task; - Assert.NotNull(response1); - Assert.NotNull(response2); - Assert.Null(response3); + Assert.That(response1, Is.Not.Null); + Assert.That(response2, Is.Not.Null); + Assert.That(response3, Is.Null); await Page.GoToAsync(TestConstants.ServerUrl + "/frame.html?foo=bar"); await response3Task; - Assert.NotNull(response1); - Assert.NotNull(response2); - Assert.NotNull(response3); + Assert.That(response1, Is.Not.Null); + Assert.That(response2, Is.Not.Null); + Assert.That(response3, Is.Not.Null); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal(TestConstants.ServerUrl + "/one-style.html", response1.Url); - Assert.Equal(TestConstants.ServerUrl + "/frame.html", response2.Url); - Assert.Equal(TestConstants.ServerUrl + "/frame.html?foo=bar", response3.Url); + Assert.That(response1.Url, Is.EqualTo(TestConstants.ServerUrl + "/one-style.html")); + Assert.That(response2.Url, Is.EqualTo(TestConstants.ServerUrl + "/frame.html")); + Assert.That(response3.Url, Is.EqualTo(TestConstants.ServerUrl + "/frame.html?foo=bar")); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with url match for same document navigations")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithUrlMatchForSameDocumentNavigations() { await Page.GoToAsync(TestConstants.EmptyPage); bool resolved = false; var waitTask = Page.WaitForNavigationAsync(new Regex("third\\.html")).ContinueWith(_ => resolved = true); - Assert.False(resolved); + Assert.That(resolved, Is.False); await Page.EvaluateAsync("() => history.pushState({}, '', '/first.html')"); - Assert.False(resolved); + Assert.That(resolved, Is.False); await Page.EvaluateAsync("() => history.pushState({}, '', '/second.html')"); - Assert.False(resolved); + Assert.That(resolved, Is.False); await Page.EvaluateAsync("() => history.pushState({}, '', '/third.html')"); await waitTask; - Assert.True(resolved); + Assert.That(resolved, Is.True); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work for cross-process navigations")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForCrossProcessNavigations() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -297,14 +289,14 @@ public async Task ShouldWorkForCrossProcessNavigations() string url = TestConstants.CrossProcessHttpPrefix + "/empty.html"; var gotoTask = Page.GoToAsync(url); var response = await waitTask; - Assert.Equal(url, response.Url); - Assert.Equal(url, Page.Url); - Assert.Equal(url, await Page.EvaluateAsync("document.location.href")); + Assert.That(response.Url, Is.EqualTo(url)); + Assert.That(Page.Url, Is.EqualTo(url)); + Assert.That(await Page.EvaluateAsync("document.location.href"), Is.EqualTo(url)); await gotoTask; } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work on frame")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkOnFrame() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); @@ -313,33 +305,33 @@ public async Task ShouldWorkOnFrame() frame.WaitForNavigationAsync(), frame.EvaluateAsync("url => window.location.href = url", TestConstants.ServerUrl + "/grid.html") ); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("grid.html", response.Url); - Assert.Same(frame, response.Frame); - Assert.Contains("/frames/one-frame.html", Page.Url); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(response.Url, Does.Contain("grid.html")); + Assert.That(response.Frame, Is.SameAs(frame)); + Assert.That(Page.Url, Does.Contain("/frames/one-frame.html")); } [PlaywrightTest("page-wait-for-navigation.spec.ts", "should fail when frame detaches")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFailWhenFrameDetaches() { await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html"); var frame = Page.Frames.ElementAt(1); Server.SetRoute("/empty.html", _ => Task.Delay(6000)); - var exceptionTask = Assert.ThrowsAnyAsync(() => frame.WaitForNavigationAsync()); + var navigationTask = frame.WaitForNavigationAsync(); try { await TaskUtils.WhenAll( - exceptionTask, + navigationTask, frame.EvaluateAsync("window.location.href = '/empty.html'"), Page.EvaluateAsync("setTimeout(() => document.querySelector(\"iframe\").remove())")); } - catch - { } - - Assert.Contains("waiting for navigation until \"Load\"", exceptionTask.Result.Message); - Assert.Contains("frame was detached", exceptionTask.Result.Message); + catch (PlaywrightSharpException ex) + { + Assert.That(ex.Message, Does.Contain("waiting for navigation until \"Load\"")); + Assert.That(ex.Message, Does.Contain("frame was detached")); + } } } } diff --git a/src/Playwright.Tests/PageWaitForRequestTests.cs b/src/Playwright.Tests/PageWaitForRequestTests.cs index 52a0dc8e22..5f52cbf24c 100644 --- a/src/Playwright.Tests/PageWaitForRequestTests.cs +++ b/src/Playwright.Tests/PageWaitForRequestTests.cs @@ -1,23 +1,15 @@ using System; using System.Text.RegularExpressions; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageWaitForRequestTests : PlaywrightSharpPageBaseTest - { - /// - public PageWaitForRequestTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-wait-for-request.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-wait-for-request.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -30,11 +22,11 @@ public async Task ShouldWork() fetch('/digits/3.png'); }") ); - Assert.Equal(TestConstants.ServerUrl + "/digits/2.png", request.Url); + Assert.That(request.Url, Is.EqualTo(TestConstants.ServerUrl + "/digits/2.png")); } [PlaywrightTest("page-wait-for-request.spec.ts", "should work with predicate")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithPredicate() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -47,28 +39,28 @@ public async Task ShouldWorkWithPredicate() fetch('/digits/3.png'); }") ); - Assert.Equal(TestConstants.ServerUrl + "/digits/2.png", requestEvent.Url); + Assert.That(requestEvent.Url, Is.EqualTo(TestConstants.ServerUrl + "/digits/2.png")); } [PlaywrightTest("page-wait-for-request.spec.ts", "should respect timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectTimeout() { - var exception = await Assert.ThrowsAsync( + var exception = Assert.ThrowsAsync( () => Page.WaitForEventAsync(PageEvent.Request, _ => false, 1)); } [PlaywrightTest("page-wait-for-request.spec.ts", "should respect default timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectDefaultTimeout() { Page.DefaultTimeout = 1; - var exception = await Assert.ThrowsAsync( + var exception = Assert.ThrowsAsync( () => Page.WaitForEventAsync(PageEvent.Request, _ => false)); } [PlaywrightTest("page-wait-for-request.spec.ts", "should work with no timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNoTimeout() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -81,11 +73,11 @@ public async Task ShouldWorkWithNoTimeout() fetch('/digits/3.png'); }, 50)") ); - Assert.Equal(TestConstants.ServerUrl + "/digits/2.png", request.Url); + Assert.That(request.Url, Is.EqualTo(TestConstants.ServerUrl + "/digits/2.png")); } [PlaywrightTest("page-wait-for-request.spec.ts", "should work with url match")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithUrlMatch() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -96,11 +88,11 @@ public async Task ShouldWorkWithUrlMatch() fetch('/digits/1.png'); }") ); - Assert.Equal(TestConstants.ServerUrl + "/digits/1.png", request.Url); + Assert.That(request.Url, Is.EqualTo(TestConstants.ServerUrl + "/digits/1.png")); } [PlaywrightTest("page-wait-for-request.spec.ts", "should work with url match regular expression from a different context")] - [Fact(Skip = "We dont't need to test this")] + [Test, Ignore("We dont't need to test this")] public void ShouldWorkWithUrlMatchRegularExpressionFromADifferentContext() { } diff --git a/src/Playwright.Tests/PageWaitForResponseTests.cs b/src/Playwright.Tests/PageWaitForResponseTests.cs index 7a1b281872..f3bd49ea6c 100644 --- a/src/Playwright.Tests/PageWaitForResponseTests.cs +++ b/src/Playwright.Tests/PageWaitForResponseTests.cs @@ -1,22 +1,14 @@ using System; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageWaitForResponseTests : PlaywrightSharpPageBaseTest - { - /// - public PageWaitForResponseTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-wait-for-response.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("page-wait-for-response.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -29,28 +21,28 @@ public async Task ShouldWork() fetch('/digits/3.png'); }") ); - Assert.Equal(TestConstants.ServerUrl + "/digits/2.png", response.Url); + Assert.That(response.Url, Is.EqualTo(TestConstants.ServerUrl + "/digits/2.png")); } [PlaywrightTest("page-wait-for-response.spec.ts", "should respect timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectTimeout() { - var exception = await Assert.ThrowsAsync( + var exception = Assert.ThrowsAsync( () => Page.WaitForEventAsync(PageEvent.Response, _ => false, 1)); } [PlaywrightTest("page-wait-for-response.spec.ts", "should respect default timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectDefaultTimeout() { Page.DefaultTimeout = 1; - var exception = await Assert.ThrowsAsync( + var exception = Assert.ThrowsAsync( () => Page.WaitForEventAsync(PageEvent.Response, _ => false)); } [PlaywrightTest("page-wait-for-response.spec.ts", "should work with predicate")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithPredicate() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -63,11 +55,11 @@ public async Task ShouldWorkWithPredicate() fetch('/digits/3.png'); }") ); - Assert.Equal(TestConstants.ServerUrl + "/digits/2.png", responseEvent.Url); + Assert.That(responseEvent.Url, Is.EqualTo(TestConstants.ServerUrl + "/digits/2.png")); } [PlaywrightTest("page-wait-for-response.spec.ts", "should work with no timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithNoTimeout() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -80,7 +72,7 @@ public async Task ShouldWorkWithNoTimeout() fetch('/digits/3.png'); }, 50)") ); - Assert.Equal(TestConstants.ServerUrl + "/digits/2.png", response.Url); + Assert.That(response.Url, Is.EqualTo(TestConstants.ServerUrl + "/digits/2.png")); } } } diff --git a/src/Playwright.Tests/PageWaitForSelector1Tests.cs b/src/Playwright.Tests/PageWaitForSelector1Tests.cs index a240e4e9ff..10b49bd622 100644 --- a/src/Playwright.Tests/PageWaitForSelector1Tests.cs +++ b/src/Playwright.Tests/PageWaitForSelector1Tests.cs @@ -1,37 +1,28 @@ using System; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageWaitForSelector1Tests : PlaywrightSharpPageBaseTest { - private const string AddElement = "tag => document.body.appendChild(document.createElement(tag))"; - - /// - public PageWaitForSelector1Tests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should throw on waitFor")] - [Fact(Skip = "We don't need to test this")] + private const string AddElement = "tag => document.body.appendChild(document.createElement(tag))"; [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should throw on waitFor")] + [Test, Ignore("We don't need to test this")] public void ShouldThrowOnWaitFor() { } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should tolerate waitFor=visible")] - [Fact(Skip = "We don't need to test this")] + [Test, Ignore("We don't need to test this")] public void ShouldTolerateWaitForVisible() { } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should immediately resolve promise if node exists")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldImmediatelyResolveTaskIfNodeExists() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -42,17 +33,17 @@ public async Task ShouldImmediatelyResolveTaskIfNodeExists() } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "elementHandle.waitForSelector should immediately resolve if node exists")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ElementHandleWaitForSelectorShouldImmediatelyResolveIfNodeExists() { await Page.SetContentAsync("extra
target
"); var div = await Page.QuerySelectorAsync("div"); var span = await div.WaitForSelectorAsync("span", WaitForSelectorState.Attached); - Assert.Equal("target", await span.EvaluateAsync("e => e.textContent")); + Assert.That(await span.EvaluateAsync("e => e.textContent"), Is.EqualTo("target")); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "elementHandle.waitForSelector should wait")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ElementHandleWaitForSelectorShouldWait() { await Page.SetContentAsync("
"); @@ -60,21 +51,21 @@ public async Task ElementHandleWaitForSelectorShouldWait() var task = div.WaitForSelectorAsync("span", WaitForSelectorState.Attached); await div.EvaluateAsync("div => div.innerHTML = 'target'"); var span = await task; - Assert.Equal("target", await span.EvaluateAsync("e => e.textContent")); + Assert.That(await span.EvaluateAsync("e => e.textContent"), Is.EqualTo("target")); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "elementHandle.waitForSelector should timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ElementHandleWaitForSelectorShouldTimeout() { await Page.SetContentAsync("
"); var div = await Page.QuerySelectorAsync("div"); - var exception = await Assert.ThrowsAnyAsync(() => div.WaitForSelectorAsync("span", WaitForSelectorState.Attached, 100)); - Assert.Contains("Timeout 100ms exceeded.", exception.Message); + var exception = Assert.CatchAsync(() => div.WaitForSelectorAsync("span", WaitForSelectorState.Attached, 100)); + Assert.That(exception.Message, Does.Contain("Timeout 100ms exceeded.")); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "elementHandle.waitForSelector should throw on navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ElementHandleWaitForSelectorShouldThrowOnNavigation() { await Page.SetContentAsync("
"); @@ -87,12 +78,12 @@ public async Task ElementHandleWaitForSelectorShouldThrowOnNavigation() } await Page.GoToAsync(TestConstants.EmptyPage); - var exception = await Assert.ThrowsAnyAsync(() => task); - Assert.Contains("Execution context was destroyed, most likely because of a navigation", exception.Message); + var exception = Assert.CatchAsync(() => task); + Assert.That(exception.Message, Does.Contain("Execution context was destroyed, most likely because of a navigation")); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should work with removed MutationObserver")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithRemovedMutationObserver() { await Page.EvaluateAsync("delete window.MutationObserver"); @@ -102,11 +93,11 @@ await TaskUtils.WhenAll( waitForSelector, Page.SetContentAsync("
anything
")); - Assert.Equal("anything", await Page.EvaluateAsync("x => x.textContent", await waitForSelector)); + Assert.That(await Page.EvaluateAsync("x => x.textContent", await waitForSelector), Is.EqualTo("anything")); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should resolve promise when node is added")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldResolveTaskWhenNodeIsAdded() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -117,11 +108,11 @@ public async Task ShouldResolveTaskWhenNodeIsAdded() var eHandle = await watchdog; var property = await eHandle.GetPropertyAsync("tagName"); string tagName = await property.JsonValueAsync(); - Assert.Equal("DIV", tagName); + Assert.That(tagName, Is.EqualTo("DIV")); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should report logs while waiting for visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportLogsWhileWaitingForVisible() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -151,17 +142,17 @@ await frame.EvaluateAsync(@"() => { }"); await GiveItTimeToLogAsync(frame); - var exception = await Assert.ThrowsAnyAsync(() => watchdog); + var exception = Assert.CatchAsync(() => watchdog); - Assert.Contains("Timeout 5000ms", exception.Message); - Assert.Contains("waiting for selector \"div\" to be visible", exception.Message); - Assert.Contains("selector resolved to hidden
abcdefghijklmnopqrstuvwyxzabcdefghijklmnopqrstuvw…
", exception.Message); - Assert.Contains("selector did not resolve to any element", exception.Message); - Assert.Contains("selector resolved to hidden
", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 5000ms")); + Assert.That(exception.Message, Does.Contain("waiting for selector \"div\" to be visible")); + Assert.That(exception.Message, Does.Contain("selector resolved to hidden
abcdefghijklmnopqrstuvwyxzabcdefghijklmnopqrstuvw…
")); + Assert.That(exception.Message, Does.Contain("selector did not resolve to any element")); + Assert.That(exception.Message, Does.Contain("selector resolved to hidden
")); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should report logs while waiting for hidden")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportLogsWhileWaitingForHidden() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -187,16 +178,16 @@ await frame.EvaluateAsync(@"() => { }"); await GiveItTimeToLogAsync(frame); - var exception = await Assert.ThrowsAnyAsync(() => watchdog); + var exception = Assert.CatchAsync(() => watchdog); - Assert.Contains("Timeout 5000ms", exception.Message); - Assert.Contains("waiting for selector \"div\" to be hidden", exception.Message); - Assert.Contains("selector resolved to visible
hello
", exception.Message); - Assert.Contains("selector resolved to visible
hello
", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 5000ms")); + Assert.That(exception.Message, Does.Contain("waiting for selector \"div\" to be hidden")); + Assert.That(exception.Message, Does.Contain("selector resolved to visible
hello
")); + Assert.That(exception.Message, Does.Contain("selector resolved to visible
hello
")); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should resolve promise when node is added in shadow dom")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldResolvePromiseWhenNodeIsAddedInShadowDom() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -218,11 +209,11 @@ await Page.EvaluateAsync(@"() => { var handle = await watchdog; - Assert.Equal("Hello from shadow", await handle.EvaluateAsync("e => e.textContent")); + Assert.That(await handle.EvaluateAsync("e => e.textContent"), Is.EqualTo("Hello from shadow")); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should work when node is added through innerHTML")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWhenNodeIsAddedThroughInnerHTML() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -233,7 +224,7 @@ public async Task ShouldWorkWhenNodeIsAddedThroughInnerHTML() } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "Page.$ waitFor is shortcut for main frame")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageWaitForSelectorAsyncIsShortcutForMainFrame() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -243,11 +234,11 @@ public async Task PageWaitForSelectorAsyncIsShortcutForMainFrame() await otherFrame.EvaluateAsync(AddElement, "div"); await Page.EvaluateAsync(AddElement, "div"); var eHandle = await watchdog; - Assert.Equal(Page.MainFrame, await eHandle.OwnerFrameAsync()); + Assert.That(await eHandle.OwnerFrameAsync(), Is.EqualTo(Page.MainFrame)); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should run in specified frame")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRunInSpecifiedFrame() { await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); @@ -258,11 +249,11 @@ public async Task ShouldRunInSpecifiedFrame() await frame1.EvaluateAsync(AddElement, "div"); await frame2.EvaluateAsync(AddElement, "div"); var eHandle = await waitForSelectorPromise; - Assert.Equal(frame2, await eHandle.OwnerFrameAsync()); + Assert.That(await eHandle.OwnerFrameAsync(), Is.EqualTo(frame2)); } [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should throw when frame is detached")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWhenFrameIsDetached() { await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); @@ -270,8 +261,8 @@ public async Task ShouldThrowWhenFrameIsDetached() var waitTask = frame.WaitForSelectorAsync(".box").ContinueWith(task => task.Exception?.InnerException); await FrameUtils.DetachFrameAsync(Page, "frame1"); var waitException = await waitTask; - Assert.NotNull(waitException); - Assert.Contains("waitForFunction failed: frame got detached.", waitException.Message); + Assert.That(waitException, Is.Not.Null); + Assert.That(waitException.Message, Does.Contain("waitForFunction failed: frame got detached.")); } private async Task GiveItTimeToLogAsync(IFrame frame) diff --git a/src/Playwright.Tests/PageWaitForSelector2Tests.cs b/src/Playwright.Tests/PageWaitForSelector2Tests.cs index 3240da51c0..8c2cdec662 100644 --- a/src/Playwright.Tests/PageWaitForSelector2Tests.cs +++ b/src/Playwright.Tests/PageWaitForSelector2Tests.cs @@ -1,88 +1,78 @@ using System; using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PageWaitForSelector2Tests : PlaywrightSharpPageBaseTest { - private const string AddElement = "tag => document.body.appendChild(document.createElement(tag))"; - - /// - public PageWaitForSelector2Tests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should survive cross-process navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + private const string AddElement = "tag => document.body.appendChild(document.createElement(tag))"; [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should survive cross-process navigation")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSurviveCrossProcessNavigation() { bool boxFound = false; var waitForSelector = Page.WaitForSelectorAsync(".box").ContinueWith(_ => boxFound = true); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.False(boxFound); + Assert.That(boxFound, Is.False); await Page.ReloadAsync(); - Assert.False(boxFound); + Assert.That(boxFound, Is.False); await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/grid.html"); await waitForSelector; - Assert.True(boxFound); + Assert.That(boxFound, Is.True); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should wait for visible")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForVisible() { bool divFound = false; var waitForSelector = Page.WaitForSelectorAsync("div", WaitForSelectorState.Visible) .ContinueWith(_ => divFound = true); await Page.SetContentAsync("
1
"); - Assert.False(divFound); + Assert.That(divFound, Is.False); await Page.EvaluateAsync("document.querySelector('div').style.removeProperty('display')"); - Assert.False(divFound); + Assert.That(divFound, Is.False); await Page.EvaluateAsync("document.querySelector('div').style.removeProperty('visibility')"); - Assert.True(await waitForSelector); - Assert.True(divFound); + Assert.That(await waitForSelector, Is.True); + Assert.That(divFound, Is.True); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should not consider visible when zero-sized")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotConsiderVisibleWhenZeroSized() { await Page.SetContentAsync("
1
"); - var exception = await Assert.ThrowsAnyAsync(() => Page.WaitForSelectorAsync("div", timeout: 1000)); - Assert.Contains("Timeout 1000ms", exception.Message); + var exception = Assert.CatchAsync(() => Page.WaitForSelectorAsync("div", timeout: 1000)); + Assert.That(exception.Message, Does.Contain("Timeout 1000ms")); await Page.EvaluateAsync("() => document.querySelector('div').style.width = '10px'"); - exception = await Assert.ThrowsAnyAsync(() => Page.WaitForSelectorAsync("div", timeout: 1000)); - Assert.Contains("Timeout 1000ms", exception.Message); + exception = Assert.CatchAsync(() => Page.WaitForSelectorAsync("div", timeout: 1000)); + Assert.That(exception.Message, Does.Contain("Timeout 1000ms")); await Page.EvaluateAsync("() => document.querySelector('div').style.height = '10px'"); - Assert.NotNull(await Page.WaitForSelectorAsync("div", timeout: 1000)); + Assert.That(await Page.WaitForSelectorAsync("div", timeout: 1000), Is.Not.Null); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should wait for visible recursively")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForVisibleRecursively() { bool divVisible = false; var waitForSelector = Page.WaitForSelectorAsync("div#inner", WaitForSelectorState.Visible).ContinueWith(_ => divVisible = true); await Page.SetContentAsync("
hi
"); - Assert.False(divVisible); + Assert.That(divVisible, Is.False); await Page.EvaluateAsync("document.querySelector('div').style.removeProperty('display')"); - Assert.False(divVisible); + Assert.That(divVisible, Is.False); await Page.EvaluateAsync("document.querySelector('div').style.removeProperty('visibility')"); - Assert.True(await waitForSelector); - Assert.True(divVisible); + Assert.That(await waitForSelector, Is.True); + Assert.That(divVisible, Is.True); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "hidden should wait for hidden")] [PlaywrightTest("page-wait-for-selector-2.spec.ts", "hidden should wait for display: none")] - [Theory] - [InlineData("visibility", "hidden")] - [InlineData("display", "none")] + [TestCase("visibility", "hidden")] + [TestCase("display", "none")] public async Task HiddenShouldWaitForVisibility(string propertyName, string propertyValue) { bool divHidden = false; @@ -90,14 +80,14 @@ public async Task HiddenShouldWaitForVisibility(string propertyName, string prop var waitForSelector = Page.WaitForSelectorAsync("div", WaitForSelectorState.Hidden) .ContinueWith(_ => divHidden = true); await Page.WaitForSelectorAsync("div"); // do a round trip - Assert.False(divHidden); + Assert.That(divHidden, Is.False); await Page.EvaluateAsync($"document.querySelector('div').style.setProperty('{propertyName}', '{propertyValue}')"); - Assert.True(await waitForSelector); - Assert.True(divHidden); + Assert.That(await waitForSelector, Is.True); + Assert.That(divHidden, Is.True); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "hidden should wait for removal")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task HiddenShouldWaitForRemoval() { await Page.SetContentAsync("
content
"); @@ -105,91 +95,91 @@ public async Task HiddenShouldWaitForRemoval() var waitForSelector = Page.WaitForSelectorAsync("div", WaitForSelectorState.Hidden) .ContinueWith(_ => divRemoved = true); await Page.WaitForSelectorAsync("div"); // do a round trip - Assert.False(divRemoved); + Assert.That(divRemoved, Is.False); await Page.EvaluateAsync("document.querySelector('div').remove()"); - Assert.True(await waitForSelector); - Assert.True(divRemoved); + Assert.That(await waitForSelector, Is.True); + Assert.That(divRemoved, Is.True); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should return null if waiting to hide non-existing element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNullIfWaitingToHideNonExistingElement() { var handle = await Page.WaitForSelectorAsync("non-existing", WaitForSelectorState.Hidden); - Assert.Null(handle); + Assert.That(handle, Is.Null); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should respect timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectTimeout() { - var exception = await Assert.ThrowsAsync(async () + var exception = Assert.ThrowsAsync(async () => await Page.WaitForSelectorAsync("div", WaitForSelectorState.Attached, 3000)); - Assert.Contains("Timeout 3000ms exceeded", exception.Message); - Assert.Contains("waiting for selector \"div\"", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 3000ms exceeded")); + Assert.That(exception.Message, Does.Contain("waiting for selector \"div\"")); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should have an error message specifically for awaiting an element to be hidden")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveAnErrorMessageSpecificallyForAwaitingAnElementToBeHidden() { await Page.SetContentAsync("
content
"); - var exception = await Assert.ThrowsAsync(async () + var exception = Assert.ThrowsAsync(async () => await Page.WaitForSelectorAsync("div", WaitForSelectorState.Hidden, 1000)); - Assert.Contains("Timeout 1000ms exceeded", exception.Message); - Assert.Contains("waiting for selector \"div\" to be hidden", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 1000ms exceeded")); + Assert.That(exception.Message, Does.Contain("waiting for selector \"div\" to be hidden")); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should respond to node attribute mutation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespondToNodeAttributeMutation() { bool divFound = false; var waitForSelector = Page.WaitForSelectorAsync(".zombo", WaitForSelectorState.Attached).ContinueWith(_ => divFound = true); await Page.SetContentAsync("
"); - Assert.False(divFound); + Assert.That(divFound, Is.False); await Page.EvaluateAsync("document.querySelector('div').className = 'zombo'"); - Assert.True(await waitForSelector); + Assert.That(await waitForSelector, Is.True); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should return the element handle")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnTheElementHandle() { var waitForSelector = Page.WaitForSelectorAsync(".zombo"); await Page.SetContentAsync("
anything
"); - Assert.Equal("anything", await Page.EvaluateAsync("x => x.textContent", await waitForSelector)); + Assert.That(await Page.EvaluateAsync("x => x.textContent", await waitForSelector), Is.EqualTo("anything")); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should have correct stack trace for timeout")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveCorrectStackTraceForTimeout() { - var exception = await Assert.ThrowsAsync(async () + var exception = Assert.ThrowsAsync(async () => await Page.WaitForSelectorAsync(".zombo", timeout: 10)); - Assert.Contains("WaitForSelector2Tests", exception.StackTrace); + Assert.That(exception.StackTrace, Does.Contain("WaitForSelector2Tests")); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should throw for unknown state option")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldThrowForUnknownStateOption() { } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should throw for visibility option")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldThrowForVisibilityOption() { } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should throw for true state option")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldThrowForTrueStateOption() { } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should throw for false state option")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldThrowForFalseStateOption() { } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should support >> selector syntax")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportSelectorSyntax() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -201,52 +191,52 @@ public async Task ShouldSupportSelectorSyntax() var eHandle = await watchdog; var tagProperty = await eHandle.GetPropertyAsync("tagName"); string tagName = await tagProperty.JsonValueAsync(); - Assert.Equal("SPAN", tagName); + Assert.That(tagName, Is.EqualTo("SPAN")); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should wait for detached if already detached")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForDetachedIfAlreadyDetached() { await Page.SetContentAsync("
43543
"); - Assert.Null(await Page.WaitForSelectorAsync("css=div", WaitForSelectorState.Detached)); + Assert.That(await Page.WaitForSelectorAsync("css=div", WaitForSelectorState.Detached), Is.Null); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should wait for detached")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForDetached() { await Page.SetContentAsync("
43543
"); var waitForTask = Page.WaitForSelectorAsync("css=div", WaitForSelectorState.Detached); - Assert.False(waitForTask.IsCompleted); + Assert.That(waitForTask.IsCompleted, Is.False); await Page.WaitForSelectorAsync("css=section"); - Assert.False(waitForTask.IsCompleted); + Assert.That(waitForTask.IsCompleted, Is.False); await Page.EvalOnSelectorAsync("div", "div => div.remove()"); await waitForTask; } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should support some fancy xpath")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportSomeFancyXpath() { await Page.SetContentAsync("

red herring

hello world

"); var waitForXPath = Page.WaitForSelectorAsync("//p[normalize-space(.)=\"hello world\"]"); - Assert.Equal("hello world ", await Page.EvaluateAsync("x => x.textContent", await waitForXPath)); + Assert.That(await Page.EvaluateAsync("x => x.textContent", await waitForXPath), Is.EqualTo("hello world ")); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should respect timeout xpath")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectTimeoutXpath() { - var exception = await Assert.ThrowsAsync(() + var exception = Assert.ThrowsAsync(() => Page.WaitForSelectorAsync("//div", WaitForSelectorState.Attached, timeout: 3000)); - Assert.Contains("Timeout 3000ms exceeded", exception.Message); - Assert.Contains("waiting for selector \"//div\"", exception.Message); + Assert.That(exception.Message, Does.Contain("Timeout 3000ms exceeded")); + Assert.That(exception.Message, Does.Contain("waiting for selector \"//div\"")); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should run in specified frame xpath")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRunInSpecifiedFrameXPath() { await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); @@ -257,37 +247,37 @@ public async Task ShouldRunInSpecifiedFrameXPath() await frame1.EvaluateAsync(AddElement, "div"); await frame2.EvaluateAsync(AddElement, "div"); var eHandle = await waitForXPathPromise; - Assert.Equal(frame2, await eHandle.OwnerFrameAsync()); + Assert.That(await eHandle.OwnerFrameAsync(), Is.EqualTo(frame2)); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should throw when frame is detached xpath")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldThrowWhenFrameIsDetachedXPath() { await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage); var frame = Page.FirstChildFrame(); var waitPromise = frame.WaitForSelectorAsync("//*[@class=\"box\"]"); await FrameUtils.DetachFrameAsync(Page, "frame1"); - var exception = await Assert.ThrowsAnyAsync(() => waitPromise); - Assert.Contains("waitForFunction failed: frame got detached.", exception.Message); + var exception = Assert.CatchAsync(() => waitPromise); + Assert.That(exception.Message, Does.Contain("waitForFunction failed: frame got detached.")); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should return the element handle xpath")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnTheElementHandleXPath() { var waitForXPath = Page.WaitForSelectorAsync("//*[@class=\"zombo\"]"); await Page.SetContentAsync("
anything
"); - Assert.Equal("anything", await Page.EvaluateAsync("x => x.textContent", await waitForXPath)); + Assert.That(await Page.EvaluateAsync("x => x.textContent", await waitForXPath), Is.EqualTo("anything")); } [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should allow you to select an element with single slash xpath")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAllowYouToSelectAnElementWithSingleSlashXPath() { await Page.SetContentAsync("
some text
"); var waitForXPath = Page.WaitForSelectorAsync("//html/body/div"); - Assert.Equal("some text", await Page.EvaluateAsync("x => x.textContent", await waitForXPath)); + Assert.That(await Page.EvaluateAsync("x => x.textContent", await waitForXPath), Is.EqualTo("some text")); } } } diff --git a/src/Playwright.Tests/PdfTests.cs b/src/Playwright.Tests/PdfTests.cs index d59d784e50..ff4679d34b 100644 --- a/src/Playwright.Tests/PdfTests.cs +++ b/src/Playwright.Tests/PdfTests.cs @@ -1,24 +1,16 @@ using System; using System.IO; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///pdf.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PdfTests : PlaywrightSharpPageBaseTest - { - /// - public PdfTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("pdf.spec.ts", "should be able to save file")] + { [PlaywrightTest("pdf.spec.ts", "should be able to save file")] [SkipBrowserAndPlatformFact(skipFirefox: true, skipWebkit: true)] public async Task ShouldBeAbleToSaveFile() { @@ -30,7 +22,7 @@ public async Task ShouldBeAbleToSaveFile() } await Page.PdfAsync(outputFile, format: PaperFormat.Letter); fileInfo = new FileInfo(outputFile); - Assert.True(new FileInfo(outputFile).Length > 0); + Assert.That(new FileInfo(outputFile).Length > 0, Is.True); if (fileInfo.Exists) { fileInfo.Delete(); @@ -39,7 +31,9 @@ public async Task ShouldBeAbleToSaveFile() [PlaywrightTest("pdf.spec.ts", "should only have pdf in chromium")] [SkipBrowserAndPlatformFact(skipChromium: true)] - public Task ShouldOnlyHavePdfInChromium() - => Assert.ThrowsAsync(() => Page.PdfAsync()); + public void ShouldOnlyHavePdfInChromium() + { + Assert.ThrowsAsync(() => Page.PdfAsync()); + } } } diff --git a/src/Playwright.Tests/PermissionsTests.cs b/src/Playwright.Tests/PermissionsTests.cs index 83c9146a6f..8a651e867c 100644 --- a/src/Playwright.Tests/PermissionsTests.cs +++ b/src/Playwright.Tests/PermissionsTests.cs @@ -1,27 +1,19 @@ using System; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PermissionsTests : PlaywrightSharpPageBaseTest - { - /// - public PermissionsTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("permissions.spec.ts", "should be prompt by default")] + { [PlaywrightTest("permissions.spec.ts", "should be prompt by default")] [SkipBrowserAndPlatformFact(skipWebkit: true)] public async Task ShouldBePromptByDefault() { await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("prompt", await GetPermissionAsync(Page, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("prompt")); } [PlaywrightTest("permissions.spec.ts", "should deny permission when not listed")] @@ -30,11 +22,11 @@ public async Task ShouldDenyPermissionWhenNotListed() { await Page.GoToAsync(TestConstants.EmptyPage); await Context.GrantPermissionsAsync(Array.Empty(), TestConstants.EmptyPage); - Assert.Equal("denied", await GetPermissionAsync(Page, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("denied")); } [PlaywrightTest("permissions.spec.ts", "should fail when bad permission is given")] - [Fact(Skip = "We don't need this test")] + [Test, Ignore("We don't need this test")] public void ShouldFailWhenBadPermissionIsGiven() { } [PlaywrightTest("permissions.spec.ts", "should grant geolocation permission when listed")] @@ -43,7 +35,7 @@ public async Task ShouldGrantGeolocationPermissionWhenListed() { await Page.GoToAsync(TestConstants.EmptyPage); await Context.GrantPermissionsAsync(ContextPermissions.Geolocation); - Assert.Equal("granted", await GetPermissionAsync(Page, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("granted")); } [PlaywrightTest("permissions.spec.ts", "should grant notifications permission when listed")] @@ -52,7 +44,7 @@ public async Task ShouldGrantNotificationsPermissionWhenListed() { await Page.GoToAsync(TestConstants.EmptyPage); await Context.GrantPermissionsAsync(ContextPermissions.Notifications); - Assert.Equal("granted", await GetPermissionAsync(Page, "notifications")); + Assert.That(await GetPermissionAsync(Page, "notifications"), Is.EqualTo("granted")); } [PlaywrightTest("permissions.spec.ts", "should accumulate when adding")] @@ -62,8 +54,8 @@ public async Task ShouldAccumulateWhenAdding() await Page.GoToAsync(TestConstants.EmptyPage); await Context.GrantPermissionsAsync(ContextPermissions.Geolocation); await Context.GrantPermissionsAsync(ContextPermissions.Notifications); - Assert.Equal("granted", await GetPermissionAsync(Page, "geolocation")); - Assert.Equal("granted", await GetPermissionAsync(Page, "notifications")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("granted")); + Assert.That(await GetPermissionAsync(Page, "notifications"), Is.EqualTo("granted")); } [PlaywrightTest("permissions.spec.ts", "should clear permissions")] @@ -72,12 +64,12 @@ public async Task ShouldClearPermissions() { await Page.GoToAsync(TestConstants.EmptyPage); await Context.GrantPermissionsAsync(ContextPermissions.Geolocation); - Assert.Equal("granted", await GetPermissionAsync(Page, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("granted")); await Context.ClearPermissionsAsync(); await Context.GrantPermissionsAsync(ContextPermissions.Notifications); - Assert.Equal("granted", await GetPermissionAsync(Page, "notifications")); - Assert.NotEqual("granted", await GetPermissionAsync(Page, "geolocation")); - Assert.Equal("granted", await GetPermissionAsync(Page, "notifications")); + Assert.That(await GetPermissionAsync(Page, "notifications"), Is.EqualTo("granted")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.Not.EqualTo("granted")); + Assert.That(await GetPermissionAsync(Page, "notifications"), Is.EqualTo("granted")); } [PlaywrightTest("permissions.spec.ts", "should grant permission when listed for all domains")] @@ -86,7 +78,7 @@ public async Task ShouldGrantPermissionWhenListedForAllDomains() { await Page.GoToAsync(TestConstants.EmptyPage); await Context.GrantPermissionsAsync(ContextPermissions.Geolocation); - Assert.Equal("granted", await GetPermissionAsync(Page, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("granted")); } [PlaywrightTest("permissions.spec.ts", "should grant permission when creating context")] @@ -100,7 +92,7 @@ public async Task ShouldGrantPermissionWhenCreatingContext() var page = await context.NewPageAsync(); await page.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("granted", await GetPermissionAsync(page, "geolocation")); + Assert.That(await GetPermissionAsync(page, "geolocation"), Is.EqualTo("granted")); } [PlaywrightTest("permissions.spec.ts", "should reset permissions")] @@ -109,9 +101,9 @@ public async Task ShouldResetPermissions() { await Page.GoToAsync(TestConstants.EmptyPage); await Context.GrantPermissionsAsync(new[] { ContextPermissions.Geolocation }, TestConstants.EmptyPage); - Assert.Equal("granted", await GetPermissionAsync(Page, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("granted")); await Context.ClearPermissionsAsync(); - Assert.Equal("prompt", await GetPermissionAsync(Page, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("prompt")); } [PlaywrightTest("permissions.spec.ts", "should trigger permission onchange")] @@ -128,17 +120,13 @@ await Page.EvaluateAsync(@"() => { }; }); }"); - Assert.Equal(new[] { "prompt" }, await Page.EvaluateAsync("window.events")); + Assert.That(await Page.EvaluateAsync("window.events"), Is.EqualTo(new[] { "prompt" })); await Context.GrantPermissionsAsync(Array.Empty(), TestConstants.EmptyPage); - Assert.Equal(new[] { "prompt", "denied" }, await Page.EvaluateAsync("window.events")); + Assert.That(await Page.EvaluateAsync("window.events"), Is.EqualTo(new[] { "prompt", "denied" })); await Context.GrantPermissionsAsync(new[] { ContextPermissions.Geolocation }, TestConstants.EmptyPage); - Assert.Equal( - new[] { "prompt", "denied", "granted" }, - await Page.EvaluateAsync("window.events")); + Assert.That(await Page.EvaluateAsync("window.events"), Is.EqualTo(new[] { "prompt", "denied", "granted" })); await Context.ClearPermissionsAsync(); - Assert.Equal( - new[] { "prompt", "denied", "granted", "prompt" }, - await Page.EvaluateAsync("window.events")); + Assert.That(await Page.EvaluateAsync("window.events"), Is.EqualTo(new[] { "prompt", "denied", "granted", "prompt" })); } [PlaywrightTest("permissions.spec.ts", "should trigger permission onchange")] @@ -149,24 +137,24 @@ public async Task ShouldIsolatePermissionsBetweenBrowserContexts() await using var otherContext = await Browser.NewContextAsync(); var otherPage = await otherContext.NewPageAsync(); await otherPage.GoToAsync(TestConstants.EmptyPage); - Assert.Equal("prompt", await GetPermissionAsync(Page, "geolocation")); - Assert.Equal("prompt", await GetPermissionAsync(otherPage, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("prompt")); + Assert.That(await GetPermissionAsync(otherPage, "geolocation"), Is.EqualTo("prompt")); await Context.GrantPermissionsAsync(Array.Empty(), TestConstants.EmptyPage); await otherContext.GrantPermissionsAsync(new[] { ContextPermissions.Geolocation }, TestConstants.EmptyPage); - Assert.Equal("denied", await GetPermissionAsync(Page, "geolocation")); - Assert.Equal("granted", await GetPermissionAsync(otherPage, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("denied")); + Assert.That(await GetPermissionAsync(otherPage, "geolocation"), Is.EqualTo("granted")); await Context.ClearPermissionsAsync(); - Assert.Equal("prompt", await GetPermissionAsync(Page, "geolocation")); - Assert.Equal("granted", await GetPermissionAsync(otherPage, "geolocation")); + Assert.That(await GetPermissionAsync(Page, "geolocation"), Is.EqualTo("prompt")); + Assert.That(await GetPermissionAsync(otherPage, "geolocation"), Is.EqualTo("granted")); await otherContext.CloseAsync(); } [PlaywrightTest("permissions.spec.ts", "should support clipboard read")] - [Fact(Skip = "Skipped in Playwright")] + [Test, Ignore("Skipped in Playwright")] public void ShouldSupportClipboardRead() { } diff --git a/src/Playwright.Tests/Playwright.Tests.csproj b/src/Playwright.Tests/Playwright.Tests.csproj index 76b3f0b6c1..605cce97b0 100644 --- a/src/Playwright.Tests/Playwright.Tests.csproj +++ b/src/Playwright.Tests/Playwright.Tests.csproj @@ -4,31 +4,26 @@ net10.0 true 0.0.0 - 1701;1702 + 1701;1702;NUnit1032;NUnit2022 Microsoft.Playwright.Tests Microsoft.Playwright.Tests - - - runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive - + - - - - PreserveNewest - - diff --git a/src/Playwright.Tests/PopupTests.cs b/src/Playwright.Tests/PopupTests.cs index b80cac5f01..ac47aab33c 100644 --- a/src/Playwright.Tests/PopupTests.cs +++ b/src/Playwright.Tests/PopupTests.cs @@ -1,22 +1,14 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class PopupTests : PlaywrightSharpBrowserBaseTest - { - /// - public PopupTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("popup.spec.ts", "should inherit user agent from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("popup.spec.ts", "should inherit user agent from browser context")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldInheritUserAgentFromBrowserContext() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions { UserAgent = "hey" }); @@ -33,12 +25,12 @@ public async Task ShouldInheritUserAgentFromBrowserContext() string userAgent = await popupTask.Result.EvaluateAsync("() => window.initialUserAgent"); await requestTcs.Task; - Assert.Equal("hey", userAgent); - Assert.Equal("hey", requestTcs.Task.Result); + Assert.That(userAgent, Is.EqualTo("hey")); + Assert.That(requestTcs.Task.Result, Is.EqualTo("hey")); } [PlaywrightTest("popup.spec.ts", "should respect routes from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectRoutesFromBrowserContext() { await using var context = await Browser.NewContextAsync(); @@ -57,11 +49,11 @@ await context.RouteAsync("**/empty.html", (route) => var popupTask = context.WaitForEventAsync(ContextEvent.Page); await TaskUtils.WhenAll(popupTask, page.ClickAsync("a")); - Assert.True(intercepted); + Assert.That(intercepted, Is.True); } [PlaywrightTest("popup.spec.ts", "should inherit extra headers from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldInheritExtraHeadersFromBrowserContext() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -79,11 +71,11 @@ public async Task ShouldInheritExtraHeadersFromBrowserContext() await page.EvaluateAsync(@"url => window._popup = window.open(url)", TestConstants.ServerUrl + "/dummy.html"); await requestTcs.Task; - Assert.Equal("bar", requestTcs.Task.Result); + Assert.That(requestTcs.Task.Result, Is.EqualTo("bar")); } [PlaywrightTest("popup.spec.ts", "should inherit offline from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldInheritOfflineFromBrowserContext() { await using var context = await Browser.NewContextAsync(); @@ -98,11 +90,11 @@ public async Task ShouldInheritOfflineFromBrowserContext() await page.EvaluateAsync(@"url => window._popup = window.open(url)", TestConstants.ServerUrl + "/dummy.html"); - Assert.False(online); + Assert.That(online, Is.False); } [PlaywrightTest("popup.spec.ts", "should inherit http credentials from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldInheritHttpCredentialsFromBrowserContext() { Server.SetAuth("/title.html", "user", "pass"); @@ -119,11 +111,11 @@ await TaskUtils.WhenAll( page.EvaluateAsync("url => window._popup = window.open(url)", TestConstants.ServerUrl + "/title.html")); await popup.Result.WaitForLoadStateAsync(LoadState.DOMContentLoaded); - Assert.Equal("Woof-Woof", await popup.Result.TitleAsync()); + Assert.That(await popup.Result.TitleAsync(), Is.EqualTo("Woof-Woof")); } [PlaywrightTest("popup.spec.ts", "should inherit touch support from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldInheritTouchSupportFromBrowserContext() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -139,11 +131,11 @@ public async Task ShouldInheritTouchSupportFromBrowserContext() return 'ontouchstart' in win; }"); - Assert.True(hasTouch); + Assert.That(hasTouch, Is.True); } [PlaywrightTest("popup.spec.ts", "should inherit viewport size from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldInheritViewportSizeFromBrowserContext() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -158,11 +150,11 @@ public async Task ShouldInheritViewportSizeFromBrowserContext() return { width: win.innerWidth, height: win.innerHeight }; }"); - Assert.Equal(new ViewportSize { Width = 400, Height = 500 }, size); + Assert.That(size, Is.EqualTo(new ViewportSize { Width = 400, Height = 500 })); } [PlaywrightTest("popup.spec.ts", "should use viewport size from window features")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUseViewportSizeFromWindowFeatures() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions @@ -183,12 +175,12 @@ public async Task ShouldUseViewportSizeFromWindowFeatures() await popup.WaitForLoadStateAsync(); var resized = await popup.EvaluateAsync(@"() => ({ width: window.innerWidth, height: window.innerHeight })"); - Assert.Equal(new ViewportSize { Width = 600, Height = 300 }, size); - Assert.Equal(new ViewportSize { Width = 500, Height = 400 }, resized); + Assert.That(size, Is.EqualTo(new ViewportSize { Width = 600, Height = 300 })); + Assert.That(resized, Is.EqualTo(new ViewportSize { Width = 500, Height = 400 })); } [PlaywrightTest("popup.spec.ts", "should respect routes from browser context using window.open")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldRespectRoutesFromBrowserContextUsingWindowOpen() { await using var context = await Browser.NewContextAsync(); @@ -208,11 +200,11 @@ await TaskUtils.WhenAll( popupTask, page.EvaluateAsync("url => window.__popup = window.open(url)", TestConstants.EmptyPage)); - Assert.True(intercepted); + Assert.That(intercepted, Is.True); } [PlaywrightTest("popup.spec.ts", "BrowserContext.addInitScript should apply to an in-process popup")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task BrowserContextAddInitScriptShouldApplyToAnInProcessPopup() { await using var context = await Browser.NewContextAsync(); @@ -225,11 +217,11 @@ public async Task BrowserContextAddInitScriptShouldApplyToAnInProcessPopup() return win.injected; }"); - Assert.Equal(123, injected); + Assert.That(injected, Is.EqualTo(123)); } [PlaywrightTest("popup.spec.ts", "BrowserContext.addInitScript should apply to a cross-process popup")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task BrowserContextAddInitScriptShouldApplyToACrossProcessPopup() { await using var context = await Browser.NewContextAsync(); @@ -243,13 +235,13 @@ await TaskUtils.WhenAll( popup, page.EvaluateAsync("url => window._popup = window.open(url)", TestConstants.CrossProcessUrl + "/title.html")); - Assert.Equal(123, await popup.Result.EvaluateAsync("injected")); + Assert.That(await popup.Result.EvaluateAsync("injected"), Is.EqualTo(123)); await popup.Result.ReloadAsync(); - Assert.Equal(123, await popup.Result.EvaluateAsync("injected")); + Assert.That(await popup.Result.EvaluateAsync("injected"), Is.EqualTo(123)); } [PlaywrightTest("popup.spec.ts", "should expose function from browser context")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldExposeFunctionFromBrowserContext() { await using var context = await Browser.NewContextAsync(); @@ -262,7 +254,7 @@ public async Task ShouldExposeFunctionFromBrowserContext() return win.add(9, 4); }"); - Assert.Equal(13, injected); + Assert.That(injected, Is.EqualTo(13)); } } } diff --git a/src/Playwright.Tests/ProxyTests.cs b/src/Playwright.Tests/ProxyTests.cs index f82e515837..e6fabdc2be 100644 --- a/src/Playwright.Tests/ProxyTests.cs +++ b/src/Playwright.Tests/ProxyTests.cs @@ -2,23 +2,15 @@ using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ProxyTests : PlaywrightSharpBaseTest - { - /// - public ProxyTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("proxy.spec.ts", "should use proxy")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("proxy.spec.ts", "should use proxy")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldUseProxy() { Server.SetRoute("/target.html", ctx => ctx.Response.WriteAsync("Served by the proxy")); @@ -30,11 +22,11 @@ public async Task ShouldUseProxy() var page = await browser.NewPageAsync(); await page.GoToAsync("http://non-existent.com/target.html"); - Assert.Equal("Served by the proxy", await page.TitleAsync()); + Assert.That(await page.TitleAsync(), Is.EqualTo("Served by the proxy")); } [PlaywrightTest("proxy.spec.ts", "should authenticate")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAuthenticate() { Server.SetRoute("/target.html", ctx => @@ -62,11 +54,11 @@ public async Task ShouldAuthenticate() var page = await browser.NewPageAsync(); await page.GoToAsync("http://non-existent.com/target.html"); - Assert.Equal("Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("user:secret")), await page.TitleAsync()); + Assert.That(await page.TitleAsync(), Is.EqualTo("Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("user:secret")))); } [PlaywrightTest("proxy.spec.ts", "should exclude patterns")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldExcludePatterns() { Server.SetRoute("/target.html", ctx => ctx.Response.WriteAsync("Served by the proxy")); @@ -82,11 +74,11 @@ public async Task ShouldExcludePatterns() var page = await browser.NewPageAsync(); await page.GoToAsync("http://non-existent.com/target.html"); - Assert.Equal("Served by the proxy", await page.TitleAsync()); + Assert.That(await page.TitleAsync(), Is.EqualTo("Served by the proxy")); - await Assert.ThrowsAnyAsync(() => page.GoToAsync("http://non-existent1.com/target.html")); - await Assert.ThrowsAnyAsync(() => page.GoToAsync("http://sub.non-existent2.com/target.html")); - await Assert.ThrowsAnyAsync(() => page.GoToAsync("http://foo.zone/target.html")); + Assert.CatchAsync(() => page.GoToAsync("http://non-existent1.com/target.html")); + Assert.CatchAsync(() => page.GoToAsync("http://sub.non-existent2.com/target.html")); + Assert.CatchAsync(() => page.GoToAsync("http://foo.zone/target.html")); } } } diff --git a/src/Playwright.Tests/QuerySelectorTests.cs b/src/Playwright.Tests/QuerySelectorTests.cs index be780adcdb..98e1f3378d 100644 --- a/src/Playwright.Tests/QuerySelectorTests.cs +++ b/src/Playwright.Tests/QuerySelectorTests.cs @@ -1,145 +1,137 @@ using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class QuerySelectorTests : PlaywrightSharpPageBaseTest - { - /// - public QuerySelectorTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("queryselector.spec.ts", "should query existing elements")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("queryselector.spec.ts", "should query existing elements")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldQueryExistingElements() { await Page.SetContentAsync("
A

B
"); var elements = await Page.QuerySelectorAllAsync("div"); - Assert.Equal(2, elements.Count()); + Assert.That(elements.Count(), Is.EqualTo(2)); var tasks = elements.Select(element => Page.EvaluateAsync("e => e.textContent", element)); - Assert.Equal(new[] { "A", "B" }, await TaskUtils.WhenAll(tasks)); + Assert.That(await TaskUtils.WhenAll(tasks), Is.EqualTo(new[] { "A", "B" })); } [PlaywrightTest("queryselector.spec.ts", "should return empty array if nothing is found")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnEmptyArrayIfNothingIsFound() { await Page.GoToAsync(TestConstants.EmptyPage); var elements = await Page.QuerySelectorAllAsync("div"); - Assert.Empty(elements); + Assert.That(elements, Is.Empty); } [PlaywrightTest("queryselector.spec.ts", "xpath should query existing element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task XpathShouldQueryExistingElement() { await Page.SetContentAsync("
test
"); var elements = await Page.QuerySelectorAllAsync("xpath=/html/body/section"); - Assert.NotNull(elements.FirstOrDefault()); - Assert.Single(elements); + Assert.That(elements.FirstOrDefault(), Is.Not.Null); + Assert.That(elements, Has.Count.EqualTo(1)); } [PlaywrightTest("queryselector.spec.ts", "should return empty array for non-existing element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnEmptyArrayForNonExistingElement() { var elements = await Page.QuerySelectorAllAsync("//html/body/non-existing-element"); - Assert.Empty(elements); + Assert.That(elements, Is.Empty); } [PlaywrightTest("queryselector.spec.ts", "should return multiple elements")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnMultipleElements() { await Page.SetContentAsync("
"); var elements = await Page.QuerySelectorAllAsync("xpath=/html/body/div"); - Assert.Equal(2, elements.Count()); + Assert.That(elements.Count(), Is.EqualTo(2)); } [PlaywrightTest("queryselector.spec.ts", "should query existing element with css selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldQueryExistingElementWithCssSelector() { await Page.SetContentAsync("
test
"); var element = await Page.QuerySelectorAsync("css=section"); - Assert.NotNull(element); + Assert.That(element, Is.Not.Null); } [PlaywrightTest("queryselector.spec.ts", "should query existing element with text selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldQueryExistingElementWithTextSelector() { await Page.SetContentAsync("
test
"); var element = await Page.QuerySelectorAsync("text=\"test\""); - Assert.NotNull(element); + Assert.That(element, Is.Not.Null); } [PlaywrightTest("queryselector.spec.ts", "should query existing element with xpath selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldQueryExistingElementWithXpathSelector() { await Page.SetContentAsync("
test
"); var element = await Page.QuerySelectorAsync("xpath=/html/body/section"); - Assert.NotNull(element); + Assert.That(element, Is.Not.Null); } [PlaywrightTest("queryselector.spec.ts", "should return null for non-existing element")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReturnNullForNonExistingElement() { var element = await Page.QuerySelectorAsync("non-existing-element"); - Assert.Null(element); + Assert.That(element, Is.Null); } [PlaywrightTest("queryselector.spec.ts", "should auto-detect xpath selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAutoDetectXpathSelector() { await Page.SetContentAsync("
test
"); var element = await Page.QuerySelectorAsync("//html/body/section"); - Assert.NotNull(element); + Assert.That(element, Is.Not.Null); } [PlaywrightTest("queryselector.spec.ts", "should auto-detect xpath selector with starting parenthesis")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAutoDetectXpathSelectorWithStartingParenthesis() { await Page.SetContentAsync("
test
"); var element = await Page.QuerySelectorAsync("(//section)[1]"); - Assert.NotNull(element); + Assert.That(element, Is.Not.Null); } [PlaywrightTest("queryselector.spec.ts", "should auto-detect text selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAutoDetectTextSelector() { await Page.SetContentAsync("
test
"); var element = await Page.QuerySelectorAsync("\"test\""); - Assert.NotNull(element); + Assert.That(element, Is.Not.Null); } [PlaywrightTest("queryselector.spec.ts", "should auto-detect css selector")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldAutoDetectCssSelector() { await Page.SetContentAsync("
test
"); var element = await Page.QuerySelectorAsync("section"); - Assert.NotNull(element); + Assert.That(element, Is.Not.Null); } [PlaywrightTest("queryselector.spec.ts", "should support >> syntax")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSupportDoubleGreaterThanSyntax() { await Page.SetContentAsync("
test
"); var element = await Page.QuerySelectorAsync("css=section >> css=div"); - Assert.NotNull(element); + Assert.That(element, Is.Not.Null); } } } diff --git a/src/Playwright.Tests/ResourceTimingTests.cs b/src/Playwright.Tests/ResourceTimingTests.cs index 7c9211e164..0485e9dd2d 100644 --- a/src/Playwright.Tests/ResourceTimingTests.cs +++ b/src/Playwright.Tests/ResourceTimingTests.cs @@ -3,25 +3,17 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///resource-timing.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ResourceTimingTests : PlaywrightSharpPageBaseTest - { - /// - public ResourceTimingTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("resource-timing.spec.ts", "should work")] - [Fact] + { [PlaywrightTest("resource-timing.spec.ts", "should work")] + [Test] public async Task ShouldWork() { var (request, _) = await TaskUtils.WhenAll( @@ -29,19 +21,19 @@ public async Task ShouldWork() Page.GoToAsync(TestConstants.EmptyPage)); var timing = request.Timing; - Assert.True(timing.DomainLookupStart >= -1); - Assert.True(timing.DomainLookupEnd >= timing.DomainLookupStart); - Assert.True(timing.ConnectStart >= timing.DomainLookupEnd); - Assert.Equal(-1, timing.SecureConnectionStart); - Assert.True(VerifyTimingValue(timing.ConnectEnd, timing.SecureConnectionStart)); - Assert.True(VerifyTimingValue(timing.RequestStart, timing.ConnectEnd)); - Assert.True(timing.ResponseStart > timing.RequestStart); - Assert.True(timing.ResponseEnd >= timing.ResponseStart); - Assert.True(timing.ResponseEnd < 10000); + Assert.That(timing.DomainLookupStart >= -1, Is.True); + Assert.That(timing.DomainLookupEnd >= timing.DomainLookupStart, Is.True); + Assert.That(timing.ConnectStart >= timing.DomainLookupEnd, Is.True); + Assert.That(timing.SecureConnectionStart, Is.EqualTo(-1)); + Assert.That(VerifyTimingValue(timing.ConnectEnd, timing.SecureConnectionStart), Is.True); + Assert.That(VerifyTimingValue(timing.RequestStart, timing.ConnectEnd), Is.True); + Assert.That(timing.ResponseStart > timing.RequestStart, Is.True); + Assert.That(timing.ResponseEnd >= timing.ResponseStart, Is.True); + Assert.That(timing.ResponseEnd < 10000, Is.True); } [PlaywrightTest("resource-timing.spec.ts", "should work for subresource")] - [Fact] + [Test] public async Task ShouldWorkForSubresource() { var requests = new List(); @@ -49,34 +41,34 @@ public async Task ShouldWorkForSubresource() Page.RequestFinished += (_, e) => requests.Add(e); await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); - Assert.Equal(2, requests.Count); + Assert.That(requests.Count, Is.EqualTo(2)); var timing = requests[1].Timing; if (TestConstants.IsWebKit && TestConstants.IsWindows) { - Assert.True(timing.DomainLookupStart >= 0); - Assert.True(timing.DomainLookupEnd >= timing.DomainLookupStart); - Assert.True(timing.ConnectStart >= timing.DomainLookupEnd); - Assert.Equal(-1, timing.SecureConnectionStart); - Assert.True(timing.ConnectEnd > timing.SecureConnectionStart); + Assert.That(timing.DomainLookupStart >= 0, Is.True); + Assert.That(timing.DomainLookupEnd >= timing.DomainLookupStart, Is.True); + Assert.That(timing.ConnectStart >= timing.DomainLookupEnd, Is.True); + Assert.That(timing.SecureConnectionStart, Is.EqualTo(-1)); + Assert.That(timing.ConnectEnd > timing.SecureConnectionStart, Is.True); } else { - Assert.True(timing.DomainLookupStart == 0 || timing.DomainLookupStart == -1); - Assert.Equal(-1, timing.DomainLookupEnd); - Assert.Equal(-1, timing.ConnectStart); - Assert.Equal(-1, timing.SecureConnectionStart); - Assert.Equal(-1, timing.ConnectEnd); + Assert.That(timing.DomainLookupStart == 0 || timing.DomainLookupStart == -1, Is.True); + Assert.That(timing.DomainLookupEnd, Is.EqualTo(-1)); + Assert.That(timing.ConnectStart, Is.EqualTo(-1)); + Assert.That(timing.SecureConnectionStart, Is.EqualTo(-1)); + Assert.That(timing.ConnectEnd, Is.EqualTo(-1)); } - Assert.True(timing.RequestStart >= 0); - Assert.True(timing.ResponseStart >= timing.RequestStart); - Assert.True(timing.ResponseEnd >= timing.ResponseStart); - Assert.True(timing.ResponseEnd < 10000); + Assert.That(timing.RequestStart >= 0, Is.True); + Assert.That(timing.ResponseStart >= timing.RequestStart, Is.True); + Assert.That(timing.ResponseEnd >= timing.ResponseStart, Is.True); + Assert.That(timing.ResponseEnd < 10000, Is.True); } [PlaywrightTest("resource-timing.spec.ts", "should work for SSL")] - [Fact(Skip = "Fix me #1058")] + [Test, Ignore("Fix me #1058")] public async Task ShouldWorkForSSL() { var page = await Browser.NewPageAsync(ignoreHTTPSErrors: true); @@ -87,17 +79,17 @@ public async Task ShouldWorkForSSL() var timing = request.Timing; if (!(TestConstants.IsWebKit && TestConstants.IsMacOSX)) { - Assert.True(timing.DomainLookupStart >= 0); - Assert.True(timing.DomainLookupEnd >= timing.DomainLookupStart); - Assert.True(timing.ConnectStart >= timing.DomainLookupEnd); - Assert.True(timing.SecureConnectionStart >= timing.ConnectStart); - Assert.True(timing.ConnectEnd > timing.SecureConnectionStart); - Assert.True(timing.RequestStart >= timing.ConnectEnd); + Assert.That(timing.DomainLookupStart >= 0, Is.True); + Assert.That(timing.DomainLookupEnd >= timing.DomainLookupStart, Is.True); + Assert.That(timing.ConnectStart >= timing.DomainLookupEnd, Is.True); + Assert.That(timing.SecureConnectionStart >= timing.ConnectStart, Is.True); + Assert.That(timing.ConnectEnd > timing.SecureConnectionStart, Is.True); + Assert.That(timing.RequestStart >= timing.ConnectEnd, Is.True); } - Assert.True(timing.ResponseStart > timing.RequestStart); - Assert.True(timing.ResponseEnd >= timing.ResponseStart); - Assert.True(timing.ResponseEnd < 10000); + Assert.That(timing.ResponseStart > timing.RequestStart, Is.True); + Assert.That(timing.ResponseEnd >= timing.ResponseStart, Is.True); + Assert.That(timing.ResponseEnd < 10000, Is.True); await page.CloseAsync(); } @@ -114,31 +106,31 @@ public async Task ShouldWorkForRedirect() // This is different on purpose, promises work different in TS. await responses[1].GetFinishedAsync(); - Assert.Equal(2, responses.Count); - Assert.Equal(TestConstants.ServerUrl + "/foo.html", responses[0].Url); - Assert.Equal(TestConstants.ServerUrl + "/empty.html", responses[1].Url); + Assert.That(responses.Count, Is.EqualTo(2)); + Assert.That(responses[0].Url, Is.EqualTo(TestConstants.ServerUrl + "/foo.html")); + Assert.That(responses[1].Url, Is.EqualTo(TestConstants.ServerUrl + "/empty.html")); var timing1 = responses[0].Request.Timing; - Assert.True(timing1.DomainLookupStart >= 0); - Assert.True(timing1.DomainLookupEnd >= timing1.DomainLookupStart); - Assert.True(timing1.ConnectStart >= timing1.DomainLookupEnd); - Assert.Equal(-1, timing1.SecureConnectionStart); - Assert.True(timing1.ConnectEnd > timing1.SecureConnectionStart); - Assert.True(timing1.RequestStart >= timing1.ConnectEnd); - Assert.True(timing1.ResponseStart > timing1.RequestStart); - Assert.True(timing1.ResponseEnd >= timing1.ResponseStart); - Assert.True(timing1.ResponseEnd < 10000); + Assert.That(timing1.DomainLookupStart >= 0, Is.True); + Assert.That(timing1.DomainLookupEnd >= timing1.DomainLookupStart, Is.True); + Assert.That(timing1.ConnectStart >= timing1.DomainLookupEnd, Is.True); + Assert.That(timing1.SecureConnectionStart, Is.EqualTo(-1)); + Assert.That(timing1.ConnectEnd > timing1.SecureConnectionStart, Is.True); + Assert.That(timing1.RequestStart >= timing1.ConnectEnd, Is.True); + Assert.That(timing1.ResponseStart > timing1.RequestStart, Is.True); + Assert.That(timing1.ResponseEnd >= timing1.ResponseStart, Is.True); + Assert.That(timing1.ResponseEnd < 10000, Is.True); var timing2 = responses[1].Request.Timing; - Assert.Equal(-1, timing2.DomainLookupStart); - Assert.Equal(-1, timing2.DomainLookupEnd); - Assert.Equal(-1, timing2.ConnectStart); - Assert.Equal(-1, timing2.SecureConnectionStart); - Assert.Equal(-1, timing2.ConnectEnd); - Assert.True(timing2.RequestStart >= 0); - Assert.True(timing2.ResponseStart >= timing2.RequestStart); - Assert.True(timing2.ResponseEnd >= timing2.ResponseStart); - Assert.True(timing2.ResponseEnd < 10000); + Assert.That(timing2.DomainLookupStart, Is.EqualTo(-1)); + Assert.That(timing2.DomainLookupEnd, Is.EqualTo(-1)); + Assert.That(timing2.ConnectStart, Is.EqualTo(-1)); + Assert.That(timing2.SecureConnectionStart, Is.EqualTo(-1)); + Assert.That(timing2.ConnectEnd, Is.EqualTo(-1)); + Assert.That(timing2.RequestStart >= 0, Is.True); + Assert.That(timing2.ResponseStart >= timing2.RequestStart, Is.True); + Assert.That(timing2.ResponseEnd >= timing2.ResponseStart, Is.True); + Assert.That(timing2.ResponseEnd < 10000, Is.True); } private bool VerifyTimingValue(float value, float previous) => value == -1 || value > 0 && value >= previous; diff --git a/src/Playwright.Tests/ScreencastTests.cs b/src/Playwright.Tests/ScreencastTests.cs index 7bfc026721..cd8b49ba7e 100644 --- a/src/Playwright.Tests/ScreencastTests.cs +++ b/src/Playwright.Tests/ScreencastTests.cs @@ -2,38 +2,30 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.Attributes; using Microsoft.Playwright.Tests.BaseTests; using Microsoft.Playwright.Tests.Helpers; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///screencast.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ScreencastTests : PlaywrightSharpBrowserBaseTest - { - /// - public ScreencastTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("screencast.spec.ts", "videoSize should require videosPath")] - [Fact(Skip = "We are not using old properties")] + { [PlaywrightTest("screencast.spec.ts", "videoSize should require videosPath")] + [Test, Ignore("We are not using old properties")] public void VideoSizeShouldRequireVideosPath() { } [PlaywrightTest("screencast.spec.ts", "should work with old options")] - [Fact(Skip = "We are not using old properties")] + [Test, Ignore("We are not using old properties")] public void ShouldWorkWithOldOptions() { } [PlaywrightTest("screencast.spec.ts", "should throw without recordVideo.dir")] - [Fact(Skip = "We don't need to test this")] + [Test, Ignore("We don't need to test this")] public void ShouldThrowWithoutRecordVideoDir() { } @@ -50,11 +42,11 @@ public async Task ShouldCaptureStaticPage() await Task.Delay(1000); await context.CloseAsync(); - Assert.NotEmpty(new DirectoryInfo(tempDirectory.Path).GetFiles("*.webm")); + Assert.That(new DirectoryInfo(tempDirectory.Path).GetFiles("*.webm"), Is.Not.Empty); } [PlaywrightTest("screencast.spec.ts", "should expose video path")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldExposeVideoPath() { using var tempDirectory = new TempDirectory(); @@ -63,14 +55,14 @@ public async Task ShouldExposeVideoPath() var page = await context.NewPageAsync(); await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'"); string path = await page.Video.GetPathAsync(); - Assert.Contains(tempDirectory.Path, path); + Assert.That(path, Does.Contain(tempDirectory.Path)); await context.CloseAsync(); - Assert.True(new FileInfo(path).Exists); + Assert.That(new FileInfo(path).Exists, Is.True); } [PlaywrightTest("screencast.spec.ts", "should expose video path blank page")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldExposeVideoPathBlankPage() { using var tempDirectory = new TempDirectory(); @@ -78,50 +70,50 @@ public async Task ShouldExposeVideoPathBlankPage() var page = await context.NewPageAsync(); string path = await page.Video.GetPathAsync(); - Assert.Contains(tempDirectory.Path, path); + Assert.That(path, Does.Contain(tempDirectory.Path)); await context.CloseAsync(); - Assert.True(new FileInfo(path).Exists); + Assert.That(new FileInfo(path).Exists, Is.True); } [PlaywrightTest("screencast.spec.ts", "should expose video path blank popup")] - [Fact(Skip = "We don't need to test video details")] + [Test, Ignore("We don't need to test video details")] public void ShouldExposeVideoPathBlankPopup() { } [PlaywrightTest("screencast.spec.ts", "should capture navigation")] - [Fact(Skip = "We don't need to test video details")] + [Test, Ignore("We don't need to test video details")] public void ShouldCaptureNavigation() { } [PlaywrightTest("screencast.spec.ts", "should capture css transformation")] - [Fact(Skip = "We don't need to test video details")] + [Test, Ignore("We don't need to test video details")] public void ShouldCaptureCssTransformation() { } [PlaywrightTest("screencast.spec.ts", "should work for popups")] - [Fact(Skip = "We don't need to test video details")] + [Test, Ignore("We don't need to test video details")] public void ShouldWorkForPopups() { } [PlaywrightTest("screencast.spec.ts", "should scale frames down to the requested size")] - [Fact(Skip = "We don't need to test video details")] + [Test, Ignore("We don't need to test video details")] public void ShouldScaleFramesDownToTheRequestedSize() { } [PlaywrightTest("screencast.spec.ts", "should use viewport as default size")] - [Fact(Skip = "We don't need to test video details")] + [Test, Ignore("We don't need to test video details")] public void ShouldUseViewportAsDefaultSize() { } [PlaywrightTest("screencast.spec.ts", "should be 1280x720 by default")] - [Fact(Skip = "We don't need to test video details")] + [Test, Ignore("We don't need to test video details")] public void ShouldBe1280x720ByDefault() { } @@ -139,7 +131,7 @@ public async Task ShouldCaptureStaticPageInPersistentContext() await Task.Delay(1000); await context.CloseAsync(); - Assert.NotEmpty(new DirectoryInfo(tempDirectory.Path).GetFiles("*.webm")); + Assert.That(new DirectoryInfo(tempDirectory.Path).GetFiles("*.webm"), Is.Not.Empty); } } } diff --git a/src/Playwright.Tests/SelectorMiscTests.cs b/src/Playwright.Tests/SelectorMiscTests.cs index 541ae699f9..2b1b0ffe56 100644 --- a/src/Playwright.Tests/SelectorMiscTests.cs +++ b/src/Playwright.Tests/SelectorMiscTests.cs @@ -1,31 +1,23 @@ using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class SelectorMiscTests : PlaywrightSharpPageBaseTest - { - /// - public SelectorMiscTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("selectors-misc.spec.ts", "should work for open shadow roots")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("selectors-misc.spec.ts", "should work for open shadow roots")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForOpenShadowRoots() { await Page.GoToAsync(TestConstants.ServerUrl + "/deep-shadow.html"); - Assert.Equal("Hello from root2", await Page.EvalOnSelectorAsync("id=target", "e => e.textContent")); - Assert.Equal("Hello from root1", await Page.EvalOnSelectorAsync("data-testid=foo", "e => e.textContent")); - Assert.Equal(3, await Page.EvalOnSelectorAllAsync("data-testid=foo", "els => els.length")); - Assert.Null(await Page.QuerySelectorAsync("id:light=target")); - Assert.Null(await Page.QuerySelectorAsync("data-testid:light=foo")); - Assert.Empty(await Page.QuerySelectorAllAsync("data-testid:light=foo")); + Assert.That(await Page.EvalOnSelectorAsync("id=target", "e => e.textContent"), Is.EqualTo("Hello from root2")); + Assert.That(await Page.EvalOnSelectorAsync("data-testid=foo", "e => e.textContent"), Is.EqualTo("Hello from root1")); + Assert.That(await Page.EvalOnSelectorAllAsync("data-testid=foo", "els => els.length"), Is.EqualTo(3)); + Assert.That(await Page.QuerySelectorAsync("id:light=target"), Is.Null); + Assert.That(await Page.QuerySelectorAsync("data-testid:light=foo"), Is.Null); + Assert.That(await Page.QuerySelectorAllAsync("data-testid:light=foo"), Is.Empty); } } } diff --git a/src/Playwright.Tests/SelectorsCssTests.cs b/src/Playwright.Tests/SelectorsCssTests.cs index 7e6c9228b4..d8e9f30a1e 100644 --- a/src/Playwright.Tests/SelectorsCssTests.cs +++ b/src/Playwright.Tests/SelectorsCssTests.cs @@ -1,116 +1,108 @@ using System.Linq; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class SelectorsCssTests : PlaywrightSharpPageBaseTest - { - /// - public SelectorsCssTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("selectors-css.spec.ts", "should work for open shadow roots")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("selectors-css.spec.ts", "should work for open shadow roots")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForOpenShadowRoots() { await Page.GoToAsync(TestConstants.ServerUrl + "/deep-shadow.html"); - Assert.Equal("Hello from root1", await Page.EvalOnSelectorAsync("css=span", "e => e.textContent")); - Assert.Equal("Hello from root3 #2", await Page.EvalOnSelectorAsync("css =[attr=\"value\\ space\"]", "e => e.textContent")); - Assert.Equal("Hello from root3 #2", await Page.EvalOnSelectorAsync("css =[attr='value\\ \\space']", "e => e.textContent")); - Assert.Equal("Hello from root2", await Page.EvalOnSelectorAsync("css=div div span", "e => e.textContent")); - Assert.Equal("Hello from root3 #2", await Page.EvalOnSelectorAsync("css=div span + span", "e => e.textContent")); - Assert.Equal("Hello from root3 #2", await Page.EvalOnSelectorAsync("css=span + [attr *=\"value\"]", "e => e.textContent")); - Assert.Equal("Hello from root3 #2", await Page.EvalOnSelectorAsync("css=[data-testid=\"foo\"] + [attr*=\"value\"]", "e => e.textContent")); - Assert.Equal("Hello from root2", await Page.EvalOnSelectorAsync("css=#target", "e => e.textContent")); - Assert.Equal("Hello from root2", await Page.EvalOnSelectorAsync("css=div #target", "e => e.textContent")); - Assert.Equal("Hello from root2", await Page.EvalOnSelectorAsync("css=div div #target", "e => e.textContent")); - Assert.Null(await Page.QuerySelectorAsync("css=div div div #target")); - Assert.Equal("Hello from root2", await Page.EvalOnSelectorAsync("css=section > div div span", "e => e.textContent")); - Assert.Equal("Hello from root3 #2", await Page.EvalOnSelectorAsync("css=section > div div span:nth-child(2)", "e => e.textContent")); - Assert.Null(await Page.QuerySelectorAsync("css=section div div div div")); + Assert.That(await Page.EvalOnSelectorAsync("css=span", "e => e.textContent"), Is.EqualTo("Hello from root1")); + Assert.That(await Page.EvalOnSelectorAsync("css =[attr=\"value\\ space\"]", "e => e.textContent"), Is.EqualTo("Hello from root3 #2")); + Assert.That(await Page.EvalOnSelectorAsync("css =[attr='value\\ \\space']", "e => e.textContent"), Is.EqualTo("Hello from root3 #2")); + Assert.That(await Page.EvalOnSelectorAsync("css=div div span", "e => e.textContent"), Is.EqualTo("Hello from root2")); + Assert.That(await Page.EvalOnSelectorAsync("css=div span + span", "e => e.textContent"), Is.EqualTo("Hello from root3 #2")); + Assert.That(await Page.EvalOnSelectorAsync("css=span + [attr *=\"value\"]", "e => e.textContent"), Is.EqualTo("Hello from root3 #2")); + Assert.That(await Page.EvalOnSelectorAsync("css=[data-testid=\"foo\"] + [attr*=\"value\"]", "e => e.textContent"), Is.EqualTo("Hello from root3 #2")); + Assert.That(await Page.EvalOnSelectorAsync("css=#target", "e => e.textContent"), Is.EqualTo("Hello from root2")); + Assert.That(await Page.EvalOnSelectorAsync("css=div #target", "e => e.textContent"), Is.EqualTo("Hello from root2")); + Assert.That(await Page.EvalOnSelectorAsync("css=div div #target", "e => e.textContent"), Is.EqualTo("Hello from root2")); + Assert.That(await Page.QuerySelectorAsync("css=div div div #target"), Is.Null); + Assert.That(await Page.EvalOnSelectorAsync("css=section > div div span", "e => e.textContent"), Is.EqualTo("Hello from root2")); + Assert.That(await Page.EvalOnSelectorAsync("css=section > div div span:nth-child(2)", "e => e.textContent"), Is.EqualTo("Hello from root3 #2")); + Assert.That(await Page.QuerySelectorAsync("css=section div div div div"), Is.Null); var root2 = await Page.QuerySelectorAsync("css=div div"); - Assert.Equal("Hello from root2", await root2.EvalOnSelectorAsync("css=#target", "e => e.textContent")); - Assert.Null(await root2.QuerySelectorAsync("css:light=#target")); + Assert.That(await root2.EvalOnSelectorAsync("css=#target", "e => e.textContent"), Is.EqualTo("Hello from root2")); + Assert.That(await root2.QuerySelectorAsync("css:light=#target"), Is.Null); var root2Shadow = (IElementHandle)await root2.EvaluateHandleAsync("r => r.shadowRoot"); - Assert.Equal("Hello from root2", await root2Shadow.EvalOnSelectorAsync("css:light=#target", "e => e.textContent")); + Assert.That(await root2Shadow.EvalOnSelectorAsync("css:light=#target", "e => e.textContent"), Is.EqualTo("Hello from root2")); var root3 = (await Page.QuerySelectorAllAsync("css=div div")).ElementAt(1); - Assert.Equal("Hello from root3", await root3.EvalOnSelectorAsync("text=root3", "e => e.textContent")); - Assert.Equal("Hello from root3 #2", await root3.EvalOnSelectorAsync("css=[attr *=\"value\"]", "e => e.textContent")); - Assert.Null(await root3.QuerySelectorAsync("css:light=[attr*=\"value\"]")); + Assert.That(await root3.EvalOnSelectorAsync("text=root3", "e => e.textContent"), Is.EqualTo("Hello from root3")); + Assert.That(await root3.EvalOnSelectorAsync("css=[attr *=\"value\"]", "e => e.textContent"), Is.EqualTo("Hello from root3 #2")); + Assert.That(await root3.QuerySelectorAsync("css:light=[attr*=\"value\"]"), Is.Null); } [PlaywrightTest("selectors-css.spec.ts", "should work with > combinator and spaces")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCombinatorAndSpaces() { await Page.SetContentAsync("
"); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("div[foo=\"bar\"][bar=\"baz\"] > span", "e => e.outerHTML"), Is.EqualTo("")); } [PlaywrightTest("selectors-css.spec.ts", "should work with comma separated list")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCommaSeparatedList() { await Page.GoToAsync(TestConstants.ServerUrl + "/deep-shadow.html"); - Assert.Equal(5, await Page.EvalOnSelectorAllAsync("css=span, section #root1", "els => els.length")); - Assert.Equal(5, await Page.EvalOnSelectorAllAsync("css=section #root1, div span", "els => els.length")); - Assert.Equal("root1", await Page.EvalOnSelectorAsync("css=doesnotexist, section #root1", "e => e.id")); - Assert.Equal(1, await Page.EvalOnSelectorAllAsync("css=doesnotexist, section #root1", "els => els.length")); - Assert.Equal(4, await Page.EvalOnSelectorAllAsync("css=span,div span", "els => els.length")); - Assert.Equal(4, await Page.EvalOnSelectorAllAsync("css=span,div span, div div span", "els => els.length")); - Assert.Equal(2, await Page.EvalOnSelectorAllAsync("css=#target,[attr=\"value\\ space\"]", "els => els.length")); - Assert.Equal(4, await Page.EvalOnSelectorAllAsync("css=#target,[data-testid=\"foo\"],[attr=\"value\\ space\"]", "els => els.length")); - Assert.Equal(4, await Page.EvalOnSelectorAllAsync("css=#target,[data-testid=\"foo\"],[attr=\"value\\ space\"],span", "els => els.length")); + Assert.That(await Page.EvalOnSelectorAllAsync("css=span, section #root1", "els => els.length"), Is.EqualTo(5)); + Assert.That(await Page.EvalOnSelectorAllAsync("css=section #root1, div span", "els => els.length"), Is.EqualTo(5)); + Assert.That(await Page.EvalOnSelectorAsync("css=doesnotexist, section #root1", "e => e.id"), Is.EqualTo("root1")); + Assert.That(await Page.EvalOnSelectorAllAsync("css=doesnotexist, section #root1", "els => els.length"), Is.EqualTo(1)); + Assert.That(await Page.EvalOnSelectorAllAsync("css=span,div span", "els => els.length"), Is.EqualTo(4)); + Assert.That(await Page.EvalOnSelectorAllAsync("css=span,div span, div div span", "els => els.length"), Is.EqualTo(4)); + Assert.That(await Page.EvalOnSelectorAllAsync("css=#target,[attr=\"value\\ space\"]", "els => els.length"), Is.EqualTo(2)); + Assert.That(await Page.EvalOnSelectorAllAsync("css=#target,[data-testid=\"foo\"],[attr=\"value\\ space\"]", "els => els.length"), Is.EqualTo(4)); + Assert.That(await Page.EvalOnSelectorAllAsync("css=#target,[data-testid=\"foo\"],[attr=\"value\\ space\"],span", "els => els.length"), Is.EqualTo(4)); } [PlaywrightTest("selectors-css.spec.ts", "should keep dom order with comma separated list")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldKeepDomOrderWithCommaSeparatedList() { await Page.SetContentAsync("
"); - Assert.Equal("SPAN,DIV", await Page.EvalOnSelectorAllAsync("css=span, div", "els => els.map(e => e.nodeName).join(',')")); - Assert.Equal("SPAN,DIV", await Page.EvalOnSelectorAllAsync("css=div, span", "els => els.map(e => e.nodeName).join(',')")); - Assert.Equal("DIV", await Page.EvalOnSelectorAllAsync("css=span div, div", "els => els.map(e => e.nodeName).join(',')")); - Assert.Equal("SECTION", await Page.EvalOnSelectorAllAsync("*css = section >> css = div, span", "els => els.map(e => e.nodeName).join(',')")); - Assert.Equal("DIV", await Page.EvalOnSelectorAllAsync("css=section >> *css = div >> css = x, y", "els => els.map(e => e.nodeName).join(',')")); - Assert.Equal("SPAN,DIV", await Page.EvalOnSelectorAllAsync("css=section >> *css = div, span >> css = x, y", "els => els.map(e => e.nodeName).join(',')")); - Assert.Equal("SPAN,DIV", await Page.EvalOnSelectorAllAsync("css=section >> *css = div, span >> css = y", "els => els.map(e => e.nodeName).join(',')")); + Assert.That(await Page.EvalOnSelectorAllAsync("css=span, div", "els => els.map(e => e.nodeName).join(',')"), Is.EqualTo("SPAN,DIV")); + Assert.That(await Page.EvalOnSelectorAllAsync("css=div, span", "els => els.map(e => e.nodeName).join(',')"), Is.EqualTo("SPAN,DIV")); + Assert.That(await Page.EvalOnSelectorAllAsync("css=span div, div", "els => els.map(e => e.nodeName).join(',')"), Is.EqualTo("DIV")); + Assert.That(await Page.EvalOnSelectorAllAsync("*css = section >> css = div, span", "els => els.map(e => e.nodeName).join(',')"), Is.EqualTo("SECTION")); + Assert.That(await Page.EvalOnSelectorAllAsync("css=section >> *css = div >> css = x, y", "els => els.map(e => e.nodeName).join(',')"), Is.EqualTo("DIV")); + Assert.That(await Page.EvalOnSelectorAllAsync("css=section >> *css = div, span >> css = x, y", "els => els.map(e => e.nodeName).join(',')"), Is.EqualTo("SPAN,DIV")); + Assert.That(await Page.EvalOnSelectorAllAsync("css=section >> *css = div, span >> css = y", "els => els.map(e => e.nodeName).join(',')"), Is.EqualTo("SPAN,DIV")); } [PlaywrightTest("selectors-css.spec.ts", "should work with comma inside text")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithCommaInsideText() { await Page.SetContentAsync("
"); - Assert.Equal("
", await Page.EvalOnSelectorAsync("css=div[attr=\"hello,world!\"]", "e => e.outerHTML")); - Assert.Equal("
", await Page.EvalOnSelectorAsync("css =[attr=\"hello,world!\"]", "e => e.outerHTML")); - Assert.Equal("
", await Page.EvalOnSelectorAsync("css=div[attr='hello,world!']", "e => e.outerHTML")); - Assert.Equal("
", await Page.EvalOnSelectorAsync("css=[attr='hello,world!']", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("css=div[attr=\"hello,world!\"], span", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("css=div[attr=\"hello,world!\"]", "e => e.outerHTML"), Is.EqualTo("
")); + Assert.That(await Page.EvalOnSelectorAsync("css =[attr=\"hello,world!\"]", "e => e.outerHTML"), Is.EqualTo("
")); + Assert.That(await Page.EvalOnSelectorAsync("css=div[attr='hello,world!']", "e => e.outerHTML"), Is.EqualTo("
")); + Assert.That(await Page.EvalOnSelectorAsync("css=[attr='hello,world!']", "e => e.outerHTML"), Is.EqualTo("
")); + Assert.That(await Page.EvalOnSelectorAsync("css=div[attr=\"hello,world!\"], span", "e => e.outerHTML"), Is.EqualTo("")); } [PlaywrightTest("selectors-css.spec.ts", "should work with attribute selectors")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithAttributeSelectors() { await Page.SetContentAsync("
>foo=bar[]\" attr3=\"] span\">
"); @@ -132,12 +124,12 @@ public async Task ShouldWorkWithAttributeSelectors() foreach (string selector in selectors) { - Assert.True(await Page.EvalOnSelectorAsync(selector, "e => e === div")); + Assert.That(await Page.EvalOnSelectorAsync(selector, "e => e === div"), Is.True); } - Assert.True(await Page.EvalOnSelectorAsync("[attr*=hello] span", "e => e.parentNode === div")); - Assert.True(await Page.EvalOnSelectorAsync("[attr*=hello] >> span", "e => e.parentNode === div")); - Assert.True(await Page.EvalOnSelectorAsync("[attr3=\"] span\"] >> span", "e => e.parentNode === div")); + Assert.That(await Page.EvalOnSelectorAsync("[attr*=hello] span", "e => e.parentNode === div"), Is.True); + Assert.That(await Page.EvalOnSelectorAsync("[attr*=hello] >> span", "e => e.parentNode === div"), Is.True); + Assert.That(await Page.EvalOnSelectorAsync("[attr3=\"] span\"] >> span", "e => e.parentNode === div"), Is.True); } } } diff --git a/src/Playwright.Tests/SelectorsRegisterTests.cs b/src/Playwright.Tests/SelectorsRegisterTests.cs index 386499feea..86a65c721c 100644 --- a/src/Playwright.Tests/SelectorsRegisterTests.cs +++ b/src/Playwright.Tests/SelectorsRegisterTests.cs @@ -1,22 +1,14 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///selectors-register.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class SelectorsRegisterTests : PlaywrightSharpPageBaseTest - { - /// - public SelectorsRegisterTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("selectors-register.spec.ts", "should work")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("selectors-register.spec.ts", "should work")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWork() { const string createTagSelector = @"({ @@ -37,21 +29,21 @@ public async Task ShouldWork() var page = await context.NewPageAsync(); await page.SetContentAsync("
"); - var exception = await Assert.ThrowsAnyAsync(() => page.QuerySelectorAsync("tAG=DIV")); - Assert.Contains("Unknown engine \"tAG\" while parsing selector tAG=DIV", exception.Message); + var exception = Assert.CatchAsync(() => page.QuerySelectorAsync("tAG=DIV")); + Assert.That(exception.Message, Does.Contain("Unknown engine \"tAG\" while parsing selector tAG=DIV")); } [PlaywrightTest("selectors-register.spec.ts", "should work with path")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithPath() { await TestUtils.RegisterEngineWithPathAsync(Playwright, "foo", TestUtils.GetWebServerFile("sectionselectorengine.js")); await Page.SetContentAsync("
"); - Assert.Equal("SECTION", await Page.EvalOnSelectorAsync("foo=whatever", "e => e.nodeName")); + Assert.That(await Page.EvalOnSelectorAsync("foo=whatever", "e => e.nodeName"), Is.EqualTo("SECTION")); } [PlaywrightTest("selectors-register.spec.ts", "should work in main and isolated world")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkInMainAndIsolatedWorld() { const string createTagSelector = @"({ @@ -69,28 +61,28 @@ public async Task ShouldWorkInMainAndIsolatedWorld() await Page.SetContentAsync("
"); await Page.EvaluateAsync("() => window['__answer'] = document.querySelector('span')"); - Assert.Equal("SPAN", await Page.EvalOnSelectorAsync("main=ignored", "e => e.nodeName")); - Assert.Equal("SPAN", await Page.EvalOnSelectorAsync("css=div >> main=ignored", "e => e.nodeName")); - Assert.True(await Page.EvalOnSelectorAllAsync("main=ignored", "es => window['__answer'] !== undefined")); - Assert.Equal(3, await Page.EvalOnSelectorAllAsync("main=ignored", "es => es.filter(e => e).length")); + Assert.That(await Page.EvalOnSelectorAsync("main=ignored", "e => e.nodeName"), Is.EqualTo("SPAN")); + Assert.That(await Page.EvalOnSelectorAsync("css=div >> main=ignored", "e => e.nodeName"), Is.EqualTo("SPAN")); + Assert.That(await Page.EvalOnSelectorAllAsync("main=ignored", "es => window['__answer'] !== undefined"), Is.True); + Assert.That(await Page.EvalOnSelectorAllAsync("main=ignored", "es => es.filter(e => e).length"), Is.EqualTo(3)); - Assert.Null(await Page.QuerySelectorAsync("isolated=ignored")); - Assert.Null(await Page.QuerySelectorAsync("css=div >> isolated=ignored")); - Assert.True(await Page.EvalOnSelectorAllAsync("isolated=ignored", "es => window['__answer'] !== undefined")); - Assert.Equal(3, await Page.EvalOnSelectorAllAsync("isolated=ignored", "es => es.filter(e => e).length")); + Assert.That(await Page.QuerySelectorAsync("isolated=ignored"), Is.Null); + Assert.That(await Page.QuerySelectorAsync("css=div >> isolated=ignored"), Is.Null); + Assert.That(await Page.EvalOnSelectorAllAsync("isolated=ignored", "es => window['__answer'] !== undefined"), Is.True); + Assert.That(await Page.EvalOnSelectorAllAsync("isolated=ignored", "es => es.filter(e => e).length"), Is.EqualTo(3)); - Assert.Equal("SPAN", await Page.EvalOnSelectorAsync("main=ignored >> isolated=ignored", "e => e.nodeName")); - Assert.Equal("SPAN", await Page.EvalOnSelectorAsync("isolated=ignored >> main=ignored", "e => e.nodeName")); + Assert.That(await Page.EvalOnSelectorAsync("main=ignored >> isolated=ignored", "e => e.nodeName"), Is.EqualTo("SPAN")); + Assert.That(await Page.EvalOnSelectorAsync("isolated=ignored >> main=ignored", "e => e.nodeName"), Is.EqualTo("SPAN")); - Assert.Equal("SECTION", await Page.EvalOnSelectorAsync("main=ignored >> css=section", "e => e.nodeName")); + Assert.That(await Page.EvalOnSelectorAsync("main=ignored >> css=section", "e => e.nodeName"), Is.EqualTo("SECTION")); } [PlaywrightTest("selectors-register.spec.ts", "should handle errors")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHandleErrors() { - var exception = await Assert.ThrowsAnyAsync(() => Page.QuerySelectorAsync("neverregister=ignored")); - Assert.Contains("Unknown engine \"neverregister\" while parsing selector neverregister=ignored", exception.Message); + var exception = Assert.CatchAsync(() => Page.QuerySelectorAsync("neverregister=ignored")); + Assert.That(exception.Message, Does.Contain("Unknown engine \"neverregister\" while parsing selector neverregister=ignored")); const string createDummySelector = @"({ create(root, target) { @@ -104,17 +96,17 @@ public async Task ShouldHandleErrors() } })"; - exception = await Assert.ThrowsAnyAsync(() => Playwright.Selectors.RegisterAsync("$", createDummySelector)); - Assert.Contains("Selector engine name may only contain [a-zA-Z0-9_] characters", exception.Message); + exception = Assert.CatchAsync(() => Playwright.Selectors.RegisterAsync("$", createDummySelector)); + Assert.That(exception.Message, Does.Contain("Selector engine name may only contain [a-zA-Z0-9_] characters")); await TestUtils.RegisterEngineAsync(Playwright, "dummy", createDummySelector); await TestUtils.RegisterEngineAsync(Playwright, "duMMy", createDummySelector); - exception = await Assert.ThrowsAnyAsync(() => Playwright.Selectors.RegisterAsync("dummy", createDummySelector)); - Assert.Contains("\"dummy\" selector engine has been already registered", exception.Message); + exception = Assert.CatchAsync(() => Playwright.Selectors.RegisterAsync("dummy", createDummySelector)); + Assert.That(exception.Message, Does.Contain("\"dummy\" selector engine has been already registered")); - exception = await Assert.ThrowsAnyAsync(() => Playwright.Selectors.RegisterAsync("css", createDummySelector)); - Assert.Contains("\"css\" is a predefined selector engine", exception.Message); + exception = Assert.CatchAsync(() => Playwright.Selectors.RegisterAsync("css", createDummySelector)); + Assert.That(exception.Message, Does.Contain("\"css\" is a predefined selector engine")); } } } diff --git a/src/Playwright.Tests/SelectorsTextTests.cs b/src/Playwright.Tests/SelectorsTextTests.cs index b01fbbb15e..6939237140 100644 --- a/src/Playwright.Tests/SelectorsTextTests.cs +++ b/src/Playwright.Tests/SelectorsTextTests.cs @@ -1,86 +1,78 @@ using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class SelectorsTextTests : PlaywrightSharpPageBaseTest - { - /// - public SelectorsTextTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("selectors-text.spec.ts", "query")] - [Fact(Skip = "We need to update this test", Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("selectors-text.spec.ts", "query")] + [Test, Ignore("We need to update this test")] public async Task Query() { await Page.SetContentAsync("
yo
ya
\nye
"); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("text=ya", "e => e.outerHTML")); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("text=\"ya\"", "e => e.outerHTML")); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("text=/^[ay]+$/", "e => e.outerHTML")); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("text=/Ya/i", "e => e.outerHTML")); - Assert.Equal("
\nye
", await Page.EvalOnSelectorAsync("text=ye", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("text=ya", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"ya\"", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.EvalOnSelectorAsync("text=/^[ay]+$/", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.EvalOnSelectorAsync("text=/Ya/i", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.EvalOnSelectorAsync("text=ye", "e => e.outerHTML"), Is.EqualTo("
\nye
")); await Page.SetContentAsync("
ye
ye
"); - Assert.Equal("
ye
", await Page.EvalOnSelectorAsync("text=\"ye\"", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"ye\"", "e => e.outerHTML"), Is.EqualTo("
ye
")); await Page.SetContentAsync("
yo
\"ya
hello world!
"); - Assert.Equal("
\"ya
", await Page.EvalOnSelectorAsync("text=\"\\\"ya\"", "e => e.outerHTML")); - Assert.Equal("
hello world!
", await Page.EvalOnSelectorAsync("text=/hello/", "e => e.outerHTML")); - Assert.Equal("
hello world!
", await Page.EvalOnSelectorAsync("text=/^\\s*heLLo/i", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"\\\"ya\"", "e => e.outerHTML"), Is.EqualTo("
\"ya
")); + Assert.That(await Page.EvalOnSelectorAsync("text=/hello/", "e => e.outerHTML"), Is.EqualTo("
hello world!
")); + Assert.That(await Page.EvalOnSelectorAsync("text=/^\\s*heLLo/i", "e => e.outerHTML"), Is.EqualTo("
hello world!
")); await Page.SetContentAsync("
yo
ya
hey
hey
"); - Assert.Equal("
yo
ya
hey
hey
", await Page.EvalOnSelectorAsync("text=hey", "e => e.outerHTML")); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("text=\"yo\" >> text =\"ya\"", "e => e.outerHTML")); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("text='yo' >> text =\"ya\"", "e => e.outerHTML")); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("text=\"yo\" >> text='ya'", "e => e.outerHTML")); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("text='yo' >> text='ya'", "e => e.outerHTML")); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("'yo' >> \"ya\"", "e => e.outerHTML")); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("\"yo\" >> 'ya'", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("text=hey", "e => e.outerHTML"), Is.EqualTo("
yo
ya
hey
hey
")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"yo\" >> text =\"ya\"", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.EvalOnSelectorAsync("text='yo' >> text =\"ya\"", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"yo\" >> text='ya'", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.EvalOnSelectorAsync("text='yo' >> text='ya'", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.EvalOnSelectorAsync("'yo' >> \"ya\"", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.EvalOnSelectorAsync("\"yo\" >> 'ya'", "e => e.outerHTML"), Is.EqualTo("
ya
")); await Page.SetContentAsync("
yo
yo
"); - Assert.Equal("
yo
\n
yo
", await Page.EvalOnSelectorAllAsync("text=yo", "es => es.map(e => e.outerHTML).join('\\n')")); + Assert.That(await Page.EvalOnSelectorAllAsync("text=yo", "es => es.map(e => e.outerHTML).join('\\n')"), Is.EqualTo("
yo
\n
yo
")); await Page.SetContentAsync("
'
\"
\\
x
"); - Assert.Equal("
\'
", await Page.EvalOnSelectorAsync("text='\\''", "e => e.outerHTML")); - Assert.Equal("
\"
", await Page.EvalOnSelectorAsync("text='\"'", "e => e.outerHTML")); - Assert.Equal("
\"
", await Page.EvalOnSelectorAsync("text=\"\\\"\"", "e => e.outerHTML")); - Assert.Equal("
\'
", await Page.EvalOnSelectorAsync("text=\"'\"", "e => e.outerHTML")); - Assert.Equal("
x
", await Page.EvalOnSelectorAsync("text=\"\\x\"", "e => e.outerHTML")); - Assert.Equal("
x
", await Page.EvalOnSelectorAsync("text='\\x'", "e => e.outerHTML")); - Assert.Equal("
\\
", await Page.EvalOnSelectorAsync("text='\\\\'", "e => e.outerHTML")); - Assert.Equal("
\\
", await Page.EvalOnSelectorAsync("text=\"\\\\\"", "e => e.outerHTML")); - Assert.Equal("
\"
", await Page.EvalOnSelectorAsync("text=\"", "e => e.outerHTML")); - Assert.Equal("
\'
", await Page.EvalOnSelectorAsync("text='", "e => e.outerHTML")); - Assert.Equal("
x
", await Page.EvalOnSelectorAsync("\"x\"", "e => e.outerHTML")); - Assert.Equal("
x
", await Page.EvalOnSelectorAsync("'x'", "e => e.outerHTML")); - - await Assert.ThrowsAnyAsync(() => Page.QuerySelectorAsync("\"")); - await Assert.ThrowsAnyAsync(() => Page.QuerySelectorAsync("'")); + Assert.That(await Page.EvalOnSelectorAsync("text='\\''", "e => e.outerHTML"), Is.EqualTo("
\'
")); + Assert.That(await Page.EvalOnSelectorAsync("text='\"'", "e => e.outerHTML"), Is.EqualTo("
\"
")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"\\\"\"", "e => e.outerHTML"), Is.EqualTo("
\"
")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"'\"", "e => e.outerHTML"), Is.EqualTo("
\'
")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"\\x\"", "e => e.outerHTML"), Is.EqualTo("
x
")); + Assert.That(await Page.EvalOnSelectorAsync("text='\\x'", "e => e.outerHTML"), Is.EqualTo("
x
")); + Assert.That(await Page.EvalOnSelectorAsync("text='\\\\'", "e => e.outerHTML"), Is.EqualTo("
\\
")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"\\\\\"", "e => e.outerHTML"), Is.EqualTo("
\\
")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"", "e => e.outerHTML"), Is.EqualTo("
\"
")); + Assert.That(await Page.EvalOnSelectorAsync("text='", "e => e.outerHTML"), Is.EqualTo("
\'
")); + Assert.That(await Page.EvalOnSelectorAsync("\"x\"", "e => e.outerHTML"), Is.EqualTo("
x
")); + Assert.That(await Page.EvalOnSelectorAsync("'x'", "e => e.outerHTML"), Is.EqualTo("
x
")); + + Assert.CatchAsync(() => Page.QuerySelectorAsync("\"")); + Assert.CatchAsync(() => Page.QuerySelectorAsync("'")); await Page.SetContentAsync("
'
\"
"); - Assert.Equal("
\"
", await Page.EvalOnSelectorAsync("text=\"", "e => e.outerHTML")); - Assert.Equal("
\'
", await Page.EvalOnSelectorAsync("text='", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"", "e => e.outerHTML"), Is.EqualTo("
\"
")); + Assert.That(await Page.EvalOnSelectorAsync("text='", "e => e.outerHTML"), Is.EqualTo("
\'
")); await Page.SetContentAsync("
Hi''>>foo=bar
"); - Assert.Equal("
Hi''>>foo=bar
", await Page.EvalOnSelectorAsync("text=\"Hi''>>foo=bar\"", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"Hi''>>foo=bar\"", "e => e.outerHTML"), Is.EqualTo("
Hi''>>foo=bar
")); await Page.SetContentAsync("
Hi'\">>foo=bar
"); - Assert.Equal("
Hi'\">>foo=bar
", await Page.EvalOnSelectorAsync("text=\"Hi'\\\">>foo=bar\"", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"Hi'\\\">>foo=bar\"", "e => e.outerHTML"), Is.EqualTo("
Hi'\">>foo=bar
")); await Page.SetContentAsync("
Hi>>
"); - Assert.Equal("", await Page.EvalOnSelectorAsync("text=\"Hi>>\">>span", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("text=\"Hi>>\">>span", "e => e.outerHTML"), Is.EqualTo("")); await Page.SetContentAsync("
a
b
a
"); - Assert.Equal("
a
b
", await Page.EvalOnSelectorAsync("text=a", "e => e.outerHTML")); - Assert.Equal("
a
b
", await Page.EvalOnSelectorAsync("text=b", "e => e.outerHTML")); - Assert.Null(await Page.QuerySelectorAsync("text=ab")); - Assert.Equal(2, await Page.EvalOnSelectorAllAsync("text=a", "els => els.length")); - Assert.Equal(1, await Page.EvalOnSelectorAllAsync("text=b", "els => els.length")); - Assert.Equal(0, await Page.EvalOnSelectorAllAsync("text=ab", "els => els.length")); + Assert.That(await Page.EvalOnSelectorAsync("text=a", "e => e.outerHTML"), Is.EqualTo("
a
b
")); + Assert.That(await Page.EvalOnSelectorAsync("text=b", "e => e.outerHTML"), Is.EqualTo("
a
b
")); + Assert.That(await Page.QuerySelectorAsync("text=ab"), Is.Null); + Assert.That(await Page.EvalOnSelectorAllAsync("text=a", "els => els.length"), Is.EqualTo(2)); + Assert.That(await Page.EvalOnSelectorAllAsync("text=b", "els => els.length"), Is.EqualTo(1)); + Assert.That(await Page.EvalOnSelectorAllAsync("text=ab", "els => els.length"), Is.EqualTo(0)); await Page.SetContentAsync("
"); await Page.EvalOnSelectorAsync("div", @"div => @@ -94,36 +86,36 @@ await Page.EvalOnSelectorAsync("span", @"span => span.appendChild(document.createTextNode('hello')); span.appendChild(document.createTextNode('world')); }"); - Assert.Equal("
helloworld
", await Page.EvalOnSelectorAsync("text=lowo", "e => e.outerHTML")); - Assert.Equal("
helloworld
helloworld", await Page.EvalOnSelectorAllAsync("text=lowo", "els => els.map(e => e.outerHTML).join('')")); + Assert.That(await Page.EvalOnSelectorAsync("text=lowo", "e => e.outerHTML"), Is.EqualTo("
helloworld
")); + Assert.That(await Page.EvalOnSelectorAllAsync("text=lowo", "els => els.map(e => e.outerHTML).join('')"), Is.EqualTo("
helloworld
helloworld")); } [PlaywrightTest("selectors-text.spec.ts", "create")] - [Fact(Skip = "Skip Hooks")] + [Test, Ignore("Skip Hooks")] public void Create() { } [PlaywrightTest("selectors-text.spec.ts", "should be case sensitive if quotes are specified")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldBeCaseSensitiveIfQuotesAreSpecified() { await Page.SetContentAsync("
yo
ya
\nye
"); - Assert.Equal("
ya
", await Page.EvalOnSelectorAsync("text=ya", "e => e.outerHTML")); - Assert.Null(await Page.QuerySelectorAsync("text=\"yA\"")); + Assert.That(await Page.EvalOnSelectorAsync("text=ya", "e => e.outerHTML"), Is.EqualTo("
ya
")); + Assert.That(await Page.QuerySelectorAsync("text=\"yA\""), Is.Null); } [PlaywrightTest("selectors-text.spec.ts", "should search for a substring without quotes")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSearchForASubstringWithoutQuotes() { await Page.SetContentAsync("
textwithsubstring
"); - Assert.Equal("
textwithsubstring
", await Page.EvalOnSelectorAsync("text=with", "e => e.outerHTML")); - Assert.Null(await Page.QuerySelectorAsync("text=\"with\"")); + Assert.That(await Page.EvalOnSelectorAsync("text=with", "e => e.outerHTML"), Is.EqualTo("
textwithsubstring
")); + Assert.That(await Page.QuerySelectorAsync("text=\"with\""), Is.Null); } [PlaywrightTest("selectors-text.spec.ts", "should skip head, script and style")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSkipHeadScriptAndStyle() { await Page.SetContentAsync(@" @@ -145,44 +137,44 @@ await Page.SetContentAsync(@" foreach (string text in new[] { "title", "script", "style" }) { - Assert.Equal("DIV", await Page.EvalOnSelectorAsync($"text={text}", "e => e.nodeName")); - Assert.Equal("DIV", await Page.EvalOnSelectorAllAsync($"text={text}", "els => els.map(e => e.nodeName).join('|')")); + Assert.That(await Page.EvalOnSelectorAsync($"text={text}", "e => e.nodeName"), Is.EqualTo("DIV")); + Assert.That(await Page.EvalOnSelectorAllAsync($"text={text}", "els => els.map(e => e.nodeName).join('|')"), Is.EqualTo("DIV")); foreach (var root in new[] { head, title, script, style }) { - Assert.Null(await root.QuerySelectorAsync($"text={text}")); - Assert.Equal(0, await root.EvalOnSelectorAllAsync($"text={text}", "els => els.length")); + Assert.That(await root.QuerySelectorAsync($"text={text}"), Is.Null); + Assert.That(await root.EvalOnSelectorAllAsync($"text={text}", "els => els.length"), Is.EqualTo(0)); } } } [PlaywrightTest("selectors-text.spec.ts", "should match input[type=button|submit]")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldMatchInputTypeButtonSubmit() { await Page.SetContentAsync(""); - Assert.Equal("", await Page.EvalOnSelectorAsync("text=hello", "e => e.outerHTML")); - Assert.Equal("", await Page.EvalOnSelectorAsync("text=world", "e => e.outerHTML")); + Assert.That(await Page.EvalOnSelectorAsync("text=hello", "e => e.outerHTML"), Is.EqualTo("")); + Assert.That(await Page.EvalOnSelectorAsync("text=world", "e => e.outerHTML"), Is.EqualTo("")); } [PlaywrightTest("selectors-text.spec.ts", "should work for open shadow roots")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkForOpenShadowRoots() { await Page.GoToAsync(TestConstants.ServerUrl + "/deep-shadow.html"); - Assert.Equal("Hello from root1", await Page.EvalOnSelectorAsync("text=root1", "e => e.textContent")); - Assert.Equal("Hello from root2", await Page.EvalOnSelectorAsync("text=root2", "e => e.textContent")); - Assert.Equal("Hello from root3", await Page.EvalOnSelectorAsync("text=root3", "e => e.textContent")); - Assert.Equal("Hello from root3", await Page.EvalOnSelectorAsync("#root1 >> text=from root3", "e => e.textContent")); - Assert.Equal("Hello from root2", await Page.EvalOnSelectorAsync("#target >> text=from root2", "e => e.textContent")); - - Assert.Null(await Page.QuerySelectorAsync("text:light=root1")); - Assert.Null(await Page.QuerySelectorAsync("text:light=root2")); - Assert.Null(await Page.QuerySelectorAsync("text:light=root3")); + Assert.That(await Page.EvalOnSelectorAsync("text=root1", "e => e.textContent"), Is.EqualTo("Hello from root1")); + Assert.That(await Page.EvalOnSelectorAsync("text=root2", "e => e.textContent"), Is.EqualTo("Hello from root2")); + Assert.That(await Page.EvalOnSelectorAsync("text=root3", "e => e.textContent"), Is.EqualTo("Hello from root3")); + Assert.That(await Page.EvalOnSelectorAsync("#root1 >> text=from root3", "e => e.textContent"), Is.EqualTo("Hello from root3")); + Assert.That(await Page.EvalOnSelectorAsync("#target >> text=from root2", "e => e.textContent"), Is.EqualTo("Hello from root2")); + + Assert.That(await Page.QuerySelectorAsync("text:light=root1"), Is.Null); + Assert.That(await Page.QuerySelectorAsync("text:light=root2"), Is.Null); + Assert.That(await Page.QuerySelectorAsync("text:light=root3"), Is.Null); } [PlaywrightTest("selectors-text.spec.ts", "should prioritize light dom over shadow dom in the same parent")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldPrioritizeLightDomOverShadowDomInTheSameParent() { await Page.EvaluateAsync(@" @@ -199,11 +191,11 @@ await Page.EvaluateAsync(@" div.appendChild(lightSpan); "); - Assert.Equal("Hello from light", await Page.EvalOnSelectorAsync("div >> text=Hello", "e => e.textContent")); + Assert.That(await Page.EvalOnSelectorAsync("div >> text=Hello", "e => e.textContent"), Is.EqualTo("Hello from light")); } [PlaywrightTest("selectors-text.spec.ts", "should waitForSelector with distributed elements")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForSelectorWithDistributedElements() { var task = Page.WaitForSelectorAsync("div >> text=Hello"); @@ -223,7 +215,7 @@ await Page.EvaluateAsync(@" "); var handle = await task; - Assert.Equal("Hello from light", await handle.TextContentAsync()); + Assert.That(await handle.TextContentAsync(), Is.EqualTo("Hello from light")); } } } diff --git a/src/Playwright.Tests/TapTests.cs b/src/Playwright.Tests/TapTests.cs index d6c527940b..301b943f2b 100644 --- a/src/Playwright.Tests/TapTests.cs +++ b/src/Playwright.Tests/TapTests.cs @@ -23,32 +23,24 @@ */ using System.Text.Json; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { /// tap.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public sealed class TapTests : PlaywrightSharpPageBaseTest { /// - public TapTests(ITestOutputHelper output) : - base(output) + public override async Task ContextSetUp() { - } - - /// - public override async Task InitializeAsync() - { - await base.InitializeAsync(); + await base.ContextSetUp(); Page = await Browser.NewPageAsync(hasTouch: true); } [PlaywrightTest("tap.spec.ts", "should send all of the correct events")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendAllOfTheCorrectEvents() { await Page.SetContentAsync( @@ -61,7 +53,7 @@ await Page.SetContentAsync( string[] result = await handle.JsonValueAsync(); - Assert.Equal(result, new string[] + Assert.That(new string[] { "pointerover", "pointerenter", "pointerdown", "touchstart", @@ -70,11 +62,11 @@ await Page.SetContentAsync( "mouseover", "mouseenter", "mousemove", "mousedown", "mouseup", "click", - }); + }, Is.EqualTo(result)); } [PlaywrightTest("tap.spec.ts", "should not send mouse events touchstart is canceled")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotSendMouseEventsTouchStartIsCanceled() { await Page.SetContentAsync(@"
a
"); @@ -88,17 +80,17 @@ await Page.EvaluateAsync( string[] result = await handle.JsonValueAsync(); - Assert.Equal(result, new string[] + Assert.That(new string[] { "pointerover", "pointerenter", "pointerdown", "touchstart", "pointerup", "pointerout", "pointerleave", "touchend", - }); + }, Is.EqualTo(result)); } [PlaywrightTest("tap.spec.ts", "should not send mouse events when touchend is canceled")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldNotSendMouseEventsWhenTouchEndIsCanceled() { await Page.SetContentAsync(@"
a
"); @@ -112,17 +104,17 @@ await Page.EvaluateAsync( string[] result = await handle.JsonValueAsync(); - Assert.Equal(result, new string[] + Assert.That(new string[] { "pointerover", "pointerenter", "pointerdown", "touchstart", "pointerup", "pointerout", "pointerleave", "touchend", - }); + }, Is.EqualTo(result)); } [PlaywrightTest("tap.spec.ts", "should wait for a navigation caused by a tap")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitForANavigationCausedByATap() { var requestResponse = new TaskCompletionSource(); @@ -139,20 +131,20 @@ public async Task ShouldWaitForANavigationCausedByATap() var awaitTask = Page.TapAsync("a").ContinueWith(_ => { // this shouldn't happen before the request is called - Assert.True(requestResponse.Task.IsCompleted); + Assert.That(requestResponse.Task.IsCompleted, Is.True); // and make sure this hasn't been set - Assert.False(loaded); + Assert.That(loaded, Is.False); loaded = true; }); await awaitTask; await requestResponse.Task; - Assert.True(loaded); + Assert.That(loaded, Is.True); } [PlaywrightTest("tap.spec.ts", "should work with modifiers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWorkWithModifiers() { await Page.SetContentAsync("hello world"); @@ -166,11 +158,11 @@ public async Task ShouldWorkWithModifiers() await Page.EvaluateAsync("() => void 0"); await Page.TapAsync("body", modifiers: new[] { KeyboardModifier.Alt }); - Assert.True((await altKeyTask)); + Assert.That((await altKeyTask), Is.True); } [PlaywrightTest("tap.spec.ts", "should send well formed touch points")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldSendWellFormedTouchPoints() { var touchStartTask = Page.EvaluateAsync(@"() => @@ -213,20 +205,20 @@ public async Task ShouldSendWellFormedTouchPoints() var touchStartResult = (await touchStartTask)[0]; var touchEndResult = await touchEndTask; - Assert.Null(touchEndResult); - Assert.Equal(40, touchStartResult.clientX); - Assert.Equal(60, touchStartResult.clientY); - Assert.Equal(1, touchStartResult.force); - Assert.Equal(0, touchStartResult.identifier); - Assert.Equal(40, touchStartResult.pageX); - Assert.Equal(60, touchStartResult.pageY); - Assert.Equal(1, touchStartResult.radiusX); - Assert.Equal(1, touchStartResult.radiusY); - Assert.Equal(0, touchStartResult.rotationAngle); + Assert.That(touchEndResult, Is.Null); + Assert.That(touchStartResult.clientX, Is.EqualTo(40)); + Assert.That(touchStartResult.clientY, Is.EqualTo(60)); + Assert.That(touchStartResult.force, Is.EqualTo(1)); + Assert.That(touchStartResult.identifier, Is.EqualTo(0)); + Assert.That(touchStartResult.pageX, Is.EqualTo(40)); + Assert.That(touchStartResult.pageY, Is.EqualTo(60)); + Assert.That(touchStartResult.radiusX, Is.EqualTo(1)); + Assert.That(touchStartResult.radiusY, Is.EqualTo(1)); + Assert.That(touchStartResult.rotationAngle, Is.EqualTo(0)); } [PlaywrightTest("tap.spec.ts", "should wait until an element is visible to tap it")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldWaitUntilAnElementIsVisibleToTapIt() { var div = (IElementHandle)await Page.EvaluateHandleAsync(@"() => { @@ -244,7 +236,7 @@ public async Task ShouldWaitUntilAnElementIsVisibleToTapIt() await tapTask; - Assert.Equal("clicked", await div.TextContentAsync()); + Assert.That(await div.TextContentAsync(), Is.EqualTo("clicked")); } private async Task TrackEventsAsync(string selector) diff --git a/src/Playwright.Tests/TestConstants.cs b/src/Playwright.Tests/TestConstants.cs index ab40ed9d32..5ced3543be 100644 --- a/src/Playwright.Tests/TestConstants.cs +++ b/src/Playwright.Tests/TestConstants.cs @@ -4,8 +4,6 @@ using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Microsoft.Playwright.Tests.Helpers; - namespace Microsoft.Playwright.Tests { internal static class TestConstants @@ -20,8 +18,6 @@ internal static class TestConstants public static string Product => string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PRODUCT")) ? ChromiumProduct : Environment.GetEnvironmentVariable("PRODUCT"); - - public const string TestFixtureBrowserCollectionName = "PlaywrightBrowserLoaderFixture collection"; public const int Port = 8081; public const int HttpsPort = Port + 1; public const string ServerUrl = "http://localhost:8081"; diff --git a/src/Playwright.Tests/TestUtils.cs b/src/Playwright.Tests/TestUtils.cs index 75abc19e9d..25fb631fc9 100644 --- a/src/Playwright.Tests/TestUtils.cs +++ b/src/Playwright.Tests/TestUtils.cs @@ -2,7 +2,7 @@ using System.IO; using System.Text; using System.Threading.Tasks; -using Xunit; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { @@ -22,20 +22,20 @@ internal static void AssertSSLError(string errorMessage) { if (TestConstants.IsChromium) { - Assert.Contains("net::ERR_CERT_AUTHORITY_INVALID", errorMessage); + Assert.That(errorMessage, Does.Contain("net::ERR_CERT_AUTHORITY_INVALID")); } else if (TestConstants.IsWebKit) { if (TestConstants.IsMacOSX) - Assert.Contains("The certificate for this server is invalid", errorMessage); + Assert.That(errorMessage, Does.Contain("The certificate for this server is invalid")); else if (TestConstants.IsWindows) - Assert.Contains("SSL peer certificate or SSH remote key was not OK", errorMessage); + Assert.That(errorMessage, Does.Contain("SSL peer certificate or SSH remote key was not OK")); else - Assert.Contains("Unacceptable TLS certificate", errorMessage); + Assert.That(errorMessage, Does.Contain("Unacceptable TLS certificate")); } else { - Assert.Contains("SSL_ERROR_UNKNOWN", errorMessage); + Assert.That(errorMessage, Does.Contain("SSL_ERROR_UNKNOWN")); } } @@ -94,10 +94,10 @@ internal static async Task RegisterEngineWithPathAsync(IPlaywright playwright, s internal static async Task VerifyViewportAsync(IPage page, int width, int height) { - Assert.Equal(width, (int)page.ViewportSize.Width); - Assert.Equal(height, (int)page.ViewportSize.Height); - Assert.Equal(width, await page.EvaluateAsync("window.innerWidth")); - Assert.Equal(height, await page.EvaluateAsync("window.innerHeight")); + Assert.That((int)page.ViewportSize.Width, Is.EqualTo(width)); + Assert.That((int)page.ViewportSize.Height, Is.EqualTo(height)); + Assert.That(await page.EvaluateAsync("window.innerWidth"), Is.EqualTo(width)); + Assert.That(await page.EvaluateAsync("window.innerHeight"), Is.EqualTo(height)); } internal static async Task RegisterEngineAsync(IPlaywright playwright, string name, string script, bool? contentScript = null) diff --git a/src/Playwright.Tests/WebSocketTests.cs b/src/Playwright.Tests/WebSocketTests.cs index 79c2838bef..32ddb0b515 100644 --- a/src/Playwright.Tests/WebSocketTests.cs +++ b/src/Playwright.Tests/WebSocketTests.cs @@ -3,24 +3,16 @@ using System.IO; using System.Threading.Tasks; using Microsoft.Playwright.Helpers; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { ///web-socket.spec.ts - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class WebSocketTests : PlaywrightSharpPageBaseTest - { - /// - public WebSocketTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("web-socket.spec.ts", "should work")] - [Fact] + { [PlaywrightTest("web-socket.spec.ts", "should work")] + [Test] public async Task ShouldWork() { string value = await Page.EvaluateAsync(@"port => { @@ -30,11 +22,11 @@ public async Task ShouldWork() ws.addEventListener('message', data => { ws.close(); cb(data.data); }); return result; }", TestConstants.Port); - Assert.Equal("incoming", value); + Assert.That(value, Is.EqualTo("incoming")); } [PlaywrightTest("web-socket.spec.ts", "should emit close events")] - [Fact] + [Test] public async Task ShouldEmitCloseEvents() { var socketClosedTcs = new TaskCompletionSource(); @@ -58,12 +50,12 @@ await Page.EvaluateAsync(@"port => { }", TestConstants.Port); await socketClosedTcs.Task.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.Equal($"open:close", string.Join(":", log)); - Assert.True(webSocket.IsClosed); + Assert.That(string.Join(":", log), Is.EqualTo($"open:close")); + Assert.That(webSocket.IsClosed, Is.True); } [PlaywrightTest("web-socket.spec.ts", "should emit frame events")] - [Fact] + [Test] public async Task ShouldEmitFrameEvents() { var socketClosedTcs = new TaskCompletionSource(); @@ -90,14 +82,14 @@ await Page.EvaluateAsync(@"port => { }", TestConstants.Port); await socketClosedTcs.Task.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.Equal("open", log[0]); - Assert.Equal("close", log[3]); + Assert.That(log[0], Is.EqualTo("open")); + Assert.That(log[3], Is.EqualTo("close")); log.Sort(); - Assert.Equal("close:open:received:sent", string.Join(":", log)); + Assert.That(string.Join(":", log), Is.EqualTo("close:open:received:sent")); } [PlaywrightTest("web-socket.spec.ts", "should emit binary frame events")] - [Fact] + [Test] public async Task ShouldEmitBinaryFrameEvents() { var socketClosedTcs = new TaskCompletionSource(); @@ -123,16 +115,16 @@ await Page.EvaluateAsync(@"port => { await socketClosedTcs.Task.WithTimeout(TestConstants.DefaultTaskTimeout); - Assert.Equal("text", log[0].Text); + Assert.That(log[0].Text, Is.EqualTo("text")); for (int i = 0; i < 5; i++) { - Assert.Equal(i, log[1].Binary[i]); + Assert.That(log[1].Binary[i], Is.EqualTo(i)); } } [PlaywrightTest("web-socket.spec.ts", "should emit error")] - [Fact] + [Test] public async Task ShouldEmitError() { var socketErrorTcs = new TaskCompletionSource(); @@ -152,16 +144,16 @@ await Page.EvaluateAsync(@"port => { if (TestConstants.IsFirefox) { - Assert.Equal("CLOSE_ABNORMAL", socketErrorTcs.Task.Result); + Assert.That(socketErrorTcs.Task.Result, Is.EqualTo("CLOSE_ABNORMAL")); } else { - Assert.Contains(": 40", socketErrorTcs.Task.Result); + Assert.That(socketErrorTcs.Task.Result, Does.Contain(": 40")); } } [PlaywrightTest("web-socket.spec.ts", "should not have stray error events")] - [Fact] + [Test] public async Task ShouldNotHaveStrayErrorEvents() { var frameReceivedTcs = new TaskCompletionSource(); @@ -182,11 +174,11 @@ await TaskUtils.WhenAll( }", TestConstants.Port)); await Page.EvaluateAsync("window.ws.close();"); - Assert.Null(socketError); + Assert.That(socketError, Is.Null); } [PlaywrightTest("web-socket.spec.ts", "should reject waitForEvent on socket close")] - [Fact] + [Test] public async Task ShouldRejectWaitForEventOnSocketClose() { var frameReceivedTcs = new TaskCompletionSource(); @@ -207,12 +199,12 @@ await TaskUtils.WhenAll( await frameReceivedTcs.Task; var frameSentTask = ws.WaitForEventAsync(WebSocketEvent.FrameSent); await Page.EvaluateAsync("window.ws.close()"); - var exception = await Assert.ThrowsAnyAsync(() => frameSentTask); - Assert.Contains("Socket closed", exception.Message); + var exception = Assert.CatchAsync(() => frameSentTask); + Assert.That(exception.Message, Does.Contain("Socket closed")); } [PlaywrightTest("web-socket.spec.ts", "should reject waitForEvent on page close")] - [Fact] + [Test] public async Task ShouldRejectWaitForEventOnPageClose() { var frameReceivedTcs = new TaskCompletionSource(); @@ -232,8 +224,8 @@ await TaskUtils.WhenAll( var frameSentTask = ws.WaitForEventAsync(WebSocketEvent.FrameSent); await Page.CloseAsync(); - var exception = await Assert.ThrowsAnyAsync(() => frameSentTask.WithTimeout(TestConstants.DefaultTaskTimeout)); - Assert.Contains("Page closed", exception.Message); + var exception = Assert.CatchAsync(() => frameSentTask.WithTimeout(TestConstants.DefaultTaskTimeout)); + Assert.That(exception.Message, Does.Contain("Page closed")); } } } diff --git a/src/Playwright.Tests/WorkersTests.cs b/src/Playwright.Tests/WorkersTests.cs index 2b8bafdeff..2e0ae1aadc 100644 --- a/src/Playwright.Tests/WorkersTests.cs +++ b/src/Playwright.Tests/WorkersTests.cs @@ -2,39 +2,31 @@ using System.Linq; using System.Text.Json; using System.Threading.Tasks; -using Microsoft.Playwright.Testing.Xunit; +using Microsoft.Playwright.Nunit; using Microsoft.Playwright.Tests.BaseTests; -using Xunit; -using Xunit.Abstractions; +using NUnit.Framework; namespace Microsoft.Playwright.Tests { - [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class WorkersTests : PlaywrightSharpPageBaseTest - { - /// - public WorkersTests(ITestOutputHelper output) : base(output) - { - } - - [PlaywrightTest("workers.spec.ts", "Page.workers")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + { [PlaywrightTest("workers.spec.ts", "Page.workers")] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task PageWorkers() { await TaskUtils.WhenAll( Page.WaitForEventAsync(PageEvent.Worker), Page.GoToAsync(TestConstants.ServerUrl + "/worker/worker.html")); var worker = Page.Workers.First(); - Assert.Contains("worker.js", worker.Url); + Assert.That(worker.Url, Does.Contain("worker.js")); - Assert.Equal("worker function result", await worker.EvaluateAsync("() => self['workerFunction']()")); + Assert.That(await worker.EvaluateAsync("() => self['workerFunction']()"), Is.EqualTo("worker function result")); await Page.GoToAsync(TestConstants.EmptyPage); - Assert.Empty(Page.Workers); + Assert.That(Page.Workers, Is.Empty); } [PlaywrightTest("workers.spec.ts", "should emit created and destroyed events")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEmitCreatedAndDestroyedEvents() { var workerCreatedTcs = new TaskCompletionSource(); @@ -46,13 +38,13 @@ public async Task ShouldEmitCreatedAndDestroyedEvents() var workerDestroyedTcs = new TaskCompletionSource(); worker.Close += (sender, _) => workerDestroyedTcs.TrySetResult((IWorker)sender); await Page.EvaluateAsync("workerObj => workerObj.terminate()", workerObj); - Assert.Same(worker, await workerDestroyedTcs.Task); - var exception = await Assert.ThrowsAnyAsync(() => workerThisObj.GetPropertyAsync("self")); - Assert.Contains("Most likely the worker has been closed.", exception.Message); + Assert.That(await workerDestroyedTcs.Task, Is.SameAs(worker)); + var exception = Assert.CatchAsync(() => workerThisObj.GetPropertyAsync("self")); + Assert.That(exception.Message, Does.Contain("Most likely the worker has been closed.")); } [PlaywrightTest("workers.spec.ts", "should report console logs")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportConsoleLogs() { var (message, _) = await TaskUtils.WhenAll( @@ -60,11 +52,11 @@ public async Task ShouldReportConsoleLogs() Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))") ); - Assert.Equal("1", message.Text); + Assert.That(message.Text, Is.EqualTo("1")); } [PlaywrightTest("workers.spec.ts", "should have JSHandles for console logs")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldHaveJSHandlesForConsoleLogs() { var consoleTcs = new TaskCompletionSource(); @@ -72,25 +64,25 @@ public async Task ShouldHaveJSHandlesForConsoleLogs() await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1,2,3,this)'], {type: 'application/javascript'})))"); var log = await consoleTcs.Task; - Assert.Equal("1 2 3 JSHandle@object", log.Text); - Assert.Equal(4, log.Args.Count()); + Assert.That(log.Text, Is.EqualTo("1 2 3 JSHandle@object")); + Assert.That(log.Args.Count(), Is.EqualTo(4)); string json = await (await log.Args.ElementAt(3).GetPropertyAsync("origin")).JsonValueAsync(); - Assert.Equal("null", json); + Assert.That(json, Is.EqualTo("null")); } [PlaywrightTest("workers.spec.ts", "should evaluate")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldEvaluate() { var workerCreatedTask = Page.WaitForEventAsync(PageEvent.Worker); await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))"); await workerCreatedTask; - Assert.Equal(2, await workerCreatedTask.Result.EvaluateAsync("1+1")); + Assert.That(await workerCreatedTask.Result.EvaluateAsync("1+1"), Is.EqualTo(2)); } [PlaywrightTest("workers.spec.ts", "should report errors")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportErrors() { var errorTcs = new TaskCompletionSource(); @@ -104,11 +96,11 @@ public async Task ShouldReportErrors() }) `], {type: 'application/javascript'})))"); string errorLog = await errorTcs.Task; - Assert.Contains("this is my error", errorLog); + Assert.That(errorLog, Does.Contain("this is my error")); } [PlaywrightTest("workers.spec.ts", "should clear upon navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClearUponNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -116,16 +108,16 @@ public async Task ShouldClearUponNavigation() await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))"); var worker = await workerCreatedTask; - Assert.Single(Page.Workers); + Assert.That(Page.Workers, Has.Count.EqualTo(1)); bool destroyed = false; worker.Close += (_, _) => destroyed = true; await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); - Assert.True(destroyed); - Assert.Empty(Page.Workers); + Assert.That(destroyed, Is.True); + Assert.That(Page.Workers, Is.Empty); } - [Fact] + [Test] public async Task WorkerShouldWaitOnClose() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -133,15 +125,15 @@ public async Task WorkerShouldWaitOnClose() await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))"); var worker = await workerCreatedTask; - Assert.Single(Page.Workers); + Assert.That(Page.Workers, Has.Count.EqualTo(1)); var t = worker.WaitForCloseAsync(); await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); await t; - Assert.Empty(Page.Workers); + Assert.That(Page.Workers, Is.Empty); } - [Fact] + [Test] public async Task WorkerShouldFailOnTimeout() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -149,16 +141,16 @@ public async Task WorkerShouldFailOnTimeout() await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))"); var worker = await workerCreatedTask; - Assert.Single(Page.Workers); + Assert.That(Page.Workers, Has.Count.EqualTo(1)); var t = worker.WaitForCloseAsync(1); await Task.Delay(100); await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html"); - await Assert.ThrowsAsync(async () => await t); + Assert.ThrowsAsync(async () => await t); } [PlaywrightTest("workers.spec.ts", "should clear upon cross-process navigation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldClearUponCrossProcessNavigation() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -166,17 +158,17 @@ public async Task ShouldClearUponCrossProcessNavigation() await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))"); var worker = await workerCreatedTask; - Assert.Single(Page.Workers); + Assert.That(Page.Workers, Has.Count.EqualTo(1)); bool destroyed = false; worker.Close += (_, _) => destroyed = true; await Page.GoToAsync(TestConstants.CrossProcessUrl + "/empty.html"); - Assert.True(destroyed); - Assert.Empty(Page.Workers); + Assert.That(destroyed, Is.True); + Assert.That(Page.Workers, Is.Empty); } [PlaywrightTest("workers.spec.ts", "should report network activity")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportNetworkActivity() { var (worker, _) = await TaskUtils.WhenAll( @@ -192,13 +184,13 @@ public async Task ShouldReportNetworkActivity() await TaskUtils.WhenAll(requestTask, responseTask); - Assert.Equal(url, requestTask.Result.Url); - Assert.Equal(requestTask.Result, responseTask.Result.Request); - Assert.True(responseTask.Result.Ok); + Assert.That(requestTask.Result.Url, Is.EqualTo(url)); + Assert.That(responseTask.Result.Request, Is.EqualTo(requestTask.Result)); + Assert.That(responseTask.Result.Ok, Is.True); } [PlaywrightTest("workers.spec.ts", "should report network activity on worker creation")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldReportNetworkActivityOnWorkerCreation() { await Page.GoToAsync(TestConstants.EmptyPage); @@ -213,13 +205,13 @@ public async Task ShouldReportNetworkActivityOnWorkerCreation() await TaskUtils.WhenAll(requestTask, responseTask); - Assert.Equal(url, requestTask.Result.Url); - Assert.Equal(requestTask.Result, responseTask.Result.Request); - Assert.True(responseTask.Result.Ok); + Assert.That(requestTask.Result.Url, Is.EqualTo(url)); + Assert.That(responseTask.Result.Request, Is.EqualTo(requestTask.Result)); + Assert.That(responseTask.Result.Ok, Is.True); } [PlaywrightTest("workers.spec.ts", "should format number using context locale")] - [Fact(Timeout = TestConstants.DefaultTestTimeout)] + [Test, Timeout(TestConstants.DefaultTestTimeout)] public async Task ShouldFormatNumberUsingContextLocale() { await using var context = await Browser.NewContextAsync(new BrowserContextOptions { Locale = "ru-RU" }); @@ -229,7 +221,7 @@ public async Task ShouldFormatNumberUsingContextLocale() page.WaitForEventAsync(PageEvent.Worker), page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))")); - Assert.Equal("10\u00A0000,2", await worker.EvaluateAsync("() => (10000.20).toLocaleString()")); + Assert.That(await worker.EvaluateAsync("() => (10000.20).toLocaleString()"), Is.EqualTo("10\u00A0000,2")); } } } diff --git a/src/Playwright.Tests/xunit.runner.json b/src/Playwright.Tests/xunit.runner.json deleted file mode 100644 index c468fda9eb..0000000000 --- a/src/Playwright.Tests/xunit.runner.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", - "diagnosticMessages": true, - "parallelizeAssembly": false, - "maxParallelThreads": 1, - "longRunningTestSeconds": 5 -} \ No newline at end of file diff --git a/src/Playwright.sln b/src/Playwright.sln index a23ccf5693..8332f232a1 100644 --- a/src/Playwright.sln +++ b/src/Playwright.sln @@ -1,3 +1,4 @@ + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.29709.97 @@ -29,42 +30,102 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlaywrightSharpTool", "tool EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlaywrightSharp.Tooling", "tools\PlaywrightSharp.Tooling\PlaywrightSharp.Tooling.csproj", "{61C89FA2-645D-4D0E-9A20-06ABE32054CF}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Playwright.Testing.Xunit", "Playwright.Testing.Xunit\Playwright.Testing.Xunit.csproj", "{FEFC3D43-748A-4825-836F-462C9B9F7D78}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Playwright.Nunit", "Playwright.Nunit\Playwright.Nunit.csproj", "{8FF798AE-E43A-4525-8A8E-21CF7DD0E424}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Debug|x64.ActiveCfg = Debug|Any CPU + {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Debug|x64.Build.0 = Debug|Any CPU + {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Debug|x86.ActiveCfg = Debug|Any CPU + {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Debug|x86.Build.0 = Debug|Any CPU {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Release|Any CPU.ActiveCfg = Release|Any CPU {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Release|Any CPU.Build.0 = Release|Any CPU + {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Release|x64.ActiveCfg = Release|Any CPU + {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Release|x64.Build.0 = Release|Any CPU + {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Release|x86.ActiveCfg = Release|Any CPU + {A907B324-4541-4FAF-8CAE-D0B512B4BC36}.Release|x86.Build.0 = Release|Any CPU {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Debug|Any CPU.Build.0 = Debug|Any CPU + {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Debug|x64.ActiveCfg = Debug|Any CPU + {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Debug|x64.Build.0 = Debug|Any CPU + {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Debug|x86.ActiveCfg = Debug|Any CPU + {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Debug|x86.Build.0 = Debug|Any CPU {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Release|Any CPU.ActiveCfg = Release|Any CPU {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Release|Any CPU.Build.0 = Release|Any CPU + {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Release|x64.ActiveCfg = Release|Any CPU + {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Release|x64.Build.0 = Release|Any CPU + {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Release|x86.ActiveCfg = Release|Any CPU + {162425E9-A05E-4ECE-8DBE-5AEC68C5DD23}.Release|x86.Build.0 = Release|Any CPU {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Debug|x64.ActiveCfg = Debug|Any CPU + {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Debug|x64.Build.0 = Debug|Any CPU + {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Debug|x86.ActiveCfg = Debug|Any CPU + {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Debug|x86.Build.0 = Debug|Any CPU {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Release|Any CPU.ActiveCfg = Release|Any CPU {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Release|Any CPU.Build.0 = Release|Any CPU + {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Release|x64.ActiveCfg = Release|Any CPU + {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Release|x64.Build.0 = Release|Any CPU + {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Release|x86.ActiveCfg = Release|Any CPU + {EAB878F1-E9FE-4C0B-8DF5-AE58522F8D0A}.Release|x86.Build.0 = Release|Any CPU {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Debug|x64.ActiveCfg = Debug|Any CPU + {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Debug|x64.Build.0 = Debug|Any CPU + {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Debug|x86.ActiveCfg = Debug|Any CPU + {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Debug|x86.Build.0 = Debug|Any CPU {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Release|Any CPU.ActiveCfg = Release|Any CPU {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Release|Any CPU.Build.0 = Release|Any CPU + {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Release|x64.ActiveCfg = Release|Any CPU + {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Release|x64.Build.0 = Release|Any CPU + {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Release|x86.ActiveCfg = Release|Any CPU + {FB3348E3-9759-4B90-9C8C-391F44AD5F8F}.Release|x86.Build.0 = Release|Any CPU {795BA2A6-D983-4D96-B817-6921A145AB56}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {795BA2A6-D983-4D96-B817-6921A145AB56}.Debug|Any CPU.Build.0 = Debug|Any CPU + {795BA2A6-D983-4D96-B817-6921A145AB56}.Debug|x64.ActiveCfg = Debug|Any CPU + {795BA2A6-D983-4D96-B817-6921A145AB56}.Debug|x64.Build.0 = Debug|Any CPU + {795BA2A6-D983-4D96-B817-6921A145AB56}.Debug|x86.ActiveCfg = Debug|Any CPU + {795BA2A6-D983-4D96-B817-6921A145AB56}.Debug|x86.Build.0 = Debug|Any CPU {795BA2A6-D983-4D96-B817-6921A145AB56}.Release|Any CPU.ActiveCfg = Release|Any CPU {795BA2A6-D983-4D96-B817-6921A145AB56}.Release|Any CPU.Build.0 = Release|Any CPU + {795BA2A6-D983-4D96-B817-6921A145AB56}.Release|x64.ActiveCfg = Release|Any CPU + {795BA2A6-D983-4D96-B817-6921A145AB56}.Release|x64.Build.0 = Release|Any CPU + {795BA2A6-D983-4D96-B817-6921A145AB56}.Release|x86.ActiveCfg = Release|Any CPU + {795BA2A6-D983-4D96-B817-6921A145AB56}.Release|x86.Build.0 = Release|Any CPU {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Debug|x64.ActiveCfg = Debug|Any CPU + {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Debug|x64.Build.0 = Debug|Any CPU + {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Debug|x86.ActiveCfg = Debug|Any CPU + {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Debug|x86.Build.0 = Debug|Any CPU {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Release|Any CPU.ActiveCfg = Release|Any CPU {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Release|Any CPU.Build.0 = Release|Any CPU - {FEFC3D43-748A-4825-836F-462C9B9F7D78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FEFC3D43-748A-4825-836F-462C9B9F7D78}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FEFC3D43-748A-4825-836F-462C9B9F7D78}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FEFC3D43-748A-4825-836F-462C9B9F7D78}.Release|Any CPU.Build.0 = Release|Any CPU + {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Release|x64.ActiveCfg = Release|Any CPU + {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Release|x64.Build.0 = Release|Any CPU + {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Release|x86.ActiveCfg = Release|Any CPU + {61C89FA2-645D-4D0E-9A20-06ABE32054CF}.Release|x86.Build.0 = Release|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Debug|x64.ActiveCfg = Debug|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Debug|x64.Build.0 = Debug|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Debug|x86.ActiveCfg = Debug|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Debug|x86.Build.0 = Debug|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Release|Any CPU.Build.0 = Release|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Release|x64.ActiveCfg = Release|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Release|x64.Build.0 = Release|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Release|x86.ActiveCfg = Release|Any CPU + {8FF798AE-E43A-4525-8A8E-21CF7DD0E424}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE