Пример #1
0
        public async Task UserDataDirOptionShouldRestoreState()
        {
            using var userDataDir = new TempDirectory();
            var options = TestConstants.GetDefaultBrowserOptions();

            options.UserDataDir = userDataDir.Path;

            await using (var browser = await Playwright.LaunchAsync(options))
            {
                var page = await browser.DefaultContext.NewPageAsync();

                await page.GoToAsync(TestConstants.EmptyPage);

                await page.EvaluateAsync("localStorage.hey = 'hello'");

                await browser.CloseAsync();
            }

            await using (var browser2 = await Playwright.LaunchAsync(options))
            {
                var page2 = await browser2.DefaultContext.NewPageAsync();

                await page2.GoToAsync(TestConstants.EmptyPage);

                Assert.Equal("hello", await page2.EvaluateAsync <string>("localStorage.hey"));
            }

            await using (var browser3 = await Playwright.LaunchAsync(TestConstants.GetDefaultBrowserOptions()))
            {
                var page3 = await browser3.DefaultContext.NewPageAsync();

                await page3.GoToAsync(TestConstants.EmptyPage);
            }
        }
Пример #2
0
        public async Task ShouldBeAbleToSaveFile()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.Args            = options.Args.Prepend("--site-per-process").ToArray();
            await using var browser = await BrowserType.LaunchAsync(options);

            var page = await browser.DefaultContext.NewPageAsync();

            string outputFile = Path.Combine(BaseDirectory, "output.pdf");
            var    fileInfo   = new FileInfo(outputFile);

            if (fileInfo.Exists)
            {
                fileInfo.Delete();
            }
            await page.GetPdfAsync(outputFile);

            fileInfo = new FileInfo(outputFile);
            Assert.True(new FileInfo(outputFile).Length > 0);
            if (fileInfo.Exists)
            {
                fileInfo.Delete();
            }
        }
Пример #3
0
        public async Task ShouldBeAbleToReconnectToADisconnectedBrowser()
        {
            await using var browserServer = await BrowserType.LaunchServerAsync(TestConstants.GetDefaultBrowserOptions());

            await using var browser = await BrowserType.ConnectAsync(new ConnectOptions { WSEndpoint = browserServer.WSEndpoint });

            var context = await browser.NewContextAsync();

            var page = await context.NewPageAsync();

            await page.GoToAsync(TestConstants.EmptyPage);

            await browser.CloseAsync();

            await using var remote = await BrowserType.ConnectAsync(new ConnectOptions { WSEndpoint = browserServer.WSEndpoint });

            context = await remote.NewContextAsync();

            page = await context.NewPageAsync();

            await page.GoToAsync(TestConstants.EmptyPage);

            await remote.CloseAsync();

            await browserServer.CloseAsync();
        }
Пример #4
0
        public async Task ShouldExcludePatterns()
        {
            Server.SetRoute("/target.html", ctx => ctx.Response.WriteAsync("<html><title>Served by the proxy</title></html>"));

            var defaultBrowserOptions = TestConstants.GetDefaultBrowserOptions();

            defaultBrowserOptions.Proxy = new ProxySettings
            {
                Server = $"localhost:{TestConstants.Port}",
                Bypass = "******",
            };

            await using var browser = await BrowserType.LaunchAsync(defaultBrowserOptions);

            var page = await browser.NewPageAsync();

            await page.GoToAsync("http://non-existent.com/target.html");

            Assert.Equal("Served by the proxy", await page.GetTitleAsync());

            await Assert.ThrowsAnyAsync <PlaywrightSharpException>(() => page.GoToAsync("http://non-existent1.com/target.html"));

            await Assert.ThrowsAnyAsync <PlaywrightSharpException>(() => page.GoToAsync("http://sub.non-existent2.com/target.html"));

            await Assert.ThrowsAnyAsync <PlaywrightSharpException>(() => page.GoToAsync("http://foo.zone/target.html"));
        }
