How to use CloseAsync method of Microsoft.Playwright.Core.Browser class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Browser.CloseAsync

BrowserTypeConnectTests.cs

Source:BrowserTypeConnectTests.cs Github

copy

Full Screen

...58 Assert.AreEqual(browserContext.Pages.Count, 0);59 var page = await browserContext.NewPageAsync();60 Assert.AreEqual(await page.EvaluateAsync<int>("11 * 11"), 121);61 await page.GotoAsync(Server.EmptyPage);62 await browser.CloseAsync();63 }64 {65 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);66 var browserContext = await browser.NewContextAsync();67 var page = await browserContext.NewPageAsync();68 await page.GotoAsync(Server.EmptyPage);69 await browser.CloseAsync();70 }71 }72 [PlaywrightTest("browsertype-connect.spec.ts", "should send default User-Agent and X-Playwright-Browser headers with connect request")]73 public async Task ShouldSendDefaultUserAgentAndPlaywrightBrowserHeadersWithConnectRequest()74 {75 var connectionRequest = Server.WaitForWebSocketConnectionRequest();76 BrowserType.ConnectAsync($"ws://localhost:{Server.Port}/ws", new()77 {78 Headers = new Dictionary<string, string>()79 {80 ["hello-foo"] = "i-am-bar",81 }82 }).IgnoreException();83 var request = await connectionRequest;84 StringAssert.Contains("Playwright", request.Headers["User-Agent"]);85 Assert.AreEqual(request.Headers["hello-foo"], "i-am-bar");86 Assert.AreEqual(request.Headers["x-playwright-browser"], BrowserType.Name);87 }88 [PlaywrightTest("browsertype-connect.spec.ts", "should be able to connect two browsers at the same time")]89 public async Task ShouldBeAbleToConnectTwoBrowsersAtTheSameTime()90 {91 var browser1 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);92 Assert.AreEqual(browser1.Contexts.Count, 0);93 await browser1.NewContextAsync();94 Assert.AreEqual(browser1.Contexts.Count, 1);95 var browser2 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);96 Assert.AreEqual(browser2.Contexts.Count, 0);97 await browser2.NewContextAsync();98 Assert.AreEqual(browser2.Contexts.Count, 1);99 Assert.AreEqual(browser1.Contexts.Count, 1);100 await browser1.CloseAsync();101 Assert.AreEqual(browser2.Contexts.Count, 1);102 var page2 = await browser2.NewPageAsync();103 Assert.AreEqual(await page2.EvaluateAsync<int>("7 * 6"), 42); // original browser should still work104 await browser2.CloseAsync();105 }106 [PlaywrightTest("browsertype-connect.spec.ts", "should timeout in connect while connecting")]107 [Skip(SkipAttribute.Targets.Windows)]108 public async Task ShouldTimeoutInConnectWhileConnecting()109 {110 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(async () => await BrowserType.ConnectAsync($"ws://localhost:{Server.Port}/ws", new BrowserTypeConnectOptions { Timeout = 100 }));111 StringAssert.Contains("BrowserType.ConnectAsync: Timeout 100ms exceeded", exception.Message);112 }113 [PlaywrightTest("browsertype-connect.spec.ts", "should support slowmo option")]114 public async Task ShouldSupportSlowMo()115 {116 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint, new BrowserTypeConnectOptions { SlowMo = 200 });117 var start = DateTime.Now;118 var context = await browser.NewContextAsync();119 await browser.CloseAsync();120 Assert.Greater((DateTime.Now - start).TotalMilliseconds, 199);121 }122 [PlaywrightTest("browsertype-connect.spec.ts", "disconnected event should be emitted when browser is closed or server is closed")]123 public async Task DisconnectedEventShouldBeEmittedWhenBrowserIsClosedOrServerIsClosed()124 {125 var browser1 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);126 await browser1.NewPageAsync();127 var browser2 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);128 await browser2.NewPageAsync();129 int disconnected1 = 0;130 int disconnected2 = 0;131 browser1.Disconnected += (_, e) => disconnected1++;132 browser2.Disconnected += (_, e) => disconnected2++;133 var tsc1 = new TaskCompletionSource<object>();134 browser1.Disconnected += (_, e) => tsc1.SetResult(null);135 await browser1.CloseAsync();136 await tsc1.Task;137 Assert.AreEqual(disconnected1, 1);138 Assert.AreEqual(disconnected2, 0);139 var tsc2 = new TaskCompletionSource<object>();140 browser2.Disconnected += (_, e) => tsc2.SetResult(null);141 await browser2.CloseAsync();142 await tsc2.Task;143 Assert.AreEqual(disconnected1, 1);144 Assert.AreEqual(disconnected2, 1);145 }146 [PlaywrightTest("browsertype-connect.spec.ts", "disconnected event should have browser as argument")]147 public async Task DisconnectedEventShouldHaveBrowserAsArguments()148 {149 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);150 IBrowser disconneced = null;151 var tsc = new TaskCompletionSource<object>();152 browser.Disconnected += (_, browser) =>153 {154 disconneced = browser;155 tsc.SetResult(null);156 };157 await browser.CloseAsync();158 await tsc.Task;159 Assert.AreEqual(browser, disconneced);160 }161 [PlaywrightTest("browsertype-connect.spec.ts", "should set the browser connected state")]162 public async Task ShouldSetTheBrowserConnectedState()163 {164 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);165 Assert.AreEqual(browser.IsConnected, true);166 var tsc = new TaskCompletionSource<bool>();167 browser.Disconnected += (_, e) => tsc.SetResult(false);168 _remoteServer.Close();169 await tsc.Task;170 Assert.AreEqual(browser.IsConnected, false);171 }172 [PlaywrightTest("browsertype-connect.spec.ts", "should throw when used after isConnected returns false")]173 public async Task ShouldThrowWhenUsedAfterIsConnectedReturnsFalse()174 {175 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);176 var page = await browser.NewPageAsync();177 var tsc = new TaskCompletionSource<bool>();178 browser.Disconnected += (_, e) => tsc.SetResult(false);179 _remoteServer.Close();180 await tsc.Task;181 Assert.AreEqual(browser.IsConnected, false);182 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.EvaluateAsync("1 + 1"));183 StringAssert.Contains("has been closed", exception.Message);184 }185 [PlaywrightTest("browsertype-connect.spec.ts", "should throw when calling waitForNavigation after disconnect")]186 public async Task ShouldThrowWhenWhenCallingWaitForNavigationAfterDisconnect()187 {188 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);189 var page = await browser.NewPageAsync();190 var tsc = new TaskCompletionSource<bool>();191 browser.Disconnected += (_, e) => tsc.SetResult(false);192 _remoteServer.Close();193 await tsc.Task;194 Assert.AreEqual(browser.IsConnected, false);195 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.WaitForNavigationAsync());196 StringAssert.Contains("Navigation failed because page was closed", exception.Message);197 }198 [PlaywrightTest("browsertype-connect.spec.ts", "should reject navigation when browser closes")]199 public async Task ShouldRejectNavigationWhenBrowserCloses()200 {201 Server.SetRoute("/one-style.css", context =>202 {203 context.Response.Redirect("/one-style.css");204 return Task.CompletedTask;205 });206 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);207 var page = await browser.NewPageAsync();208 var PageGoto = page.GotoAsync(Server.Prefix + "/one-style.html", new PageGotoOptions { Timeout = 60000 });209 await Server.WaitForRequest("/one-style.css");210 await browser.CloseAsync();211 Assert.AreEqual(browser.IsConnected, false);212 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await PageGoto);213 StringAssert.Contains("has been closed", exception.Message);214 }215 [PlaywrightTest("browsertype-connect.spec.ts", "should reject waitForSelector when browser closes")]216 public async Task ShouldRejectWaitForSelectorWhenBrowserCloses()217 {218 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);219 var page = await browser.NewPageAsync();220 var watchdog = page.WaitForSelectorAsync("div");221 await browser.CloseAsync();222 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await watchdog);223 Assert.That(exception.Message, Contains.Substring("has been closed"));224 }225 [PlaywrightTest("browsertype-connect.spec.ts", "should emit close events on pages and contexts")]226 public async Task ShouldEmitCloseEventsOnPagesAndContexts()227 {228 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);229 var context = await browser.NewContextAsync();230 var tsc = new TaskCompletionSource<object>();231 context.Close += (_, e) => tsc.SetResult(null);232 var page = await context.NewPageAsync();233 bool pageClosed = false;234 page.Close += (_, e) => pageClosed = true;235 _remoteServer.Close();236 await tsc.Task;237 Assert.AreEqual(pageClosed, true);238 }239 [PlaywrightTest("browsertype-connect.spec.ts", "should terminate network waiters")]240 public async Task ShouldTerminateNetworkWaiters()241 {242 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);243 var page = await browser.NewPageAsync();244 var requestWatchdog = page.WaitForRequestAsync(Server.EmptyPage);245 var responseWatchog = page.WaitForResponseAsync(Server.EmptyPage);246 _remoteServer.Close();247 async Task CheckTaskHasException(Task task)248 {249 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await task);250 StringAssert.Contains("Page closed", exception.Message);251 StringAssert.DoesNotContain("Timeout", exception.Message);252 }253 await CheckTaskHasException(requestWatchdog);254 await CheckTaskHasException(responseWatchog);255 }256 [PlaywrightTest("browsertype-connect.spec.ts", "should not throw on close after disconnect")]257 public async Task ShouldNotThrowOnCloseAfterDisconnect()258 {259 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);260 var page = await browser.NewPageAsync();261 var tcs = new TaskCompletionSource<bool>();262 browser.Disconnected += (_, e) => tcs.SetResult(true);263 _remoteServer.Close();264 await tcs.Task;265 await browser.CloseAsync();266 }267 [PlaywrightTest("browsertype-connect.spec.ts", "should not throw on context.close after disconnect")]268 public async Task ShouldNotThrowOnContextCloseAfterDisconnect()269 {270 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);271 var context = await browser.NewContextAsync();272 await context.NewPageAsync();273 var tcs = new TaskCompletionSource<bool>();274 browser.Disconnected += (_, e) => tcs.SetResult(true);275 _remoteServer.Close();276 await tcs.Task;277 await context.CloseAsync();278 }279 [PlaywrightTest("browsertype-connect.spec.ts", "should not throw on page.close after disconnect")]280 public async Task ShouldNotThrowOnPageCloseAfterDisconnect()281 {282 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);283 var context = await browser.NewContextAsync();284 var page = await context.NewPageAsync();285 var tcs = new TaskCompletionSource<bool>();286 browser.Disconnected += (_, e) => tcs.SetResult(true);287 _remoteServer.Close();288 await tcs.Task;289 await page.CloseAsync();290 }291 [PlaywrightTest("browsertype-connect.spec.ts", "should saveAs videos from remote browser")]292 public async Task ShouldSaveAsVideosFromRemoteBrowser()293 {294 using var tempDirectory = new TempDirectory();295 var videoPath = tempDirectory.Path;296 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);297 var context = await browser.NewContextAsync(new()298 {299 RecordVideoDir = videoPath,300 RecordVideoSize = new() { Height = 320, Width = 240 }301 });302 var page = await context.NewPageAsync();303 await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'");304 await Task.Delay(1000);305 await context.CloseAsync();306 var videoSavePath = tempDirectory.Path + "my-video.webm";307 await page.Video.SaveAsAsync(videoSavePath);308 Assert.That(videoSavePath, Does.Exist);309 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.Video.PathAsync());310 StringAssert.Contains("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy", exception.Message);311 }312 [PlaywrightTest("browsertype-connect.spec.ts", "should save download")]313 public async Task ShouldSaveDownload()314 {315 Server.SetRoute("/download", context =>316 {317 context.Response.Headers["Content-Type"] = "application/octet-stream";318 context.Response.Headers["Content-Disposition"] = "attachment";319 return context.Response.WriteAsync("Hello world");320 });321 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);322 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });323 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");324 var downloadTask = page.WaitForDownloadAsync();325 await TaskUtils.WhenAll(326 downloadTask,327 page.ClickAsync("a"));328 using var tmpDir = new TempDirectory();329 string userPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "download.txt");330 var download = downloadTask.Result;331 await download.SaveAsAsync(userPath);332 Assert.True(new FileInfo(userPath).Exists);333 Assert.AreEqual("Hello world", File.ReadAllText(userPath));334 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.PathAsync());335 Assert.AreEqual("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy.", exception.Message);336 await browser.CloseAsync();337 }338 [PlaywrightTest("browsertype-connect.spec.ts", "should error when saving download after deletion")]339 public async Task ShouldErrorWhenSavingDownloadAfterDeletion()340 {341 Server.SetRoute("/download", context =>342 {343 context.Response.Headers["Content-Type"] = "application/octet-stream";344 context.Response.Headers["Content-Disposition"] = "attachment";345 return context.Response.WriteAsync("Hello world");346 });347 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);348 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });349 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");350 var downloadTask = page.WaitForDownloadAsync();351 await TaskUtils.WhenAll(352 downloadTask,353 page.ClickAsync("a"));354 using var tmpDir = new TempDirectory();355 string userPath = Path.Combine(tmpDir.Path, "download.txt");356 var download = downloadTask.Result;357 await download.DeleteAsync();358 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));359 StringAssert.Contains("Target page, context or browser has been closed", exception.Message);360 await browser.CloseAsync();361 }362 [PlaywrightTest("browsertype-connect.spec.ts", "should save har")]363 public async Task ShouldSaveHar()364 {365 using var tempDirectory = new TempDirectory();366 var harPath = tempDirectory.Path + "/test.har";367 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);368 var context = await browser.NewContextAsync(new()369 {370 RecordHarPath = harPath371 });372 var page = await context.NewPageAsync();373 await page.GotoAsync(Server.EmptyPage);374 await context.CloseAsync();375 await browser.CloseAsync();376 Assert.That(harPath, Does.Exist);377 var logString = System.IO.File.ReadAllText(harPath);378 StringAssert.Contains(Server.EmptyPage, logString);379 }380 [PlaywrightTest("browsertype-connect.spec.ts", "should record trace with sources")]381 public async Task ShouldRecordContextTraces()382 {383 using var tempDirectory = new TempDirectory();384 var tracePath = tempDirectory.Path + "/trace.zip";385 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);386 var context = await browser.NewContextAsync();387 var page = await context.NewPageAsync();388 await context.Tracing.StartAsync(new() { Sources = true });389 await page.GotoAsync(Server.EmptyPage);390 await page.SetContentAsync("<button>Click</button>");391 await page.ClickAsync("button");392 await context.Tracing.StopAsync(new TracingStopOptions { Path = tracePath });393 await browser.CloseAsync();394 Assert.That(tracePath, Does.Exist);395 ZipFile.ExtractToDirectory(tracePath, tempDirectory.Path);396 Assert.That(tempDirectory.Path + "/trace.trace", Does.Exist);397 Assert.That(tempDirectory.Path + "/trace.network", Does.Exist);398 Assert.AreEqual(1, Directory.GetFiles(Path.Join(tempDirectory.Path, "resources"), "*.txt").Length);399 }400 [PlaywrightTest("browsertype-connect.spec.ts", "should upload large file")]401 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]402 public async Task ShouldUploadLargeFile()403 {404 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);405 var context = await browser.NewContextAsync();406 var page = await context.NewPageAsync();407 await page.GotoAsync(Server.Prefix + "/input/fileupload.html");...

