Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Download
TestRunner.cs
Source: TestRunner.cs
1// Licensed to the .NET Foundation under one or more agreements.2// The .NET Foundation licenses this file to you under the MIT license.3using System;4using System.Collections.Generic;5using System.IO;6using System.IO.Compression;7using System.Runtime.InteropServices;8using System.Threading;9using System.Threading.Tasks;10#if INSTALLPLAYWRIGHT11using PlaywrightSharp;12#endif13namespace RunTests14{15 public class TestRunner16 {17 public TestRunner(RunTestsOptions options)18 {19 Options = options;20 EnvironmentVariables = new Dictionary<string, string>();21 }22 public RunTestsOptions Options { get; set; }23 public Dictionary<string, string> EnvironmentVariables { get; set; }24 public bool SetupEnvironment()25 {26 try27 {28 EnvironmentVariables.Add("DOTNET_CLI_HOME", Options.HELIX_WORKITEM_ROOT);29 EnvironmentVariables.Add("PATH", Options.Path);30 EnvironmentVariables.Add("helix", Options.HelixQueue);31 Console.WriteLine($"Current Directory: {Options.HELIX_WORKITEM_ROOT}");32 var helixDir = Options.HELIX_WORKITEM_ROOT;33 Console.WriteLine($"Setting HELIX_DIR: {helixDir}");34 EnvironmentVariables.Add("HELIX_DIR", helixDir);35 EnvironmentVariables.Add("NUGET_FALLBACK_PACKAGES", helixDir);36 var nugetRestore = Path.Combine(helixDir, "nugetRestore");37 EnvironmentVariables.Add("NUGET_RESTORE", nugetRestore);38 var dotnetEFFullPath = Path.Combine(nugetRestore, helixDir, "dotnet-ef.exe");39 Console.WriteLine($"Set DotNetEfFullPath: {dotnetEFFullPath}");40 EnvironmentVariables.Add("DotNetEfFullPath", dotnetEFFullPath);41 var appRuntimePath = $"{Options.DotnetRoot}/shared/Microsoft.AspNetCore.App/{Options.RuntimeVersion}";42 Console.WriteLine($"Set ASPNET_RUNTIME_PATH: {appRuntimePath}");43 EnvironmentVariables.Add("ASPNET_RUNTIME_PATH", appRuntimePath);44 var dumpPath = Environment.GetEnvironmentVariable("HELIX_DUMP_FOLDER");45 Console.WriteLine($"Set VSTEST_DUMP_PATH: {dumpPath}");46 EnvironmentVariables.Add("VSTEST_DUMP_PATH", dumpPath);47#if INSTALLPLAYWRIGHT48 // Playwright will download and look for browsers to this directory49 var playwrightBrowsers = Environment.GetEnvironmentVariable("PLAYWRIGHT_BROWSERS_PATH");50 Console.WriteLine($"Setting PLAYWRIGHT_BROWSERS_PATH: {playwrightBrowsers}");51 EnvironmentVariables.Add("PLAYWRIGHT_BROWSERS_PATH", playwrightBrowsers);52 var playrightDriver = Environment.GetEnvironmentVariable("PLAYWRIGHT_DRIVER_PATH");53 Console.WriteLine($"Setting PLAYWRIGHT_DRIVER_PATH: {playrightDriver}");54 EnvironmentVariables.Add("PLAYWRIGHT_DRIVER_PATH", playrightDriver);55#else56 Console.WriteLine($"Skipping setting PLAYWRIGHT_BROWSERS_PATH");57#endif58 Console.WriteLine($"Creating nuget restore directory: {nugetRestore}");59 Directory.CreateDirectory(nugetRestore);60 // Rename default.runner.json to xunit.runner.json if there is not a custom one from the project61 if (!File.Exists("xunit.runner.json"))62 {63 File.Copy("default.runner.json", "xunit.runner.json");64 }65 DisplayContents(Path.Combine(Options.DotnetRoot, "host", "fxr"));66 DisplayContents(Path.Combine(Options.DotnetRoot, "shared", "Microsoft.NETCore.App"));67 DisplayContents(Path.Combine(Options.DotnetRoot, "shared", "Microsoft.AspNetCore.App"));68 DisplayContents(Path.Combine(Options.DotnetRoot, "packs", "Microsoft.AspNetCore.App.Ref"));69 return true;70 }71 catch (Exception e)72 {73 Console.WriteLine($"Exception in SetupEnvironment: {e.ToString()}");74 return false;75 }76 }77 public void DisplayContents(string path = "./")78 {79 try80 {81 Console.WriteLine();82 Console.WriteLine($"Displaying directory contents for {path}:");83 foreach (var file in Directory.EnumerateFiles(path))84 {85 Console.WriteLine(Path.GetFileName(file));86 }87 foreach (var file in Directory.EnumerateDirectories(path))88 {89 Console.WriteLine(Path.GetFileName(file));90 }91 Console.WriteLine();92 }93 catch (Exception e)94 {95 Console.WriteLine($"Exception in DisplayContents: {e.ToString()}");96 }97 }98#if INSTALLPLAYWRIGHT99 public async Task<bool> InstallPlaywrightAsync()100 {101 try102 {103 Console.WriteLine($"Installing Playwright to Browsers: {Environment.GetEnvironmentVariable("PLAYWRIGHT_BROWSERS_PATH")} Driver: {Environment.GetEnvironmentVariable("PLAYWRIGHT_DRIVER_PATH")}");104 await Playwright.InstallAsync(Environment.GetEnvironmentVariable("PLAYWRIGHT_BROWSERS_PATH"), Environment.GetEnvironmentVariable("PLAYWRIGHT_DRIVER_PATH"));105 DisplayContents(Environment.GetEnvironmentVariable("PLAYWRIGHT_BROWSERS_PATH"));106 return true;107 }108 catch (Exception e)109 {110 Console.WriteLine($"Exception installing playwright: {e.ToString()}");111 return false;112 }113 }114#endif115 public async Task<bool> InstallDotnetToolsAsync()116 {117 try118 {119 // Install dotnet-dump first so we can catch any failures from running dotnet after this (installing tools, running tests, etc.)120 await ProcessUtil.RunAsync($"{Options.DotnetRoot}/dotnet",121 $"tool install dotnet-dump --tool-path {Options.HELIX_WORKITEM_ROOT} --version 5.0.0-*",122 environmentVariables: EnvironmentVariables,123 outputDataReceived: Console.WriteLine,124 errorDataReceived: Console.Error.WriteLine,125 throwOnError: false,126 cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(2)).Token);127 Console.WriteLine($"Adding current directory to nuget sources: {Options.HELIX_WORKITEM_ROOT}");128 await ProcessUtil.RunAsync($"{Options.DotnetRoot}/dotnet",129 $"nuget add source {Options.HELIX_WORKITEM_ROOT} --configfile NuGet.config",130 environmentVariables: EnvironmentVariables,131 outputDataReceived: Console.WriteLine,132 errorDataReceived: Console.Error.WriteLine,133 throwOnError: false,134 cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(2)).Token);135 // Write nuget sources to console, useful for debugging purposes136 await ProcessUtil.RunAsync($"{Options.DotnetRoot}/dotnet",137 "nuget list source",138 environmentVariables: EnvironmentVariables,139 outputDataReceived: Console.WriteLine,140 errorDataReceived: Console.Error.WriteLine,141 throwOnError: false,142 cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(2)).Token);143 await ProcessUtil.RunAsync($"{Options.DotnetRoot}/dotnet",144 $"tool install dotnet-ef --version {Options.EfVersion} --tool-path {Options.HELIX_WORKITEM_ROOT}",145 environmentVariables: EnvironmentVariables,146 outputDataReceived: Console.WriteLine,147 errorDataReceived: Console.Error.WriteLine,148 throwOnError: false,149 cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(2)).Token);150 await ProcessUtil.RunAsync($"{Options.DotnetRoot}/dotnet",151 $"tool install dotnet-serve --tool-path {Options.HELIX_WORKITEM_ROOT}",152 environmentVariables: EnvironmentVariables,153 outputDataReceived: Console.WriteLine,154 errorDataReceived: Console.Error.WriteLine,155 throwOnError: false,156 cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(2)).Token);157 return true;158 }159 catch (Exception e)160 {161 Console.WriteLine($"Exception in InstallDotnetTools: {e}");162 return false;163 }164 }165 public async Task<bool> CheckTestDiscoveryAsync()166 {167 try168 {169 // Run test discovery so we know if there are tests to run170 var discoveryResult = await ProcessUtil.RunAsync($"{Options.DotnetRoot}/dotnet",171 $"vstest {Options.Target} -lt",172 environmentVariables: EnvironmentVariables,173 cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(2)).Token);174 if (discoveryResult.StandardOutput.Contains("Exception thrown"))175 {176 Console.WriteLine("Exception thrown during test discovery.");177 Console.WriteLine(discoveryResult.StandardOutput);178 return false;179 }180 return true;181 }182 catch (Exception e)183 {184 Console.WriteLine($"Exception in CheckTestDiscovery: {e.ToString()}");185 return false;186 }187 }188 public async Task<int> RunTestsAsync()189 {190 var exitCode = 0;191 try192 {193 // Timeout test run 5 minutes before the Helix job would timeout194 var cts = new CancellationTokenSource(Options.Timeout.Subtract(TimeSpan.FromMinutes(5)));195 var diagLog = Path.Combine(Environment.GetEnvironmentVariable("HELIX_WORKITEM_UPLOAD_ROOT"), "vstest.log");196 var commonTestArgs = $"test {Options.Target} --diag:{diagLog} --logger:xunit --logger:\"console;verbosity=normal\" --blame \"CollectHangDump;TestTimeout=15m\"";197 if (Options.Quarantined)198 {199 Console.WriteLine("Running quarantined tests.");200 // Filter syntax: https://github.com/Microsoft/vstest-docs/blob/master/docs/filter.md201 var result = await ProcessUtil.RunAsync($"{Options.DotnetRoot}/dotnet",202 commonTestArgs + " --TestCaseFilter:\"Quarantined=true\"",203 environmentVariables: EnvironmentVariables,204 outputDataReceived: Console.WriteLine,205 errorDataReceived: Console.Error.WriteLine,206 throwOnError: false,207 cancellationToken: cts.Token);208 if (result.ExitCode != 0)209 {210 Console.WriteLine($"Failure in quarantined tests. Exit code: {result.ExitCode}.");211 }212 }213 else214 {215 Console.WriteLine("Running non-quarantined tests.");216 // Filter syntax: https://github.com/Microsoft/vstest-docs/blob/master/docs/filter.md217 var result = await ProcessUtil.RunAsync($"{Options.DotnetRoot}/dotnet",218 commonTestArgs + " --TestCaseFilter:\"Quarantined!=true|Quarantined=false\"",219 environmentVariables: EnvironmentVariables,220 outputDataReceived: Console.WriteLine,221 errorDataReceived: Console.Error.WriteLine,222 throwOnError: false,223 cancellationToken: cts.Token);224 if (result.ExitCode != 0)225 {226 Console.WriteLine($"Failure in non-quarantined tests. Exit code: {result.ExitCode}.");227 exitCode = result.ExitCode;228 }229 }230 }231 catch (Exception e)232 {233 Console.WriteLine($"Exception in RunTests: {e.ToString()}");234 exitCode = 1;235 }236 return exitCode;237 }238 public void UploadResults()239 {240 // 'testResults.xml' is the file Helix looks for when processing test results241 Console.WriteLine("Trying to upload results...");242 if (File.Exists("TestResults/TestResults.xml"))243 {244 Console.WriteLine("Copying TestResults/TestResults.xml to ./testResults.xml");245 File.Copy("TestResults/TestResults.xml", "testResults.xml");246 }247 else248 {249 Console.WriteLine("No test results found.");250 }251 var HELIX_WORKITEM_UPLOAD_ROOT = Environment.GetEnvironmentVariable("HELIX_WORKITEM_UPLOAD_ROOT");252 if (string.IsNullOrEmpty(HELIX_WORKITEM_UPLOAD_ROOT))253 {254 Console.WriteLine("No HELIX_WORKITEM_UPLOAD_ROOT specified, skipping log copy");255 return;256 }257 Console.WriteLine($"Copying artifacts/log/ to {HELIX_WORKITEM_UPLOAD_ROOT}/");258 if (Directory.Exists("artifacts/log"))259 {260 foreach (var file in Directory.EnumerateFiles("artifacts/log", "*.log", SearchOption.AllDirectories))261 {262 // Combine the directory name + log name for the copied log file name to avoid overwriting duplicate test names in different test projects263 var logName = $"{Path.GetFileName(Path.GetDirectoryName(file))}_{Path.GetFileName(file)}";264 Console.WriteLine($"Copying: {file} to {Path.Combine(HELIX_WORKITEM_UPLOAD_ROOT, logName)}");265 File.Copy(file, Path.Combine(HELIX_WORKITEM_UPLOAD_ROOT, logName));266 }267 }268 else269 {270 Console.WriteLine("No logs found in artifacts/log");271 }272 Console.WriteLine($"Copying TestResults/**/Sequence*.xml to {HELIX_WORKITEM_UPLOAD_ROOT}/");273 if (Directory.Exists("TestResults"))274 {275 foreach (var file in Directory.EnumerateFiles("TestResults", "Sequence*.xml", SearchOption.AllDirectories))276 {277 var fileName = Path.GetFileName(file);278 Console.WriteLine($"Copying: {file} to {Path.Combine(HELIX_WORKITEM_UPLOAD_ROOT, fileName)}");279 File.Copy(file, Path.Combine(HELIX_WORKITEM_UPLOAD_ROOT, fileName));280 }281 }282 else283 {284 Console.WriteLine("No TestResults directory found.");285 }286 }287 }288}...
DownloadAnchorTest.cs
Source: DownloadAnchorTest.cs
...13using Xunit;14using Xunit.Abstractions;15namespace Microsoft.AspNetCore.Components.E2ETest.Tests16{17 public class DownloadAnchorTest18 : ServerTestBase<ToggleExecutionModeServerFixture<Program>>19 {20 public DownloadAnchorTest(21 ToggleExecutionModeServerFixture<Program> serverFixture,22 ITestOutputHelper output)23 : base(serverFixture, output)24 { 25 }26 protected override Type TestComponent { get; } = typeof(TestRouter);27 [QuarantinedTest("New experimental test that need bake time.")]28 [ConditionalTheory]29 [InlineData(BrowserKind.Chromium)]30 [InlineData(BrowserKind.Firefox)]31 // NOTE: BrowserKind argument must be first32 public async Task DownloadFileFromAnchor(BrowserKind browserKind)33 {34 if (ShouldSkip(browserKind)) 35 {36 return;37 }38 // Arrange39 var initialUrl = TestPage.Url;40 var downloadTask = TestPage.WaitForEventAsync(PageEvent.Download);41 // Act42 await Task.WhenAll(43 downloadTask,44 TestPage.ClickAsync("a[download]"));45 // Assert URL should still be same as before click46 Assert.Equal(initialUrl, TestPage.Url);47 // Assert that the resource was downloaded 48 var download = downloadTask.Result.Download;49 Assert.Equal($"{_serverFixture.RootUri}subdir/images/blazor_logo_1000x.png", download.Url);50 Assert.Equal("blazor_logo_1000x.png", download.SuggestedFilename);51 }52 }53}
Download
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 await using var playwright = await Playwright.CreateAsync();9 var browser = await playwright.Chromium.LaunchAsync();10 var context = await browser.NewContextAsync();11 var page = await context.NewPageAsync();12 var download = await page.RunAndWaitForDownloadAsync(async () =>13 {14 await page.ClickAsync("text=Download");15 });16 Console.WriteLine(download.SuggestedFilename);17 await browser.CloseAsync();18 }19 }20}21using Microsoft.Playwright;22using System;23using System.Threading.Tasks;24{25 {26 static async Task Main(string[] args)27 {28 await using var playwright = await Playwright.CreateAsync();29 var browser = await playwright.Chromium.LaunchAsync();30 var context = await browser.NewContextAsync();31 var page = await context.NewPageAsync();32 var download = await page.RunAndWaitForDownloadAsync(async () =>33 {34 await page.ClickAsync("text=Download");35 });36 Console.WriteLine(download.SuggestedFilename);37 await browser.CloseAsync();38 }39 }40}41using Microsoft.Playwright;42using NUnit.Framework;43using System;44using System.Threading.Tasks;45{46 {47 private IPlaywright playwright;48 private IBrowser browser;49 private IBrowserContext context;50 private IPage page;51 public async Task OneTimeSetUp()52 {53 playwright = await Playwright.CreateAsync();54 }55 public async Task OneTimeTearDown()56 {57 await playwright?.DisposeAsync();58 }59 public async Task SetUp()60 {61 browser = await playwright.Chromium.LaunchAsync();62 context = await browser.NewContextAsync();63 page = await context.NewPageAsync();64 }65 public async Task TearDown()66 {
Download
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 await using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync();10 var page = await browser.NewPageAsync();11 var downloadTask = page.WaitForEventAsync(PageEvent.Download);12 await page.ClickAsync("text=English");13 var download = await downloadTask;14 await download.PathAsync();15 }16 }17}18await page.ClickAsync("text=English");19await page.SetDefaultDownloadPathAsync(@"C:\Users\user\Downloads");20await page.ClickAsync("text=English");21await page.ClickAsync("text=हिन्दी");22await page.ClickAsync("text=தமிழ்");23await page.ClickAsync("text=తెలుగు");24await page.ClickAsync("text=मराठी");25await page.ClickAsync("text=বাংলা");26await page.ClickAsync("text=ગુજરાતી");27await page.ClickAsync("text=ಕನ್ನಡ");28await page.ClickAsync("text=മലയാളം");29await page.ClickAsync("text=ਪੰਜਾਬੀ");30await page.ClickAsync("text=اردو");31await page.ClickAsync("text=فارسی");32await page.ClickAsync("text=پ
Download
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {
Download
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 downloadPath = @"C:\Users\username\Downloads\";10 var fileName = "dummy.pdf";11 var downloadFile = downloadPath + fileName;12 var download = new Download();13 await download.DownloadFile(url, downloadFile);14 }15 }16}17using Microsoft.Playwright;18using System;19using System.IO;20using System.Threading.Tasks;21{22 {23 public async Task DownloadFile(string url, string downloadFile)24 {25 await using var playwright = await Playwright.CreateAsync();26 await using var browser = await playwright.Chromium.LaunchAsync();27 var context = await browser.NewContextAsync();28 var page = await context.NewPageAsync();29 await page.GotoAsync(url);30 await page.WaitForLoadStateAsync(LoadState.NetworkIdle);31 await page.ClickAsync("a");32 await page.WaitForLoadStateAsync(LoadState.NetworkIdle);33 await page.WaitForTimeoutAsync(5000);34 await page.CloseAsync();35 }36 }37}
Download
Using AI Code Generation
1var playwright = await Microsoft.Playwright.Core.Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync();3var page = await browser.NewPageAsync();4await page.ClickAsync("text=Download");5await page.WaitForDownloadAsync();6var downloads = await page.GetDownloadsAsync();7var download = downloads[0];8await download.SaveAsAsync(@"C:\Users\user\Desktop\2.pdf");9await page.CloseAsync();10await browser.CloseAsync();11await playwright.StopAsync();12WebClient webClient = new WebClient();13HttpClient httpClient = new HttpClient();14httpClient.DefaultRequestHeaders.Add("User-Agent", "C# console program");15response.EnsureSuccessStatusCode();16var file = await response.Content.ReadAsByteArrayAsync();17await File.WriteAllBytesAsync(@"C:\Users\user\Desktop\3.pdf", file);18request.Method = "GET";19request.UserAgent = "C# console program";20using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())21{22 response.EnsureSuccessStatusCode();23 using (Stream stream = response.GetResponseStream())24 {25 using (FileStream fileStream = new FileStream(@"C
Download
Using AI Code Generation
1using System;2using System.IO;3using System.Threading.Tasks;4using Microsoft.Playwright;5{6 {7 static async Task Main(string[] args)8 {9 var playwright = await Playwright.CreateAsync();10 var browser = await playwright.Chromium.LaunchAsync();11 var context = await browser.NewContextAsync();12 var page = await context.NewPageAsync();13 await page.ClickAsync("text=Images");14 await page.ClickAsync("#islrg > div.islrc > div:nth-child(2) > a.wXeWr.islib.nfEiy.mM5pbd > div.bRMDJf.islir > img");15 await page.ClickAsync("#Sva75c > div > div > div.pxAole > div.tvh9oe.BIB1wf > c-wiz > div > div > div.OUZ5W > div > div > div.irc_mi > a > img");16 await page.ClickAsync("text=Download");17 var download = await page.WaitForDownloadAsync();18 await download.SaveAsAsync(@"C:\Users\jayap\Downloads\img.jpg");19 await browser.CloseAsync();20 }21 }22}23using System;24using System.IO;25using System.Threading.Tasks;26using Microsoft.Playwright;27{28 {29 static async Task Main(string[] args)30 {31 var playwright = await Playwright.CreateAsync();32 var browser = await playwright.Chromium.LaunchAsync();33 var context = await browser.NewContextAsync();34 var page = await context.NewPageAsync();
Playwright Multiple Elements - Is there an equivalent to Selenium FindElements?
How to handle multiple file downloads in Playwright?
Run Playwright.NET tests in Docker container
How to handle multiple file downloads in Playwright?
Running playwright in headed mode C#
Playwright (.NET) tries to use different browser versions than installed
Playwright "Element is not attached to the DOM"
Playwright Multiple Elements - Is there an equivalent to Selenium FindElements?
Microsoft.Playwright.PlaywrightException : unable to verify the first certificate Using Playwright C# While connecting Moon
How do you create a global configuration for Playwright .NET?
Using a selector that finds a list of locators in Playwright is exactly the same as calling .FindElements() in selenium, except that Playwright does not have a specifically named method like .FindLocators().
Playwright - a selector that matches multiple elements returns a list of locators, which you then iterate over:
var rows = page.GetByRole(AriaRole.Listitem);
var count = await rows.CountAsync();
for (int i = 0; i < count; ++i)
Console.WriteLine(await rows.Nth(i).TextContentAsync());
Selenium - FindElements returns a list of elements that you have to iterate over.
IList < IWebElement > elements = driver.FindElements(By.TagName("p"));
foreach(IWebElement e in elements) {
System.Console.WriteLine(e.Text);
}
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!!