forked from dotnet/try
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlaywrightSession.cs
More file actions
67 lines (53 loc) · 2.41 KB
/
PlaywrightSession.cs
File metadata and controls
67 lines (53 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Playwright;
namespace Microsoft.TryDotNet.IntegrationTests;
public class PlaywrightSession : IDisposable
{
private IPlaywright _playwright;
public PlaywrightSession(IPlaywright playwright, IBrowser browser)
{
_playwright = playwright;
Browser = browser;
}
public IBrowser Browser { get; }
public static async Task<PlaywrightSession> StartAsync(string? browserName = null)
{
string? selectedBrowser = browserName
?? Environment.GetEnvironmentVariable("Playwright.BrowserName")
?? Environment.GetEnvironmentVariable("Playwright_BrowserName");
int exitCode;
if (!string.IsNullOrWhiteSpace(selectedBrowser))
{
selectedBrowser = selectedBrowser.ToLowerInvariant();
exitCode = Playwright.Program.Main(["install", selectedBrowser]);
}
else
{
exitCode = Playwright.Program.Main(["install"]);
selectedBrowser = "chromium";
}
if (exitCode is not 0)
{
throw new Exception($"Playwright exited with code {exitCode}");
}
var session = await Playwright.Playwright.CreateAsync().Timeout(TimeSpan.FromMinutes(5), "Timeout creating Playwright session");
var browserTypeLaunchOptions = new BrowserTypeLaunchOptions();
if (Debugger.IsAttached)
{
browserTypeLaunchOptions.Headless = false;
}
IBrowser browser = selectedBrowser switch
{
"chromium" => await session.Chromium.LaunchAsync(browserTypeLaunchOptions).Timeout(TimeSpan.FromMinutes(5), "Timeout launching browser"),
"firefox" => await session.Firefox.LaunchAsync(browserTypeLaunchOptions).Timeout(TimeSpan.FromMinutes(5), "Timeout launching browser"),
"webkit" => await session.Webkit.LaunchAsync(browserTypeLaunchOptions).Timeout(TimeSpan.FromMinutes(5), "Timeout launching browser"),
_ => throw new ArgumentException($"Unknown browser '{selectedBrowser}'. Valid values: chromium, firefox, webkit.")
};
return new PlaywrightSession(session, browser);
}
public void Dispose() => _playwright.Dispose();
}