Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Stream.Write
BotCore.cs
Source:BotCore.cs
...147 {148 if (!File.Exists(_loginCookiesPath))149 {150 var item = new Dictionary<string, List<MyCookie>> {{cookie.Item1, myCookie}};151 File.WriteAllText(_loginCookiesPath, JsonConvert.SerializeObject(item), Encoding.UTF8);152 return;153 }154 var readCookiesJson = File.ReadAllText(_loginCookiesPath);155 var readCookies = JsonConvert.DeserializeObject<Dictionary<string, List<MyCookie>>>(readCookiesJson);156 readCookies.TryGetValue(cookie.Item1, out var value);157 if (value?.Count > 0)158 readCookies[cookie.Item1] = myCookie;159 else160 readCookies.Add(cookie.Item1, myCookie);161 File.WriteAllText(_loginCookiesPath, JsonConvert.SerializeObject(readCookies), Encoding.UTF8);162 }163 }164 private List<MyCookie> GetCookie(string username)165 {166 lock (_lockObject)167 {168 if (!File.Exists(_loginCookiesPath)) return new List<MyCookie>();169 var readCookiesJson = File.ReadAllText(_loginCookiesPath);170 var readCookies = JsonConvert.DeserializeObject<Dictionary<string, List<MyCookie>>>(readCookiesJson);171 return readCookies.FirstOrDefault(x => x.Key == username).Value;172 }173 }174 private void KillAllProcesses()175 {...
DownloadTests.cs
Source:DownloadTests.cs
...37 Server.SetRoute("/download", context =>38 {39 context.Response.Headers["Content-Type"] = "application/octet-stream";40 context.Response.Headers["Content-Disposition"] = "attachment";41 return context.Response.WriteAsync("Hello world");42 });43 Server.SetRoute("/downloadWithFilename", context =>44 {45 context.Response.Headers["Content-Type"] = "application/octet-stream";46 context.Response.Headers["Content-Disposition"] = "attachment; filename=file.txt";47 return context.Response.WriteAsync("Hello world");48 });49 Server.SetRoute("/downloadWithDelay", async context =>50 {51 context.Response.Headers["Content-Type"] = "application/octet-stream";52 context.Response.Headers["Content-Disposition"] = "attachment;";53 // Chromium requires a large enough payload to trigger the download event soon enough54 await context.Response.WriteAsync("a".PadLeft(4096, 'a'));55 await Task.Delay(3000);56 await context.Response.WriteAsync("foo hello world");57 });58 Server.SetRoute("/downloadLarge", context =>59 {60 context.Response.Headers["Content-Type"] = "application/octet-stream";61 context.Response.Headers["Content-Disposition"] = "attachment";62 var payload = string.Empty;63 for (var i = 0; i < 10_000; i++)64 {65 payload += $"a{i}";66 }67 return context.Response.WriteAsync(payload);68 });69 }70 [PlaywrightTest("download.spec.ts", "should report downloads with acceptDownloads: false")]71 public async Task ShouldReportDownloadsWithAcceptDownloadsFalse()72 {73 await Page.SetContentAsync($"<a href=\"{Server.Prefix}/downloadWithFilename\">download</a>");74 var downloadTask = Page.WaitForDownloadAsync();75 await TaskUtils.WhenAll(76 downloadTask,77 Page.ClickAsync("a"));78 var download = downloadTask.Result;79 Assert.AreEqual($"{Server.Prefix}/downloadWithFilename", download.Url);80 Assert.AreEqual("file.txt", download.SuggestedFilename);81 string path = await download.PathAsync();82 Assert.True(new FileInfo(path).Exists);83 Assert.AreEqual("Hello world", File.ReadAllText(path));84 }85 [PlaywrightTest("download.spec.ts", "should report downloads with acceptDownloads: true")]86 public async Task ShouldReportDownloadsWithAcceptDownloadsTrue()87 {88 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });89 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");90 var download = await page.RunAndWaitForDownloadAsync(async () =>91 {92 await page.ClickAsync("a");93 });94 string path = await download.PathAsync();95 Assert.True(new FileInfo(path).Exists);96 Assert.AreEqual("Hello world", File.ReadAllText(path));97 }98 [PlaywrightTest("download.spec.ts", "should save to user-specified path")]99 public async Task ShouldSaveToUserSpecifiedPath()100 {101 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });102 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");103 var download = await page.RunAndWaitForDownloadAsync(async () =>104 {105 await page.ClickAsync("a");106 });107 using var tmpDir = new TempDirectory();108 string userPath = Path.Combine(tmpDir.Path, "download.txt");109 await download.SaveAsAsync(userPath);110 Assert.True(new FileInfo(userPath).Exists);111 Assert.AreEqual("Hello world", File.ReadAllText(userPath));112 await page.CloseAsync();113 }114 [PlaywrightTest("download.spec.ts", "should save to user-specified path without updating original path")]115 public async Task ShouldSaveToUserSpecifiedPathWithoutUpdatingOriginalPath()116 {117 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });118 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");119 var download = await page.RunAndWaitForDownloadAsync(async () =>120 {121 await page.ClickAsync("a");122 });123 using var tmpDir = new TempDirectory();124 string userPath = Path.Combine(tmpDir.Path, "download.txt");125 await download.SaveAsAsync(userPath);126 Assert.True(new FileInfo(userPath).Exists);127 Assert.AreEqual("Hello world", File.ReadAllText(userPath));128 string originalPath = await download.PathAsync();129 Assert.True(new FileInfo(originalPath).Exists);130 Assert.AreEqual("Hello world", File.ReadAllText(originalPath));131 await page.CloseAsync();132 }133 [PlaywrightTest("download.spec.ts", "should save to two different paths with multiple saveAs calls")]134 public async Task ShouldSaveToTwoDifferentPathsWithMultipleSaveAsCalls()135 {136 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });137 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");138 var download = await page.RunAndWaitForDownloadAsync(async () =>139 {140 await page.ClickAsync("a");141 });142 using var tmpDir = new TempDirectory();143 string userPath = Path.Combine(tmpDir.Path, "download.txt");144 await download.SaveAsAsync(userPath);145 Assert.True(new FileInfo(userPath).Exists);146 Assert.AreEqual("Hello world", File.ReadAllText(userPath));147 string anotherUserPath = Path.Combine(tmpDir.Path, "download (2).txt");148 await download.SaveAsAsync(anotherUserPath);149 Assert.True(new FileInfo(anotherUserPath).Exists);150 Assert.AreEqual("Hello world", File.ReadAllText(anotherUserPath));151 await page.CloseAsync();152 }153 [PlaywrightTest("download.spec.ts", "should save to overwritten filepath")]154 public async Task ShouldSaveToOverwrittenFilepath()155 {156 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });157 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");158 var downloadTask = page.WaitForDownloadAsync();159 await TaskUtils.WhenAll(160 downloadTask,161 page.ClickAsync("a"));162 using var tmpDir = new TempDirectory();163 string userPath = Path.Combine(tmpDir.Path, "download.txt");164 var download = downloadTask.Result;165 await download.SaveAsAsync(userPath);166 Assert.AreEqual(1, new DirectoryInfo(tmpDir.Path).GetFiles().Length);167 await download.SaveAsAsync(userPath);168 Assert.AreEqual(1, new DirectoryInfo(tmpDir.Path).GetFiles().Length);169 await page.CloseAsync();170 }171 [PlaywrightTest("download.spec.ts", "should create subdirectories when saving to non-existent user-specified path")]172 public async Task ShouldCreateSubdirectoriesWhenSavingToNonExistentUserSpecifiedPath()173 {174 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });175 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");176 var downloadTask = page.WaitForDownloadAsync();177 await TaskUtils.WhenAll(178 downloadTask,179 page.ClickAsync("a"));180 using var tmpDir = new TempDirectory();181 string userPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "download.txt");182 var download = downloadTask.Result;183 await download.SaveAsAsync(userPath);184 Assert.True(new FileInfo(userPath).Exists);185 Assert.AreEqual("Hello world", File.ReadAllText(userPath));186 await page.CloseAsync();187 }188 [PlaywrightTest("download.spec.ts", "should error when saving with downloads disabled")]189 public async Task ShouldErrorWhenSavingWithDownloadsDisabled()190 {191 var page = await Browser.NewPageAsync(new() { AcceptDownloads = false });192 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");193 var downloadTask = page.WaitForDownloadAsync();194 await TaskUtils.WhenAll(195 downloadTask,196 page.ClickAsync("a"));197 using var tmpDir = new TempDirectory();198 string userPath = Path.Combine(tmpDir.Path, "download.txt");199 var download = downloadTask.Result;200 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));201 StringAssert.Contains("Pass { acceptDownloads: true } when you are creating your browser context", exception.Message);202 }203 [PlaywrightTest("download.spec.ts", "should error when saving after deletion")]204 public async Task ShouldErrorWhenSavingAfterDeletion()205 {206 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });207 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");208 var downloadTask = page.WaitForDownloadAsync();209 await TaskUtils.WhenAll(210 downloadTask,211 page.ClickAsync("a"));212 using var tmpDir = new TempDirectory();213 string userPath = Path.Combine(tmpDir.Path, "download.txt");214 var download = downloadTask.Result;215 await download.DeleteAsync();216 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));217 StringAssert.Contains("Target page, context or browser has been closed", exception.Message);218 }219 [PlaywrightTest("download.spec.ts", "should report non-navigation downloads")]220 public async Task ShouldReportNonNavigationDownloads()221 {222 Server.SetRoute("/download", context =>223 {224 context.Response.Headers["Content-Type"] = "application/octet-stream";225 return context.Response.WriteAsync("Hello world");226 });227 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });228 await page.GotoAsync(Server.EmptyPage);229 await page.SetContentAsync($"<a download=\"file.txt\" href=\"{Server.Prefix}/download\">download</a>");230 var downloadTask = page.WaitForDownloadAsync();231 await TaskUtils.WhenAll(232 downloadTask,233 page.ClickAsync("a"));234 var download = downloadTask.Result;235 Assert.AreEqual("file.txt", download.SuggestedFilename);236 string path = await download.PathAsync();237 Assert.True(new FileInfo(path).Exists);238 Assert.AreEqual("Hello world", File.ReadAllText(path));239 await page.CloseAsync();240 }241 [PlaywrightTest("download.spec.ts", "should report download path within page.on('download', â¦) handler for Files")]242 public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForFiles()243 {244 var downloadPathTcs = new TaskCompletionSource<string>();245 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });246 page.Download += async (_, e) =>247 {248 downloadPathTcs.TrySetResult(await e.PathAsync());249 };250 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");251 await page.ClickAsync("a");252 string path = await downloadPathTcs.Task;253 Assert.AreEqual("Hello world", File.ReadAllText(path));254 await page.CloseAsync();255 }256 [PlaywrightTest("download.spec.ts", "should report download path within page.on('download', â¦) handler for Blobs")]257 public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForBlobs()258 {259 var downloadPathTcs = new TaskCompletionSource<string>();260 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });261 page.Download += async (_, e) =>262 {263 downloadPathTcs.TrySetResult(await e.PathAsync());264 };265 await page.GotoAsync(Server.Prefix + "/download-blob.html");266 await page.ClickAsync("a");267 string path = await downloadPathTcs.Task;268 Assert.AreEqual("Hello world", File.ReadAllText(path));269 await page.CloseAsync();270 }271 [PlaywrightTest("download.spec.ts", "should report alt-click downloads")]272 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]273 public async Task ShouldReportAltClickDownloads()274 {275 Server.SetRoute("/download", context =>276 {277 context.Response.Headers["Content-Type"] = "application/octet-stream";278 return context.Response.WriteAsync("Hello world");279 });280 var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });281 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");282 var downloadTask = page.WaitForDownloadAsync();283 await TaskUtils.WhenAll(284 downloadTask,285 page.ClickAsync("a", new() { Modifiers = new[] { KeyboardModifier.Alt } }));286 var download = downloadTask.Result;287 string path = await download.PathAsync();288 Assert.True(new FileInfo(path).Exists);289 Assert.AreEqual("Hello world", File.ReadAllText(path));290 }291 [PlaywrightTest("download.spec.ts", "should report new window downloads")]292 public async Task ShouldReportNewWindowDownloads()...
PageNetworkRequestTest.cs
Source:PageNetworkRequestTest.cs
...166 ctx.Response.Headers["content-type"] = "text/event-stream";167 ctx.Response.Headers["connection"] = "keep-alive";168 ctx.Response.Headers["cache-control"] = "no-cache";169 await ctx.Response.Body.FlushAsync();170 await ctx.Response.WriteAsync($"data: {sseMessage}\r\r");171 await ctx.Response.Body.FlushAsync();172 });173 await Page.GotoAsync(Server.EmptyPage);174 var requests = new List<IRequest>();175 Page.Request += (_, e) => requests.Add(e);176 Assert.AreEqual(sseMessage, await Page.EvaluateAsync<string>(@"() => {177 const eventSource = new EventSource('/sse');178 return new Promise(resolve => {179 eventSource.onmessage = e => resolve(e.data);180 });181 }"));182 Assert.AreEqual("eventsource", requests[0].ResourceType);183 }184 [PlaywrightTest("page-network-request.spec.ts", "should return navigation bit")]185 public async Task ShouldReturnNavigationBit()186 {187 var requests = new Dictionary<string, IRequest>();188 Page.Request += (_, e) => requests[e.Url.Split('/').Last()] = e;189 Server.SetRedirect("/rrredirect", "/frames/one-frame.html");190 await Page.GotoAsync(Server.Prefix + "/rrredirect");191 Assert.True(requests["rrredirect"].IsNavigationRequest);192 Assert.True(requests["one-frame.html"].IsNavigationRequest);193 Assert.True(requests["frame.html"].IsNavigationRequest);194 Assert.False(requests["script.js"].IsNavigationRequest);195 Assert.False(requests["style.css"].IsNavigationRequest);196 }197 [PlaywrightTest("page-network-request.spec.ts", "Request.isNavigationRequest", "should return navigation bit when navigating to image")]198 public async Task ShouldReturnNavigationBitWhenNavigatingToImage()199 {200 var requests = new List<IRequest>();201 Page.Request += (_, e) => requests.Add(e);202 await Page.GotoAsync(Server.Prefix + "/pptr.png");203 Assert.True(requests[0].IsNavigationRequest);204 }205 [PlaywrightTest("page-network-request.spec.ts", "should set bodySize and headersSize")]206 public async Task ShouldSetBodySizeAndHeaderSize()207 {208 await Page.GotoAsync(Server.EmptyPage);209 var tsc = new TaskCompletionSource<RequestSizesResult>();210 Page.Request += async (sender, r) =>211 {212 await (await r.ResponseAsync()).FinishedAsync();213 tsc.SetResult(await r.SizesAsync());214 };215 await Page.EvaluateAsync("() => fetch('./get', { method: 'POST', body: '12345'}).then(r => r.text())");216 var sizes = await tsc.Task;217 Assert.AreEqual(5, sizes.RequestBodySize);218 Assert.GreaterOrEqual(sizes.RequestHeadersSize, 200);219 }220 [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize to 0 if there was no body")]221 public async Task ShouldSetBodysizeTo0IfThereWasNoBody()222 {223 await Page.GotoAsync(Server.EmptyPage);224 var tsc = new TaskCompletionSource<RequestSizesResult>();225 Page.Request += async (sender, r) =>226 {227 await (await r.ResponseAsync()).FinishedAsync();228 tsc.SetResult(await r.SizesAsync());229 };230 await Page.EvaluateAsync("() => fetch('./get').then(r => r.text())");231 var sizes = await tsc.Task;232 Assert.AreEqual(0, sizes.RequestBodySize);233 Assert.GreaterOrEqual(sizes.RequestHeadersSize, 200);234 }235 [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize, headersSize, and transferSize")]236 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Chromium, SkipAttribute.Targets.Webkit)]237 public async Task ShouldSetAllTheResponseSizes()238 {239 Server.SetRoute("/get", async ctx =>240 {241 ctx.Response.Headers["Content-Type"] = "text/plain; charset=utf-8";242 await ctx.Response.WriteAsync("abc134");243 await ctx.Response.CompleteAsync();244 });245 await Page.GotoAsync(Server.EmptyPage);246 var tsc = new TaskCompletionSource<RequestSizesResult>();247 Page.Request += async (sender, r) =>248 {249 await (await r.ResponseAsync()).FinishedAsync();250 tsc.SetResult(await r.SizesAsync());251 };252 var message = await Page.EvaluateAsync<string>("() => fetch('./get').then(r => r.arrayBuffer()).then(b => b.bufferLength)");253 var sizes = await tsc.Task;254 Assert.AreEqual(6, sizes.ResponseBodySize);255 Assert.GreaterOrEqual(sizes.ResponseHeadersSize, 142);256 }...
InputFileTest.cs
Source:InputFileTest.cs
...241 }242 public static TempFile Create(string tempDirectory, string extension, byte[] contents)243 {244 var file = new TempFile(tempDirectory, extension, contents);245 File.WriteAllBytes(file.Path, contents);246 return file;247 }248 public static TempFile Create(string tempDirectory, string extension, string text)249 => Create(tempDirectory, extension, Encoding.ASCII.GetBytes(text));250 }251 }252}...
AspNetProcess.cs
Source:AspNetProcess.cs
...52 })53 {54 Timeout = TimeSpan.FromMinutes(2)55 };56 output.WriteLine("Running ASP.NET Core application...");57 string process;58 string arguments;59 if (published)60 {61 if (usePublishedAppHost)62 {63 // When publishingu used the app host to run the app. This makes it easy to consistently run for regular and single-file publish64 process = Path.ChangeExtension(dllPath, OperatingSystem.IsWindows() ? ".exe" : null);65 arguments = null;66 }67 else68 {69 process = DotNetMuxer.MuxerPathOrDefault();70 arguments = $"exec {dllPath}";71 }72 }73 else74 {75 process = DotNetMuxer.MuxerPathOrDefault();76 arguments = "run --no-build";77 }78 logger?.LogInformation($"AspNetProcess - process: {process} arguments: {arguments}");79 var finalEnvironmentVariables = new Dictionary<string, string>(environmentVariables)80 {81 ["ASPNETCORE_Kestrel__Certificates__Default__Path"] = _developmentCertificate.CertificatePath,82 ["ASPNETCORE_Kestrel__Certificates__Default__Password"] = _developmentCertificate.CertificatePassword,83 };84 Process = ProcessEx.Run(output, workingDirectory, process, arguments, envVars: finalEnvironmentVariables);85 logger?.LogInformation("AspNetProcess - process started");86 if (hasListeningUri)87 {88 logger?.LogInformation("AspNetProcess - Getting listening uri");89 ListeningUri = ResolveListeningUrl(output);90 logger?.LogInformation($"AspNetProcess - Got {ListeningUri}");91 }92 }93 public async Task VisitInBrowserAsync(IPage page)94 {95 _output.WriteLine($"Opening browser at {ListeningUri}...");96 await page.GoToAsync(ListeningUri.AbsoluteUri);97 }98 public async Task AssertPagesOk(IEnumerable<Page> pages)99 {100 foreach (var page in pages)101 {102 await AssertOk(page.Url);103 await ContainsLinks(page);104 }105 }106 public async Task ContainsLinks(Page page)107 {108 var response = await RetryHelper.RetryRequest(async () =>109 {110 var request = new HttpRequestMessage(111 HttpMethod.Get,112 new Uri(ListeningUri, page.Url));113 return await _httpClient.SendAsync(request);114 }, logger: NullLogger.Instance);115 Assert.Equal(HttpStatusCode.OK, response.StatusCode);116 var parser = new HtmlParser();117 var html = await parser.ParseAsync(await response.Content.ReadAsStreamAsync());118 foreach (IHtmlLinkElement styleSheet in html.GetElementsByTagName("link"))119 {120 Assert.Equal("stylesheet", styleSheet.Relation);121 await AssertOk(styleSheet.Href.Replace("about://", string.Empty));122 }123 foreach (var script in html.Scripts)124 {125 if (!string.IsNullOrEmpty(script.Source))126 {127 await AssertOk(script.Source);128 }129 }130 Assert.True(html.Links.Length == page.Links.Count(), $"Expected {page.Url} to have {page.Links.Count()} links but it had {html.Links.Length}");131 foreach ((var link, var expectedLink) in html.Links.Zip(page.Links, Tuple.Create))132 {133 IHtmlAnchorElement anchor = (IHtmlAnchorElement)link;134 if (string.Equals(anchor.Protocol, "about:"))135 {136 Assert.True(anchor.PathName.EndsWith(expectedLink, StringComparison.Ordinal), $"Expected next link on {page.Url} to be {expectedLink} but it was {anchor.PathName}: {html.Source.Text}");137 await AssertOk(anchor.PathName);138 }139 else140 {141 Assert.True(string.Equals(anchor.Href, expectedLink), $"Expected next link to be {expectedLink} but it was {anchor.Href}.");142 var result = await RetryHelper.RetryRequest(async () =>143 {144 return await _httpClient.GetAsync(anchor.Href);145 }, logger: NullLogger.Instance);146 Assert.True(IsSuccessStatusCode(result), $"{anchor.Href} is a broken link!");147 }148 }149 }150 private Uri ResolveListeningUrl(ITestOutputHelper output)151 {152 // Wait until the app is accepting HTTP requests153 output.WriteLine("Waiting until ASP.NET application is accepting connections...");154 var listeningMessage = GetListeningMessage();155 if (!string.IsNullOrEmpty(listeningMessage))156 {157 listeningMessage = listeningMessage.Trim();158 // Verify we have a valid URL to make requests to159 var listeningUrlString = listeningMessage.Substring(listeningMessage.IndexOf(160 ListeningMessagePrefix, StringComparison.Ordinal) + ListeningMessagePrefix.Length);161 output.WriteLine($"Detected that ASP.NET application is accepting connections on: {listeningUrlString}");162 listeningUrlString = string.Concat(listeningUrlString.AsSpan(0, listeningUrlString.IndexOf(':')),163 "://localhost",164 listeningUrlString.AsSpan(listeningUrlString.LastIndexOf(':')));165 output.WriteLine("Sending requests to " + listeningUrlString);166 return new Uri(listeningUrlString, UriKind.Absolute);167 }168 else169 {170 return null;171 }172 }173 private string GetListeningMessage()174 {175 var buffer = new List<string>();176 try177 {178 foreach (var line in Process.OutputLinesAsEnumerable)179 {...
DownloadsPathTests.cs
Source:DownloadsPathTests.cs
...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}...
Artifact.cs
Source:Artifact.cs
...62 System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path));63 var stream = await _channel.SaveAsStreamAsync().ConfigureAwait(false);64 await using (stream.ConfigureAwait(false))65 {66 using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))67 {68 await stream.StreamImpl.CopyToAsync(fileStream).ConfigureAwait(false);69 }70 }71 }72 public async Task<System.IO.Stream> CreateReadStreamAsync()73 {74 var stream = await _channel.StreamAsync().ConfigureAwait(false);75 return stream.StreamImpl;76 }77 internal Task CancelAsync() => _channel.CancelAsync();78 internal Task<string> FailureAsync() => _channel.FailureAsync();79 internal Task DeleteAsync() => _channel.DeleteAsync();80 }...
Stream.cs
Source:Stream.cs
...51 _stream = stream;52 }53 public override bool CanRead => true;54 public override bool CanSeek => false;55 public override bool CanWrite => throw new NotImplementedException();56 public override long Length => throw new NotImplementedException();57 public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }58 public override void Flush() => throw new NotImplementedException();59 public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException();60 public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)61 {62 var result = await _stream.ReadAsync(count).ConfigureAwait(false);63 result.CopyTo(buffer, offset);64 return result.Length;65 }66 public override void Close() => _stream.CloseAsync().ConfigureAwait(false);67 public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();68 public override void SetLength(long value) => throw new NotImplementedException();69 public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();70 }71}...
Write
Using AI Code Generation
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 page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });11 await page.PdfAsync(new PagePdfOptions { Path = "google.pdf" });12 using var stream = await page.PdfStreamAsync();13 await stream.WriteAsync(new byte[] { 1, 2, 3 });14 await stream.CloseAsync();15 }16 }17}18using Microsoft.Playwright;19using System.Threading.Tasks;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();26 var page = await browser.NewPageAsync();27 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });28 await page.PdfAsync(new PagePdfOptions { Path = "google.pdf" });29 using var stream = await page.PdfStreamAsync();30 await stream.WriteAsync(new byte[] { 1, 2, 3 });31 await stream.CloseAsync();32 }33 }34}35using Microsoft.Playwright;36using System.Threading.Tasks;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();43 var page = await browser.NewPageAsync();44 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });45 await page.PdfAsync(new PagePdfOptions { Path = "google.pdf" });46 using var stream = await page.PdfStreamAsync();47 await stream.WriteAsync(new byte[] { 1
Write
Using AI Code Generation
1using Microsoft.Playwright;2using System;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 var userAgent = await page.EvaluateAsync<string>("() => navigator.userAgent");11 Console.WriteLine(userAgent);12 await page.ScreenshotAsync(path: "example.png");13 await page.ScreenshotAsync(path: "example.pdf");14 await page.ScreenshotAsync(path: "example.jpeg");15 await page.ScreenshotAsync(path: "example.webp");16 }17 }18}19using Microsoft.Playwright;20using System;21{22 {23 static async Task Main(string[] args)24 {25 using var playwright = await Playwright.CreateAsync();26 await using var browser = await playwright.Chromium.LaunchAsync();27 var page = await browser.NewPageAsync();28 var userAgent = await page.EvaluateAsync<string>("() => navigator.userAgent");29 Console.WriteLine(userAgent);30 await page.ScreenshotAsync(path: "example.png");31 await page.ScreenshotAsync(path: "example.pdf");32 await page.ScreenshotAsync(path: "example.jpeg");33 await page.ScreenshotAsync(path: "example.webp");34 }35 }36}37using Microsoft.Playwright;38using System;39{40 {41 static async Task Main(string[] args)42 {43 using var playwright = await Playwright.CreateAsync();44 await using var browser = await playwright.Chromium.LaunchAsync();45 var page = await browser.NewPageAsync();46 var userAgent = await page.EvaluateAsync<string>("() => navigator.userAgent");47 Console.WriteLine(userAgent);48 await page.ScreenshotAsync(path: "example.png");49 await page.ScreenshotAsync(path: "example.pdf");50 await page.ScreenshotAsync(path: "example.jpeg");
Write
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.IO;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 var playwright = await Playwright.CreateAsync();10 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var page = await browser.NewPageAsync();14 var title = await page.TitleAsync();15 await page.ScreenshotAsync("screenshot.png");16 await browser.CloseAsync();17 await playwright.StopAsync();18 Console.WriteLine("Title of the page is: " + title);19 using (var stream = File.OpenWrite("screenshot.png"))20 {21 await page.ScreenshotAsync(new PageScreenshotOptions22 {23 });24 }25 }26 }27}
Write
Using AI Code Generation
1using Microsoft.Playwright.Core;2using Microsoft.Playwright.Transport;3using System;4using System.IO;5using System.Threading.Tasks;6{7 {8 static async Task Main(string[] args)9 {10 var playwright = await Playwright.CreateAsync();11 var browser = await playwright.Chromium.LaunchAsync(headless: false);12 var page = await browser.NewPageAsync();13 var stream = await page.ScreenshotStreamAsync();14 await stream.WriteAsync(new FileStream("2.png", FileMode.Create));15 await browser.CloseAsync();16 await playwright.StopAsync();17 }18 }19}20using Microsoft.Playwright.Core;21using Microsoft.Playwright.Transport;22using System;23using System.IO;24using System.Threading.Tasks;25{26 {27 static async Task Main(string[] args)28 {29 var playwright = await Playwright.CreateAsync();30 var browser = await playwright.Chromium.LaunchAsync(headless: false);31 var page = await browser.NewPageAsync();32 var stream = await page.ScreenshotStreamAsync();33 await stream.WriteAsync(new FileStream("3.png", FileMode.Create));34 await browser.CloseAsync();35 await playwright.StopAsync();36 }37 }38}39using Microsoft.Playwright.Core;40using Microsoft.Playwright.Transport;41using System;42using System.IO;43using System.Threading.Tasks;44{45 {46 static async Task Main(string[] args)47 {48 var playwright = await Playwright.CreateAsync();49 var browser = await playwright.Chromium.LaunchAsync(headless: false);50 var page = await browser.NewPageAsync();51 var stream = await page.ScreenshotStreamAsync();52 await stream.WriteAsync(new FileStream("4.png", FileMode.Create));53 await browser.CloseAsync();54 await playwright.StopAsync();55 }56 }57}58using Microsoft.Playwright.Core;59using Microsoft.Playwright.Transport;60using System;
Write
Using AI Code Generation
1var stream = new Microsoft.Playwright.Core.Stream();2var buffer = new byte[100];3stream.Write(buffer, 0, 100);4var stream = new Microsoft.Playwright.Core.Stream();5var buffer = new byte[100];6await stream.ReadAsync(buffer, 0, 100);7var stream = new Microsoft.Playwright.Core.Stream();8var buffer = new byte[100];9stream.Read(buffer, 0, 100);10var stream = new Microsoft.Playwright.Core.Stream();11stream.Seek(100, SeekOrigin.Begin);12var stream = new Microsoft.Playwright.Core.Stream();13stream.SetLength(100);14var stream = new Microsoft.Playwright.Core.Stream();15stream.Flush();16var stream = new Microsoft.Playwright.Core.Stream();17stream.Dispose();18var stream = new Microsoft.Playwright.Core.Stream();19var buffer = new byte[100];20await stream.WriteAsync(buffer, 0, 100);21var stream = new Microsoft.Playwright.Core.Stream();22await stream.DisposeAsync();23var stream = new Microsoft.Playwright.Core.Stream();24var stream2 = new Microsoft.Playwright.Core.Stream();25await stream.CopyToAsync(stream2);26var stream = new Microsoft.Playwright.Core.Stream();27var stream2 = new Microsoft.Playwright.Core.Stream();28stream.CopyTo(stream2);29var stream = new Microsoft.Playwright.Core.Stream();30stream.Close();
Write
Using AI Code Generation
1var stream = new Stream();2await stream.WriteAsync("Hello World");3Console.WriteLine(stream.ToString());4var stream = new Stream();5await stream.WriteAsync("Hello World");6Console.WriteLine(await stream.ReadAsync());7var stream = new Stream();8await stream.WriteAsync("Hello World");9Console.WriteLine(await stream.ReadAllAsync());10var stream = new Stream();11await stream.CloseAsync();12var stream = new Stream();13await stream.DisposeAsync();14var stream = new Stream();15await stream.WriteAsync("Hello World");16Console.WriteLine(await stream.ReadableAsync());17var stream = new Stream();18await stream.WriteAsync("Hello World");19Console.WriteLine(await stream.WritableAsync());20var stream = new Stream();21await stream.SetEncodingAsync(Encoding.UTF8);22var stream = new Stream();23await stream.SetNoDelayAsync(true);24var stream = new Stream();25await stream.SetTimeoutAsync(1000);26var stream = new Stream();27await stream.SetKeepAliveAsync(true, 1000);28var stream = new Stream();29await stream.SetNoDelayAsync(true);30var stream = new Stream();31await stream.SetTimeoutAsync(1000);
Write
Using AI Code Generation
1var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");2await stream.WriteAsync("Hello World");3var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");4var data = await stream.ReadAsync();5var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");6await stream.CloseAsync();7var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");8var reader = await stream.GetReadAsync();9var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");10var reader = await stream.GetReadAsync();11var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");12var reader = await stream.GetReadAsync();13var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");14var reader = await stream.GetReadAsync();15var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");16var reader = await stream.GetReadAsync();17var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");18var reader = await stream.GetReadAsync();19var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");20var reader = await stream.GetReadAsync();21var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");22var reader = await stream.GetReadAsync();23var stream = await page.EvaluateHandleAsync("() => document.querySelector('body').firstChild");24var reader = await stream.GetReadAsync();
Write
Using AI Code Generation
1await stream . WriteAsync ( "C:\\Users\\Downloads\\googlelogo_color_272x92dp.png" ) ;2 var bytes = await stream . ReadAsync ( ) ; 3 var image = System . Drawing . Image . FromStream ( new System . IO . MemoryStream ( bytes ) ) ;4stream . Dispose ( ) ;5 var bytes = await response . GetResponseBodyAsync ( ) ;6 var bytes = await response . GetResponseBodyAsync ( ) ;
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!!