Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ wwwroot=$(find artifacts/publish -type d -name "wwwroot" | head -1)
# Run tests in headless Chrome
device-runners wasm test \
--app "$wwwroot" \
--timeout 300 \
--logger "trx;LogFileName=test-results.trx" \
--results-directory artifacts/test-results

Expand All @@ -64,11 +63,14 @@ device-runners wasm test \
| `--app` | *(required)* | Path to the published WASM app directory (the `wwwroot` folder) |
| `--results-directory` | `artifacts` | Directory for test output files |
| `--logger` | *(none)* | Result format and file name (e.g. `trx;LogFileName=results.trx`) |
| `--timeout` | `300` | Test execution timeout in seconds |
| `--connection-timeout` | `120` | Seconds to wait for the first browser message (the app booting and reporting). |
| `--data-timeout` | `30` | Inactivity timeout: seconds without any browser output before the run is considered stalled. Resets on every message, so a long healthy run keeps going. |
| `--headed` | `false` | Run browser in visible mode (useful for debugging) |
| `--server-port` | `0` (auto) | HTTP port for the local web server |
| `--output` | `default` | CLI output format: `default`, `json`, `xml`, or `text` |

> A run that hits either of these timeouts before completing is treated as a **crash and fails** (exit code 2) — it is never reported as a passing run.

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.

### `wasm serve`
Expand Down Expand Up @@ -97,15 +99,17 @@ The CLI searches for Chrome/Chromium in standard installation paths. If your Chr

### Tests hang or timeout

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. Use `--timeout` to increase the timeout for large test suites.
Runs are governed by two timeouts: `--connection-timeout` (waiting for the app to boot and send its first browser message) and `--data-timeout` (an inactivity timeout that resets on every browser message). A large but healthy suite will keep running as long as it keeps producing output, so you rarely need to raise anything. If a run stalls, it **fails** rather than silently passing — check `browser-console.log` for the last output before the stall.

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.

### Console output is empty

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.

### 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.
Use `--headed` to launch a visible browser window. This lets you see the Blazor visual runner UI and inspect the browser console directly. Bumping `--data-timeout` gives you more time between output before the run is considered stalled, which is useful for interactive debugging.

### Reviewing browser logs

Expand Down
13 changes: 10 additions & 3 deletions docs/articles/dotnet-test-wasm.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,17 @@ Blazor WebAssembly runs on a single thread. To keep the UI responsive during tes

## Configuration

To change the test execution timeout, set `DeviceRunnersWasmTimeout` (default: 300 seconds):
WASM runs are governed by the same two timeouts as the device platforms:

| Property | Default | Description |
|----------|---------|-------------|
| `DeviceRunnersConnectionTimeout` | `120` | Seconds to wait for the first browser message (the app booting and reporting). |
| `DeviceRunnersDataTimeout` | `30` | Inactivity timeout: seconds without any browser output before the run is considered stalled. Resets on every message, so a long healthy suite keeps running as long as it produces output. |

A run that hits either timeout before completing is treated as a crash and **fails** (exit code 2) — it is never reported as a passing run. Because the data timeout resets on every message, you rarely need to raise anything for large suites; only bump `DeviceRunnersDataTimeout` if individual tests legitimately produce no output for long stretches:

```bash
dotnet test MyApp.BrowserTests.csproj -p:DeviceRunnersWasmTimeout=600
dotnet test MyApp.BrowserTests.csproj -p:DeviceRunnersDataTimeout=120
```

## Troubleshooting
Expand All @@ -75,7 +82,7 @@ The CLI searches for Chrome/Chromium in standard installation paths. If your Chr

### Tests hang or timeout

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.
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. A healthy suite keeps running as long as it produces output (the data timeout resets per message); if a run stalls it **fails** instead of passing silently — check `browser-console.log` for the last output before the stall.

### Console output is empty