Full Screen

Full Screen

BrowserContextBasicTests.cs

Source:BrowserContextBasicTests.cs Github

copy

Full Screen

...40 await using var context = await browser.NewContextAsync();41 Assert.That(browser.Contexts, Has.Length.EqualTo(1));42 CollectionAssert.Contains(browser.Contexts, context);43 Assert.AreEqual(browser, context.Browser);44 await context.CloseAsync();45 Assert.IsEmpty(browser.Contexts);46 Assert.AreEqual(browser, context.Browser);47 }48 [PlaywrightTest("browsercontext-basic.spec.ts", "window.open should use parent tab context")]49 public async Task WindowOpenShouldUseParentTabContext()50 {51 await using var context = await Browser.NewContextAsync();52 var page = await context.NewPageAsync();53 await page.GotoAsync(Server.EmptyPage);54 var popupTargetCompletion = new TaskCompletionSource<IPage>();55 page.Popup += (_, e) => popupTargetCompletion.SetResult(e);56 var (popupTarget, _) = await TaskUtils.WhenAll(57 popupTargetCompletion.Task,58 page.EvaluateAsync("url => window.open(url)", Server.EmptyPage)59 );60 Assert.AreEqual(context, popupTarget.Context);61 await context.CloseAsync();62 }63 [PlaywrightTest("browsercontext-basic.spec.ts", "should isolate localStorage and cookies")]64 public async Task ShouldIsolateLocalStorageAndCookies()65 {66 // Create two incognito contexts.67 await using var browser = await BrowserType.LaunchAsync();68 var context1 = await browser.NewContextAsync();69 var context2 = await browser.NewContextAsync();70 Assert.IsEmpty(context1.Pages);71 Assert.IsEmpty(context2.Pages);72 // Create a page in first incognito context.73 var page1 = await context1.NewPageAsync();74 await page1.GotoAsync(Server.EmptyPage);75 await page1.EvaluateAsync(@"() => {76 localStorage.setItem('name', 'page1');77 document.cookie = 'name=page1';78 }");79 Assert.That(context1.Pages, Has.Count.EqualTo(1));80 Assert.IsEmpty(context2.Pages);81 // Create a page in second incognito context.82 var page2 = await context2.NewPageAsync();83 await page2.GotoAsync(Server.EmptyPage);84 await page2.EvaluateAsync(@"() => {85 localStorage.setItem('name', 'page2');86 document.cookie = 'name=page2';87 }");88 Assert.That(context1.Pages, Has.Count.EqualTo(1));89 Assert.AreEqual(page1, context1.Pages.FirstOrDefault());90 Assert.That(context2.Pages, Has.Count.EqualTo(1));91 Assert.AreEqual(page2, context2.Pages.FirstOrDefault());92 // Make sure pages don't share localstorage or cookies.93 Assert.AreEqual("page1", await page1.EvaluateAsync<string>("() => localStorage.getItem('name')"));94 Assert.AreEqual("name=page1", await page1.EvaluateAsync<string>("() => document.cookie"));95 Assert.AreEqual("page2", await page2.EvaluateAsync<string>("() => localStorage.getItem('name')"));96 Assert.AreEqual("name=page2", await page2.EvaluateAsync<string>("() => document.cookie"));97 // Cleanup contexts.98 await TaskUtils.WhenAll(context1.CloseAsync(), context2.CloseAsync());99 Assert.IsEmpty(browser.Contexts);100 }101 [PlaywrightTest("browsercontext-basic.spec.ts", "should propagate default viewport to the page")]102 public async Task ShouldPropagateDefaultViewportToThePage()103 {104 await using var context = await Browser.NewContextAsync(new()105 {106 ViewportSize = new()107 {108 Width = 456,109 Height = 789110 }111 });112 var page = await context.NewPageAsync();113 await TestUtils.VerifyViewportAsync(page, 456, 789);114 }115 [PlaywrightTest("browsercontext-basic.spec.ts", "should make a copy of default viewport")]116 public async Task ShouldMakeACopyOfDefaultViewport()117 {118 var viewport = new ViewportSize119 {120 Width = 456,121 Height = 789122 };123 await using var context = await Browser.NewContextAsync(new() { ViewportSize = viewport });124 viewport.Width = 567;125 var page = await context.NewPageAsync();126 await TestUtils.VerifyViewportAsync(page, 456, 789);127 }128 [PlaywrightTest("browsercontext-basic.spec.ts", "should respect deviceScaleFactor")]129 public async Task ShouldRespectDeviceScaleFactor()130 {131 await using var context = await Browser.NewContextAsync(new()132 {133 DeviceScaleFactor = 3134 });135 var page = await context.NewPageAsync();136 Assert.AreEqual(3, await page.EvaluateAsync<int>("window.devicePixelRatio"));137 }138 [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow deviceScaleFactor with null viewport")]139 public async Task ShouldNotAllowDeviceScaleFactorWithViewportDisabled()140 {141 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Browser.NewContextAsync(new()142 {143 ViewportSize = ViewportSize.NoViewport,144 DeviceScaleFactor = 3,145 }));146 Assert.AreEqual("\"deviceScaleFactor\" option is not supported with null \"viewport\"", exception.Message);147 }148 [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow isMobile with null viewport")]149 public async Task ShouldNotAllowIsMobileWithViewportDisabled()150 {151 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Browser.NewContextAsync(new()152 {153 ViewportSize = ViewportSize.NoViewport,154 IsMobile = true,155 }));156 Assert.AreEqual("\"isMobile\" option is not supported with null \"viewport\"", exception.Message);157 }158 [PlaywrightTest("browsercontext-basic.spec.ts", "close() should work for empty context")]159 public async Task CloseShouldWorkForEmptyContext()160 {161 var context = await Browser.NewContextAsync();162 await context.CloseAsync();163 }164 [PlaywrightTest("browsercontext-basic.spec.ts", "close() should abort waitForEvent")]165 public async Task CloseShouldAbortWaitForEvent()166 {167 var context = await Browser.NewContextAsync();168 var waitTask = context.WaitForPageAsync();169 await context.CloseAsync();170 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => waitTask);171 Assert.AreEqual("Context closed", exception.Message);172 }173 [PlaywrightTest("browsercontext-basic.spec.ts", "should not report frameless pages on error")]174 public async Task ShouldNotReportFramelessPagesOnError()175 {176 var context = await Browser.NewContextAsync();177 var page = await context.NewPageAsync();178 Server.SetRoute("/empty.html", context =>179 {180 context.Response.ContentType = "text/html";181 return context.Response.WriteAsync($"<a href=\"{Server.EmptyPage}\" target=\"_blank\">Click me</a>");182 });183 IPage popup = null;184 context.Page += (_, e) => popup = e;185 await page.GotoAsync(Server.EmptyPage);186 await page.ClickAsync("'Click me'");187 await context.CloseAsync();188 if (popup != null)189 {190 Assert.True(popup.IsClosed);191 Assert.NotNull(popup.MainFrame);192 }193 }194 [PlaywrightTest("browsercontext-basic.spec.ts", "close() should be callable twice")]195 public async Task CloseShouldBeCallableTwice()196 {197 var context = await Browser.NewContextAsync();198 await TaskUtils.WhenAll(context.CloseAsync(), context.CloseAsync());199 await context.CloseAsync();200 }201 [PlaywrightTest("browsercontext-basic.spec.ts", "should return all of the pages")]202 public async Task ShouldReturnAllOfThePages()203 {204 await using var context = await Browser.NewContextAsync();205 var page = await context.NewPageAsync();206 var second = await context.NewPageAsync();207 Assert.AreEqual(2, context.Pages.Count);208 CollectionAssert.Contains(context.Pages, page);209 CollectionAssert.Contains(context.Pages, second);210 }211 [PlaywrightTest("browsercontext-basic.spec.ts", "BrowserContext.pages()", "should close all belonging pages once closing context")]212 public async Task ShouldCloseAllBelongingPagesOnceClosingContext()213 {214 await using var context = await Browser.NewContextAsync();215 await context.NewPageAsync();216 Assert.That(context.Pages, Has.Count.EqualTo(1));217 await context.CloseAsync();218 Assert.IsEmpty(context.Pages);219 }220 [PlaywrightTest("browsercontext-basic.spec.ts", "should disable javascript")]221 public async Task ShouldDisableJavascript()222 {223 await using (var context = await Browser.NewContextAsync(new() { JavaScriptEnabled = false }))224 {225 var page = await context.NewPageAsync();226 await page.GotoAsync("data:text/html, <script>var something = 'forbidden'</script>");227 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.EvaluateAsync("something"));228 StringAssert.Contains(229 TestConstants.IsWebKit ? "Can't find variable: something" : "something is not defined",230 exception.Message);231 }...

Full Screen

Full Screen

DownloadsPathTests.cs

Source:DownloadsPathTests.cs Github

copy

Full Screen

...44 var download = downloadTask.Result;45 Assert.AreEqual($"{Server.Prefix}/download", download.Url);46 Assert.AreEqual("file.txt", download.SuggestedFilename);47 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.PathAsync());48 await page.CloseAsync();49 await _browser.CloseAsync();50 Assert.True(new DirectoryInfo(_tmp.Path).Exists);51 }52 [PlaywrightTest("downloads-path.spec.ts", "should delete downloads when context closes")]53 public async Task ShouldDeleteDownloadsWhenContextCloses()54 {55 var page = await _browser.NewPageAsync(new() { AcceptDownloads = true });56 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");57 var downloadTask = page.WaitForDownloadAsync();58 await TaskUtils.WhenAll(59 downloadTask,60 page.ClickAsync("a"));61 var download = downloadTask.Result;62 string path = await download.PathAsync();63 Assert.True(new FileInfo(path).Exists);64 await page.CloseAsync();65 Assert.False(new FileInfo(path).Exists);66 }67 [PlaywrightTest("downloads-path.spec.ts", "should report downloads in downloadsPath folder")]68 public async Task ShouldReportDownloadsInDownloadsPathFolder()69 {70 var page = await _browser.NewPageAsync(new() { AcceptDownloads = true });71 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");72 var downloadTask = page.WaitForDownloadAsync();73 await TaskUtils.WhenAll(74 downloadTask,75 page.ClickAsync("a"));76 var download = downloadTask.Result;77 string path = await download.PathAsync();78 Assert.That(path, Does.StartWith(_tmp.Path));79 await page.CloseAsync();80 }81 [PlaywrightTest("downloads-path.spec.ts", "should report downloads in downloadsPath folder with a relative path")]82 public async Task ShouldReportDownloadsInDownloadsPathFolderWithARelativePath()83 {84 var browser = await Playwright[TestConstants.BrowserName]85 .LaunchAsync(new()86 {87 DownloadsPath = "."88 });89 var page = await browser.NewPageAsync(new()90 {91 AcceptDownloads = true92 });93 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");94 var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));95 string path = await download.PathAsync();96 Assert.That(path, Does.StartWith(Directory.GetCurrentDirectory()));97 await page.CloseAsync();98 }99 [PlaywrightTest("downloads-path.spec.ts", "should accept downloads in persistent context")]100 public async Task ShouldAcceptDownloadsInPersistentContext()101 {102 var userProfile = new TempDirectory();103 var browser = await Playwright[TestConstants.BrowserName]104 .LaunchPersistentContextAsync(userProfile.Path, new()105 {106 AcceptDownloads = true,107 DownloadsPath = _tmp.Path108 });109 var page = await browser.NewPageAsync();110 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");111 var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));112 Assert.AreEqual($"{Server.Prefix}/download", download.Url);113 Assert.AreEqual("file.txt", download.SuggestedFilename);114 Assert.That(await download.PathAsync(), Does.StartWith(_tmp.Path));115 await page.CloseAsync();116 }117 [PlaywrightTest("downloads-path.spec.ts", "should delete downloads when persistent context closes")]118 public async Task ShouldDeleteDownloadsWhenPersistentContextCloses()119 {120 var userProfile = new TempDirectory();121 var browser = await Playwright[TestConstants.BrowserName]122 .LaunchPersistentContextAsync(userProfile.Path, new()123 {124 AcceptDownloads = true,125 DownloadsPath = _tmp.Path126 });127 var page = await browser.NewPageAsync();128 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");129 var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));130 var path = await download.PathAsync();131 Assert.IsTrue(File.Exists(path));132 await browser.CloseAsync();133 Assert.IsFalse(File.Exists(path));134 }135 [SetUp]136 public async Task InitializeAsync()137 {138 Server.SetRoute("/download", context =>139 {140 context.Response.Headers["Content-Type"] = "application/octet-stream";141 context.Response.Headers["Content-Disposition"] = "attachment; filename=file.txt";142 return context.Response.WriteAsync("Hello world");143 });144 _tmp = new();145 _browser = await Playwright[TestConstants.BrowserName].LaunchAsync(new() { DownloadsPath = _tmp.Path });146 }147 [TearDown]148 public async Task DisposeAsync()149 {150 await _browser.CloseAsync();151 _tmp.Dispose();152 }153 }154}...

Full Screen

Full Screen

WebHostServerFixture.cs

Source:WebHostServerFixture.cs Github

copy

Full Screen

...81 internal async Task ShutDownAsync()82 {83 try84 {85 await Browser.CloseAsync();86 Playwright.Dispose();87 }88 catch (Exception ex)89 {90 Console.WriteLine(ex);91 throw new Exception("Shutdown failed", ex);92 }93 }94 public void Dispose()95 {96 Host?.Dispose();97 Host?.StopAsync();98 }99 protected IHost CreateWebHost()...

Full Screen

Full Screen

BinaryHttpClientTest.cs

Source:BinaryHttpClientTest.cs Github

copy

Full Screen

...55 // JS interop call to intercept navigation56 await socket.WaitForEventAsync(WebSocketEvent.FrameReceived);57 await socket.WaitForEventAsync(WebSocketEvent.FrameSent);58 await page.WaitForSelectorAsync("ul");*/59 await page.CloseAsync();60 }61 //IssueRequest("/subdir/api/data");62 //Assert.Equal("OK", _responseStatus.Text);63 //Assert.Equal("OK", _responseStatusText.Text);64 //Assert.Equal("", _testOutcome.Text);65 }66 private void IssueRequest()67 {68 //var targetUri = new Uri(_apiServerFixture.RootUri, relativeUri);69 //SetValue("request-uri", targetUri.AbsoluteUri);70 //_appElement.FindElement(By.Id("send-request")).Click();71 //_responseStatus = Browser.Exists(By.Id("response-status"));72 //_responseStatusText = _appElement.FindElement(By.Id("response-status-text"));73 //_testOutcome = _appElement.FindElement(By.Id("test-outcome"));...

Full Screen

Full Screen

BrowserFactory.cs

Source:BrowserFactory.cs Github

copy

Full Screen

...65 }66 }67 finally 68 {69 await browser.CloseAsync();70 browser = null;71 }72 }73 }74}...

