How to configure Playwright service for .NET?
There are two ways:
if you are using Playwright Nunit you just need to specify to env variables:
PLAYWRIGHT_SERVICE_ACCESS_TOKEN={MY-ACCESS-TOKEN}
PLAYWRIGHT_SERVICE_URL={MY-REGION-ENDPOINT}
to configure number of workers you can use runsettings file:
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<!-- NUnit adapter -->
<NUnit>
<NumberOfTestWorkers>50</NumberOfTestWorkers>
</NUnit>
<!-- General run configuration -->
<RunConfiguration>
<EnvironmentVariables>
<!-- For debugging selectors, it's recommend to set the following environment variable -->
<!-- <DEBUG>pw:api</DEBUG> -->
</EnvironmentVariables>
<MaxCpuCount>0</MaxCpuCount>
</RunConfiguration>
</RunSettings>
if you are using Playwright Library you need to add the following code on browser initialization:
private Tuple<string, BrowserTypeConnectOptions> PlaywrightServiceConfiguration()
{
var accessKey = Environment.GetEnvironmentVariable("PLAYWRIGHT_SERVICE_ACCESS_KEY");
var serviceUrl = Environment.GetEnvironmentVariable("PLAYWRIGHT_SERVICE_URL");
if (!accessKey.IsNullOrEmpty() && !serviceUrl.IsNullOrEmpty())
{
var exposeNetwork = Environment.GetEnvironmentVariable("PLAYWRIGHT_SERVICE_EXPOSE_NETWORK") ?? "<loopback>";
var caps = new Dictionary<string, string>
{
["os"] = Environment.GetEnvironmentVariable("PLAYWRIGHT_SERVICE_OS") ?? "linux",
["runId"] = Environment.GetEnvironmentVariable("RELEASE_RELEASENAME") ?? DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture),
};
var wsEndpoint = $"{serviceUrl}?cap={JsonSerializer.Serialize(caps)}";
var connectOptions = new BrowserTypeConnectOptions
{
Timeout = 3 * 60 * 1000,
ExposeNetwork = exposeNetwork,
Headers = new Dictionary<string, string>
{
["x-mpt-access-key"] = accessKey
}
};
return new Tuple<string, BrowserTypeConnectOptions>(wsEndpoint, connectOptions);
}
else
{
return new Tuple<string, BrowserTypeConnectOptions>(null, null);
}
}
and use it in
// service configuration
Tuple<string, BrowserTypeConnectOptions> serviceConfig = PlaywrightServiceConfiguration();
var browserTypeLaunchOptions = new BrowserTypeLaunchOptions()
{
Headless = StartConfiguration.Headless,
Channel = StartConfiguration.Browser,
//Args = new[] { "--start-maximized" }
//SlowMo = 200
};
if (serviceConfig.Item1.IsNullOrEmpty() || serviceConfig.Item2 is null)
Browser = await BrowserType.LaunchAsync(browserTypeLaunchOptions).ConfigureAwait(false);
else
Browser = await BrowserType.ConnectAsync(serviceConfig.Item1, serviceConfig.Item2).ConfigureAwait(false);