Esempio n. 1
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());
        }
Esempio n. 2
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"));
        }
Esempio n. 3
0
        public async Task ShouldDeleteDownloadsOnBrowserGone()
        {
            var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var page = await browser.NewPageAsync(new BrowserContextOptions { AcceptDownloads = true });

            await page.SetContentAsync($"<a href=\"{TestConstants.ServerUrl}/download\">download</a>");

            var download1Task = page.WaitForEventAsync(PageEvent.Download);

            await TaskUtils.WhenAll(
                download1Task,
                page.ClickAsync("a"));

            var download2Task = page.WaitForEventAsync(PageEvent.Download);

            await TaskUtils.WhenAll(
                download2Task,
                page.ClickAsync("a"));

            string path1 = await download1Task.Result.Download.GetPathAsync();

            string path2 = await download2Task.Result.Download.GetPathAsync();

            Assert.True(new FileInfo(path1).Exists);
            Assert.True(new FileInfo(path2).Exists);
            await browser.CloseAsync();

            Assert.False(new FileInfo(path1).Exists);
            Assert.False(new FileInfo(path2).Exists);
            Assert.False(new FileInfo(Path.Combine(path1, "..")).Exists);
        }
        public async Task ShouldBeCallableTwice()
        {
            await using var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

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

            await browser.CloseAsync();
        }
        public async Task ShouldThrowIfPageArgumentIsPassed()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.Args = new[] { TestConstants.EmptyPage };

            await Assert.ThrowsAnyAsync <PlaywrightSharpException>(() => BrowserType.LaunchAsync(options));
        }
        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 <ArgumentException>(() => BrowserType.LaunchAsync(options));

            Assert.Contains("LaunchPersistentContextAsync", exception.Message);
        }
Esempio n. 8
0
        public async Task ShouldThrowIfPageArgumentIsPassed()
        {
            var tmp     = new TempDirectory();
            var options = TestConstants.GetDefaultBrowserOptions();

            options.Args = new[] { TestConstants.EmptyPage };

            await Assert.ThrowsAnyAsync <PlaywrightSharpException>(() => BrowserType.LaunchPersistentContextAsync(tmp.Path, options));

            tmp.Dispose();
        }
        public async Task ShouldWorkWithEnvironmentVariables()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.Env = new Dictionary <string, string>
            {
                ["Foo"] = "Var"
            };

            await using var browser = await BrowserType.LaunchAsync(options);
        }
        public async Task ShouldValidateFirefoxUserPrefs()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.FirefoxUserPrefs = new Dictionary <string, object>
            {
                ["Foo"] = "Var"
            };

            await Assert.ThrowsAsync <ArgumentException>(() => BrowserType.LaunchPersistentContextAsync("foo", options));
        }
Esempio n. 11
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);
        }
        public async Task ShouldFireCloseEventForAllContexts()
        {
            await using var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var context = await browser.NewContextAsync();

            var closeTask = new TaskCompletionSource <bool>();

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

            await TaskUtils.WhenAll(browser.CloseAsync(), closeTask.Task);
        }
        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);
        }
        public async Task ShouldIsolateLocalStorageAndCookies()
        {
            // Create two incognito contexts.
            await using var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var context1 = await browser.NewContextAsync();

            var context2 = await browser.NewContextAsync();

            Assert.Empty(context1.Pages);
            Assert.Empty(context2.Pages);

            // 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(context1.Pages);
            Assert.Empty(context2.Pages);

            // 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(context1.Pages);
            Assert.Equal(page1, context1.Pages[0]);
            Assert.Single(context2.Pages);
            Assert.Equal(page2, context2.Pages[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 TaskUtils.WhenAll(context1.CloseAsync(), context2.CloseAsync());

            Assert.Empty(browser.Contexts);
        }
        public async Task ShouldCreateNewContext()
        {
            await using var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            Assert.Empty(browser.Contexts);
            await using var context = await browser.NewContextAsync();

            Assert.Single(browser.Contexts);
            Assert.Contains(context, browser.Contexts);
            Assert.Same(browser, context.Browser);
            await context.CloseAsync();

            Assert.Empty(browser.Contexts);
            Assert.Same(browser, context.Browser);
        }
        /// <inheritsdoc/>
        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();

            var options = TestConstants.GetDefaultBrowserOptions();

            options.DownloadsPath = _tmp.Path;
            _browser = await Playwright[TestConstants.Product].LaunchAsync(options);
        }
        public async Task ShouldWorkWithIgnoreDefaultArgs()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.IgnoreAllDefaultArgs = true;
            options.Args = new[]
            {
                "--remote-debugging-pipe",
                "--headless",
                "--hide-scrollbars",
                "--mute-audio",
                "--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4"
            };

            await using var browser = await BrowserType.LaunchAsync(options);
        }
Esempio n. 18
0
        public async Task ShouldWorkWitIgnoreHTTPSErrors()
        {
            await using var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var context = await browser.NewContextAsync(new BrowserContextOptions
            {
                IgnoreHTTPSErrors = true
            });

            var page = await context.NewPageAsync();

            await page.RouteAsync("**/*", (route, request) => route.ContinueAsync());

            var response = await page.GoToAsync(TestConstants.HttpsPrefix + "/empty.html");

            Assert.Equal(HttpStatusCode.OK, response.Status);
        }
