Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Response
PageNetworkResponseTests.cs
Source:PageNetworkResponseTests.cs
...32using Microsoft.Playwright.NUnit;33using NUnit.Framework;34namespace Microsoft.Playwright.Tests35{36 public class PageNetworkResponseTests : PageTestEx37 {38 [PlaywrightTest("page-network-response.spec.ts", "should return body")]39 public async Task ShouldReturnBody()40 {41 var response = await Page.GotoAsync(Server.Prefix + "/pptr.png");42 byte[] imageBuffer = File.ReadAllBytes(TestUtils.GetAsset("pptr.png"));43 Assert.AreEqual(imageBuffer, await response.BodyAsync());44 }45 [PlaywrightTest("page-network-response.spec.ts", "should return body with compression")]46 public async Task ShouldReturnBodyWithCompression()47 {48 Server.EnableGzip("/pptr.png");49 var response = await Page.GotoAsync(Server.Prefix + "/pptr.png");50 byte[] imageBuffer = File.ReadAllBytes(TestUtils.GetAsset("pptr.png"));51 Assert.AreEqual(imageBuffer, await response.BodyAsync());52 }53 [PlaywrightTest("page-network-response.spec.ts", "should work")]54 public async Task ShouldWork()55 {56 Server.SetRoute("/empty.html", (context) =>57 {58 context.Response.Headers["foo"] = "bar";59 return Task.CompletedTask;60 });61 var response = await Page.GotoAsync(Server.EmptyPage);62#pragma warning disable 061263 StringAssert.Contains("bar", response.Headers["foo"]);64#pragma warning restore 061265 }66 [PlaywrightTest("page-network-response.spec.ts", "should return json")]67 public async Task ShouldReturnJson()68 {69 var response = await Page.GotoAsync(Server.Prefix + "/simple.json");70 Assert.AreEqual("{\"foo\": \"bar\"}", (await response.JsonAsync())?.GetRawText());71 }72 public async Task ShouldWorkWithGenerics()73 {74 var response = await Page.GotoAsync(Server.Prefix + "/simple.json");75 var root = await response.JsonAsync();76 Assert.AreEqual("bar", root?.GetProperty("foo").GetString());77 }78 [PlaywrightTest("page-network-response.spec.ts", "should return status text")]79 public async Task ShouldReturnStatusText()80 {81 Server.SetRoute("/cool", (context) =>82 {83 context.Response.StatusCode = 200;84 //There are some debates about this on these issues85 //https://github.com/aspnet/HttpAbstractions/issues/39586 //https://github.com/aspnet/HttpAbstractions/issues/48687 //https://github.com/aspnet/HttpAbstractions/issues/79488 context.Features.Get<IHttpResponseFeature>().ReasonPhrase = "cool!";89 return Task.CompletedTask;90 });91 var response = await Page.GotoAsync(Server.Prefix + "/cool");92 Assert.AreEqual("cool!", response.StatusText);93 }94 [PlaywrightTest("page-network-response.spec.ts", "should return text")]95 public async Task ShouldReturnText()96 {97 var response = await Page.GotoAsync(Server.Prefix + "/simple.json");98 Assert.AreEqual("{\"foo\": \"bar\"}", (await response.TextAsync()).Trim());99 }100 [PlaywrightTest("page-network-response.spec.ts", "should return uncompressed text")]101 public async Task ShouldReturnUncompressedText()102 {103 Server.EnableGzip("/simple.json");104 var response = await Page.GotoAsync(Server.Prefix + "/simple.json");105#pragma warning disable 0612106 Assert.AreEqual("gzip", response.Headers["content-encoding"]);107#pragma warning restore 0612108 Assert.AreEqual("{\"foo\": \"bar\"}", (await response.TextAsync()).Trim());109 }110 [PlaywrightTest("page-network-response.spec.ts", "should throw when requesting body of redirected response")]111 public async Task ShouldThrowWhenRequestingBodyOfRedirectedResponse()112 {113 Server.SetRedirect("/foo.html", "/empty.html");114 var response = await Page.GotoAsync(Server.Prefix + "/foo.html");115 var redirectedFrom = response.Request.RedirectedFrom;116 Assert.NotNull(redirectedFrom);117 var redirected = await redirectedFrom.ResponseAsync();118 Assert.AreEqual((int)HttpStatusCode.Redirect, redirected.Status);119 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => redirected.TextAsync());120 StringAssert.Contains("Response body is unavailable for redirect responses", exception.Message);121 }122 [PlaywrightTest("page-network-response.spec.ts", "should wait until response completes")]123 public async Task ShouldWaitUntilResponseCompletes()124 {125 await Page.GotoAsync(Server.EmptyPage);126 // Setup server to trap request.127 var serverResponseCompletion = new TaskCompletionSource<bool>();128 HttpResponse serverResponse = null;129 Server.SetRoute("/get", context =>130 {131 serverResponse = context.Response;132 context.Response.Headers["Content-Type"] = "text/plain; charset=utf-8";133 context.Response.WriteAsync("hello ");134 return serverResponseCompletion.Task;135 });136 // Setup page to trap response.137 bool requestFinished = false;138 Page.RequestFinished += (_, e) => requestFinished = requestFinished || e.Url.Contains("/get");139 // send request and wait for server response140 var (pageResponse, _) = await TaskUtils.WhenAll(141 Page.WaitForResponseAsync("**/*"),142 Page.EvaluateAsync("fetch('./get', { method: 'GET'})"),143 Server.WaitForRequest("/get")144 );145 Assert.NotNull(serverResponse);146 Assert.NotNull(pageResponse);147 Assert.AreEqual((int)HttpStatusCode.OK, pageResponse.Status);148 Assert.False(requestFinished);149 var responseText = pageResponse.TextAsync();150 // Write part of the response and wait for it to be flushed.151 await serverResponse.WriteAsync("wor");152 // Finish response.153 await serverResponse.WriteAsync("ld!");154 serverResponseCompletion.SetResult(true);155 Assert.AreEqual("hello world!", await responseText);156 }157 [PlaywrightTest("har.spec.ts", "should return security details directly from response")]158 [Skip(SkipAttribute.Targets.Webkit | SkipAttribute.Targets.Linux)]159 public async Task ShouldReturnSecurityDetails()160 {161 var response = await Page.GotoAsync(HttpsServer.EmptyPage);162 var details = await response.SecurityDetailsAsync();163 var name = "puppeteer-tests";164 Assert.AreEqual(name, details.SubjectName);165 if (TestConstants.IsWebKit)166 {167 Assert.AreEqual(1550084863f, details.ValidFrom);168 }169 else170 {171 Assert.AreEqual(name, details.Issuer);172 StringAssert.Contains("TLS 1.", details.Protocol);173 }174 }175 [PlaywrightTest("har.spec.ts", "should return server address directly from response")]176 public async Task ShouldReturnServerAddressFromResponse()177 {178 var response = await Page.GotoAsync(HttpsServer.EmptyPage);179 var details = await response.ServerAddrAsync();180 Assert.IsNotEmpty(details.IpAddress);181 Assert.Greater(details.Port, 0);182 }183 public override BrowserNewContextOptions ContextOptions() => new() { IgnoreHTTPSErrors = true };184 [PlaywrightTest("har.spec.ts", "should report multiple set-cookie headers")]185 public async Task ShouldReportMultipleSetCookieHeaders()186 {187 Server.SetRoute("/headers", async ctx =>188 {189 ctx.Response.Headers.Append("Set-Cookie", "a=b");190 ctx.Response.Headers.Append("Set-Cookie", "c=d");191 await Task.CompletedTask;192 });193 await Page.GotoAsync(Server.EmptyPage);194 var responseTask = Page.WaitForResponseAsync("**/*");195 await Task.WhenAll(responseTask, Page.EvaluateAsync("() => fetch('/headers')"));196 var response = responseTask.Result;197 var resultedHeaders = (await response.HeadersArrayAsync()).Where(x => x.Name.ToLower() == "set-cookie");198 var values = resultedHeaders.Select(x => x.Value).ToArray();199 CollectionAssert.AreEqual(new string[] { "a=b", "c=d" }, values);200 Assert.IsNull(await response.HeaderValueAsync("not-there"));201 Assert.AreEqual("a=b\nc=d", await response.HeaderValueAsync("set-cookie"));202 Assert.AreEqual(new string[] { "a=b", "c=d" }, (await response.HeaderValuesAsync("set-cookie")).ToArray());203 }204 [PlaywrightTest("page-network-response.spec.ts", "should behave the same way for headers and allHeaders")]205 [Skip(SkipAttribute.Targets.Webkit | SkipAttribute.Targets.Windows)] // libcurl does not support non-set-cookie multivalue headers206 public async Task ShouldBehaveTheSameWayForHeadersAndAllHeaders()207 {208 Server.SetRoute("/headers", async ctx =>209 {210 if (!TestConstants.IsChromium)211 {212 ctx.Response.Headers.Append("Set-Cookie", "a=b");213 ctx.Response.Headers.Append("Set-Cookie", "c=d");214 }215 ctx.Response.Headers.Append("Name-A", "v1");216 ctx.Response.Headers.Append("name-B", "v4");217 ctx.Response.Headers.Append("Name-a", "v2");218 ctx.Response.Headers.Append("name-A", "v3");219 await ctx.Response.WriteAsync("\r\n");220 await ctx.Response.CompleteAsync();221 });222 await Page.GotoAsync(Server.EmptyPage);223 var responseTask = Page.WaitForResponseAsync("**/*");224 await Task.WhenAll(responseTask, Page.EvaluateAsync("() => fetch('/headers')"));225 var response = responseTask.Result;226 var allHeaders = await response.AllHeadersAsync();227#pragma warning disable 0612228 Assert.AreEqual(response.Headers, allHeaders);229#pragma warning restore 0612230 }231 }232}...
ColesOnlineService.cs
Source:ColesOnlineService.cs
1using CatalogueScanner.Core.Utility;2using CatalogueScanner.WebScraping.Dto.ColesOnline;3using CatalogueScanner.WebScraping.JavaScript;4using CatalogueScanner.WebScraping.Options;5using Microsoft.Extensions.Logging;6using Microsoft.Extensions.Options;7using Microsoft.Playwright;8using System;9using System.Net.Http;10using System.Text.Json;11using System.Threading;12using System.Threading.Tasks;13namespace CatalogueScanner.WebScraping.Service14{15 public class ColesOnlineService16 {17 private const string ColesBaseUrl = "https://shop.coles.com.au";18 private readonly ColesOnlineOptions options;19 private readonly ILogger<ColesOnlineService> logger;20 private readonly PlaywrightBrowserManager browserManager;21 public ColesOnlineService(IOptionsSnapshot<ColesOnlineOptions> optionsAccessor, ILogger<ColesOnlineService> logger, PlaywrightBrowserManager browserManager)22 {23 #region null checks24 if (optionsAccessor is null)25 {26 throw new ArgumentNullException(nameof(optionsAccessor));27 }28 #endregion29 options = optionsAccessor.Value;30 this.logger = logger ?? throw new ArgumentNullException(nameof(logger));31 this.browserManager = browserManager ?? throw new ArgumentNullException(nameof(browserManager));32 #region options null checks33 if (options.StoreId is null)34 {35 throw new ArgumentException($"{ColesOnlineOptions.ColesOnline}.{nameof(options.StoreId)} is null", nameof(optionsAccessor));36 }37 #endregion38 }39 /// <summary>40 /// The time of week when Coles Online changes its specials.41 /// </summary>42 public static TimeOfWeek SpecialsResetTime => new(TimeSpan.Zero, DayOfWeek.Wednesday, "AUS Eastern Standard Time");43 public Uri ProductUrlTemplate => new($"{ColesBaseUrl}/a/{options.StoreId}/product/[productToken]");44 public async Task<int> GetSpecialsTotalPageCountAsync(string instanceId, CancellationToken cancellationToken = default)45 {46 var context = await browserManager.NewContextAsync(instanceId, cancellationToken: cancellationToken).ConfigureAwait(false);47 await using var _ = context.ConfigureAwait(false);48 var page = await CreateAndInitialiseSpecialsPage(context).ConfigureAwait(false);49 await page.WaitForFunctionAsync("CatalogueScanner_ColesOnline.instance.isPaginationLoaded").ConfigureAwait(false);50 return await page.EvaluateAsync<int>("CatalogueScanner_ColesOnline.instance.totalPageCount").ConfigureAwait(false);51 }52 public async Task<ColrsCatalogEntryList> GetSpecialsPageAsync(string instanceId, int pageNum, CancellationToken cancellationToken = default)53 {54 var context = await browserManager.NewContextAsync(instanceId, cancellationToken: cancellationToken).ConfigureAwait(false);55 await using var _ = context.ConfigureAwait(false);56 var page = await CreateAndInitialiseSpecialsPage(context).ConfigureAwait(false);57 logger.LogDebug("Page {PageNum} - Starting", pageNum);58 await page.WaitForFunctionAsync("CatalogueScanner_ColesOnline.instance.isPaginationLoaded").ConfigureAwait(false);59 await page.EvaluateAsync("pageNum => CatalogueScanner_ColesOnline.instance.loadPage(pageNum)", pageNum).ConfigureAwait(false);60 // The server returns the JSON data in compressed form with keys like "p1" and "a" that then get converted to full keys like "name" and "attributesMap".61 // Wait until the data has been decompressed before we read it.62 await page.WaitForFunctionAsync("CatalogueScanner_ColesOnline.instance.isDataLoaded").ConfigureAwait(false);63 logger.LogDebug("Page {PageNum} - Data Loaded", pageNum);64 // Playwright's EvaluateArgumentValueConverter doesn't seem to be able to deserialise to ColrsCatalogEntryList (and doesn't handle custom names),65 // so serialise the data to JSON in the browser and then deserialise to ColrsCatalogEntryList (using Newtonsoft.Json rather than System.Text.Json).66 var productDataJson = await page.EvaluateAsync<string>("JSON.stringify(CatalogueScanner_ColesOnline.instance.productListData)")67 .ConfigureAwait(false);68 if (productDataJson is null)69 {70 throw new InvalidOperationException($"{nameof(productDataJson)} is null after evaluating productListData expression");71 }72 logger.LogDebug("Page {PageNum} - Data Received from Playwright", pageNum);73 var productData = JsonSerializer.Deserialize(productDataJson, ColesOnlineSerializerContext.Default.ColrsCatalogEntryList);74 if (productData is null)75 {76 throw new InvalidOperationException($"{nameof(productData)} is null after deserialising from {nameof(productDataJson)}");77 }78 return productData;79 }80 private async Task<IPage> CreateAndInitialiseSpecialsPage(IBrowserContext context)81 {82 var page = await context.NewPageAsync().ConfigureAwait(false);83 page.SetDefaultTimeout((float)TimeSpan.FromMinutes(3).TotalMilliseconds);84 await page.AddInitScriptAsync(script: JavaScriptFiles.ColesOnline).ConfigureAwait(false);85 // Prevent all external requests for advertising, tracking, etc.86 await page.RouteAsync(87 (url) => !url.StartsWith(ColesBaseUrl, StringComparison.OrdinalIgnoreCase),88 (route) => route.AbortAsync()89 ).ConfigureAwait(false);90 // Navigate to the Specials page91 var response = await page.GotoAsync(92 $"{ColesBaseUrl}/a/{options.StoreId}/specials/browse",93 new PageGotoOptions94 {95 WaitUntil = WaitUntilState.DOMContentLoaded,96 }97 ).ConfigureAwait(false);98 if (response is null)99 {100 throw new InvalidOperationException("Page goto response is null");101 }102 if (!response.Ok)103 {104 throw new HttpRequestException($"Coles Online request failed with status {response.Status} ({response.StatusText}) - {await response.TextAsync().ConfigureAwait(false)}");105 }106 return page;107 }108 }109}...
FrameGoToTests.cs
Source:FrameGoToTests.cs
...65 StringAssert.Contains("Timeout 5000ms", exception.Message);66 StringAssert.Contains($"navigating to \"{url}\", waiting until \"networkidle\"", exception.Message);67 }68 [PlaywrightTest("frame-goto.spec.ts", "should return matching responses")]69 public async Task ShouldReturnMatchingResponses()70 {71 await Page.GotoAsync(Server.EmptyPage);72 // Attach three frames.73 var matchingData = new MatchingResponseData[]74 {75 new() { FrameTask = FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage)},76 new() { FrameTask = FrameUtils.AttachFrameAsync(Page, "frame2", Server.EmptyPage)},77 new() { FrameTask = FrameUtils.AttachFrameAsync(Page, "frame3", Server.EmptyPage)}78 };79 await TaskUtils.WhenAll(matchingData.Select(m => m.FrameTask));80 // Navigate all frames to the same URL.81 var requestHandler = new RequestDelegate(async (context) =>82 {83 if (int.TryParse(context.Request.Query["index"], out int index))84 {85 await context.Response.WriteAsync(await matchingData[index].ServerResponseTcs.Task);86 }87 });88 Server.SetRoute("/one-style.html?index=0", requestHandler);89 Server.SetRoute("/one-style.html?index=1", requestHandler);90 Server.SetRoute("/one-style.html?index=2", requestHandler);91 for (int i = 0; i < 3; ++i)92 {93 var waitRequestTask = Server.WaitForRequest("/one-style.html");94 matchingData[i].NavigationTask = matchingData[i].FrameTask.Result.GotoAsync($"{Server.Prefix}/one-style.html?index={i}");95 await waitRequestTask;96 }97 // Respond from server out-of-order.98 string[] serverResponseTexts = new string[] { "AAA", "BBB", "CCC" };99 for (int i = 0; i < 3; ++i)100 {101 matchingData[i].ServerResponseTcs.TrySetResult(serverResponseTexts[i]);102 var response = await matchingData[i].NavigationTask;103 Assert.AreEqual(matchingData[i].FrameTask.Result, response.Frame);104 Assert.AreEqual(serverResponseTexts[i], await response.TextAsync());105 }106 }107 class MatchingResponseData108 {109 public Task<IFrame> FrameTask { get; internal set; }110 public TaskCompletionSource<string> ServerResponseTcs { get; internal set; } = new();111 public Task<IResponse> NavigationTask { get; internal set; }112 }113 }114}...
IgnoreHttpsErrorsTests.cs
Source:IgnoreHttpsErrorsTests.cs
...62 public async Task ShouldWorkWithMixedContent()63 {64 HttpsServer.SetRoute("/mixedcontent.html", async (context) =>65 {66 await context.Response.WriteAsync($"<iframe src='{Server.EmptyPage}'></iframe>");67 });68 await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });69 var page = await context.NewPageAsync();70 await page.GotoAsync(HttpsServer.Prefix + "/mixedcontent.html", new() { WaitUntil = WaitUntilState.DOMContentLoaded });71 Assert.AreEqual(2, page.Frames.Count);72 Assert.AreEqual(3, await page.MainFrame.EvaluateAsync<int>("1 + 2"));73 Assert.AreEqual(5, await page.FirstChildFrame().EvaluateAsync<int>("2 + 3"));74 }75 [PlaywrightTest("ignorehttpserrors.spec.ts", "should work with WebSocket")]76 public async Task ShouldWorkWithWebSocket()77 {78 HttpsServer.SendOnWebSocketConnection("incoming");79 await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });80 var page = await context.NewPageAsync();...
ProxyTests.cs
Source:ProxyTests.cs
...33 {34 [PlaywrightTest("proxy.spec.ts", "should use proxy")]35 public async Task ShouldUseProxy()36 {37 Server.SetRoute("/target.html", ctx => ctx.Response.WriteAsync("<html><title>Served by the proxy</title></html>"));38 var proxy = new Proxy { Server = $"localhost:{Server.Port}" };39 await using var browser = await BrowserType.LaunchAsync(new() { Proxy = proxy });40 var page = await browser.NewPageAsync();41 await page.GotoAsync("http://non-existent.com/target.html");42 Assert.AreEqual("Served by the proxy", await page.TitleAsync());43 }44 [PlaywrightTest("proxy.spec.ts", "should authenticate")]45 public async Task ShouldAuthenticate()46 {47 Server.SetRoute("/target.html", ctx =>48 {49 string auth = ctx.Request.Headers["proxy-authorization"];50 if (string.IsNullOrEmpty(auth))51 {52 ctx.Response.StatusCode = 407;53 ctx.Response.Headers["Proxy-Authenticate"] = "Basic realm=\"Access to internal site\"";54 }55 return ctx.Response.WriteAsync($"<html><title>{auth}</title></html>");56 });57 var proxy = new Proxy58 {59 Server = $"localhost:{Server.Port}",60 Username = "user",61 Password = "secret"62 };63 await using var browser = await BrowserType.LaunchAsync(new() { Proxy = proxy });64 var page = await browser.NewPageAsync();65 await page.GotoAsync("http://non-existent.com/target.html");66 Assert.AreEqual("Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("user:secret")), await page.TitleAsync());67 }68 [PlaywrightTest("proxy.spec.ts", "should exclude patterns")]69 public async Task ShouldExcludePatterns()70 {71 Server.SetRoute("/target.html", ctx => ctx.Response.WriteAsync("<html><title>Served by the proxy</title></html>"));72 var proxy = new Proxy73 {74 Server = $"localhost:{Server.Port}",75 Bypass = "non-existent1.com, .non-existent2.com, .another.test",76 };77 await using var browser = await BrowserType.LaunchAsync(new() { Proxy = proxy });78 var page = await browser.NewPageAsync();79 await page.GotoAsync("http://non-existent.com/target.html");80 Assert.AreEqual("Served by the proxy", await page.TitleAsync());81 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync("http://non-existent1.com/target.html"));82 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync("http://sub.non-existent2.com/target.html"));83 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync("http://foo.is.the.another.test/target.html"));84 }85 }...
BinaryHttpClientTest.cs
Source:BinaryHttpClientTest.cs
1// Copyright (c) .NET Foundation. All rights reserved.2// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.3using System;4using System.Linq;5using System.Threading.Tasks;6using BasicTestApp.HttpClientTest;7using Microsoft.AspNetCore.BrowserTesting;8using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;9using Microsoft.AspNetCore.Components.E2ETest.Infrastructure;10using Microsoft.AspNetCore.Testing;11using PlaywrightSharp;12using TestServer;13using Xunit;14using Xunit.Abstractions;15namespace Microsoft.AspNetCore.Components.E2ETest.Tests16{17 public class BinaryHttpClientTest : PlaywrightTestBase,18 IClassFixture<BasicTestAppServerSiteFixture<CorsStartup>>,19 IClassFixture<DevHostServerFixture<BasicTestApp.Program>>20 {21 private readonly DevHostServerFixture<BasicTestApp.Program> _devHostServerFixture;22 readonly ServerFixture _apiServerFixture;23 //IWebElement _appElement;24 //IWebElement _responseStatus;25 //IWebElement _responseStatusText;26 //IWebElement _testOutcome;27 public BinaryHttpClientTest(28 DevHostServerFixture<BasicTestApp.Program> devHostServerFixture,29 BasicTestAppServerSiteFixture<CorsStartup> apiServerFixture,30 ITestOutputHelper output)31 : base(output)32 {33 _devHostServerFixture = devHostServerFixture;34 _devHostServerFixture.PathBase = "/subdir";35 _apiServerFixture = apiServerFixture;36 }37 //protected override void InitializeAsyncCore()38 //{39 // //Browser.Navigate(_devHostServerFixture.RootUri, "/subdir", noReload: true);40 // //_appElement = Browser.MountTestComponent<BinaryHttpRequestsComponent>();41 //}42 [Fact]43 public async Task CanSendAndReceiveBytes()44 {45 if (BrowserManager.IsAvailable(BrowserKind.Chromium))46 {47 await using var browser = await BrowserManager.GetBrowserInstance(BrowserKind.Chromium, BrowserContextInfo);48 var page = await browser.NewPageAsync();49 await page.GoToAsync(_devHostServerFixture.RootUri + "/subdir/api/data");50/* var socket = BrowserContextInfo.Pages[page].WebSockets.SingleOrDefault() ??51 (await page.WaitForEventAsync(PageEvent.WebSocket)).WebSocket;52 // Receive render batch53 await socket.WaitForEventAsync(WebSocketEvent.FrameReceived);54 await socket.WaitForEventAsync(WebSocketEvent.FrameSent);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"));74 }75 }76}...
ReportController.cs
Source:ReportController.cs
...28 }29 [HttpGet]30 [Route("json")]31 [Produces(MediaTypeNames.Application.Json)]32 [ProducesResponseType(typeof(IAsyncEnumerable<Report>), StatusCodes.Status200OK)]33 public IActionResult GetJson(CancellationToken cancellationToken)34 => Ok(_reportProvider.GetAllRoles(cancellationToken));35 [HttpGet]36 [Route("html")]37 [Produces(MediaTypeNames.Text.Html)]38 [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]39 public async Task<IActionResult> GetHtml(CancellationToken cancellationToken)40 {41 var reports = await _reportProvider.GetAllRoles(cancellationToken).ToArrayAsync(cancellationToken);42 return View("~/Pages/Report/Index.cshtml", reports);43 }44 [HttpGet]45 [Route("pdf")]46 [Produces(MediaTypeNames.Text.Html)]47 [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]48 public async Task<IActionResult> GetPdf(CancellationToken cancellationToken)49 {50 var reports = await _reportProvider.GetAllRoles(cancellationToken).ToArrayAsync(cancellationToken);51 return await Pdf("~/Pages/Report/Index.cshtml", reports);52 }53 private async Task<FileContentResult> Pdf<TModel>(string view, TModel model)54 {55 using var playwright = await Playwright.CreateAsync();56 await using var browser = await playwright.Chromium.LaunchAsync(57 new BrowserTypeLaunchOptions58 {59 Headless = true60 });61 var page = await browser.NewPageAsync();...
HomeController.cs
Source:HomeController.cs
...38 <body>39 <div>Test header template</div>40 </body>41 </html>";42 var bytesResponse = await page.GetPdfAsync(null, 1, true, headerTemplate, "<div>Test footer template</div>", true, false, "", null,43 null, null, new Margin { Bottom = "1in", Top = "2in" }, false);44 FileResult fileResult = new FileContentResult(bytesResponse, "application/pdf");45 fileResult.FileDownloadName = "test.pdf";46 return fileResult;47 }48 public IActionResult Privacy()49 {50 return View();51 }52 [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]53 public IActionResult Error()54 {55 return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });56 }57 }58}...
Response
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions3{4});5var context = await browser.NewContextAsync(new BrowserNewContextOptions6{7 {8 }9});10var page = await context.NewPageAsync();11await page.FillAsync("input[title='Search']", "Playwright");12await page.PressAsync("input[title='Search']", "Enter");13await page.ScreenshotAsync("screenshot.png");14await browser.CloseAsync();15var playwright = await Playwright.CreateAsync();16var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions17{18});19var context = await browser.NewContextAsync(new BrowserNewContextOptions20{21 {22 }23});24var page = await context.NewPageAsync();25await page.FillAsync("input[title='Search']", "Playwright");26await page.PressAsync("input[title='Search']", "Enter");27await page.ScreenshotAsync("screenshot.png");28await browser.CloseAsync();29var playwright = await Playwright.CreateAsync();30var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions31{32});33var context = await browser.NewContextAsync(new BrowserNewContextOptions34{35 {36 }37});38var page = await context.NewPageAsync();39await page.FillAsync("input[title='Search']", "Playwright");40await page.PressAsync("input[title='Search']", "Enter");41await page.ScreenshotAsync("screenshot.png");42await browser.CloseAsync();43var playwright = await Playwright.CreateAsync();
Response
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync();3var page = await browser.NewPageAsync();4await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });5await browser.CloseAsync();6var playwright = await Playwright.CreateAsync();7var browser = await playwright.Chromium.LaunchAsync();8var page = await browser.NewPageAsync();9await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });10await browser.CloseAsync();11public async Task SearchGoogle()12{13 var playwright = await Playwright.CreateAsync();14 var browser = await playwright.Chromium.LaunchAsync();15 var page = await browser.NewPageAsync();16 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });17 await browser.CloseAsync();18}
Response
Using AI Code Generation
1var browser = await playwright.Chromium.LaunchAsync();2var context = await browser.NewContextAsync();3var page = await context.NewPageAsync();4var userAgent = await page.EvaluateAsync<string>("() => navigator.userAgent");5var title = await page.EvaluateAsync<string>("() => document.title");6Console.WriteLine($"User Agent: {userAgent}");7Console.WriteLine($"Title: {title}");8await browser.CloseAsync();9User Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.0 Safari/537.3610var playwright = await Playwright.CreateAsync();11var browser = await playwright.Chromium.LaunchAsync();12var context = await browser.NewContextAsync();13var page = await context.NewPageAsync();14var userAgent = await page.EvaluateAsync<string>("() => navigator.userAgent");15var title = await page.EvaluateAsync<string>("() => document.title");16Console.WriteLine($"User Agent: {userAgent}");17Console.WriteLine($"Title: {title}");18await browser.CloseAsync();19User Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.0 Safari/537.3620var playwright = await Playwright.CreateAsync();21var browser = await playwright.Chromium.LaunchAsync();22var context = await browser.NewContextAsync();23var page = await context.NewPageAsync();24var userAgent = await page.EvaluateAsync<string>("() => navigator.userAgent");25var title = await page.EvaluateAsync<string>("() => document.title");26Console.WriteLine($"User Agent: {userAgent}");27Console.WriteLine($"Title: {title}");28await browser.CloseAsync();29User Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89
Response
Using AI Code Generation
1using Microsoft.Playwright.Core;2using Microsoft.Playwright;3using Microsoft.Playwright;4using Microsoft.Playwright;5using Microsoft.Playwright;6using Microsoft.Playwright;7using Microsoft.Playwright;8using Microsoft.Playwright;9using Microsoft.Playwright;10using Microsoft.Playwright;11using Microsoft.Playwright;12using Microsoft.Playwright;13using Microsoft.Playwright;14using Microsoft.Playwright;15using Microsoft.Playwright;16using Microsoft.Playwright;17using Microsoft.Playwright;18using Microsoft.Playwright;19using Microsoft.Playwright;20using Microsoft.Playwright;21using Microsoft.Playwright;22using Microsoft.Playwright;23using Microsoft.Playwright;24using Microsoft.Playwright;25using Microsoft.Playwright;26using Microsoft.Playwright;27using Microsoft.Playwright;
Response
Using AI Code Generation
1{2 public async Task TestMethod()3 {4 var playwright = await Playwright.CreateAsync();5 var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions6 {7 });8 var context = await browser.NewContextAsync();9 var page = await context.NewPageAsync();10 var response = await page.WaitForResponseAsync("**/*");11 Console.WriteLine(response.Status);12 }13}14{15 public async Task TestMethod()16 {17 var playwright = await Playwright.CreateAsync();18 var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions19 {20 });21 var context = await browser.NewContextAsync();22 var page = await context.NewPageAsync();23 var response = await page.WaitForResponseAsync("**/*", new WaitForResponseOptions24 {25 });26 Console.WriteLine(response.Status);27 }28}29{30 public async Task TestMethod()31 {32 var playwright = await Playwright.CreateAsync();33 var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions34 {35 });36 var context = await browser.NewContextAsync();37 var page = await context.NewPageAsync();
Response
Using AI Code Generation
1var body = await response.TextAsync();2var body = await response.TextAsync();3var body = await response.TextAsync();4var body = await response.TextAsync();5var body = await response.TextAsync();6var body = await response.TextAsync();7var body = await response.TextAsync();8var body = await response.TextAsync();9var body = await response.TextAsync();10var body = await response.TextAsync();11var body = await response.TextAsync();12var body = await response.TextAsync();13var body = await response.TextAsync();
Response
Using AI Code Generation
1context.Response.Headers["Content-Type"] = "application/json";2context.Response.StatusCode = 200;3string json = JsonConvert.SerializeObject(new { name = "John" });4await context.Response.WriteAsync(json);5context.Response.ContentType = "application/json";6context.Response.StatusCode = 200;7var json = JsonConvert.SerializeObject(new { name = "John" });8await context.Response.WriteAsync(json);
Response
Using AI Code Generation
1var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/2"));2var responseBody = await response.TextAsync();3var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/2"));4var responseBody = await response.TextAsync();5var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/3"));6var responseBody = await response.TextAsync();7var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/3"));8var responseBody = await response.TextAsync();9var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/4"));10var responseBody = await response.TextAsync();11var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/4"));12var responseBody = await response.TextAsync();13var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/5"));14var responseBody = await response.TextAsync();15var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/5"));16var responseBody = await response.TextAsync();17var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/6"));18var responseBody = await response.TextAsync();19var response = await page.WaitForResponseAsync(request => request.Url.Contains("api/6"));20var responseBody = await response.TextAsync();
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.
Get 100 minutes of automation test minutes FREE!!