Пример #5
0
        public async Task ShouldTakeElementScreenshotWhenDefaultViewportIsNullAndRestoreBack()
        {
            await using var browser = await Playwright.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var page = await NewPageAsync(browser, new BrowserContextOptions { Viewport = null });

            await page.SetContentAsync(@"
                <div style=""height: 14px"">oooo</div>
                <style>
                div.to-screenshot {
                    border: 1px solid blue;
                    width: 600px;
                    height: 600px;
                    margin-left: 50px;
                }
                ::-webkit-scrollbar{
                    display: none;
                }
                </style>
                <div class=""to-screenshot""></div>
                <div class=""to-screenshot""></div>
                <div class=""to-screenshot""></div>
            ");

            var sizeBefore = await page.EvaluateAsync <Viewport>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");

            var elementHandle = await page.QuerySelectorAsync("div.to-screenshot");

            byte[] screenshot = await elementHandle.ScreenshotAsync();

            Assert.NotEmpty(screenshot);
            var sizeAfter = await page.EvaluateAsync <Viewport>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");

            Assert.Equal(sizeBefore, sizeAfter);
        }
Пример #6
0
        public async Task ShouldAuthenticate()
        {
            Server.SetRoute("/target.html", ctx =>
            {
                string auth = ctx.Request.Headers["proxy-authorization"];

                if (string.IsNullOrEmpty(auth))
                {
                    ctx.Response.StatusCode = 407;
                    ctx.Response.Headers["Proxy-Authenticate"] = "Basic realm=\"Access to internal site\"";
                }

                return(ctx.Response.WriteAsync($"<html><title>{auth}</title></html>"));
            });

            var defaultBrowserOptions = TestConstants.GetDefaultBrowserOptions();

            defaultBrowserOptions.Proxy = new ProxySettings
            {
                Server   = $"localhost:{TestConstants.Port}",
                Username = "******",
                Password = "******"
            };

            await using var browser = await BrowserType.LaunchAsync(defaultBrowserOptions);

            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.GetTitleAsync());
        }
Пример #7
0
        public async Task UserDataDirOptionShouldRestoreCookies()
        {
            using var userDataDir = new TempDirectory();
            var options = TestConstants.GetDefaultBrowserOptions();

            options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();

            using (var browser = await Playwright.LaunchAsync(options))
            {
                var page = await browser.DefaultContext.NewPageAsync();

                await page.GoToAsync(TestConstants.EmptyPage);

                await page.EvaluateAsync(
                    "document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");
            }

            using (var browser2 = await Playwright.LaunchAsync(options))
            {
                var page2 = await browser2.DefaultContext.NewPageAsync();

                await page2.GoToAsync(TestConstants.EmptyPage);

                Assert.Equal("doSomethingOnlyOnce=true", await page2.EvaluateAsync <string>("document.cookie"));
            }
        }
Пример #8
0
        public async Task ShouldRestoreDefaultViewportAfterFullPageScreenshot()
        {
            await using var browser = await Playwright.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var page = await NewPageAsync(browser, new BrowserContextOptions
            {
                Viewport = new Viewport
                {
                    Width  = 456,
                    Height = 789
                }
            });

            Assert.Equal(456, page.Viewport.Width);
            Assert.Equal(789, page.Viewport.Height);
            Assert.Equal(456, await page.EvaluateAsync <int>("window.innerWidth"));
            Assert.Equal(789, await page.EvaluateAsync <int>("window.innerHeight"));

            byte[] screenshot = await page.ScreenshotAsync(new ScreenshotOptions
            {
                FullPage = true
            });

            Assert.NotEmpty(screenshot);
            Assert.Equal(456, page.Viewport.Width);
            Assert.Equal(789, page.Viewport.Height);
            Assert.Equal(456, await page.EvaluateAsync <int>("window.innerWidth"));
            Assert.Equal(789, await page.EvaluateAsync <int>("window.innerHeight"));
        }
