Repository navigation
Enable Microsoft.Testing.Platform on browser-wasm (#2196) #9857
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 6 commits
bff1785
e91368b
f8a438d
b740fcf
d8f721e
b7f592b
6e8b701
33059f3
95d742e
2b5e8b2
ccb3cf5
694eaab
461cd75
5304cf1
a8fda39
85548b6
d33364c
4173533
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| <RuntimeIdentifier>browser-wasm</RuntimeIdentifier> | ||
| <!-- | ||
| Publishing browser-wasm must be self-contained so the mono browser-wasm runtime | ||
| pack is resolved; targeting net10.0 under an 11.0 SDK does not infer this on its own. | ||
| --> | ||
| <SelfContained>true</SelfContained> | ||
|
|
||
| <!-- | ||
| The JS boot module that the WebAssembly runtime loads first. It creates the | ||
| .NET runtime via dotnet.js and invokes the (MTP-generated) Program.Main. | ||
| See wwwroot/main.js. | ||
|
Evangelink marked this conversation as resolved.
Resolved
Evangelink marked this conversation as resolved.
Resolved
|
||
| --> | ||
| <WasmMainJSPath>wwwroot\main.js</WasmMainJSPath> | ||
|
|
||
| <!-- Use the pre-built dotnet.native.wasm (no emscripten / wasm-sdk relink required). --> | ||
| <WasmBuildNative>false</WasmBuildNative> | ||
| <PublishTrimmed>false</PublishTrimmed> | ||
|
|
||
| <Nullable>enable</Nullable> | ||
| <!-- | ||
| IsTestingPlatformApplication is intentionally NOT set when running under | ||
| 'dotnet test' (CI's Debug Test step on TestFx.slnx passes -p:UsingDotNetTest=true). | ||
| The browser-wasm output can only be launched through a JS host (a browser or | ||
| node importing dotnet.js), which is not wired into 'dotnet test'. Keeping the | ||
| property true during a normal build ensures the MTP entry point is still | ||
| generated and baked into the wasm bundle. | ||
|
Evangelink marked this conversation as resolved.
Resolved
|
||
| --> | ||
| <IsTestingPlatformApplication Condition=" '$(UsingDotNetTest)' != 'true' ">true</IsTestingPlatformApplication> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="$(RepoRoot)src\Platform\Microsoft.Testing.Platform\Microsoft.Testing.Platform.csproj" /> | ||
| <ProjectReference Include="$(RepoRoot)src\Platform\Microsoft.Testing.Extensions.Telemetry\Microsoft.Testing.Extensions.Telemetry.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectCapability Include="DiagnoseCapabilities" /> | ||
| <ProjectCapability Include="TestingPlatformServer" /> | ||
| <ProjectCapability Include="TestContainer" /> | ||
|
Copilot marked this conversation as resolved.
Resolved
|
||
| </ItemGroup> | ||
|
|
||
| <!-- | ||
| Ship the node headless runner and the browser page inside the published AppBundle. | ||
| The wasm SDK copies the WasmMainJSPath module (wwwroot/main.js) into the AppBundle; | ||
| WasmExtraFilesToDeploy places additional files (the node runner and index.html) next | ||
| to it so 'node runtests.mjs' / a browser can boot the app from the bundle (see README). | ||
| --> | ||
| <ItemGroup> | ||
| <WasmExtraFilesToDeploy Include="wwwroot\runtests.mjs" /> | ||
| <WasmExtraFilesToDeploy Include="wwwroot\index.html" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| using Microsoft.Testing.Extensions; | ||
| using Microsoft.Testing.Platform.Builder; | ||
| using Microsoft.Testing.Platform.Capabilities.TestFramework; | ||
| using Microsoft.Testing.Platform.Extensions.Messages; | ||
| using Microsoft.Testing.Platform.Extensions.TestFramework; | ||
|
|
||
| ITestApplicationBuilder testApplicationBuilder = await TestApplication.CreateBuilderAsync(args); | ||
|
|
||
| testApplicationBuilder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_, _) => new DummyFramework()); | ||
|
|
||
| testApplicationBuilder.AddAppInsightsTelemetryProvider(); | ||
|
|
||
| // The following extensions are intentionally NOT registered on browser-wasm: | ||
| // - AddTrxReportProvider: with --report-trx enabled, TrxDataConsumer creates a | ||
| // TrxResultStreamingStore whose background writer calls ITask.RunLongRunning (and uses | ||
| // BlockingCollection<T>), both unsupported on browser; the TRX lifecycle handlers are | ||
| // themselves gated by OperatingSystem.IsBrowser() (see TrxReportExtensions). Registering it | ||
| // would let a user pass --report-trx and hit PlatformNotSupportedException. | ||
| // - AddHangDumpProvider / AddCrashDumpProvider: dumps rely on System.Diagnostics.Process, | ||
| // which is unsupported in the browser sandbox (see #8557). | ||
| // - AddAzureDevOpsProvider: its HttpClient sets AutomaticDecompression, which the browser | ||
| // HttpClientHandler does not support. | ||
| // Threading is not an issue for the registered providers: the platform detects the | ||
| // single-threaded wasm runtime (RuntimeFeatureHelper.IsMultiThreaded == false) and runs the | ||
| // pipeline inline, exactly as it does on wasi-wasm. | ||
| using ITestApplication testApplication = await testApplicationBuilder.BuildAsync(); | ||
| return await testApplication.RunAsync(); | ||
|
|
||
| internal sealed class DummyFramework : ITestFramework, IDataProducer | ||
| { | ||
| public string Uid => nameof(DummyFramework); | ||
|
|
||
| public string Version => "1.0.0"; | ||
|
|
||
| public string DisplayName => "DummyFramework"; | ||
|
|
||
| public string Description => DisplayName; | ||
|
Evangelink marked this conversation as resolved.
Resolved
|
||
|
|
||
| public Type[] DataTypesProduced => [typeof(TestNodeUpdateMessage)]; | ||
|
|
||
| public Task<CloseTestSessionResult> CloseTestSessionAsync(CloseTestSessionContext context) | ||
| => Task.FromResult(new CloseTestSessionResult() { IsSuccess = true }); | ||
|
|
||
| public Task<CreateTestSessionResult> CreateTestSessionAsync(CreateTestSessionContext context) | ||
| => Task.FromResult(new CreateTestSessionResult() { IsSuccess = true }); | ||
|
|
||
| public async Task ExecuteRequestAsync(ExecuteRequestContext context) | ||
| { | ||
| await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, new TestNode() | ||
| { | ||
| DisplayName = "Test display name", | ||
| Uid = "Uid1", | ||
| Properties = new PropertyBag(PassedTestNodeStateProperty.CachedInstance), | ||
| })); | ||
| context.Complete(); | ||
| } | ||
|
|
||
| public Task<bool> IsEnabledAsync() => Task.FromResult(true); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| # BrowserPlayground | ||
|
|
||
| Demonstrates hosting [Microsoft.Testing.Platform](https://aka.ms/testingplatform/) on | ||
| `browser-wasm` — the WebAssembly runtime that runs inside a browser (and, headlessly, | ||
| under [Node.js](https://nodejs.org/) via the same `dotnet.js` loader). | ||
|
|
||
| This is the browser counterpart to [`samples/WasiPlayground`](../WasiPlayground/README.md). | ||
| Both run on a single-threaded WebAssembly runtime; the platform work that makes that | ||
|
Evangelink marked this conversation as resolved.
Resolved
|
||
| possible is shared (see [#2196](https://github.com/microsoft/testfx/issues/2196)). The | ||
| only real difference is the **host**: `wasi-wasm` runs headless under `wasmtime`, whereas | ||
| `browser-wasm` boots through a small JavaScript module (`wwwroot/main.js`) that loads | ||
| `dotnet.js` and invokes the generated `Program.Main`. | ||
|
Evangelink marked this conversation as resolved.
Resolved
Evangelink marked this conversation as resolved.
Resolved
|
||
|
|
||
| ## Build & run | ||
|
|
||
| > **Not part of `TestFx.slnx`.** `browser-wasm` needs the `wasm-tools` workload even to | ||
| > *build*. The repo bootstrap installs that workload (see `eng/restore-toolset`), but | ||
| > adding this project to the solution would still break the default `.\build.cmd` on any | ||
| > environment where the workload is missing, so `BrowserPlayground` is intentionally | ||
| > excluded from the solution and built on demand with the explicit `dotnet publish` below. | ||
|
Evangelink marked this conversation as resolved.
Resolved
|
||
|
|
||
| Prerequisites: | ||
|
|
||
| - The repo-local .NET SDK (`.dotnet\dotnet.exe` on Windows, `.dotnet/dotnet` on | ||
| Linux/macOS). Bootstrap it once by running `.\build.cmd` (Windows) or `./build.sh` | ||
| (Linux/macOS) from the repo root. The bootstrap also installs the `wasm-tools-net10` | ||
| workload this sample needs (see | ||
| [`eng/restore-toolset.ps1`](../../eng/restore-toolset.ps1) / | ||
| [`eng/restore-toolset.sh`](../../eng/restore-toolset.sh)). If you use a machine-installed | ||
| SDK instead, install the workload manually: | ||
|
|
||
| ``` | ||
|
Check failure on line 32 in samples/BrowserPlayground/README.md
|
||
| dotnet workload install wasm-tools-net10 | ||
| ``` | ||
|
|
||
| - For the headless run: [Node.js](https://nodejs.org/) on `PATH`. | ||
| For the browser run: any static web server (see step 2b). | ||
|
|
||
| > The commands below use the repo-local SDK so the `.dotnet/packs` lookup resolves — that | ||
| > is `.\.dotnet\dotnet.exe` on Windows and `./.dotnet/dotnet` on Linux/macOS (shown as | ||
| > `dotnet` below for brevity). Swap in a machine-installed `dotnet` if you prefer. Windows | ||
| > examples use `\` path separators; on Linux/macOS use `/` (e.g. | ||
| > `artifacts/bin/BrowserPlayground/Debug/net10.0/browser-wasm/AppBundle`). | ||
|
Evangelink marked this conversation as resolved.
Resolved
|
||
|
|
||
| ### 1. Publish | ||
|
|
||
| ``` | ||
|
Check failure on line 47 in samples/BrowserPlayground/README.md
|
||
| dotnet publish samples/BrowserPlayground/BrowserPlayground.csproj -c Debug -f net10.0 | ||
| ``` | ||
|
|
||
| The published app bundle lands under | ||
| `artifacts/bin/BrowserPlayground/Debug/net10.0/browser-wasm/AppBundle` and contains | ||
| `_framework/dotnet.js`, the managed assemblies, `index.html`, `main.js`, and | ||
| `runtests.mjs`. | ||
|
|
||
| ### 2a. Run headlessly under Node | ||
|
|
||
| From the bundle directory: | ||
|
|
||
| ``` | ||
|
Check failure on line 60 in samples/BrowserPlayground/README.md
|
||
| cd artifacts/bin/BrowserPlayground/Debug/net10.0/browser-wasm/AppBundle | ||
| node runtests.mjs | ||
| ``` | ||
|
|
||
| `runtests.mjs` boots the same bundle under Node (no DOM required — Microsoft.Testing.Platform | ||
| never touches the DOM), forwards stdout/stderr, and maps the .NET exit code onto the Node | ||
| process exit code. This is the mode the `BrowserWasmExecutionTests` acceptance test uses. | ||
|
|
||
| ### 2b. Run in a browser | ||
|
|
||
| Serve the bundle over HTTP (WebAssembly cannot be loaded from `file://`) and open it. Any | ||
| static file server works; two options that need no extra provisioning: | ||
|
|
||
| ``` | ||
|
Check failure on line 74 in samples/BrowserPlayground/README.md
|
||
| cd artifacts/bin/BrowserPlayground/Debug/net10.0/browser-wasm/AppBundle | ||
|
|
||
| # Using Node (installed for step 2a): | ||
| npx --yes http-server -o | ||
|
|
||
| # ...or using Python 3: | ||
| python3 -m http.server 8080 | ||
| ``` | ||
|
|
||
| Then browse to the served URL (`http-server` opens it automatically; for the Python server | ||
| open <http://localhost:8080/>). The test run output appears in the browser's developer-tools | ||
| **Console**. Pass Microsoft.Testing.Platform options through the page query string, e.g. | ||
| `index.html?arg=--minimum-expected-tests&arg=1`. | ||
|
|
||
| ## Status | ||
|
|
||
| Microsoft.Testing.Platform boots on `browser-wasm` (the banner reads | ||
| `[browser-wasm - net10.0]`) and tests run to completion, exactly as on `wasi-wasm`. | ||
| Running this sample — which hosts a `DummyFramework` with a single passing test — | ||
| produces: | ||
|
|
||
| ```console | ||
| Test run summary: Passed! | ||
| total: 1 | ||
| failed: 0 | ||
| succeeded: 1 | ||
| skipped: 0 | ||
| ``` | ||
|
|
||
| MSTest itself (not just the raw platform) also runs end-to-end on `browser-wasm`; that | ||
| is covered by the gated `BrowserWasmExecutionTests.BrowserWasmExecution_RunsTestsUnderNode` | ||
| acceptance test (see | ||
| [`test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs`](../../test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs)), | ||
| which publishes a real MSTest project and runs it under Node. | ||
|
|
||
| ### Why it works | ||
|
|
||
| The single-threaded WebAssembly constraint is the same as `wasi-wasm`: there is no | ||
| thread pool, so `Task.Run` continuations never execute and blocking waits throw | ||
| `PlatformNotSupportedException`. The platform and the MSTest adapter detect this | ||
| (`RuntimeFeatureHelper.IsMultiThreaded` / `RuntimeContext.IsMultiThreaded`, derived from | ||
| `OperatingSystem.IsBrowser()`) and fall back to inline/synchronous execution on the run | ||
| path — the message-bus consumers, the shutdown watchdog, the telemetry ingest loop, the | ||
| countdown-event wait, and the adapter's per-test task factory. | ||
|
|
||
| Console output is routed through `BrowserOutputDevice`, which forwards to the browser's | ||
| `globalThis.console.*` APIs via `[JSImport]`. | ||
|
|
||
| ### Feature matrix (what is *not* available on browser-wasm) | ||
|
|
||
| Several extensions/capabilities are intentionally unavailable in the browser sandbox and | ||
| are guarded off by `OperatingSystem.IsBrowser()` in the platform: | ||
|
|
||
| | Feature | Reason | | ||
| | --- | --- | | ||
| | TRX report (`--report-trx`) | `TrxDataConsumer` creates a `TrxResultStreamingStore` whose background writer uses `BlockingCollection<T>` and `ITask.RunLongRunning`, both unsupported on browser; the TRX lifecycle handlers are gated by `OperatingSystem.IsBrowser()`. | | ||
| | Hang dump / crash dump | Rely on `System.Diagnostics.Process`, unsupported in the browser (see [#8557](https://github.com/microsoft/testfx/issues/8557)). | | ||
| | Azure DevOps report | Its `HttpClient` sets `AutomaticDecompression`, unsupported by the browser `HttpClientHandler`. | | ||
| | Server mode / `dotnet test` pipe | Depends on TCP/named-pipe IPC, unavailable in the browser. | | ||
| | `--exit-on-process-exit`, wait-for-debugger | No host process model in the browser. | | ||
| | Synchronous file-logger flush | Not supported in the browser (throws `PlatformNotSupportedException`). | | ||
|
|
||
| That is why `Program.cs` registers only the telemetry provider (`AddAppInsightsTelemetryProvider`). | ||
|
|
||
| ## Build configuration notes | ||
|
|
||
| `BrowserPlayground.csproj` ships with a few non-obvious switches: | ||
|
|
||
| | Property | Reason | | ||
| | --- | --- | | ||
| | `SelfContained=true` | Publishing browser-wasm must be self-contained so the `Microsoft.NETCore.App.Runtime.Mono.browser-wasm` runtime pack is resolved. Targeting `net10.0` under an `11.0` SDK does not infer this on its own, so publish fails with an empty `MicrosoftNetCoreAppRuntimePackDir` without it. | | ||
| | `WasmBuildNative=false` | Use the pre-built `dotnet.native.wasm`. A native relink needs the emscripten toolchain (pulled in by the `wasm-tools` workload) and is slower; the pre-built runtime is enough to boot MTP. | | ||
| | (no `InvariantGlobalization`) | On browser-wasm, `InvariantGlobalization=true` forces `WasmBuildNative=true` (an emscripten relink), so it is intentionally left unset — the browser bundle ships ICU (`icudt*.dat`) by default. This differs from `WasiPlayground`, which keeps `InvariantGlobalization=true` and stages `icudt.dat` manually. | | ||
|
Evangelink marked this conversation as resolved.
Resolved
|
||
| | `WasmExtraFilesToDeploy` | Copies the node runner (`runtests.mjs`) and `index.html` into the published `AppBundle` next to `main.js` (the `WasmMainJSPath` module). Plain `CopyToOutputDirectory` would only reach the build output folder, not the `AppBundle`. | | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| <!DOCTYPE html> | ||
| <!-- Copyright (c) Microsoft Corporation. All rights reserved. --> | ||
| <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. --> | ||
| <html lang="en"> | ||
|
|
||
| <head> | ||
| <meta charset="utf-8" /> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | ||
| <title>BrowserPlayground</title> | ||
| </head> | ||
|
|
||
| <body> | ||
| <p>Running Microsoft.Testing.Platform on browser-wasm. Open the developer-tools console to see the test run output.</p> | ||
| <!-- Boots the .NET WebAssembly runtime and Microsoft.Testing.Platform (see wwwroot/main.js). --> | ||
| <script type="module" src="./main.js"></script> | ||
| </body> | ||
|
|
||
| </html> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| // Browser boot module. The WebAssembly runtime loads this file first (it is the | ||
| // project's WasmMainJSPath). It creates the .NET runtime through dotnet.js and runs the | ||
| // (MTP-generated) Program.Main, which boots Microsoft.Testing.Platform. | ||
|
Evangelink marked this conversation as resolved.
Resolved
Evangelink marked this conversation as resolved.
Resolved
|
||
| import { dotnet } from './_framework/dotnet.js'; | ||
|
|
||
| const { runMain } = await dotnet | ||
| // A browser page has no argv, so Microsoft.Testing.Platform command-line options are | ||
| // taken from the page's query string, e.g.: | ||
| // index.html?arg=--minimum-expected-tests&arg=1 | ||
| .withApplicationArgumentsFromQuery() | ||
| .create(); | ||
|
|
||
| // runMain() invokes Program.Main and resolves to its exit code (0 = all tests passed, | ||
| // non-zero = failures / policy violation). | ||
| const exitCode = await runMain(); | ||
|
|
||
| // Surface the result so a headless browser driver (Playwright/Puppeteer) can read it, | ||
| // and so a human sees it in the dev-tools console / tab title. | ||
| console.log(`Microsoft.Testing.Platform exit code: ${exitCode}`); | ||
| globalThis.mtpExitCode = exitCode; | ||
| document.title = `exit:${exitCode}`; | ||
Uh oh!
There was an error while loading. Please reload this page.