Full Screen

Full Screen

BlazorWASMPlaywrightTests.cs

Source:BlazorWASMPlaywrightTests.cs Github

copy

Full Screen

...15 var page = await browser.NewPageAsync();16 await page.GotoAsync(_server.RootUri.AbsoluteUri);17 var header = await page.WaitForSelectorAsync("h1");18 Assert.Equal("Hello, world!", await header.InnerTextAsync());19 await browser.CloseAsync();20 }21 [Fact]22 public async Task Counter()23 {24 var browser = await GetBrowser();25 var page = await browser.NewPageAsync();26 await page.GotoAsync(_server.RootUri + "counter", new PageGotoOptions() { WaitUntil = WaitUntilState.NetworkIdle });27 await page.ClickAsync("#IncrementBtn");28 // Selectors are not only CSS selectors. You can use xpath, css, or text selectors29 // By default there is a timeout of 30s. If the selector isn't found after the timeout, an exception is thrown.30 // More about selectors: https://playwright.dev/#version=v1.4.2&path=docs%2Fselectors.md31 await page.WaitForSelectorAsync("text=Current count: 1");32 await browser.CloseAsync();33 }34 public static async Task<IBrowser> GetBrowser()35 {36 var playwright = await Playwright.CreateAsync();37 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions()38 {39 Headless = false,40 SlowMo = 500041 });42 return browser;43 }44 }45}...

Full Screen

Full Screen

Html2Pdf.cs

Source:Html2Pdf.cs Github

copy

Full Screen

...42 return bytes;43 }44 finally45 {46 await context.CloseAsync();47 }48 }49 }50 public class Html2PdfConversionRequest51 {52 public string Html { get; set; }53 }54}...

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await browser.CloseAsync();14 }15 }16}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await browser.CloseAsync();14 }15 }16}17using System;18using System.Threading.Tasks;19using Microsoft.Playwright;20{21 {22 static async Task Main(string[] args)23 {24 using var playwright = await Playwright.CreateAsync();25 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions26 {27 });28 var context = await browser.NewContextAsync();29 var page = await context.NewPageAsync();30 await context.CloseAsync();31 }32 }33}34using System;35using System.Threading.Tasks;36using Microsoft.Playwright;37{38 {39 static async Task Main(string[] args)40 {41 using var playwright = await Playwright.CreateAsync();42 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions43 {44 });45 var context = await browser.NewContextAsync();46 var page = await context.NewPageAsync();47 await page.CloseAsync();48 }49 }50}51using System;52using System.Threading.Tasks;53using Microsoft.Playwright;54{55 {56 static async Task Main(string[] args)57 {58 using var playwright = await Playwright.CreateAsync();59 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions60 {61 });

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 await using var browser = await playwright.Chromium.LaunchAsync();9 var page = await browser.NewPageAsync();10 await browser.CloseAsync();11 }12 }13}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync();10 var page = await browser.NewPageAsync();11 await browser.CloseAsync();12 Console.WriteLine("Press any key to exit.");13 Console.ReadKey();14 }15 }16}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 using var playwright = await Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync();11 await browser.CloseAsync();12 }13 }14}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System.Threading.Tasks;2using Microsoft.Playwright;3{4 {5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 var browser = await playwright.Chromium.LaunchAsync();9 var context = await browser.NewContextAsync();10 var page = await context.NewPageAsync();11 await page.ScreenshotAsync("google.png");12 await browser.CloseAsync();13 }14 }15}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2{3 {4 static async Task Main(string[] args)5 {6 using var playwright = await Playwright.CreateAsync();7 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions8 {9 });10 var page = await browser.NewPageAsync();11 await browser.CloseAsync();12 }13 }14}15using Microsoft.Playwright;16{17 {18 static async Task Main(string[] args)19 {20 using var playwright = await Playwright.CreateAsync();21 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions22 {23 });24 var page = await browser.NewPageAsync();25 await browser.NewContextAsync().CloseAsync();26 }27 }28}29using Microsoft.Playwright;30{31 {32 static async Task Main(string[] args)33 {34 using var playwright = await Playwright.CreateAsync();35 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions36 {37 });38 var page = await browser.NewPageAsync();39 await page.CloseAsync();40 }41 }42}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 using var browser = await playwright.Webkit.LaunchAsync();9 using var page = await browser.NewPageAsync();10 await browser.CloseAsync();11 }12 }13}14using Microsoft.Playwright;15using System.Threading.Tasks;16{17 {18 static async Task Main(string[] args)19 {20 using var playwright = await Playwright.CreateAsync();21 using var browser = await playwright.Webkit.LaunchAsync();22 using var page = await browser.NewPageAsync();23 await browser.DisposeAsync();24 }25 }26}27using Microsoft.Playwright;28using System.Threading.Tasks;29{30 {31 static async Task Main(string[] args)32 {33 using var playwright = await Playwright.CreateAsync();34 using var browser = await playwright.Webkit.LaunchAsync();35 using var page = await browser.NewPageAsync();

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright-dotnet automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful