How to use Playwright class of Microsoft.Playwright package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Playwright

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

WebHostServerFixture.cs

Source: WebHostServerFixture.cs Github

copy
1using Microsoft.AspNetCore.Hosting;
2using Microsoft.AspNetCore.Hosting.Server;
3using Microsoft.AspNetCore.Hosting.Server.Features;
4using Microsoft.AspNetCore.TestHost;
5using Microsoft.Extensions.DependencyInjection;
6using Microsoft.Extensions.Hosting;
7using PlaywrightSharp;
8using Serilog;
9using Serilog.Events;
10using System;
11using System.IO;
12using System.Linq;
13using System.Runtime.ExceptionServices;
14using System.Threading;
15using System.Threading.Tasks;
16using Xunit;
17
18namespace PlaywrightFeatureTest.Infrastructure
19{
20    [CollectionDefinition(TestConstants.TestFixtureBrowserCollectionName, DisableParallelization = true)]
21    public class ShareWebserver : ICollectionFixture<WebHostServerFixture>
22    {
23    }
24    public class WebHostServerFixture : IDisposable, IAsyncLifetime
25    {
26        internal static IPlaywright Playwright { get; private set; }
27        internal static IBrowser Browser { get; private set; }
28        private readonly Lazy<Uri> _rootUriInitializer;
29        public Uri RootUri => _rootUriInitializer.Value;
30        public IHost Host { get; set; }
31
32        public WebHostServerFixture()
33        {
34            _rootUriInitializer = new Lazy<Uri>(() => new Uri(StartAndGetRootUri()));
35        }
36
37        protected static void RunInBackgroundThread(Action action)
38        {
39            using var isDone = new ManualResetEvent(false);
40
41            ExceptionDispatchInfo edi = null;
42            new Thread(() =>
43            {
44                try
45                {
46                    action();
47                }
48                catch (Exception ex)
49                {
50                    edi = ExceptionDispatchInfo.Capture(ex);
51                }
52
53                isDone.Set();
54            }).Start();
55
56            if (!isDone.WaitOne(TimeSpan.FromSeconds(150)))
57                throw new TimeoutException("Timed out waiting for: " + action);
58
59            if (edi != null)
60                throw edi.SourceException;
61        }
62
63        protected string StartAndGetRootUri()
64        {
65            // As the port is generated automatically, we can use IServerAddressesFeature to get the actual server URL
66            Host = CreateWebHost();
67            RunInBackgroundThread(Host.Start);
68            return Host.Services.GetRequiredService<IServer>().Features
69                .Get<IServerAddressesFeature>()
70                .Addresses.FirstOrDefault();
71        }
72        /// <inheritdoc/>
73        public Task InitializeAsync() => LaunchBrowserAsync();
74
75        /// <inheritdoc/>
76        public Task DisposeAsync() => ShutDownAsync();
77
78        private async Task LaunchBrowserAsync()
79        {
80            try
81            {
82                Playwright = await PlaywrightSharp.Playwright.CreateAsync(TestConstants.LoggerFactory, debug: "pw*");
83                Browser = await Playwright[TestConstants.Product].LaunchAsync(TestConstants.GetDefaultBrowserOptions());
84
85            }
86            catch (Exception ex)
87            {
88                Console.WriteLine(ex);
89                throw new Exception("Launch failed", ex);
90            }
91        }
92
93        internal async Task ShutDownAsync()
94        {
95            try
96            {
97                await Browser.CloseAsync();
98                Playwright.Dispose();
99            }
100            catch (Exception ex)
101            {
102                Console.WriteLine(ex);
103                throw new Exception("Shutdown failed", ex);
104            }
105        }
106
107        public void Dispose()
108        {
109            Host?.Dispose();
110            Host?.StopAsync();
111        }
112
113        protected IHost CreateWebHost()
114        {
115            var osPath = Path.DirectorySeparatorChar;
116            var path = $"..{osPath}..{osPath}";            
117           
118            Log.Logger = new LoggerConfiguration()
119               .MinimumLevel.Debug()
120               .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
121               .Enrich.FromLogContext()
122               .WriteTo.Console()
123               .CreateLogger();
124            var host = new HostBuilder()
125                .ConfigureWebHost(webHostBuilder => webHostBuilder
126                    .UseKestrel()
127                    .UseSolutionRelativeContentRoot(path, "AspnetPlaywrightFeatureTest.sln")                    
128                    .UseStaticWebAssets()
129                    .UseStartup<WebUnderTest.Startup>()
130                    .UseSerilog() 
131                    .UseUrls($"http://127.0.0.1:0"))
132                .Build();
133
134            return host;
135        }
136    }
137}
138
Full Screen

NUnitPlaywrightBase.cs

Source: NUnitPlaywrightBase.cs Github