Esempio n. 19
0
        public async Task ShouldCreateNewPage()
        {
            var browser = await Playwright[TestConstants.Product].LaunchAsync(TestConstants.GetDefaultBrowserOptions());
            var page1   = await browser.NewPageAsync();

            Assert.Single(browser.Contexts);

            var page2 = await browser.NewPageAsync();

            Assert.Equal(2, browser.Contexts.Length);

            await page1.CloseAsync();

            Assert.Single(browser.Contexts);

            await page2.CloseAsync();
        }
Esempio n. 20
0
        public async Task ShouldUseProxy()
        {
            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}"
            };

            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());
        }
        public async Task ShouldIsolateCookiesBetweenLaunches()
        {
            await using (var browser1 = await Playwright[TestConstants.Product].LaunchAsync(TestConstants.GetDefaultBrowserOptions()))
            {
                var context1 = await Browser.NewContextAsync();

                await Context.AddCookiesAsync(new SetNetworkCookieParam
                {
                    Name    = "cookie-in-context-1",
                    Value   = "value",
                    Expires = DateTimeOffset.Now.ToUnixTimeSeconds() + 10000,
                    Url     = TestConstants.EmptyPage
                });
            }

            await using (var browser2 = await Playwright[TestConstants.Product].LaunchAsync(TestConstants.GetDefaultBrowserOptions()))
            {
                var context1 = await Browser.NewContextAsync();

                var cookies = await context1.GetCookiesAsync();

                Assert.Empty(cookies);
            }
        }
Esempio n. 22
0
        public async Task ShouldRestoreStateFromUserDataDir()
        {
            using var userDataDir = new TempDirectory();

            await using (var browserContext = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path, TestConstants.GetDefaultBrowserOptions()))
            {
                var page = await browserContext.NewPageAsync();

                await page.GoToAsync(TestConstants.EmptyPage);

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

            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path, TestConstants.GetDefaultBrowserOptions()))
            {
                var page = await browserContext2.NewPageAsync();

                await page.GoToAsync(TestConstants.EmptyPage);

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

            using var userDataDir2 = new TempDirectory();
            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir2.Path, TestConstants.GetDefaultBrowserOptions()))
            {
                var page = await browserContext2.NewPageAsync();

                await page.GoToAsync(TestConstants.EmptyPage);

                Assert.NotEqual("hello", await page.EvaluateAsync <string>("() => localStorage.hey"));
            }

            userDataDir2.Dispose();
            userDataDir.Dispose();
        }
Esempio n. 23
0
        public async Task ShouldRestoreCookiesFromUserDataDir()
        {
            var userDataDir = new TempDirectory();

            await using (var browserContext = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path, TestConstants.GetDefaultBrowserOptions()))
            {
                var page = await browserContext.NewPageAsync();

                await page.GoToAsync(TestConstants.EmptyPage);

                string documentCookie = await page.EvaluateAsync <string>(@"() => {
                    document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT';
                    return document.cookie;
                }");

                Assert.Equal("doSomethingOnlyOnce=true", documentCookie);
            }

            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path, TestConstants.GetDefaultBrowserOptions()))
            {
                var page = await browserContext2.NewPageAsync();

                await page.GoToAsync(TestConstants.EmptyPage);

                Assert.Equal("doSomethingOnlyOnce=true", await page.EvaluateAsync <string>("() => document.cookie"));
            }

            var userDataDir2 = new TempDirectory();

            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir2.Path, TestConstants.GetDefaultBrowserOptions()))
            {
                var page = await browserContext2.NewPageAsync();

                await page.GoToAsync(TestConstants.EmptyPage);

                Assert.NotEqual("doSomethingOnlyOnce=true", await page.EvaluateAsync <string>("() => document.cookie"));
            }

            userDataDir2.Dispose();
            userDataDir.Dispose();
        }
Esempio n. 24
0
        public async Task HeadlessShouldBeAbleToReadCookiesWrittenByHeadful()
        {
            using var userDataDir = new TempDirectory();

            // Write a cookie in headful chrome
            var headfulOptions = TestConstants.GetHeadfulOptions();

            headfulOptions.UserDataDir = userDataDir.Path;

            await using var headfulContext = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path, TestConstants.GetHeadfulOptions());

            var headfulPage = await headfulContext.NewPageAsync();

            await headfulPage.GoToAsync(TestConstants.EmptyPage);

            await headfulPage.EvaluateAsync("() => document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");

            await headfulContext.CloseAsync();

            var headlessContext = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path, TestConstants.GetDefaultBrowserOptions());

            var headlessPage = await headlessContext.NewPageAsync();

            await headlessPage.GoToAsync(TestConstants.EmptyPage);

            string cookie = await headlessPage.EvaluateAsync <string>("() => document.cookie");

            await headlessContext.CloseAsync();

            Assert.Equal("foo=true", cookie);
        }
        public async Task ShouldWork()
        {
            await using var browser = await Playwright[TestConstants.Product].LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            const string func = "() => new Date(1479579154987).toString()";

            await using (var context = await browser.NewContextAsync(new BrowserContextOptions {
                TimezoneId = "America/Jamaica"
            }))
            {
                var page = await context.NewPageAsync();

                string result = await page.EvaluateAsync <string>(func);

                Assert.Equal(
                    "Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)",
                    result);
            }

            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 <string>(func));
            }

            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 <string>(func));
            }

            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 <string>(func));
            }
        }