Expand Down
5 changes: 2 additions & 3 deletions docs/articles/using-dotnet-test.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,11 +153,10 @@ All settings are MSBuild properties that can be set in your `.csproj` or passed
| Property | Default | Description |
|----------|---------|-------------|
| `DeviceRunnersPort` | `16384` | TCP port for test result collection |
| `DeviceRunnersConnectionTimeout` | `120` | Seconds to wait for the app to connect |
| `DeviceRunnersDataTimeout` | `30` | Seconds of silence before assuming the run ended |
| `DeviceRunnersConnectionTimeout` | `120` | Seconds to wait for the first sign of life (first connection, or first browser message on WASM) |
| `DeviceRunnersDataTimeout` | `30` | Inactivity timeout: seconds of silence before the run is considered stalled. Resets on every event, so a long healthy run keeps going as long as it produces output. A run that stalls **fails** (exit code 2). |
| `DeviceRunnersDevice` | _(auto)_ | Target device ID (Android emulator serial, iOS simulator UDID) |
| `DeviceRunnersBin` | _(bundled)_ | Override the CLI tool path (for using a globally installed tool) |
| `DeviceRunnersWasmTimeout` | `300` | WASM: test execution timeout in seconds |

Example:

Expand Down
7 changes: 4 additions & 3 deletions src/DeviceRunners.Cli/Commands/BaseTestCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,9 +207,10 @@ await networkService.StartTcpListener(

WriteConsoleOutput($" - Results: Total={eventStream.TotalCount}, Passed={eventStream.PassedCount}, Failed={eventStream.FailedCount}, Skipped={eventStream.SkippedCount}", settings);

// Detect app crash: if we received a "begin" event and test results but
// never got the "end" event, the app crashed or was killed mid-run.
// Return -1 to signal crash to the caller (mapped to exit code 2).
// Detect app crash or timeout: if we received a "begin" event and test
// results but never got the "end" event, the app crashed, was killed, or
// timed out mid-run. Signal that as a crash (mapped to exit code 2) so an
// incomplete run never looks like a clean pass.
var outcome = ClassifyRun(eventStream.HasStarted, eventStream.HasEnded, eventStream.TotalCount);

if (outcome == TestRunOutcome.Crashed)
Expand Down
51 changes: 34 additions & 17 deletions src/DeviceRunners.Cli/Commands/Wasm/WasmTestCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,6 @@ public class Settings : BaseTestCommandSettings
[CommandOption("--server-port")]
[DefaultValue(0)]
public int ServerPort { get; set; }

[Description("Test execution timeout in seconds")]
[CommandOption("--timeout")]
[DefaultValue(300)]
public int Timeout { get; set; } = 300;
}

protected override async Task<int> ExecuteAsync(CommandContext context, Settings settings)
Expand Down Expand Up @@ -127,9 +122,34 @@ protected override async Task<int> ExecuteAsync(CommandContext context, Settings

await using var browser = new BrowserService();

// Two timeouts, mirroring the TCP runner so every platform behaves the
// same way:
// - connection timeout: how long to wait for the FIRST browser message
// (a sign the app booted and started reporting);
// - data timeout: an inactivity timeout that resets on every message, so
// a long but healthy run keeps going as long as it produces output.
// A single resettable source models the connection-then-inactivity window:
// it starts with the connection timeout and, once any message arrives, is
// reset to the (shorter) data timeout on every subsequent message. The
// reset is guarded below because a late console message can race with the
// disposal of the source during teardown.
using var inactivityCts = new CancellationTokenSource();
inactivityCts.CancelAfter(TimeSpan.FromSeconds(settings.ConnectionTimeout));
inactivityCts.Token.Register(() => testRunEnded.TrySetCanceled());

browser.ConsoleMessageReceived += (_, msg) =>
{
consoleLog.WriteLine(msg);
// Reset the inactivity window on every message received. Guard against a
// message racing with disposal at the very end of the run.
try
{
if (!inactivityCts.IsCancellationRequested)
inactivityCts.CancelAfter(TimeSpan.FromSeconds(settings.DataTimeout));
}
catch (ObjectDisposedException)
{
}
eventStream.ReceiveData(msg + "\n");
};

Expand All @@ -139,21 +159,25 @@ protected override async Task<int> ExecuteAsync(CommandContext context, Settings
await browser.LaunchAsync(testUrl, headless: !settings.Headed);
WriteConsoleOutput($" Browser launched, running tests...", settings);

// Wait for test completion or timeout
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(settings.Timeout));
cts.Token.Register(() => testRunEnded.TrySetCanceled());

// Wait for test completion or one of the timeouts.
try
{
await testRunEnded.Task;
}
catch (OperationCanceledException)
{
WriteConsoleOutput($" [yellow]Test execution timed out after {settings.Timeout}s[/]", settings);
WriteConsoleOutput($" [yellow]Browser timed out waiting for test results.[/]", settings);
}

eventStream.Flush();

// Classify the run the same way the TCP listener does so a crash or
// timeout mid-run (begin + some results, but no "end") is reported as a
// failure instead of being mistaken for a successful run. A clean empty
// run (begin + end, no results) still succeeds, mirroring `dotnet test
// --filter` exit 0.
var outcome = ClassifyRun(eventStream.HasStarted, eventStream.HasEnded, eventStream.TotalCount);

WriteConsoleOutput($"[blue]------------------------------------------------------------[/]", settings);

if (resultChannel is not null)
Expand All @@ -166,13 +190,6 @@ protected override async Task<int> ExecuteAsync(CommandContext context, Settings

WriteConsoleOutput($" - Results: Total={eventStream.TotalCount}, Passed={eventStream.PassedCount}, Failed={eventStream.FailedCount}, Skipped={eventStream.SkippedCount}", settings);

// Classify the run the same way the TCP listener does so a crash or
// timeout mid-run (begin + some results, but no "end") is reported as a
// failure instead of being mistaken for a successful run. A clean empty
// run (begin + end, no results) still succeeds, mirroring `dotnet test
// --filter` exit 0.
var outcome = ClassifyRun(eventStream.HasStarted, eventStream.HasEnded, eventStream.TotalCount);

if (outcome == TestRunOutcome.Crashed)
WriteConsoleOutput($" [red]The app crashed or timed out before the run completed. Only {eventStream.TotalCount} test result(s) were received before the connection was lost. Check browser-console.log for details.[/]", settings);
else if (outcome == TestRunOutcome.NoResults)
Expand Down
6 changes: 3 additions & 3 deletions src/DeviceRunners.Cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ device-runners windows test --app "path/to/app.msix" --port 8080 --connection-ti
- `--certificate` - Path to the certificate file (optional, auto-detected if not provided)
- `--results-directory` - Results directory for test outputs (default: "artifacts")
- `--port` - TCP port to listen on (default: 16384)
- `--connection-timeout` - Connection timeout in seconds (default: 30)
- `--data-timeout` - Data timeout in seconds (default: 30)
- `--connection-timeout` - Seconds to wait for the app to connect (default: 120)
- `--data-timeout` - Inactivity timeout in seconds; resets on every event (default: 30). A run that stalls fails (exit code 2).

**Workflow:**
1. **Preparation Phase:**
Expand All @@ -195,7 +195,7 @@ device-runners windows test --app "path/to/app.msix" --port 8080 --connection-ti
2. **Execution Phase:**
- Launches the application
- Starts TCP listener on specified port (default: 16384) for test results
- Waits for test completion with configurable timeouts (defaults: 30s connection, 30s data)
- Waits for test completion with configurable timeouts (defaults: 120s connection, 30s inactivity)
- Analyzes test results

3. **Cleanup Phase:**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,13 @@
<!-- TCP port the CLI tool listens on (and the app connects to). -->
<DeviceRunnersPort Condition="'$(DeviceRunnersPort)' == ''">16384</DeviceRunnersPort>

<!-- How long (seconds) the CLI waits for the first TCP connection from the device. -->
<!-- How long (seconds) the CLI waits for the first sign of life from the app:
the first TCP connection (device platforms) or the first browser message (WASM). -->
<DeviceRunnersConnectionTimeout Condition="'$(DeviceRunnersConnectionTimeout)' == ''">120</DeviceRunnersConnectionTimeout>

<!-- How long (seconds) the CLI waits for more data after the last received packet. -->
<!-- Inactivity timeout (seconds): how long the CLI waits for more output after the
last event. Resets on every packet/message, so a long but healthy run keeps
going as long as it keeps producing results. Applies to all platforms incl. WASM. -->
<DeviceRunnersDataTimeout Condition="'$(DeviceRunnersDataTimeout)' == ''">30</DeviceRunnersDataTimeout>

<!--
Expand All @@ -61,9 +64,6 @@
UseArtifactsOutput=true, otherwise to $(MSBuildProjectDirectory)\test-results. -->
<TestResultsDirectory Condition="'$(TestResultsDirectory)' == '' And '$(ArtifactsPath)' != ''">$([MSBuild]::EnsureTrailingSlash('$(ArtifactsPath)'))test-results\</TestResultsDirectory>
<TestResultsDirectory Condition="'$(TestResultsDirectory)' == ''">$(MSBuildProjectDirectory)\test-results\</TestResultsDirectory>

<!-- WASM: test execution timeout in seconds (default 5 minutes). -->
<DeviceRunnersWasmTimeout Condition="'$(DeviceRunnersWasmTimeout)' == ''">300</DeviceRunnersWasmTimeout>
</PropertyGroup>


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,9 @@
<Error Text="Published WASM output not found at '$(PublishDir)'. Make sure the project publishes successfully."
Condition="!Exists('$(_DeviceRunnersWasmDir)')" />
<PropertyGroup>
<!-- WASM uses different CLI flags: no port/TCP, instead uses browser console capture -->
<_DeviceRunnersCliArgs>wasm test --app &quot;$(_DeviceRunnersWasmDir)&quot; --results-directory &quot;$(_DeviceRunnersResultsDir)&quot;$(_DeviceRunnersLoggerArg)$(_DeviceRunnersFilterArg) --timeout $(DeviceRunnersWasmTimeout)</_DeviceRunnersCliArgs>
<!-- WASM uses a browser instead of TCP, but honours the same connection and
data (inactivity) timeouts as the device platforms. -->
<_DeviceRunnersCliArgs>wasm test --app &quot;$(_DeviceRunnersWasmDir)&quot; --results-directory &quot;$(_DeviceRunnersResultsDir)&quot;$(_DeviceRunnersLoggerArg)$(_DeviceRunnersFilterArg) --connection-timeout $(DeviceRunnersConnectionTimeout) --data-timeout $(DeviceRunnersDataTimeout)</_DeviceRunnersCliArgs>
</PropertyGroup>
<Message Importance="high" Text="DeviceRunners: running WASM browser tests from $(_DeviceRunnersWasmDir)" />
</Target>
Expand Down Expand Up @@ -366,15 +367,15 @@
CLI exit codes: 0 = success, 1 = test failures, 2 = app crashed.
-->
<Error Code="TESTERROR"
Text="Test summary: total: $(_TrxTotal), failed: $(_TrxFailed), succeeded: $(_TrxPassed), skipped: @(_TrxSkipped->Count()), duration: $(_TrxDuration)s (incomplete: app crashed)"
Text="Test summary: total: $(_TrxTotal), failed: $(_TrxFailed), succeeded: $(_TrxPassed), skipped: @(_TrxSkipped->Count()), duration: $(_TrxDuration)s (incomplete: the app crashed or the run timed out before it finished)"
Condition="'$(_DeviceRunnersTrxExists)' == 'true' And '$(_DeviceRunnersExitCode)' == '2'" />

<Error Code="TESTERROR"
Text="Test summary: total: $(_TrxTotal), failed: $(_TrxFailed), succeeded: $(_TrxPassed), skipped: @(_TrxSkipped->Count()), duration: $(_TrxDuration)s"
Condition="'$(_DeviceRunnersTrxExists)' == 'true' And '$(_DeviceRunnersExitCode)' == '1'" />

<Error Code="TESTERROR"
Text="The application crashed before producing any test results (exit code 2). Check the device log for details."
Text="The application crashed or the run timed out before producing any test results (exit code 2). Check the device/browser log for details."
Condition="'$(_DeviceRunnersTrxExists)' == 'false' And '$(_DeviceRunnersExitCode)' == '2'" />

<Error Code="TESTERROR" Text="DeviceRunners CLI exited with code $(_DeviceRunnersExitCode) and no TRX was written. Check the output above for details."
Expand Down
Loading