Пример #9
0
        public async Task ShouldBeAbleToReconnectToADisconnectedBrowser()
        {
            using var browserApp = await Playwright.LaunchBrowserAppAsync(TestConstants.GetDefaultBrowserOptions());

            using var browser = await Playwright.ConnectAsync(browserApp.ConnectOptions);

            string url  = TestConstants.ServerUrl + "/frames/nested-frames.html";
            var    page = await browser.DefaultContext.NewPageAsync();

            await page.GoToAsync(url);

            await browser.DisconnectAsync();

            using var remote = await Playwright.ConnectAsync(browserApp.ConnectOptions);

            var pages        = (await remote.DefaultContext.GetPagesAsync()).ToList();
            var restoredPage = pages.FirstOrDefault(x => x.Url == url);

            Assert.NotNull(restoredPage);
            var frameDump = FrameUtils.DumpFrames(restoredPage.MainFrame);

            Assert.Equal(TestConstants.NestedFramesDumpResult, frameDump);
            int response = await restoredPage.EvaluateAsync <int>("7 * 8");

            Assert.Equal(56, response);

            await remote.DisconnectAsync();
        }
Пример #10
0
        public async Task ShouldBeCallableTwice()
        {
            await using var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            await Task.WhenAll(browser.CloseAsync(), browser.CloseAsync());

            await browser.CloseAsync();
        }
Пример #11
0
        public async Task ShouldHaveDefaultUrlWhenLaunchingBrowser()
        {
            using var browser = await Playwright.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var pages = (await browser.DefaultContext.GetPagesAsync()).Select(page => page.Url);

            Assert.Equal(new[] { TestConstants.AboutBlank }, pages);
        }
        public async Task ShouldFireCloseEvent()
        {
            var tcs = new TaskCompletionSource <bool>();

            await using var browserServer = await BrowserType.LaunchServerAsync(TestConstants.GetDefaultBrowserOptions());

            browserServer.Closed += (sender, e) => tcs.TrySetResult(true);
            await Task.WhenAll(tcs.Task, browserServer.CloseAsync());
        }
Пример #13
0
        /// <inheritdoc/>
        public async Task InitializeAsync()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.Args = new[] { "--site-per-process" };
            _browser     = await BrowserType.LaunchAsync(options);

            _page = await _browser.NewPageAsync();
        }
        public async Task ShouldRejectIfExecutablePathIsInvalid()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.ExecutablePath = "random-invalid-path";

            var exception = await Assert.ThrowsAsync <PlaywrightSharpException>(() => BrowserType.LaunchAsync(options));

            Assert.Contains("Failed to launch", exception.Message);
        }
        public async Task ShouldThrowIfUserDataDirOptionIsPassed()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.UserDataDir = "random-invalid-path";

            var exception = await Assert.ThrowsAsync <PlaywrightSharpException>(() => BrowserType.LaunchAsync(options));

            Assert.Contains("launchPersistentContext", exception.Message);
        }
Пример #16
0
        public async Task ShouldHaveDefaultContext()
        {
            await using var browser = await Playwright.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            Assert.Single(browser.BrowserContexts);
            var defaultContext = browser.BrowserContexts.First();
            var exception      = await Assert.ThrowsAsync <PlaywrightSharpException>(defaultContext.CloseAsync);

            Assert.Same(defaultContext, browser.DefaultContext);
            Assert.Contains("cannot be closed", exception.Message);
        }
Пример #17
0
        private async Task <(TempDirectory tmp, IBrowserContext context, IPage page)> LaunchAsync(BrowserContextOptions options = null)
        {
            var tmp     = new TempDirectory();
            var context = await BrowserType.LaunchPersistentContextAsync(
                tmp.Path,
                TestConstants.GetDefaultBrowserOptions().ToPersistentOptions() + (options ?? new BrowserContextOptions()));

            var page = context.Pages.First();

            return(tmp, context, page);
        }
