From 8a1d36503a0f529cf2bb815e45374fb1a5621c1f Mon Sep 17 00:00:00 2001 From: mattleibow Date: Thu, 30 Jul 2026 01:43:50 +0200 Subject: [PATCH] Allow extra switches to be passed to the WASM browser The browser that `device-runners wasm test` launches was not configurable in any way, so a test needing a specific Chrome switch had no route to it. The case that surfaced this was WebGPU: on a CI agent with no GPU, `navigator.gpu.requestAdapter()` resolves to null unless Chrome is started with `--enable-unsafe-webgpu`, and there was no supported way to add it. device-runners wasm test --app "$wwwroot" --browser-args=--enable-unsafe-webgpu --enable-unsafe-webgpu Scoped to the browser rather than made generic. `--` stays unused so it can later mean "arguments for the app under test", which is a different thing: on WASM those would become query-string parameters, and on Mac Catalyst they would be process arguments. Reserving it now keeps that option open. `--browser-args` takes a command-line fragment and splits it with shell quoting rules, so a switch whose value contains a space just needs quotes: "--host-resolver-rules=MAP a.test 127.0.0.1" The splitting lives in ArgumentTokenizer rather than in MSBuild, where it would have to be expressed as property functions and could not be tested. A backslash only escapes inside double quotes, so Windows paths survive without doubling. The option is repeatable, and the "=" form is required because Spectre.Console treats a following token starting with "-" as another option. This is a passthrough only: no switch is added by default, so behaviour is unchanged unless a caller opts in. Which switches WebGL and WebGPU need is documented rather than baked in, because the right set differs per host OS and forcing a software adapter would degrade machines that have a real GPU. Two bugs turned up while validating this end to end: Arguments were joined with spaces into ProcessStartInfo.Arguments, so any value containing a space was split and Chrome refused to start with "Multiple targets are not supported in headless mode". Use ArgumentList, which quotes each entry. Caller switches were appended after `--headless=new` was already added, which contradicts the "caller wins" ordering that Chrome's last-one-wins switch handling implies. Add the CLI's own switches first, then the caller's, then the URL. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 02526701-9a20-4572-a052-559b88b33061 --- ...runner-for-wasm-using-devicerunners-cli.md | 65 ++++++++++++ docs/articles/dotnet-test-wasm.md | 73 ++++++++++++++ .../Commands/Wasm/WasmTestCommand.cs | 16 ++- .../Services/ArgumentTokenizer.cs | 88 +++++++++++++++++ .../Services/BrowserService.cs | 91 +++++++++++------ .../build/DeviceRunners.Testing.Targets.props | 12 +++ .../DeviceRunners.Testing.Targets.targets | 12 ++- .../Services/ArgumentTokenizerTests.cs | 99 +++++++++++++++++++ .../Services/BrowserServiceTests.cs | 92 +++++++++++++++++ 9 files changed, 518 insertions(+), 30 deletions(-) create mode 100644 src/DeviceRunners.Cli/Services/ArgumentTokenizer.cs create mode 100644 test/DeviceRunners.Cli.Tests/Services/ArgumentTokenizerTests.cs create mode 100644 test/DeviceRunners.Cli.Tests/Services/BrowserServiceTests.cs diff --git a/docs/articles/cli-device-runner-for-wasm-using-devicerunners-cli.md b/docs/articles/cli-device-runner-for-wasm-using-devicerunners-cli.md index 754ac00c..1d104458 100644 --- a/docs/articles/cli-device-runner-for-wasm-using-devicerunners-cli.md +++ b/docs/articles/cli-device-runner-for-wasm-using-devicerunners-cli.md @@ -67,10 +67,44 @@ device-runners wasm test \ | `--timeout` | `300` | Test execution timeout in seconds | | `--headed` | `false` | Run browser in visible mode (useful for debugging) | | `--server-port` | `0` (auto) | HTTP port for the local web server | +| `--browser-args` | *(none)* | Extra switches for the browser, quoted as in a shell. Repeatable. Use the `=` form: `--browser-args=--enable-unsafe-webgpu` | | `--output` | `default` | CLI output format: `default`, `json`, `xml`, or `text` | The test command also generates a `browser-console.log` file in the results directory containing all browser console output, similar to `logcat.txt` on Android or `ios-device-log.txt` on iOS. +#### Passing switches to the browser + +`--browser-args` takes a command-line fragment and splits it using shell quoting rules, so a +switch whose value contains a space just needs quotes: + +```bash +device-runners wasm test --app "$wwwroot" \ + --browser-args='--enable-unsafe-webgpu "--host-resolver-rules=MAP a.test 127.0.0.1"' +``` + +It is repeatable, so this is equivalent: + +```bash +device-runners wasm test --app "$wwwroot" \ + --browser-args=--enable-unsafe-swiftshader \ + --browser-args=--enable-unsafe-webgpu +``` + +Use the `=` form. Spectre.Console treats a following token that starts with `-` as another +option, so `--browser-args --enable-unsafe-webgpu` is rejected. + +The switches are appended after everything the CLI sets itself, so they win for the switches +where Chrome keeps only the last occurrence. The full command line is printed as +`Browser args:` at the start of every run. + +> [!NOTE] +> This configures the **browser**, not the app under test. The app is configured through the +> runner's own query-string parameters (`?device-runners-autorun=1`), the WASM equivalent of +> the `DEVICE_RUNNERS_*` environment variables used on the other platforms. + +This is a passthrough — the CLI adds no graphics-related switches of its own. See +[WebGL and WebGPU](#webgl-and-webgpu) below for what those APIs need on a CI agent. + ### `wasm serve` | Option | Default | Description | @@ -103,6 +137,37 @@ If the app fails to boot, check the Blazor WebAssembly publish output to ensure Ensure the test app calls `AddConsoleResultChannel()` in its `Program.cs`. When using `UseVisualTestRunner` on `WebAssemblyHostBuilder`, the CLI configuration is automatically injected — when the browser navigates to `?device-runners-autorun=1`, the `EventStreamFormatter` console output is enabled. +### WebGL and WebGPU + +A browser on a machine with no usable GPU — most CI agents — reports WebGL as unavailable +(`canvas.getContext("webgl")` returns `null`) and WebGPU as adapter-less +(`navigator.gpu.requestAdapter()` resolves to `null`). Headless mode is not the cause: a +visible browser behaves the same. The cause is the missing GPU. + +Chrome can fall back to the SwiftShader software renderer, but only when asked. Measured with +Chrome 150 on GPU-less GitHub-hosted runners: + +| Host | For WebGL | For WebGPU | +| --- | --- | --- | +| Linux | *(works already)* | `--enable-unsafe-webgpu` | +| macOS | `--enable-unsafe-swiftshader` | `--enable-unsafe-webgpu` | +| Windows | *(works already, via D3D11 WARP)* | `--enable-unsafe-webgpu --use-webgpu-adapter=swiftshader` | + +Notes: + +- On **Windows**, `--enable-unsafe-swiftshader` moves ANGLE onto the SwiftShader Vulkan + device, after which Dawn cannot enumerate any WebGPU adapter. Don't combine it with the + WebGPU switches there. +- `--use-webgpu-adapter=swiftshader` forces software rendering even when a real GPU is + present, so apply it on CI rather than everywhere. +- Avoid passing `--disable-gpu`. On Windows it removes the fallback WebGPU needs, and + `requestAdapter()` returns `null` even with `--use-webgpu-adapter=swiftshader`. +- `navigator.gpu` only exists in a [secure context]. The built-in server uses + `http://127.0.0.1`, which qualifies; a plain `http://` LAN address does not, and WebGPU + silently disappears there. + +[secure context]: https://developer.mozilla.org/docs/Web/Security/Secure_Contexts + ### Debugging with headed mode Use `--headed` to launch a visible browser window. This lets you see the Blazor visual runner UI and inspect the browser console directly. Combined with `--timeout 0` (infinite), this is useful for interactive debugging. diff --git a/docs/articles/dotnet-test-wasm.md b/docs/articles/dotnet-test-wasm.md index b98316a5..0b3ff0eb 100644 --- a/docs/articles/dotnet-test-wasm.md +++ b/docs/articles/dotnet-test-wasm.md @@ -67,6 +67,41 @@ To change the test execution timeout, set `DeviceRunnersWasmTimeout` (default: 3 dotnet test MyApp.BrowserTests.csproj -p:DeviceRunnersWasmTimeout=600 ``` +### Passing switches to the browser + +`DeviceRunnersWasmBrowserArgs` sets extra switches on the browser the CLI launches: + +```bash +dotnet test MyApp.BrowserTests.csproj -p:DeviceRunnersWasmBrowserArgs=--enable-unsafe-webgpu +``` + +```xml + + --enable-unsafe-swiftshader --enable-unsafe-webgpu + +``` + +The value is a command-line fragment, not an MSBuild list. Separate switches with spaces and +quote any value that contains one, exactly as you would in a shell: + +```xml + + --enable-unsafe-webgpu "--host-resolver-rules=MAP a.test 127.0.0.1" + +``` + +The switches are appended after everything the CLI sets itself, so they win for the switches +where Chrome keeps only the last occurrence. The full command line is printed as `Browser +args:` at the start of every run. + +> [!NOTE] +> This configures the **browser**, not the app under test. The app is configured through the +> runner's own query-string parameters (`?device-runners-autorun=1`), which is the WASM +> equivalent of the `DEVICE_RUNNERS_*` environment variables used on the other platforms. + +This is a passthrough — the CLI adds no graphics-related switches of its own. See +[WebGL and WebGPU](#webgl-and-webgpu) for the switches those APIs need on a CI agent. + ## Troubleshooting ### Chrome not found @@ -77,6 +112,44 @@ The CLI searches for Chrome/Chromium in standard installation paths. If your Chr If the app fails to boot, check the Blazor WebAssembly publish output to ensure the `wwwroot` directory contains `_framework/blazor.webassembly.js` and the app's DLLs. The default timeout is 300 seconds — use `--timeout` to increase it for large test suites. +### WebGL and WebGPU + +A browser on a machine with no usable GPU — which describes most CI agents — reports WebGL as +unavailable (`canvas.getContext("webgl")` returns `null`) and WebGPU as adapter-less +(`navigator.gpu.requestAdapter()` resolves to `null`). This is not caused by headless mode: a +visible browser behaves the same way. It is caused by there being no GPU. + +Chrome can fall back to the SwiftShader software renderer, but only when asked. Measured with +Chrome 150 on GPU-less GitHub-hosted runners: + +| Host | For WebGL | For WebGPU | +| --- | --- | --- | +| Linux | *(works already)* | `--enable-unsafe-webgpu` | +| macOS | `--enable-unsafe-swiftshader` | `--enable-unsafe-webgpu` | +| Windows | *(works already, via D3D11 WARP)* | `--enable-unsafe-webgpu --use-webgpu-adapter=swiftshader` | + +For example, on a GPU-less Linux or macOS agent: + +```bash +dotnet test MyApp.BrowserTests.csproj \ + -p:DeviceRunnersWasmBrowserArgs="--enable-unsafe-swiftshader --enable-unsafe-webgpu" +``` + +Notes: + +- On **Windows**, `--enable-unsafe-swiftshader` moves ANGLE onto the SwiftShader Vulkan + device, after which Dawn cannot enumerate any WebGPU adapter. Don't combine it with the + WebGPU switches there. +- `--use-webgpu-adapter=swiftshader` forces software rendering even when a real GPU is + present, so apply it on CI rather than in a checked-in property. +- Avoid `--disable-gpu`. On Windows it removes the fallback WebGPU needs, and + `requestAdapter()` returns `null` even with `--use-webgpu-adapter=swiftshader`. +- `navigator.gpu` only exists in a [secure context]. The built-in server uses + `http://127.0.0.1`, which qualifies; a plain `http://` LAN address does not, and WebGPU + silently disappears there. + +[secure context]: https://developer.mozilla.org/docs/Web/Security/Secure_Contexts + ### Console output is empty When using `UseVisualTestRunner` on `WebAssemblyHostBuilder`, CLI configuration is automatically injected — the `EventStreamFormatter` console output is enabled when `?device-runners-autorun=1` is in the URL. If you're building a custom setup, ensure `AddConsoleResultChannel()` is called. diff --git a/src/DeviceRunners.Cli/Commands/Wasm/WasmTestCommand.cs b/src/DeviceRunners.Cli/Commands/Wasm/WasmTestCommand.cs index f1edde38..b464c095 100644 --- a/src/DeviceRunners.Cli/Commands/Wasm/WasmTestCommand.cs +++ b/src/DeviceRunners.Cli/Commands/Wasm/WasmTestCommand.cs @@ -26,6 +26,10 @@ public class Settings : BaseTestCommandSettings [CommandOption("--timeout")] [DefaultValue(300)] public int Timeout { get; set; } = 300; + + [Description("Extra switches for the browser, quoted as they would be in a shell. Repeatable. Example: --browser-args \"--enable-unsafe-webgpu\"")] + [CommandOption("--browser-args")] + public string[] BrowserArgs { get; set; } = []; } protected override async Task ExecuteAsync(CommandContext context, Settings settings) @@ -136,7 +140,17 @@ protected override async Task ExecuteAsync(CommandContext context, Settings var testUrl = $"{url}?device-runners-autorun=1"; if (!string.IsNullOrWhiteSpace(settings.Filter)) testUrl += $"&device-runners-filter={Uri.EscapeDataString(settings.Filter)}"; - await browser.LaunchAsync(testUrl, headless: !settings.Headed); + // Each --browser-args value is a command-line fragment: the shell that + // launched us only stripped the outer quotes, so the inner grouping still + // has to be resolved. "--" is deliberately left alone — it is reserved for + // arguments aimed at the app under test rather than at the browser. + var browserArgs = settings.BrowserArgs.SelectMany(ArgumentTokenizer.Tokenize).ToList(); + + await browser.LaunchAsync( + testUrl, + headless: !settings.Headed, + extraArguments: browserArgs); + WriteConsoleOutput($" Browser args: [grey]{Markup.Escape(string.Join(' ', browser.LaunchArguments))}[/]", settings); WriteConsoleOutput($" Browser launched, running tests...", settings); // Wait for test completion or timeout diff --git a/src/DeviceRunners.Cli/Services/ArgumentTokenizer.cs b/src/DeviceRunners.Cli/Services/ArgumentTokenizer.cs new file mode 100644 index 00000000..3d69cc71 --- /dev/null +++ b/src/DeviceRunners.Cli/Services/ArgumentTokenizer.cs @@ -0,0 +1,88 @@ +namespace DeviceRunners.Cli.Services; + +/// +/// Splits a command-line fragment into individual arguments using the quoting rules a +/// shell would apply. +/// +/// +/// +/// Needed because options such as --browser-args receive a whole fragment as a +/// single value — the shell that launched the CLI only stripped the outer quotes, so the +/// inner grouping still has to be resolved. +/// +/// +/// A backslash is only an escape character inside double quotes, so Windows paths can be +/// written without doubling: --user-data-dir=C:\temp\profile means what it looks +/// like. Inside double quotes, \" produces a literal quote. +/// +/// +public static class ArgumentTokenizer +{ + public static IReadOnlyList Tokenize(string? value) + { + var results = new List(); + + if (string.IsNullOrWhiteSpace(value)) + return results; + + var current = new System.Text.StringBuilder(); + var hasToken = false; + var quote = '\0'; + + for (var i = 0; i < value.Length; i++) + { + var c = value[i]; + + if (quote != '\0') + { + // Only double quotes support escaping, matching POSIX shells. + if (quote == '"' && c == '\\' && i + 1 < value.Length && value[i + 1] == '"') + { + current.Append('"'); + i++; + continue; + } + + if (c == quote) + { + quote = '\0'; + continue; + } + + current.Append(c); + continue; + } + + if (c is '"' or '\'') + { + // An empty quoted section still produces an argument. + quote = c; + hasToken = true; + continue; + } + + if (char.IsWhiteSpace(c)) + { + if (hasToken) + { + results.Add(current.ToString()); + current.Clear(); + hasToken = false; + } + + continue; + } + + current.Append(c); + hasToken = true; + } + + if (quote != '\0') + throw new FormatException($"Unbalanced {quote} quote in arguments: {value}"); + + if (hasToken) + results.Add(current.ToString()); + + return results; + } +} diff --git a/src/DeviceRunners.Cli/Services/BrowserService.cs b/src/DeviceRunners.Cli/Services/BrowserService.cs index 051c2856..65b56442 100644 --- a/src/DeviceRunners.Cli/Services/BrowserService.cs +++ b/src/DeviceRunners.Cli/Services/BrowserService.cs @@ -22,7 +22,19 @@ public class BrowserService : IAsyncDisposable public event EventHandler? ConsoleMessageReceived; - public async Task LaunchAsync(string url, bool headless = true) + /// + /// The full argument list the browser was launched with. Useful for diagnostics. + /// + public IReadOnlyList LaunchArguments { get; private set; } = []; + + /// + /// Extra switches appended to the browser command line. They come last, so they win + /// for the switches where Chrome keeps only the final occurrence. + /// + public async Task LaunchAsync( + string url, + bool headless = true, + IEnumerable? extraArguments = null) { var chromePath = FindChrome(); if (chromePath is null) @@ -33,38 +45,28 @@ public async Task LaunchAsync(string url, bool headless = true) _userDataDir = Path.Combine(Path.GetTempPath(), "device-runners-chrome-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(_userDataDir); - var args = new List - { - "--remote-debugging-port=0", - $"--user-data-dir={_userDataDir}", - "--no-first-run", - "--no-default-browser-check", - "--disable-extensions", - "--disable-background-networking", - "--disable-sync", - "--disable-translate", - "--metrics-recording-only", - "--safebrowsing-disable-auto-update", - }; + var args = BuildLaunchArguments(_userDataDir, extraArguments, headless); - if (headless) - args.Add("--headless=new"); - - args.Add("about:blank"); + LaunchArguments = args; - _chromeProcess = new Process + var startInfo = new ProcessStartInfo { - StartInfo = new ProcessStartInfo - { - FileName = chromePath, - Arguments = string.Join(' ', args), - RedirectStandardError = true, - RedirectStandardOutput = true, - UseShellExecute = false, - CreateNoWindow = true, - } + FileName = chromePath, + RedirectStandardError = true, + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true, }; + // ArgumentList quotes each entry as needed. Joining into a single Arguments + // string would split any argument that contains a space, and Chrome would treat + // the trailing part as an extra page to open ("Multiple targets are not + // supported in headless mode"). + foreach (var arg in args) + startInfo.ArgumentList.Add(arg); + + _chromeProcess = new Process { StartInfo = startInfo }; + _chromeProcess.Start(); // Chrome prints the DevTools URL to stderr: "DevTools listening on ws://..." @@ -88,6 +90,39 @@ public async Task LaunchAsync(string url, bool headless = true) await SendCdpCommandAsync("Page.navigate", new CdpNavigateParams { Url = url }); } + /// + /// Assembles the browser command line. Caller arguments are placed after everything + /// the CLI sets itself, because Chrome keeps only the last occurrence of most + /// switches — so a caller can always override a default. The target URL stays last, + /// since a positional value after it would be treated as a second page to open. + /// + internal static List BuildLaunchArguments(string userDataDir, IEnumerable? extraArguments, bool headless) + { + var args = new List + { + "--remote-debugging-port=0", + $"--user-data-dir={userDataDir}", + "--no-first-run", + "--no-default-browser-check", + "--disable-extensions", + "--disable-background-networking", + "--disable-sync", + "--disable-translate", + "--metrics-recording-only", + "--safebrowsing-disable-auto-update", + }; + + if (headless) + args.Add("--headless=new"); + + if (extraArguments is not null) + args.AddRange(extraArguments.Where(a => !string.IsNullOrWhiteSpace(a))); + + args.Add("about:blank"); + + return args; + } + static async Task ReadDevToolsUrlAsync(Process process, TimeSpan timeout) { using var cts = new CancellationTokenSource(timeout); diff --git a/src/DeviceRunners.Testing.Targets/build/DeviceRunners.Testing.Targets.props b/src/DeviceRunners.Testing.Targets/build/DeviceRunners.Testing.Targets.props index 1bde5f3b..1ee3ed64 100644 --- a/src/DeviceRunners.Testing.Targets/build/DeviceRunners.Testing.Targets.props +++ b/src/DeviceRunners.Testing.Targets/build/DeviceRunners.Testing.Targets.props @@ -64,6 +64,18 @@ 300 + + + diff --git a/src/DeviceRunners.Testing.Targets/build/DeviceRunners.Testing.Targets.targets b/src/DeviceRunners.Testing.Targets/build/DeviceRunners.Testing.Targets.targets index e7bd2e9d..e10efa71 100644 --- a/src/DeviceRunners.Testing.Targets/build/DeviceRunners.Testing.Targets.targets +++ b/src/DeviceRunners.Testing.Targets/build/DeviceRunners.Testing.Targets.targets @@ -249,8 +249,18 @@ + + <_DeviceRunnersBrowserArgs Condition="'$(DeviceRunnersWasmBrowserArgs)' != ''"> --browser-args="$(DeviceRunnersWasmBrowserArgs.Replace('"', '\"'))" + - <_DeviceRunnersCliArgs>wasm test --app "$(_DeviceRunnersWasmDir)" --results-directory "$(_DeviceRunnersResultsDir)"$(_DeviceRunnersLoggerArg)$(_DeviceRunnersFilterArg) --timeout $(DeviceRunnersWasmTimeout) + <_DeviceRunnersCliArgs>wasm test --app "$(_DeviceRunnersWasmDir)" --results-directory "$(_DeviceRunnersResultsDir)"$(_DeviceRunnersLoggerArg)$(_DeviceRunnersFilterArg) --timeout $(DeviceRunnersWasmTimeout)$(_DeviceRunnersBrowserArgs) diff --git a/test/DeviceRunners.Cli.Tests/Services/ArgumentTokenizerTests.cs b/test/DeviceRunners.Cli.Tests/Services/ArgumentTokenizerTests.cs new file mode 100644 index 00000000..11c78a44 --- /dev/null +++ b/test/DeviceRunners.Cli.Tests/Services/ArgumentTokenizerTests.cs @@ -0,0 +1,99 @@ +using DeviceRunners.Cli.Services; + +using Xunit; + +namespace DeviceRunners.Cli.Tests; + +public class ArgumentTokenizerTests +{ + [Fact] + public void EmptyInputProducesNoArguments() + { + Assert.Empty(ArgumentTokenizer.Tokenize(null)); + Assert.Empty(ArgumentTokenizer.Tokenize("")); + Assert.Empty(ArgumentTokenizer.Tokenize(" ")); + } + + [Fact] + public void SplitsOnWhitespace() + { + var args = ArgumentTokenizer.Tokenize("--enable-unsafe-swiftshader --enable-unsafe-webgpu"); + + Assert.Equal(["--enable-unsafe-swiftshader", "--enable-unsafe-webgpu"], args); + } + + [Fact] + public void CollapsesRepeatedWhitespace() + { + var args = ArgumentTokenizer.Tokenize(" --a \t --b\n--c "); + + Assert.Equal(["--a", "--b", "--c"], args); + } + + [Fact] + public void DoubleQuotesGroupAValueContainingSpaces() + { + var args = ArgumentTokenizer.Tokenize("--a \"--host-resolver-rules=MAP a.test 127.0.0.1\" --b"); + + Assert.Equal(["--a", "--host-resolver-rules=MAP a.test 127.0.0.1", "--b"], args); + } + + [Fact] + public void SingleQuotesGroupAValueContainingSpaces() + { + var args = ArgumentTokenizer.Tokenize("--a '--rules=MAP a.test 127.0.0.1'"); + + Assert.Equal(["--a", "--rules=MAP a.test 127.0.0.1"], args); + } + + [Fact] + public void QuotesMayStartPartWayThroughAnArgument() + { + var args = ArgumentTokenizer.Tokenize("--host-resolver-rules=\"MAP a.test 127.0.0.1\""); + + Assert.Equal(["--host-resolver-rules=MAP a.test 127.0.0.1"], args); + } + + [Fact] + public void EscapedQuoteInsideDoubleQuotesIsLiteral() + { + var args = ArgumentTokenizer.Tokenize("--a=\"say \\\"hi\\\"\""); + + Assert.Equal(["--a=say \"hi\""], args); + } + + [Fact] + public void BackslashOutsideQuotesIsNotAnEscape() + { + // Windows paths must survive without doubling. + var args = ArgumentTokenizer.Tokenize(@"--user-data-dir=C:\temp\profile"); + + Assert.Equal([@"--user-data-dir=C:\temp\profile"], args); + } + + [Fact] + public void BackslashInsideSingleQuotesIsNotAnEscape() + { + var args = ArgumentTokenizer.Tokenize(@"'--dir=C:\temp\a b'"); + + Assert.Equal([@"--dir=C:\temp\a b"], args); + } + + [Fact] + public void AnEmptyQuotedSectionStillProducesAnArgument() + { + var args = ArgumentTokenizer.Tokenize("--a \"\" --b"); + + Assert.Equal(["--a", "", "--b"], args); + } + + [Fact] + public void UnbalancedQuoteIsReported() + { + // Silently dropping the rest of the line would be far harder to diagnose than + // a message naming the offending value. + var ex = Assert.Throws(() => ArgumentTokenizer.Tokenize("--a \"--b")); + + Assert.Contains("Unbalanced", ex.Message); + } +} diff --git a/test/DeviceRunners.Cli.Tests/Services/BrowserServiceTests.cs b/test/DeviceRunners.Cli.Tests/Services/BrowserServiceTests.cs new file mode 100644 index 00000000..ea73f064 --- /dev/null +++ b/test/DeviceRunners.Cli.Tests/Services/BrowserServiceTests.cs @@ -0,0 +1,92 @@ +using DeviceRunners.Cli.Services; + +using Xunit; + +namespace DeviceRunners.Cli.Tests; + +public class BrowserServiceTests +{ + // LaunchAsync starts a real browser, so exercise the argument assembly through the + // same helper it uses rather than launching Chrome from a unit test. + static List BuildArgs(IEnumerable? extra, bool headless = true) => + BrowserService.BuildLaunchArguments("/tmp/profile", extra, headless); + + [Fact] + public void NoExtraArgumentsKeepsTheBaseSwitchesOnly() + { + var args = BuildArgs(null); + + Assert.Contains("--remote-debugging-port=0", args); + Assert.Contains("--user-data-dir=/tmp/profile", args); + Assert.Contains("--headless=new", args); + Assert.Equal("about:blank", args[^1]); + } + + [Fact] + public void ExtraArgumentsAreAppended() + { + var args = BuildArgs(["--enable-unsafe-webgpu", "--use-webgpu-adapter=swiftshader"]); + + Assert.Contains("--enable-unsafe-webgpu", args); + Assert.Contains("--use-webgpu-adapter=swiftshader", args); + } + + [Fact] + public void ExtraArgumentsComeAfterEverythingTheCliSets() + { + // Chrome keeps only the last occurrence of most switches, so a caller must be + // able to override anything the CLI sets itself. + var args = BuildArgs(["--headless=old"]); + + Assert.True(args.IndexOf("--headless=old") > args.IndexOf("--headless=new")); + } + + [Fact] + public void ExtraArgumentsComeBeforeTheTargetUrl() + { + // A positional value after the URL would be treated as a second page to open. + var args = BuildArgs(["--enable-unsafe-webgpu"]); + + Assert.True(args.IndexOf("--enable-unsafe-webgpu") < args.IndexOf("about:blank")); + } + + [Fact] + public void ExtraArgumentOrderIsPreserved() + { + var args = BuildArgs(["--first", "--second", "--third"]); + + Assert.True(args.IndexOf("--first") < args.IndexOf("--second")); + Assert.True(args.IndexOf("--second") < args.IndexOf("--third")); + } + + [Fact] + public void BlankExtraArgumentsAreIgnored() + { + // Defensive: an empty entry would otherwise become a stray empty token on the + // command line. + var args = BuildArgs(["", " ", "--enable-unsafe-webgpu"]); + + Assert.DoesNotContain(args, string.IsNullOrWhiteSpace); + Assert.Contains("--enable-unsafe-webgpu", args); + } + + [Fact] + public void AnArgumentContainingSpacesStaysASingleEntry() + { + // The shell has already tokenised the command line, so a quoted value arrives as + // one entry and must stay that way. Chrome would otherwise treat the trailing + // part as an extra page to open and refuse to start ("Multiple targets are not + // supported in headless mode"). + var args = BuildArgs(["--host-resolver-rules=MAP a.test 127.0.0.1"]); + + Assert.Contains("--host-resolver-rules=MAP a.test 127.0.0.1", args); + } + + [Fact] + public void HeadedModeOmitsTheHeadlessSwitch() + { + var args = BuildArgs(null, headless: false); + + Assert.DoesNotContain("--headless=new", args); + } +}