copy
1using Microsoft.Extensions.Configuration;
2using Microsoft.Playwright;
3using NUnit.Framework;
4using NUnit.Framework.Interfaces;
5using System;
6using System.IO;
7using System.Threading.Tasks;
8
9namespace PlaywrightCSharp
10{
11    [TestFixture]
12    public abstract class NUnitPlaywrightBase
13    {
14        protected IPlaywright playwright;
15        protected IBrowser browser;
16        protected IPage page;
17        protected IBrowserContext context;
18        private string CurrentTestFolder = TestContext.CurrentContext.TestDirectory;
19        private DirectoryInfo LogsFolder;
20        private DirectoryInfo ScreenshotsFolder;
21
22        [OneTimeSetUp]
23        public void CreateiPlaywrightAndiBrowserContextInstances()
24        {
25            var config = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory).AddJsonFile("appsettings.json").Build();
26            var section = config.GetSection(nameof(PlaywrightBrowserSettings));
27            var playwrightConfig = section.Get<PlaywrightBrowserSettings>();
28            CurrentTestFolder = string.IsNullOrEmpty(playwrightConfig.LogFolderPath) ? CurrentTestFolder : playwrightConfig.LogFolderPath;
29            LogsFolder = Directory.CreateDirectory(Path.Combine(CurrentTestFolder, "Logs"));
30            ScreenshotsFolder = Directory.CreateDirectory(Path.Combine(CurrentTestFolder, "Screenshots"));
31
32            LaunchBrowser(playwrightConfig.Browser, playwrightConfig.Headless);
33        }
34
35        [SetUp]
36        public async Task CreateiBrowserContextAndiPageContextInstances()
37        {
38            context = await browser.NewContextAsync();
39            page = await context.NewPageAsync();
40            await page.SetViewportSizeAsync(1920, 1080);
41        }                
42
43        [TearDown]
44        public async Task DisposeiPageContextAndiBrowserContextInstances()
45        {
46            var testResult = TestContext.CurrentContext.Result.Outcome;
47
48            // Take screenshot and log the test results to a log file if the test fails.
49            if (testResult.Status.Equals(TestStatus.Failed) || testResult.Status.Equals(ResultState.Error))
50            {
51                var testSpecificScreenshotFolder = Directory.CreateDirectory(Path.Combine(ScreenshotsFolder.FullName, TestContext.CurrentContext.Test.Name));
52                var screenshotPath = Path.Combine(testSpecificScreenshotFolder.FullName, $"TestFailure_{DateTime.Now.ToString("yyyyMMddHHmmss")}.png");
53                //Take a screenshot
54                await page.ScreenshotAsync(new PageScreenshotOptions { Path = screenshotPath });
55                //var testSpecificLogsFolder = Directory.CreateDirectory(Path.Combine(LogsFolder.FullName, TestContext.CurrentContext.Test.Name));
56            }
57
58            //await page.CloseAsync();
59            await context.CloseAsync();
60        }
61
62        [OneTimeTearDown]
63        public void DisposeiBrowserContextAndiPlaywrightContextInstances()
64        {
65            //await page.CloseAsync();
66            //await browser.CloseAsync();
67            playwright?.Dispose();
68        }
69
70        #region Private Methods        
71
72        private void LaunchBrowser(string browsertype, bool headless = false)
73        {
74            if (browser == null)
75            {
76                if (headless == false)
77                {
78                    browser = Task.Run(() => GetBrowserAsync(browsertype, headless: false)).Result;                    
79                }
80                else
81                {
82                    browser = Task.Run(() => GetBrowserAsync(browsertype, headless: true)).Result;
83                }
84            }
85        }
86
87        private async Task<IBrowser> GetBrowserAsync(string browserName, bool headless = false)
88        {
89            var playwright = await Playwright.CreateAsync();
90
91            IBrowser browser;
92
93            switch (browserName)
94            {
95                case "chrome":
96                    if (headless)
97                    {
98                        browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = true });
99                    }
100                    else
101                    {
102                        browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = false, SlowMo = 1000 });
103                    }
104                    break;
105                case "msedge":
106                    if (headless)
107                    {
108                        browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = true });
109                    }
110                    else
111                    {
112                        browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = false, SlowMo = 1000 });
113                    }
114                    break;
115                case "firefox":
116                    if (headless)
117                    {
118                        browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = true });
119                    }
120                    else
121                    {
122                        browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = false, SlowMo = 1000 });
123                    }
124                    break;
125                case "safari":
126                    if (headless)
127                    {
128                        browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = true });
129                    }
130                    else
131                    {
132                        browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = false, SlowMo = 1000 });
133                    }
134                    break;
135
136                default:
137                    throw new Exception("Invalid value for parameter named browser in the config file");
138            }
139
140            return browser;
141        }
142
143        #endregion
144    }
145}
Full Screen

PlaywrightFixture.cs

Source: PlaywrightFixture.cs Github

copy
1using System;
2using Microsoft.Playwright;
3
4namespace xUnitTests.Framework
5{
6    public class PlaywrightFixture : IPlaywrightFixture
7    {
8        private readonly IConfiguration _configuration;
9
10        public IBrowser Browser { get; }
11
12        public IPlaywright Playwright { get; }
13
14        public IBrowserType BrowserType { get; }
15        public IBrowserContext Context
16        {
17            get
18            {
19
20                var context = Browser.NewContextAsync().Result;
21                context.SetDefaultNavigationTimeout(_configuration.DefaultTimeout);
22                context.SetDefaultTimeout(_configuration.DefaultTimeout);
23                return context;
24            }
25        }
26
27
28        public PlaywrightFixture(IConfiguration configuration)
29        {
30            _configuration = configuration;
31
32            Playwright = Microsoft.Playwright.Playwright.CreateAsync().Result;
33
34            BrowserType = Playwright[_configuration.BrowserName];
35            Browser = BrowserType.LaunchAsync(new BrowserTypeLaunchOptions
36            {
37                Headless = _configuration.Headless,
38                SlowMo = _configuration.SlowMo,
39            }).Result;
40
41            
42
43
44        }
45
46        private bool _disposedValue;
47
48        public virtual void Dispose(bool disposing)
49        {
50            if (!_disposedValue)
51            {
52                if (disposing)
53                {
54                    Playwright.Dispose();
55                }
56
57                _disposedValue = true;
58            }
59        }
60
61        public void Dispose()
62        {
63            Dispose(disposing: true);
64            GC.SuppressFinalize(this);
65        }
66    }
67}
68
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in Playwright

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)