Пример #18
0
        public async Task ShouldSetTheBrowserConnectedState()
        {
            await using var browserServer = await BrowserType.LaunchServerAsync(TestConstants.GetDefaultBrowserOptions());

            var remote = await BrowserType.ConnectAsync(new ConnectOptions { WSEndpoint = browserServer.WSEndpoint });

            Assert.True(remote.IsConnected);
            await remote.CloseAsync();

            Assert.False(remote.IsConnected);
        }
        public async Task ShouldRejectAllPromisesWhenBrowserIsClosed()
        {
            await using var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var page          = await(await browser.NewContextAsync()).NewPageAsync();
            var neverResolves = page.EvaluateHandleAsync("() => new Promise(r => {})");
            await browser.CloseAsync();

            var exception = await Assert.ThrowsAsync <TargetClosedException>(() => neverResolves);

            Assert.Contains("Protocol error", exception.Message);
        }
Пример #20
0
        /// <inheritdoc/>
        public HeadfulTests(ITestOutputHelper output) : base(output)
        {
            string extensionPath = TestUtils.GetWebServerFile("simple-extension");

            _extensionOptions          = TestConstants.GetDefaultBrowserOptions();
            _extensionOptions.Headless = false;
            _extensionOptions.Args     = new[]
            {
                $"--disable-extensions-except={extensionPath}",
                $"--load-extension={extensionPath}"
            };
        }
Пример #21
0
        public async Task ShouldFireCloseEventForAllContexts()
        {
            await using var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var context = await browser.NewContextAsync();

            var closeTask = new TaskCompletionSource <bool>();

            context.Closed += (sender, e) => closeTask.TrySetResult(true);

            await Task.WhenAll(browser.CloseAsync(), closeTask.Task);
        }
Пример #22
0
        public async Task ShouldBeAbleToCloseRemoteBrowser()
        {
            using var browserApp = await Playwright.LaunchBrowserAppAsync(TestConstants.GetDefaultBrowserOptions());

            using var remote = await Playwright.ConnectAsync(browserApp.ConnectOptions);

            var closeTask = new TaskCompletionSource <bool>();

            browserApp.Closed += (sender, e) => closeTask.TrySetResult(true);

            await Task.WhenAll(remote.CloseAsync(), closeTask.Task);
        }
Пример #23
0
        /// <inheritdoc/>
        public HeadfulTests(ITestOutputHelper output) : base(output)
        {
            string extensionPath = Path.Combine(Directory.GetCurrentDirectory(), "Assets", "simple-extension");

            _extensionOptions          = TestConstants.GetDefaultBrowserOptions();
            _extensionOptions.Headless = false;
            _extensionOptions.Args     = new[]
            {
                $"--disable-extensions-except={extensionPath}",
                $"--load-extension={extensionPath}"
            };
        }
Пример #24
0
        /// <inheritdoc cref="IAsyncLifetime.InitializeAsync"/>
        public override async Task InitializeAsync()
        {
            await base.InitializeAsync();

            _controlledBrowser = await Playwright.LaunchBrowserAppAsync(TestConstants.GetDefaultBrowserOptions());

            await Page.GoToAsync(TestConstants.ServerUrl + "/test/assets/playwrightweb.html");

            await Page.EvaluateAsync(
                "(product, connectOptions) => setup(product, connectOptions)",
                TestConstants.Product.ToLower(),
                _controlledBrowser.ConnectOptions);
        }
Пример #25
0
        public async Task ShouldCreateNewIncognitoContext()
        {
            await using var browser = await Playwright.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            Assert.Single(browser.BrowserContexts);
            var context = await browser.NewContextAsync();

            Assert.Equal(2, browser.BrowserContexts.Count());
            Assert.Contains(context, browser.BrowserContexts);
            await context.CloseAsync();

            Assert.Single(browser.BrowserContexts);
        }
Пример #26
0
        public async Task ShouldIsolateLocalStorageAndCookies()
        {
            // Create two incognito contexts.
            await using var browser = await Playwright.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var context1 = await browser.NewContextAsync();

            var context2 = await browser.NewContextAsync();

            Assert.Empty(await context1.GetPagesAsync());
            Assert.Empty(await context2.GetPagesAsync());

            // Create a page in first incognito context.
            var page1 = await context1.NewPageAsync();

            await page1.GoToAsync(TestConstants.EmptyPage);

            await page1.EvaluateAsync(@"() => {
                localStorage.setItem('name', 'page1');
                document.cookie = 'name=page1';
            }");

            Assert.Single(await context1.GetPagesAsync());
            Assert.Empty(await context2.GetPagesAsync());

            // Create a page in second incognito context.
            var page2 = await context2.NewPageAsync();

            await page2.GoToAsync(TestConstants.EmptyPage);

            await page2.EvaluateAsync(@"() => {
                localStorage.setItem('name', 'page2');
                document.cookie = 'name=page2';
            }");

            Assert.Single(await context1.GetPagesAsync());
            Assert.Equal(page1, (await context1.GetPagesAsync())[0]);
            Assert.Single(await context2.GetPagesAsync());
            Assert.Equal(page2, (await context2.GetPagesAsync())[0]);

            // Make sure pages don't share localstorage or cookies.
            Assert.Equal("page1", await page1.EvaluateAsync <string>("() => localStorage.getItem('name')"));
            Assert.Equal("name=page1", await page1.EvaluateAsync <string>("() => document.cookie"));
            Assert.Equal("page2", await page2.EvaluateAsync <string>("() => localStorage.getItem('name')"));
            Assert.Equal("name=page2", await page2.EvaluateAsync <string>("() => document.cookie"));

            // Cleanup contexts.
            await Task.WhenAll(context1.CloseAsync(), context2.CloseAsync());

            Assert.Single(browser.BrowserContexts);
        }
Пример #27
0
        public async Task ShouldThrowIfUsedAfterDisconnect()
        {
            using var browserApp = await Playwright.LaunchBrowserAppAsync(TestConstants.GetDefaultBrowserOptions());

            var remote = await Playwright.ConnectAsync(browserApp.ConnectOptions);

            var page = await remote.DefaultContext.NewPageAsync();

            await remote.DisconnectAsync();

            var exception = await Assert.ThrowsAnyAsync <PlaywrightSharpException>(() => page.EvaluateAsync("1 + 1"));

            Assert.Contains("has been closed", exception.Message);
        }
Пример #28
0
        public async Task UserDataDirOption()
        {
            using var userDataDir = new TempDirectory();
            var options = TestConstants.GetDefaultBrowserOptions();

            options.UserDataDir = userDataDir.Path;

            using var browser = await Playwright.LaunchAsync(options);

            Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);
            await browser.CloseAsync();

            Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);
        }
Пример #29
0
        public async Task ShouldFireDisconnectedWhenClosingWithWebSocket()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            using var browserApp = await Playwright.LaunchBrowserAppAsync(options);

            using var browser = await Playwright.ConnectAsync(browserApp.ConnectOptions);

            var disconnectedTask = new TaskCompletionSource <bool>();

            browser.Disconnected += (sender, e) => disconnectedTask.TrySetResult(true);
            browserApp.Kill();
            await disconnectedTask.Task;
        }
Пример #30
0
        public async Task ShouldSupportTheWebSocketOption()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            using var browserApp = await Playwright.LaunchBrowserAppAsync(options);

            using var browser = await Playwright.ConnectAsync(browserApp.ConnectOptions);

            Assert.Single(await browser.DefaultContext.GetPagesAsync());
            Assert.NotNull(browserApp.WebSocketEndpoint);
            var page = await browser.DefaultContext.NewPageAsync();

            Assert.Equal(121, await page.EvaluateAsync <int>("11 * 11"));
        }