diff --git a/docs/README.md b/docs/README.md index bd37222f2d..6a0d5ba7bb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -37,6 +37,10 @@ For technical reasoning and implementation details, you can refer to the list of - [DataSource Attribute Vs ITestDataSource](RFCs/007-DataSource-Attribute-VS-ITestDataSource.md) - [Test case timeout via runsettings](RFCs/008-TestCase-Timeout.md) +## Guides + +- [Testing WinUI apps](winui-testing.md): packaged (MSIX) vs unpackaged WinUI, and how the test host is started for each. + ## Design notes - [MSTest source generator — design](source-generator/design.md): scope, fallback categories, discovery limitations and trim/AOT story for the `MSTest.SourceGeneration` package. diff --git a/docs/glossary.md b/docs/glossary.md index 26874f7733..d24cc6690c 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -375,7 +375,7 @@ An experimental MTP extension (`Microsoft.Testing.Extensions.Logging`, `[TPEXP]` ### Microsoft.Testing.Extensions.PackagedApp -An experimental MTP extension (`Microsoft.Testing.Extensions.PackagedApp`, `[Experimental("TPEXP")]`, ships as `1.0.0-alpha`) that enables testing packaged Windows apps (UWP / WinUI) by deploying the test payload to an isolated directory and launching it via the [ITestHostLauncher](#itesthostlauncher) extension point, rather than a plain `Process.Start`. Register via `builder.AddPackagedAppDeployment()`. Full AUMID activation (for apps requiring the app identity manifest) is planned for a follow-up release. Introduced in [PR #9454](https://github.com/microsoft/testfx/pull/9454). See also [ITestHostLauncher](#itesthostlauncher). +An experimental MTP extension (`Microsoft.Testing.Extensions.PackagedApp`, `[Experimental("TPEXP")]`, ships as `1.0.0-alpha`) that enables testing packaged Windows apps (full-trust MSIX desktop, e.g. packaged WinUI) by registering the layout with the `PackageManager` and activating it by AUMID through the [ITestHostLauncher](#itesthostlauncher) extension point, rather than a plain `Process.Start`. Register via `builder.AddPackagedAppDeployment()`, or simply by referencing the package (its MSBuild props register the hook). The launcher only enables itself when the test application is a packaged layout — a manifest in the app's own directory, or an ancestor `AppxManifest.xml` whose `Application/@Executable` resolves back to the app directory — so referencing it from an **unpackaged** app does not force the test host controller process model or copy the build output; `TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER` (`auto`/`always`/`never`) overrides that decision. Introduced in [PR #9454](https://github.com/microsoft/testfx/pull/9454); AUMID activation added in [PR #9970](https://github.com/microsoft/testfx/pull/9970). See also [ITestHostLauncher](#itesthostlauncher) and [docs/winui-testing.md](winui-testing.md). ## N diff --git a/docs/winui-testing.md b/docs/winui-testing.md new file mode 100644 index 0000000000..47614e94ff --- /dev/null +++ b/docs/winui-testing.md @@ -0,0 +1,176 @@ +# Testing WinUI apps with MSTest and Microsoft.Testing.Platform + +WinUI 3 test apps come in two flavors, and which one you use decides how the test host is started: + +| Flavor | `WindowsPackageType` | Has an `AppxManifest.xml` in the build output | How the test host starts | +| --- | --- | --- | --- | +| **Packaged** (MSIX) | unset (the default) | yes | The app must be registered with the OS and activated by Application User Model ID (AUMID). `Process.Start` cannot start it. | +| **Unpackaged** | `None` | no | It is an ordinary Windows executable. `Process.Start` is all that is needed. | + +Both flavors are supported when you run on [Microsoft.Testing.Platform](https://learn.microsoft.com/dotnet/core/testing/unit-testing-platform-intro) (MTP), which you enable with `true`. Under MTP the WinUI app **is** the test host: it hosts the platform in-process, so VSTest's appx runtime provider is never involved. A packaged app still needs the [`Microsoft.Testing.Extensions.PackagedApp`](#packaged-msix-winui) launcher to register and AUMID-activate that host, because a packaged app cannot be started with `Process.Start`; an unpackaged app needs nothing extra. + +> [!NOTE] +> Unpackaged WinUI is not supported under VSTest. VSTest routes every `UseWinUI` project through its `UwpTestHostRuntimeProvider`, which unconditionally reads an `AppxManifest.xml` from the build output and fails with `FileNotFoundException` when there is none. That provider ships in Visual Studio, not in this repository. See [#2784](https://github.com/microsoft/testfx/issues/2784). + +## Unpackaged WinUI + +Set `WindowsPackageType` to `None` and enable the MSTest runner: + +```xml + + + + Exe + net9.0-windows10.0.19041.0 + 10.0.17763.0 + true + + + None + + true + + + + + + + + +``` + +Point `[UITestMethod]` at a dispatcher queue so UI tests run on the UI thread. Which mechanism you use depends on whether the test app is itself the WinUI app: + +**Self-hosted (the app is the test host).** A WinUI app already generates its own entry point from its `ApplicationDefinition`, so tell the platform not to generate a competing one, and host the platform yourself from `OnLaunched`: + +```xml + + true + + false + +``` + +The process has already called `Application.Start`, so publish that dispatcher directly rather than letting the attribute start another application: + +```csharp +protected override async void OnLaunched(LaunchActivatedEventArgs args) +{ + _window = new UnitTestAppWindow(); + _window.Activate(); + UITestMethodAttribute.DispatcherQueue = _window.DispatcherQueue; + + string[] cliArgs = Environment.GetCommandLineArgs().Skip(1).ToArray(); + ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(cliArgs); + builder.AddSelfRegisteredExtensions(cliArgs); + using ITestApplication app = await builder.BuildAsync(); + + // The WinUI-generated entry point is 'void', so publish the exit code yourself. + Environment.ExitCode = await app.RunAsync(); + _window.Close(); + Exit(); +} +``` + +> [!IMPORTANT] +> Do **not** use `[assembly: WinUITestTarget(...)]` in a self-hosted app. That attribute makes `UITestMethodAttribute` start an application itself, which would be a second `Application.Start` in the same process and fails. + +**Separate host.** When the test host is an ordinary executable and no `Application` has been started yet, let the attribute start one: + +```csharp +[assembly: WinUITestTarget(typeof(MyApp.App))] +``` + +With either setup, `dotnet run` (or `dotnet test`) starts the executable directly and the run finishes in a single process. + +### Building unpackaged WinUI projects + +Build with `dotnet build` as usual. Note that older Windows App SDK releases required the MrtCore PRI generation +MSBuild tasks that ship with Visual Studio (`Microsoft.Build.Packaging.Pri.Tasks.dll`); on those versions a +`dotnet` CLI build fails with: + +```text +error MSB4062: The "Microsoft.Build.Packaging.Pri.Tasks.ExpandPriContent" task could not be loaded +``` + +If you hit that, either build from Visual Studio (or with its `MSBuild.exe`) or move to a newer +`Microsoft.WindowsAppSDK`. This is a Windows App SDK build requirement, not an MSTest one. + +## Packaged (MSIX) WinUI + +A packaged app keeps the default `WindowsPackageType` and ships a `Package.appxmanifest`. Because it cannot be started with `Process.Start`, the test host has to be registered and activated by AUMID. Add the [`Microsoft.Testing.Extensions.PackagedApp`](https://www.nuget.org/packages/Microsoft.Testing.Extensions.PackagedApp) package, which does exactly that through the platform's `ITestHostLauncher` extension point: + +```xml + +``` + +Referencing the package is enough — its MSBuild props register the launcher. Do **not** also call `builder.AddPackagedAppDeployment()` when you already use `AddSelfRegisteredExtensions`, because at most one test host launcher may be registered per run. + +Requirements and limitations: + +- Target a Windows TFM at platform version `10.0.19041.0` or higher (for example `net8.0-windows10.0.19041.0`) so NuGet resolves the Windows asset that contains the register-and-activate path. The plain `net8.0`/`net9.0` asset fails fast with an actionable message instead. +- Registering an unsigned build-output layout requires **Developer Mode** (or sideloading) to be enabled on the machine. +- Only **full-trust packaged desktop** hosts are supported. True UWP/AppContainer hosts are not: activation arguments are not delivered as `argv` there, and the controller pipe is not granted the package SID. + +See [#9933](https://github.com/microsoft/testfx/issues/9933) for the implementation of this path. + +## When does the PackagedApp launcher take over? + +Registering an *enabled* test host launcher switches the whole run to the test host controller (process restart) model, because a custom launcher only has an effect when an out-of-process test host is started. That is the right trade for a packaged app, but it is pure overhead for an app that just needs `Process.Start`. + +The launcher therefore decides for itself, per run: + +| Situation | Launcher enabled? | Effect | +| --- | --- | --- | +| Not Windows | no | Nothing changes. Packaged Windows apps are a Windows-only concept. | +| Packaged layout (an `AppxManifest.xml` that describes this app — see below) | yes | The layout is registered and activated by AUMID. | +| Any other layout — including unpackaged WinUI and ordinary console test apps | no | The platform keeps its default in-process / `Process.Start` path. | + +So an **unpackaged** WinUI app that references `Microsoft.Testing.Extensions.PackagedApp` (directly, or transitively through a shared `Directory.Packages.props`) pays nothing for it: no extra process, and no copy of the build output into a deployment directory. + +### How a manifest is attributed to your app + +"Packaged layout" means a manifest that actually describes *this* app, not merely any `AppxManifest.xml` somewhere above it: + +- An `AppxManifest.xml` **in the app's own directory** is taken as the app's layout. +- An `AppxManifest.xml` in an **ancestor** directory is used only when one of its `` entries declares an `Executable` that resolves back to the app directory — and, when the launcher is actually starting the host, to that exact executable. This is what lets `Application/@Executable` point into a subdirectory of the package root at any depth. +- An ancestor manifest that declares no matching `Executable` is ignored, so a stray manifest in a shared build root or CI staging directory cannot classify an unrelated test app as packaged. + +### Overriding the decision + +Set the `TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER` environment variable to override the layout probe. Values are compared case-insensitively; anything unrecognized falls back to `auto` rather than failing the run. + +| Value | Behavior | +| --- | --- | +| unset, or `auto` | Enable only for a packaged layout. This is the default described above. | +| `always` | Always enable. Use this to deploy a **non-packaged** layout into an isolated directory and launch the produced executable from there, for tests that must not run from the build output. | +| `never` | Never enable, even for a packaged layout. Escape hatch if the automatic detection gets in your way. | + +## Behavior notes + +- **The app must be able to exit.** `Application.Start` pumps a message loop that never returns, so `UITestMethodAttribute` runs it on a background thread. Otherwise the process would stay alive after the run and hang when the test app is itself the test host — which is exactly the unpackaged MTP case. See [#9904](https://github.com/microsoft/testfx/pull/9904). +- **Publish the exit code yourself.** The WinUI-generated entry point is `void`, so a self-hosted test app must assign `Environment.ExitCode = await app.RunAsync();` and then call `Exit()`. Without it the process always exits `0` and failing tests never fail the build. +- **MrtCore warns about MSTest's satellite assemblies.** A WinUI build indexes resources with MrtCore, which reports `PRI257`/`PRI263` because MSTest ships localized satellite assemblies that carry no `en-US` default. It is benign — the warning is about resource *lookup* fallback, not about your tests. Note it cannot be silenced with `NoWarn` or `MSBuildWarningsAsMessages`, because MrtCore puts the `PRI…` code in the message text rather than in the MSBuild warning code; if you build with warnings as errors, exclude this project from that setting. +- **Avoid `dotnet exec`.** WinUI resolves its PRI resources relative to the *process* path, so running the test app under `dotnet.exe` breaks resource loading. `Microsoft.Testing.Platform.MSBuild` already prefers launching the apphost directly when one is available. +- **Startup failures surface as test failures.** If the application cannot be brought up on the `WinUITestTarget` path — a throwing `Application` constructor, or in an unpackaged app a Windows App SDK runtime that cannot be resolved (`COMException` / `REGDB_E_CLASSNOTREG`) — the failure is now reported on the test. Earlier versions swallowed it and the run hung with no diagnostic at all. + +## How the Windows App SDK gets initialized + +An unpackaged app has no MSIX manifest declaring a framework dependency, so the Windows App SDK runtime has to be resolved at startup by the *bootstrapper*. You normally write no code for this: when + +- `WindowsPackageType` is `None`, +- `WindowsAppSDKSelfContained` is not `true`, and +- `OutputType` is `Exe` or `WinExe`, + +the Windows App SDK build injects a [module initializer](https://learn.microsoft.com/dotnet/csharp/language-reference/proposals/csharp-9.0/module-initializers) into **your app assembly** that calls `Bootstrap.Initialize`. The CLR runs a module initializer before the first use of any type in that assembly, so it has already run by the time your tests execute. + +That is why a plain `[TestMethod]` — not just `[UITestMethod]` — can call Windows App SDK WinRT APIs in an unpackaged test app. + +Note those conditions are evaluated per project, and a **class library** does not get the initializer. If your tests live in a library loaded by a host that is not itself a Windows App SDK app, set `true` explicitly. + +## Related + +- [`Microsoft.Testing.Extensions.PackagedApp` package readme](../src/Platform/Microsoft.Testing.Extensions.PackagedApp/PACKAGE.md) +- [RFC 017 — Test host launcher](RFCs/017-TestHost-Launcher.md) +- [`MSTestRunnerWinUI` sample](../samples/public/mstest-runner/MSTestRunnerWinUI) (packaged, MTP) +- [`MSTestRunnerWinUIUnpackaged` sample](../samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged) (unpackaged, MTP) diff --git a/samples/public/mstest-runner/MSTestRunnerWinUI/MSTestRunnerWinUI/MSTestRunnerWinUI.csproj b/samples/public/mstest-runner/MSTestRunnerWinUI/MSTestRunnerWinUI/MSTestRunnerWinUI.csproj index a578462ebb..e8ad3795c0 100644 --- a/samples/public/mstest-runner/MSTestRunnerWinUI/MSTestRunnerWinUI/MSTestRunnerWinUI.csproj +++ b/samples/public/mstest-runner/MSTestRunnerWinUI/MSTestRunnerWinUI/MSTestRunnerWinUI.csproj @@ -54,10 +54,12 @@ diff --git a/samples/public/mstest-runner/MSTestRunnerWinUI/MSTestRunnerWinUI/UnitTestApp.xaml.cs b/samples/public/mstest-runner/MSTestRunnerWinUI/MSTestRunnerWinUI/UnitTestApp.xaml.cs index 7925dab0d3..e554984855 100644 --- a/samples/public/mstest-runner/MSTestRunnerWinUI/MSTestRunnerWinUI/UnitTestApp.xaml.cs +++ b/samples/public/mstest-runner/MSTestRunnerWinUI/MSTestRunnerWinUI/UnitTestApp.xaml.cs @@ -63,16 +63,21 @@ void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args) ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(cliArgs); // Registers all MSBuild-contributed extensions, including the Microsoft.Testing.Extensions.PackagedApp - // launcher (from the PackageReference in the csproj). That launcher deploys this packaged WinUI test - // host into an isolated directory and launches it from there through the platform's ITestHostLauncher - // extension point. + // launcher (from the PackageReference in the csproj). Because this app is packaged (MSIX), that + // launcher registers the layout with the OS and activates it by Application User Model ID through + // the platform's ITestHostLauncher extension point, instead of a plain Process.Start. builder.AddSelfRegisteredExtensions(cliArgs); using ITestApplication app = await builder.BuildAsync(); - await app.RunAsync(); + + // The WinUI-generated entry point is 'void', so the run's exit code has to be published through + // Environment.ExitCode. Without this the app would always exit 0 and failing tests would never + // fail the build. + Environment.ExitCode = await app.RunAsync(); } finally { _window.Close(); + Exit(); } #else Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.Run(Environment.CommandLine); diff --git a/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged.slnx b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged.slnx new file mode 100644 index 0000000000..897a30e191 --- /dev/null +++ b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged.slnx @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged.csproj b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged.csproj new file mode 100644 index 0000000000..173b6134dc --- /dev/null +++ b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged.csproj @@ -0,0 +1,61 @@ + + + Exe + net8.0-windows10.0.19041.0 + 10.0.17763.0 + MSTestRunnerWinUIUnpackaged + app.manifest + x86;x64;ARM64 + win-x86;win-x64;win-arm64 + true + enable + + + None + + + false + + + + true + + false + + + + + + + + + + + + + + + + + + + + + + False + False + + diff --git a/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/Properties/launchSettings.json b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/Properties/launchSettings.json new file mode 100644 index 0000000000..e678aecf94 --- /dev/null +++ b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/Properties/launchSettings.json @@ -0,0 +1,7 @@ +{ + "profiles": { + "MSTestRunnerWinUIUnpackaged (Unpackaged)": { + "commandName": "Project" + } + } +} diff --git a/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestApp.xaml b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestApp.xaml new file mode 100644 index 0000000000..e72238f10e --- /dev/null +++ b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestApp.xaml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestApp.xaml.cs b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestApp.xaml.cs new file mode 100644 index 0000000000..36252009ba --- /dev/null +++ b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestApp.xaml.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Linq; +using System.Threading.Tasks; + +using Microsoft.Testing.Platform.Builder; +using Microsoft.UI.Xaml; +using Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer; + +namespace MSTestRunnerWinUIUnpackaged; + +/// +/// Provides application-specific behavior to supplement the default Application class. +/// +public partial class UnitTestApp : Application +{ + private Window? _window; + + /// + /// Initializes the singleton application object. This is the first line of authored code + /// executed, and as such is the logical equivalent of main() or WinMain(). + /// + public UnitTestApp() => InitializeComponent(); + + /// + /// Invoked when the application is launched. + /// + /// Details about the launch request and process. + protected override async void OnLaunched(LaunchActivatedEventArgs args) + { + _window = new UnitTestAppWindow(); + _window.Activate(); + + // Tests marked [UITestMethod] run on this window's dispatcher queue. This process has already + // called Application.Start, so the dispatcher has to be published here. Do NOT use + // [assembly: WinUITestTarget(...)] in a self-hosted app like this one: it would make + // UITestMethodAttribute start a second application in the same process. + UITestMethodAttribute.DispatcherQueue = _window.DispatcherQueue; + + try + { + // Ideally we would want to reuse the generated main so we don't have to manually handle all + // dependencies, but this type is generated too late in the build process so we fail before. + // You can build, inspect the generated type to copy its content if you want. + string[] cliArgs = Environment.GetCommandLineArgs() + .Skip(1) + .Where(arg => !arg.Contains("EnableMSTestRunner")) + .ToArray(); + ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(cliArgs); + builder.AddSelfRegisteredExtensions(cliArgs); + using ITestApplication app = await builder.BuildAsync(); + + // The WinUI-generated entry point is 'void', so the run's exit code has to be published + // through Environment.ExitCode. Without this the app would always exit 0 and failing tests + // would never fail the build. + Environment.ExitCode = await app.RunAsync(); + } + finally + { + // Closing the window lets the message loop drain so the process can exit once the run is + // done. Without this an unpackaged test app — which is itself the test host — would hang + // after reporting results. + _window.Close(); + Exit(); + } + } +} diff --git a/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestAppWindow.xaml b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestAppWindow.xaml new file mode 100644 index 0000000000..6bf8b5fc40 --- /dev/null +++ b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestAppWindow.xaml @@ -0,0 +1,15 @@ + + + + + + + diff --git a/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestAppWindow.xaml.cs b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestAppWindow.xaml.cs new file mode 100644 index 0000000000..01f33bfabb --- /dev/null +++ b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTestAppWindow.xaml.cs @@ -0,0 +1,11 @@ +// 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.UI.Xaml; + +namespace MSTestRunnerWinUIUnpackaged; + +public sealed partial class UnitTestAppWindow : Window +{ + public UnitTestAppWindow() => InitializeComponent(); +} diff --git a/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTests.cs b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTests.cs new file mode 100644 index 0000000000..35eb9e0b2a --- /dev/null +++ b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/UnitTests.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; + +using Microsoft.UI.Xaml.Controls; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer; + +namespace MSTestRunnerWinUIUnpackaged; + +[TestClass] +public partial class UnitTest1 +{ + /// + /// Asserts the property that defines this sample: the app runs with no MSIX package identity. + /// Package.Current is only available to a packaged app and throws otherwise. + /// + [TestMethod] + public void AppRunsWithoutPackageIdentity() + => Assert.ThrowsExactly(() => _ = Windows.ApplicationModel.Package.Current); + + /// + /// A plain [TestMethod] that touches a Windows App SDK WinRT type. In an unpackaged app this only + /// resolves once the Windows App SDK bootstrapper has run, which the Windows App SDK arranges + /// through a module initializer it injects into this assembly. It is covered here because it is the + /// case that does NOT go through [UITestMethod]. + /// + [TestMethod] + public void WindowsAppSdkWinRTIsUsableFromAPlainTestMethod() + { + var releaseInfo = Microsoft.Windows.ApplicationModel.WindowsAppRuntime.RuntimeInfo.AsString; + + // A parseable version proves the bootstrapper resolved a real runtime, rather than the call + // merely returning some non-empty string. + Assert.IsNotNull(releaseInfo); + Assert.IsTrue(Version.TryParse(releaseInfo, out _), $"Expected a Windows App Runtime version, got '{releaseInfo}'."); + } + + /// + /// Use [UITestMethod] for tests that need the UI thread. WinUI controls can only be created there, + /// so constructing one would fail with RPC_E_WRONG_THREAD from a plain [TestMethod]. The control + /// reports the dispatcher of the thread that created it, and that dispatcher confirms the test body + /// is itself running on that thread. + /// + [UITestMethod] + public void UITestMethodCreatesWinUIControlsOnTheUIThread() + { + var grid = new Grid(); + + Assert.IsNotNull(grid.DispatcherQueue); + Assert.IsTrue(grid.DispatcherQueue.HasThreadAccess, "The Grid was not created on the UI thread."); + } +} diff --git a/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/app.manifest b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/app.manifest new file mode 100644 index 0000000000..f07fcbb1f1 --- /dev/null +++ b/samples/public/mstest-runner/MSTestRunnerWinUIUnpackaged/MSTestRunnerWinUIUnpackaged/app.manifest @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + PerMonitorV2 + + + diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/AppxManifestInfo.cs b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/AppxManifestInfo.cs index 30ad3d37e1..6beba7cb18 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/AppxManifestInfo.cs +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/AppxManifestInfo.cs @@ -74,33 +74,127 @@ private AppxManifestInfo(string packageName, string publisher, IReadOnlyList - /// Searches and each of its ancestors for an - /// AppxManifest.xml and returns the path to the nearest one. A packaged app's manifest - /// lives at the package layout root, but an Application/@Executable can point into a - /// subdirectory (for example bin\host.exe), so the executable's own directory is not - /// necessarily the root. Walking up locates the manifest in that valid layout too, so the launcher - /// does not miss a packaged layout and fall through to Process.Start. Like - /// this is a cheap existence probe that never parses. + /// Searches and its ancestors for an AppxManifest.xml + /// that plausibly describes the app under . A packaged app's + /// manifest lives at the package layout root, but an Application/@Executable can point into + /// an arbitrarily deep subdirectory (for example bin\host.exe), so the executable's own + /// directory is not necessarily the root. The manifest in is + /// accepted as the app's own layout without parsing; ancestor manifests are parsed and accepted only + /// when an application executable resolves back to . Malformed or + /// unreadable ancestor manifests are ignored. /// /// The directory to start searching from (typically the executable's directory). /// - /// The full path to the nearest AppxManifest.xml at or above ; - /// otherwise . + /// The full path to the nearest AppxManifest.xml at or above + /// that matches the app directory; otherwise . /// public static string? FindManifestPath(string startDirectory) + => FindManifestPathCore(startDirectory, executablePath: null); + + /// + /// Searches and its ancestors for an AppxManifest.xml + /// that plausibly describes . The manifest in + /// is accepted as the app's own layout without parsing; an + /// ancestor manifest is parsed and accepted only when one of its applications declares exactly + /// . Matching the whole path (rather than just the directory, as + /// the enablement overload must) keeps a package that declares a different application alongside it + /// from being activated under the wrong Application User Model ID. Malformed or unreadable ancestor + /// manifests are ignored. + /// + /// The directory to start searching from (typically the executable's directory). + /// The executable that the manifest must describe when found in an ancestor directory. + /// + /// The full path to the nearest matching AppxManifest.xml at or above + /// ; otherwise . + /// + public static string? FindManifestPath(string startDirectory, string executablePath) + => FindManifestPathCore(startDirectory, executablePath); + + private static string? FindManifestPathCore(string startDirectory, string? executablePath) { - for (DirectoryInfo? directory = new(startDirectory); directory is not null; directory = directory.Parent) + // The trailing separator matters: the launcher passes AppContext.BaseDirectory, which ends with + // one, while Path.GetDirectoryName never returns one. Comparing the two unnormalized would never + // match, so a valid ancestor manifest would never be attributed during enablement. + string fullStartDirectory = NormalizeDirectory(startDirectory); + string? fullExecutablePath = executablePath is null ? null : Path.GetFullPath(executablePath); + DirectoryInfo? directory = new(startDirectory); + bool isStartDirectory = true; + while (directory is not null) { string? manifestPath = GetManifestPath(directory.FullName); - if (manifestPath is not null) + if (manifestPath is not null + && (isStartDirectory || IsAncestorManifestForApp(manifestPath, directory.FullName, fullStartDirectory, fullExecutablePath))) { return manifestPath; } + + directory = directory.Parent; + isStartDirectory = false; } return null; } + private static bool IsAncestorManifestForApp(string manifestPath, string manifestDirectory, string appDirectory, string? executablePath) + { + AppxManifestInfo manifestInfo; + try + { + manifestInfo = ReadFromManifest(manifestPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or System.Xml.XmlException) + { + return false; + } + + foreach (AppxApplicationInfo application in manifestInfo.Applications) + { + if (application.Executable is null) + { + continue; + } + + string? applicationExecutablePath = ResolvePackageRelativePath(manifestDirectory, application.Executable); + if (applicationExecutablePath is null) + { + continue; + } + + if (executablePath is not null) + { + // The launch path knows exactly which executable it was asked to start, so it must match + // that entry. Accepting any executable that merely sits in the same directory would let a + // package that declares a different application there be activated under the wrong + // Application User Model ID. + if (string.Equals(applicationExecutablePath, executablePath, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + continue; + } + + // Enablement only knows the app directory (there is no launch context yet), so attribute the + // manifest when it places an application there. + string? applicationDirectory = Path.GetDirectoryName(applicationExecutablePath); + if (applicationDirectory is not null + && string.Equals(NormalizeDirectory(applicationDirectory), appDirectory, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + } + + /// + /// Returns as a full path without a trailing directory separator, so + /// that directories obtained from different APIs compare equal. AppContext.BaseDirectory ends + /// with a separator while never does. + /// + private static string NormalizeDirectory(string directory) + => Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); + /// Reads and parses the manifest at . /// The path to an AppxManifest.xml. /// The parsed manifest info. @@ -152,6 +246,65 @@ public static AppxManifestInfo ReadFromManifest(Stream manifestStream) return new AppxManifestInfo(name, publisher, applications); } + /// + /// Resolves the application whose test host the platform asked to launch, preferring the one whose + /// declared executable resolves exactly to . A package may declare + /// several applications whose executables share a file name in different subdirectories, and the + /// file name alone cannot tell those apart; the full path can. Falls back to file-name matching + /// (see ) when no application declares this exact path, + /// which is the usual case for a manifest that omits Application/@Executable. + /// + /// The directory holding the manifest, used to resolve package-relative executables. + /// The full path of the executable the platform asked to launch. + /// + /// The matching application, or when the manifest declares no application. + /// + /// + /// The manifest declares application executables but none of them is + /// (so it describes a different application), or several + /// applications declare that same executable (so it cannot identify one of them). + /// + public AppxApplicationInfo? ResolveApplication(string manifestDirectory, string executablePath) + { + string fullExecutablePath = Path.GetFullPath(executablePath); + AppxApplicationInfo[] exactMatches = [.. Applications.Where(application => + application.Executable is not null + && string.Equals(ResolvePackageRelativePath(manifestDirectory, application.Executable), fullExecutablePath, StringComparison.OrdinalIgnoreCase))]; + + if (exactMatches.Length == 1) + { + return exactMatches[0]; + } + + if (exactMatches.Length > 1) + { + // Several applications declare this very executable, so it cannot identify one of them. That + // is an ambiguity, not a mismatch: name the candidate Application User Model IDs rather than + // claiming nothing matched. + throw new InvalidOperationException( + string.Format( + CultureInfo.CurrentCulture, + ExtensionResources.AmbiguousAppxManifestApplication, + executablePath, + string.Join(", ", exactMatches.Select(static application => application.AppUserModelId)))); + } + + // The manifest names executables, but not the one we were asked to launch: it describes a + // different application, and activating that would use the wrong Application User Model ID. Only + // fall back to file-name resolution when nothing declares an executable, which is the case that + // cannot be validated at all (a minimal manifest that omits Application/@Executable). + AppxApplicationInfo[] declaringApplications = [.. Applications.Where(static application => application.Executable is not null)]; + + return declaringApplications.Length == 0 + ? ResolveApplication(Path.GetFileName(executablePath)) + : throw new InvalidOperationException( + string.Format( + CultureInfo.CurrentCulture, + ExtensionResources.AppxManifestApplicationExecutableMismatch, + executablePath, + string.Join(", ", declaringApplications.Select(static application => application.Executable)))); + } + /// /// Resolves the application whose test host the platform asked to launch. Most packages declare a /// single application, which is returned directly. When a package declares several, the entry is @@ -204,6 +357,28 @@ private static string GetExecutableFileName(string executable) return lastSeparator < 0 ? executable : executable[(lastSeparator + 1)..]; } + private static string? ResolvePackageRelativePath(string manifestDirectory, string packageRelativePath) + { + if (packageRelativePath.Length == 0 + || packageRelativePath[0] is '\\' or '/' + || packageRelativePath.Contains(':', StringComparison.Ordinal)) + { + return null; + } + + string fullManifestDirectory = Path.GetFullPath(manifestDirectory); + string[] pathSegments = packageRelativePath.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries); + string resolvedPath = Path.GetFullPath(Path.Combine([fullManifestDirectory, .. pathSegments])); + string relativePath = Path.GetRelativePath(fullManifestDirectory, resolvedPath); + + return relativePath == ".." + || relativePath.StartsWith($"..{Path.DirectorySeparatorChar}", StringComparison.Ordinal) + || relativePath.StartsWith($"..{Path.AltDirectorySeparatorChar}", StringComparison.Ordinal) + || Path.IsPathRooted(relativePath) + ? null + : resolvedPath; + } + /// /// Computes the 13-character publisher id (the suffix of the package family name) for /// , using the public Windows algorithm: base32-encode the first 8 diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/InternalAPI/InternalAPI.Unshipped.txt index ca7986868c..c1dce813e9 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/InternalAPI/InternalAPI.Unshipped.txt @@ -12,9 +12,11 @@ Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.PackageFamilyName.get Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.PackageName.get -> string! Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.Publisher.get -> string! Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.ResolveApplication(string? executableFileName) -> Microsoft.Testing.Extensions.PackagedApp.AppxApplicationInfo? +Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.ResolveApplication(string! manifestDirectory, string! executablePath) -> Microsoft.Testing.Extensions.PackagedApp.AppxApplicationInfo? const Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.AppxManifestFileName = "AppxManifest.xml" -> string! static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.ComputePublisherId(string! publisher) -> string! static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.FindManifestPath(string! startDirectory) -> string? +static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.FindManifestPath(string! startDirectory, string! executablePath) -> string? static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.GetManifestPath(string! layoutDirectory) -> string? static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.ReadFromManifest(System.IO.Stream! manifestStream) -> Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo! static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.ReadFromManifest(string! manifestPath) -> Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo! @@ -28,3 +30,5 @@ static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake. static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.TryGetTestHostControllerPid(System.Collections.Generic.IReadOnlyList! arguments) -> string? static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.Write(string! filePath, System.Collections.Generic.IEnumerable>! entries) -> void static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackReader.TryApplyConnectBackEnvironment(System.Collections.Generic.IReadOnlyList! commandLineArguments) -> void +Microsoft.Testing.Extensions.PackagedApp.PackagedAppTestHostLauncher.PackagedAppTestHostLauncher(string! testApplicationDirectory, System.Func! getEnvironmentVariable) -> void +const Microsoft.Testing.Extensions.PackagedApp.PackagedAppTestHostLauncher.LauncherModeEnvironmentVariable = "TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER" -> string! diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Microsoft.Testing.Extensions.PackagedApp.csproj b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Microsoft.Testing.Extensions.PackagedApp.csproj index 42c738368c..ac0837c3cc 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Microsoft.Testing.Extensions.PackagedApp.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Microsoft.Testing.Extensions.PackagedApp.csproj @@ -33,7 +33,7 @@ +This package extends Microsoft Testing Platform to start Windows test hosts that cannot simply be Process.Started. In its Windows build (net*-windows) it registers a packaged, full-trust MSIX desktop app layout with the PackageManager and activates it by Application User Model ID (see https://github.com/microsoft/testfx/issues/9933); a non-packaged (loose-layout) Windows test host can optionally be deployed to an isolated directory and launched from there. The launcher enables itself only for a packaged layout, so referencing it from an unpackaged app (for example unpackaged WinUI) does not change how that app runs. True UWP/AppContainer hosts are not supported.]]> diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PACKAGE.md b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PACKAGE.md index 7c55cacfb7..a652d3d3fd 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PACKAGE.md +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PACKAGE.md @@ -3,12 +3,28 @@ > [!IMPORTANT] > This package is experimental and consumes the experimental `ITestHostLauncher` extension point of [Microsoft.Testing.Platform](https://www.nuget.org/packages/Microsoft.Testing.Platform). The API may change or be removed in a future update. -`Microsoft.Testing.Extensions.PackagedApp` is an extension for [Microsoft.Testing.Platform](https://www.nuget.org/packages/Microsoft.Testing.Platform) that deploys and launches Windows test hosts: a non-packaged (loose-layout) host (for example, unpackaged WinUI) is deployed into an isolated directory and launched from there, and — in its Windows build (`net*-windows`) — a packaged, full-trust MSIX desktop host is registered with the OS and activated by Application User Model ID (AUMID). +`Microsoft.Testing.Extensions.PackagedApp` is an extension for [Microsoft.Testing.Platform](https://www.nuget.org/packages/Microsoft.Testing.Platform) that starts Windows test hosts which cannot simply be `Process.Start`ed. In its Windows build (`net*-windows`) a packaged, full-trust MSIX desktop host is registered with the OS and activated by Application User Model ID (AUMID); a non-packaged (loose-layout) host can optionally be deployed into an isolated directory and launched from there. It is the consumer of the platform's `ITestHostLauncher` extension point for Windows test hosts. Packaged Windows apps require package identity and ship as MSIX; VSTest exposes a single `UwpTestHostRuntimeProvider` for the equivalent scenario, built on Visual-Studio-internal deployment components, whereas this extension uses only public, redistributable Windows APIs: -- **Deploy + launch loose layout**: a non-packaged (loose-layout) app — one without an `AppxManifest.xml`, such as unpackaged WinUI — is deployed to a deployment directory and the produced executable is launched from there. - **Packaged AUMID activation** (Windows build): a packaged (MSIX) layout is registered in place with the `PackageManager` and the app is activated by AUMID via `IApplicationActivationManager` — the scenario tracked by [#9933](https://github.com/microsoft/testfx/issues/9933). This connect-back transport targets **full-trust packaged (MSIX) desktop hosts**; true UWP/AppContainer hosts are not supported, and registering an unsigned build-output layout requires Developer Mode (or sideloading). The plain `net8.0`/`net9.0` build rejects a packaged layout with an actionable error pointing at the Windows TFM. +- **Deploy + launch loose layout** (opt-in): a non-packaged app — one without an `AppxManifest.xml` — is deployed to a deployment directory and the produced executable is launched from there. + +## When the launcher takes over + +Registering an *enabled* test host launcher switches the run to the test host controller (process restart) model, because a launcher only has an effect when an out-of-process test host is started. To avoid charging that cost to apps that do not need it, the launcher enables itself only when it has real work to do: + +| Situation | Enabled? | +| --- | --- | +| Not Windows | no | +| Packaged layout (an `AppxManifest.xml` that describes this app) | yes | +| Any other layout, including **unpackaged WinUI** and ordinary console test apps | no | + +A manifest in the app's own directory is taken as the app's layout. A manifest in an ancestor directory is used only when one of its `` entries declares an `Executable` resolving back to the app directory (and, at launch, to that exact executable), which supports `Application/@Executable` pointing into a package subdirectory at any depth while keeping a stray manifest in a shared build root from classifying an unrelated app as packaged. + +So referencing this package from an unpackaged app costs nothing: no extra process, and no copy of the build output. + +Set `TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER` to override that decision — `always` opts a non-packaged layout into deploy-and-launch, `never` keeps the launcher out of the way entirely, and `auto` (the default) probes the layout. Microsoft.Testing.Platform is open source. You can find `Microsoft.Testing.Extensions.PackagedApp` code in the [microsoft/testfx](https://github.com/microsoft/testfx) GitHub repository. @@ -22,7 +38,7 @@ dotnet add package Microsoft.Testing.Extensions.PackagedApp This package extends Microsoft.Testing.Platform with: -- **Deployment + launch**: stages a non-packaged (loose-layout) Windows test host payload (for example, unpackaged WinUI) into an isolated directory and launches the deployed copy; the Windows build additionally registers and activates a packaged, full-trust MSIX desktop host by AUMID (see [#9933](https://github.com/microsoft/testfx/issues/9933)). +- **Registration + activation**: registers a packaged, full-trust MSIX desktop test host and activates it by AUMID (see [#9933](https://github.com/microsoft/testfx/issues/9933)); optionally stages a non-packaged (loose-layout) Windows test host payload into an isolated directory and launches the deployed copy. - **Mechanism-agnostic monitoring**: returns an `ITestHostHandle` that exposes only the lifecycle the platform needs (surfacing the activated process id for the packaged path, and none for the deployed loose-layout path). ## Documentation diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppExtensions.cs b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppExtensions.cs index b253e9b677..17f9ce889a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppExtensions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppExtensions.cs @@ -7,21 +7,26 @@ namespace Microsoft.Testing.Extensions; /// -/// Provides extension methods for adding Windows test host deployment support (non-packaged -/// loose layouts such as unpackaged WinUI, and packaged, full-trust MSIX desktop apps) to the test -/// application builder. +/// Provides extension methods for adding Windows test host launch support (packaged, full-trust MSIX +/// desktop apps, and — when opted in — non-packaged loose layouts) to the test application builder. /// [Experimental("TPEXP", UrlFormat = "https://aka.ms/testingplatform/diagnostics#{0}")] public static class PackagedAppExtensions { /// - /// Registers a test host launcher for Windows test applications. Non-packaged (loose-layout) hosts - /// (for example, unpackaged WinUI) are deployed into an isolated directory and launched from there. - /// Packaged, full-trust MSIX desktop hosts are registered with the OS and activated by Application - /// User Model ID in the Windows build of this extension (see - /// https://github.com/microsoft/testfx/issues/9933); the plain build rejects a packaged layout with - /// an actionable error. True UWP/AppContainer hosts are not supported by this connect-back transport. + /// Registers a test host launcher for Windows test applications. Packaged, full-trust MSIX desktop + /// hosts are registered with the OS and activated by Application User Model ID in the Windows build + /// of this extension (see https://github.com/microsoft/testfx/issues/9933); the plain build rejects + /// a packaged layout with an actionable error. True UWP/AppContainer hosts are not supported by this + /// connect-back transport. /// + /// + /// The launcher only enables itself when the test application is a packaged layout, so calling this + /// from an app that is started normally — an unpackaged WinUI app, or an ordinary console test app — + /// leaves the platform on its default launch path and costs nothing. Set + /// TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER to always to opt a non-packaged (loose) layout + /// into deploy-and-launch, or to never to disable the launcher entirely. + /// /// The test application builder. public static void AddPackagedAppDeployment(this ITestApplicationBuilder builder) { diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.cs b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.cs index 5ecc235b48..6bfd764730 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.cs +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.cs @@ -11,10 +11,10 @@ namespace Microsoft.Testing.Extensions.PackagedApp; /// /// An for Windows test applications. It handles two layouts: -/// a non-packaged (loose-layout) host — for example unpackaged WinUI — which is deployed into an -/// isolated directory and launched from there; and a packaged, full-trust MSIX desktop host, which -/// cannot be started with Process.Start and is instead registered with the OS and activated by -/// Application User Model ID (AUMID). +/// a packaged, full-trust MSIX desktop host, which cannot be started with Process.Start and is +/// instead registered with the OS and activated by Application User Model ID (AUMID); and — when +/// explicitly opted in — a non-packaged (loose-layout) host, which is deployed into an isolated +/// directory and launched from there. /// /// /// @@ -39,8 +39,8 @@ namespace Microsoft.Testing.Extensions.PackagedApp; /// there, and the controller pipe is not granted the package SID. The full register-and-activate path /// ships only in the Windows build of this extension (net*-windows10.0.19041.0), where the /// PackageManager WinRT projection is available. The plain net8.0/net9.0 build -/// still deploys and launches non-packaged loose layouts, but rejects a packaged layout with an -/// actionable error so a consumer that resolves that build is told to target a Windows TFM. Registering +/// still deploys and launches an opted-in non-packaged loose layout, but rejects a packaged layout with +/// an actionable error so a consumer that resolves that build is told to target a Windows TFM. Registering /// an unsigned build-output layout additionally requires Developer Mode (or sideloading) to be enabled /// on the machine. /// @@ -49,9 +49,58 @@ namespace Microsoft.Testing.Extensions.PackagedApp; /// the PID handshake, and the lifetime-handler dispatch; this launcher only performs the /// deploy/register-and-create step and returns an the platform monitors. /// +/// +/// Registering an enabled launcher forces the platform onto the test host controller +/// (process restart) model, because a custom launcher only has an effect when an out-of-process test +/// host is started. That is the right trade for a packaged app, which genuinely cannot be started in +/// place, but it is pure overhead for an app that is simply started with Process.Start — most +/// notably an unpackaged WinUI test app, which additionally does not want its layout copied +/// to a deployment directory. The launcher therefore reports itself enabled only when it actually has +/// work to do; see . +/// /// internal sealed class PackagedAppTestHostLauncher : ITestHostLauncher { + /// + /// The environment variable that overrides how the launcher decides whether to take over the test + /// host launch. Accepted values are auto (the default when unset), always and + /// never, compared case-insensitively; any other value is treated as auto rather than + /// failing a run over a typo in an environment variable. + /// + internal const string LauncherModeEnvironmentVariable = "TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"; + + /// Always take over the launch, even for a non-packaged (loose) layout. + private const string AlwaysMode = "always"; + + /// Never take over the launch, even for a packaged layout. + private const string NeverMode = "never"; + +#if PACKAGEDAPP_WINRT + // The prefix of the environment variables the platform uses for the controller-to-host connect-back + // (pipe name, correlation id, parent PID, start time, skip-extension flag). Only these are handed off + // to the activated packaged host: they are exactly what the host needs to reach its controller, they + // contain no user-provided data (unlike broader TESTINGPLATFORM_* variables such as inline + // runsettings, which can carry secrets), and they are read after this extension's builder hook runs. + private const string ConnectBackEnvironmentVariablePrefix = "TESTINGPLATFORM_TESTHOSTCONTROLLER_"; +#endif + + private readonly string _testApplicationDirectory; + private readonly Func _getEnvironmentVariable; + + public PackagedAppTestHostLauncher() + // The controller process runs the very test application whose host is about to be launched, so + // its base directory is the layout the platform will ask this launcher to start. The launch + // context (which carries the authoritative path) does not exist yet when enablement is decided. + : this(AppContext.BaseDirectory, Environment.GetEnvironmentVariable) + { + } + + internal PackagedAppTestHostLauncher(string testApplicationDirectory, Func getEnvironmentVariable) + { + _testApplicationDirectory = testApplicationDirectory; + _getEnvironmentVariable = getEnvironmentVariable; + } + public string Uid => nameof(PackagedAppTestHostLauncher); public string Version => ExtensionVersion.DefaultSemVer; @@ -60,10 +109,47 @@ internal sealed class PackagedAppTestHostLauncher : ITestHostLauncher public string Description => ExtensionResources.PackagedAppExtensionDescription; - // Packaged Windows apps (UWP/WinUI) are a Windows-only concept. On other operating systems the - // launcher stays disabled so it is never registered, which keeps the platform on its default - // in-process/Process.Start path instead of forcing the controller (deploy-and-launch) host. - public Task IsEnabledAsync() => Task.FromResult(OperatingSystem.IsWindows()); + /// + /// Reports whether this launcher should take over starting the test host. + /// + /// + /// + /// Enabling a launcher is not free: the platform switches to the test host controller (process + /// restart) model for the whole run. The launcher therefore opts in only when the layout really + /// needs it — that is, when it is a packaged (MSIX) layout, which cannot be started with + /// Process.Start at all. A non-packaged layout (an ordinary console test app, or an + /// unpackaged WinUI app) is left to the platform's default in-process/Process.Start path, so + /// referencing this package in such an app costs nothing and never copies its layout to a + /// deployment directory. + /// + /// + /// Packaged Windows apps (UWP/WinUI) are a Windows-only concept, so the launcher stays disabled on + /// every other operating system regardless of the layout or the override. + /// + /// + /// overrides the layout probe: always opts an + /// explicitly non-packaged (loose) layout into deploy-and-launch, and never is the escape + /// hatch that keeps the launcher out of the way even for a packaged layout. + /// + /// + /// A task producing when the launcher should be registered. + public Task IsEnabledAsync() => Task.FromResult(IsEnabled()); + + private bool IsEnabled() + { + if (!OperatingSystem.IsWindows()) + { + return false; + } + + string? mode = _getEnvironmentVariable(LauncherModeEnvironmentVariable)?.Trim(); + + // 'never' wins over everything (escape hatch), 'always' opts a loose layout in, and anything + // else — including an unset or misspelled value — falls back to probing the layout. + return !string.Equals(mode, NeverMode, StringComparison.OrdinalIgnoreCase) + && (string.Equals(mode, AlwaysMode, StringComparison.OrdinalIgnoreCase) + || AppxManifestInfo.FindManifestPath(_testApplicationDirectory) is not null); + } public async Task LaunchTestHostAsync(TestHostLaunchContext context, CancellationToken cancellationToken) { @@ -73,11 +159,11 @@ public async Task LaunchTestHostAsync(TestHostLaunchContext con string sourceDirectory = Path.GetDirectoryName(context.FileName) ?? throw new InvalidOperationException($"Unable to determine the source directory of '{context.FileName}'."); - // A packaged (MSIX) app is detected by the presence of an AppxManifest.xml. The manifest lives - // at the package layout root, which may be an ancestor of the executable's directory + // A packaged (MSIX) app is detected by a matching AppxManifest.xml. The manifest lives at the + // package layout root, which may be an ancestor of the executable's directory // (Application/@Executable can point into a subdirectory), so search upward rather than only the - // executable's directory. - string? manifestPath = AppxManifestInfo.FindManifestPath(sourceDirectory); + // executable's directory while rejecting stray ancestor manifests that do not describe this host. + string? manifestPath = AppxManifestInfo.FindManifestPath(sourceDirectory, context.FileName); if (manifestPath is not null) { return await LaunchPackagedAsync(context, manifestPath, cancellationToken).ConfigureAwait(false); @@ -89,13 +175,6 @@ public async Task LaunchTestHostAsync(TestHostLaunchContext con } #if PACKAGEDAPP_WINRT - // The prefix of the environment variables the platform uses for the controller-to-host connect-back - // (pipe name, correlation id, parent PID, start time, skip-extension flag). Only these are handed off - // to the activated packaged host: they are exactly what the host needs to reach its controller, they - // contain no user-provided data (unlike broader TESTINGPLATFORM_* variables such as inline - // runsettings, which can carry secrets), and they are read after this extension's builder hook runs. - private const string ConnectBackEnvironmentVariablePrefix = "TESTINGPLATFORM_TESTHOSTCONTROLLER_"; - private static async Task LaunchPackagedAsync(TestHostLaunchContext context, string manifestPath, CancellationToken cancellationToken) { var manifestInfo = AppxManifestInfo.ReadFromManifest(manifestPath); @@ -103,7 +182,7 @@ private static async Task LaunchPackagedAsync(TestHostLaunchCon // Resolve the application matching the executable the platform asked to launch so activation // targets the AUMID of the right app (a package can declare several applications). A package // that declares no application has no AUMID to activate. - AppxApplicationInfo application = manifestInfo.ResolveApplication(Path.GetFileName(context.FileName)) + AppxApplicationInfo application = manifestInfo.ResolveApplication(Path.GetDirectoryName(manifestPath)!, context.FileName) ?? throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, @@ -185,7 +264,7 @@ private static Task LaunchPackagedAsync(TestHostLaunchContext c // cannot host the run. _ = cancellationToken; var manifestInfo = AppxManifestInfo.ReadFromManifest(manifestPath); - AppxApplicationInfo? application = manifestInfo.ResolveApplication(Path.GetFileName(context.FileName)); + AppxApplicationInfo? application = manifestInfo.ResolveApplication(Path.GetDirectoryName(manifestPath)!, context.FileName); throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/ExtensionResources.resx b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/ExtensionResources.resx index e249734e88..37896699d1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/ExtensionResources.resx +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/ExtensionResources.resx @@ -118,7 +118,8 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher @@ -126,6 +127,10 @@ The packaged app manifest declares multiple applications and none uniquely matches the executable '{0}'. Candidate Application User Model IDs: {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.cs.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.cs.xlf index 0415d71fc2..b91ed9c08c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.cs.xlf @@ -7,15 +7,20 @@ Manifest zabalené aplikace deklaruje více aplikací a žádná jednoznačně neodpovídá spustitelnému souboru '{0}'. Kandidátní ID modelu uživatele aplikace: {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. Manifest zabalené aplikace nedeklaruje platný prvek <Identity Name="..." Publisher="..." />. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - Nasadí nezabaleného hostitele testů Windows s volným rozložením souborů (například nezabalené WinUI) do izolovaného adresáře a spustí ho odtud a – v sestavení Windows – zaregistruje zabaleného desktopového hostitele testů MSIX s plnou důvěryhodností a aktivuje ho pomocí Application User Model ID. Skuteční hostitelé UWP/AppContainer nejsou podporováni. Viz https://github.com/microsoft/testfx/issues/9933. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Nasadí nezabaleného hostitele testů Windows s volným rozložením souborů (například nezabalené WinUI) do izolovaného adresáře a spustí ho odtud a – v sestavení Windows – zaregistruje zabaleného desktopového hostitele testů MSIX s plnou důvěryhodností a aktivuje ho pomocí Application User Model ID. Skuteční hostitelé UWP/AppContainer nejsou podporováni. Viz https://github.com/microsoft/testfx/issues/9933. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.de.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.de.xlf index 4a28f909c1..307cafc470 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.de.xlf @@ -7,15 +7,20 @@ Das App-Paketmanifest deklariert mehrere Anwendungen, und keine davon stimmt eindeutig mit der ausführbaren Datei „{0}“ überein. Benutzermodell-IDs der Kandidatenanwendungen: {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. Das App-Paketmanifest deklariert kein gültiges <Identity Name="..." Publisher="..." /> Element. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - Stellt einen nicht gepackten Windows-Testhost (loses Layout) (z. B. entpackte WinUI) in einem isolierten Verzeichnis bereit und startet ihn von dort aus. Im Windows-Build wird ein gepackter, voll vertrauenswürdiger MSIX-Desktoptesthost registriert und anhand der Anwendungsbenutzermodell-ID aktiviert. Echte UWP-/AppContainer-Hosts werden nicht unterstützt. Siehe https://github.com/microsoft/testfx/issues/9933. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Stellt einen nicht gepackten Windows-Testhost (loses Layout) (z. B. entpackte WinUI) in einem isolierten Verzeichnis bereit und startet ihn von dort aus. Im Windows-Build wird ein gepackter, voll vertrauenswürdiger MSIX-Desktoptesthost registriert und anhand der Anwendungsbenutzermodell-ID aktiviert. Echte UWP-/AppContainer-Hosts werden nicht unterstützt. Siehe https://github.com/microsoft/testfx/issues/9933. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.es.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.es.xlf index 68335fb507..1032c30bdb 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.es.xlf @@ -7,15 +7,20 @@ El manifiesto de aplicación empaquetada declara varias aplicaciones y ninguna coincide de forma única con el ejecutable "{0}". Identificadores de modelo de usuario de la aplicación candidata: {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - Implementa un host de prueba de Windows no empaquetado (diseño flexible) (por ejemplo, WinUI sin empaquetar) en un directorio aislado y lo inicia desde allí y, en la compilación de Windows, registra un host de prueba de escritorio MSIX empaquetado y de plena confianza y lo activa mediante el identificador del modelo de usuario de aplicación. No se admiten los hosts verdaderos de UWP/AppContainer. Consulte https://github.com/microsoft/testfx/issues/9933. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Implementa un host de prueba de Windows no empaquetado (diseño flexible) (por ejemplo, WinUI sin empaquetar) en un directorio aislado y lo inicia desde allí y, en la compilación de Windows, registra un host de prueba de escritorio MSIX empaquetado y de plena confianza y lo activa mediante el identificador del modelo de usuario de aplicación. No se admiten los hosts verdaderos de UWP/AppContainer. Consulte https://github.com/microsoft/testfx/issues/9933. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.fr.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.fr.xlf index 6f4445ea5e..c50b3d769d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.fr.xlf @@ -7,15 +7,20 @@ Le manifeste de l’application packagée déclare plusieurs applications et aucune ne correspond de manière unique à l’exécutable « {0} ». ID de modèle d’utilisateur d’application candidat : {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.it.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.it.xlf index 6e4c029191..e2ad968f67 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.it.xlf @@ -7,15 +7,20 @@ Il manifesto dell'app in pacchetto dichiara più applicazioni e nessuna corrisponde in modo univoco all'eseguibile '{0}'. ID modello utente applicazione candidata: {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. Il manifesto dell'app in pacchetto non dichiara un elemento <Identity Name="..." Publisher="..." /> valido. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - Distribuisce un host di test di Windows non in pacchetto, o a layout libero (ad esempio, WinUI non in pacchetto), in una directory isolata, da cui lo avvia, e nella build di Windows registra un host di test desktop MSIX in pacchetto con attendibilità totale e lo attiva in base all'ID modello utente applicazione. Gli host UWP/AppContainer effettivi non sono supportati. Vedere https://github.com/microsoft/testfx/issues/9933. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Distribuisce un host di test di Windows non in pacchetto, o a layout libero (ad esempio, WinUI non in pacchetto), in una directory isolata, da cui lo avvia, e nella build di Windows registra un host di test desktop MSIX in pacchetto con attendibilità totale e lo attiva in base all'ID modello utente applicazione. Gli host UWP/AppContainer effettivi non sono supportati. Vedere https://github.com/microsoft/testfx/issues/9933. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ja.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ja.xlf index 2f54102736..a32ad0c852 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ja.xlf @@ -7,15 +7,20 @@ パッケージ化されたアプリ マニフェストで複数のアプリケーションが宣言されており、実行可能ファイル '{0}' に一意に一致するものがありません。候補のアプリケーション ユーザー モデル ID: {1}。 + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. パッケージ アプリ マニフェストに有効な <Identity Name="..." Publisher="..." />要素が宣言されていません。 - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - パッケージ化されていない (loose-layout) Windows テスト ホスト (例: パッケージ化されていない WinUI) を分離ディレクトリに配置してそこから起動します。また、Windows ビルドでは、パッケージ化されたフル トラストの MSIX デスクトップ テスト ホストを登録して、アプリケーション ユーザー モデル ID によってアクティブ化します。実際の UWP/AppContainer ホストはサポートされていません。https://github.com/microsoft/testfx/issues/9933 を参照してください。 - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + パッケージ化されていない (loose-layout) Windows テスト ホスト (例: パッケージ化されていない WinUI) を分離ディレクトリに配置してそこから起動します。また、Windows ビルドでは、パッケージ化されたフル トラストの MSIX デスクトップ テスト ホストを登録して、アプリケーション ユーザー モデル ID によってアクティブ化します。実際の UWP/AppContainer ホストはサポートされていません。https://github.com/microsoft/testfx/issues/9933 を参照してください。 + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ko.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ko.xlf index 8b8a99a50a..888436e9f0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ko.xlf @@ -7,15 +7,20 @@ 패키지된 앱 매니페스트는 여러 애플리케이션을 선언하지만 실행 파일 '{0}'에 고유하게 일치하는 애플리케이션이 없습니다. 후보 애플리케이션 사용자 모델 ID: {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. 패키지된 앱 매니페스트에 유효한 <Identity Name="..." Publisher="..." /> 요소가 선언되어 있지 않습니다. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - 패키지되지 않은(느슨한 레이아웃) Windows 테스트 호스트(예: 패키지되지 않은 WinUI)를 격리된 디렉터리에 배포한 다음, 그 위치에서 시작합니다. 그리고 Windows 빌드에서는 패키지된 완전 신뢰 MSIX 데스크톱 테스트 호스트를 등록하고 애플리케이션 사용자 모델 ID로 활성화합니다. 신뢰 UWP/AppContainer 호스트는 지원되지 않습니다. https://github.com/microsoft/testfx/issues/9933을 참조하세요. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + 패키지되지 않은(느슨한 레이아웃) Windows 테스트 호스트(예: 패키지되지 않은 WinUI)를 격리된 디렉터리에 배포한 다음, 그 위치에서 시작합니다. 그리고 Windows 빌드에서는 패키지된 완전 신뢰 MSIX 데스크톱 테스트 호스트를 등록하고 애플리케이션 사용자 모델 ID로 활성화합니다. 신뢰 UWP/AppContainer 호스트는 지원되지 않습니다. https://github.com/microsoft/testfx/issues/9933을 참조하세요. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.pl.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.pl.xlf index 6da6127b11..5fc253fd76 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.pl.xlf @@ -7,15 +7,20 @@ Manifest spakowanej aplikacji deklaruje wiele aplikacji i żaden z nich nie jest jednoznacznie zgodny z plikiem wykonywalnym „{0}”. Identyfikatory modelu użytkownika aplikacji (Application User Model ID): {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. Manifest spakowanej aplikacji nie deklaruje prawidłowego <Identity Name="..." Publisher="..." /> element. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.pt-BR.xlf index 3a7ba36591..6920f0953f 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.pt-BR.xlf @@ -7,15 +7,20 @@ O manifesto do aplicativo empacotado declara vários aplicativos e nenhum corresponde exclusivamente ao executável ''{0}''. IDs de Modelo de Usuário do Aplicativo Candidato: {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. O manifesto do aplicativo empacotado não declara um elemento <Identity Name="..." Publisher="..." /> válido. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - Implanta um host de teste do Windows não empacotado (layout solto), como um aplicativo WinUI não empacotado, em um diretório isolado e o inicia a partir desse diretório. Na compilação do Windows, também registra um host de teste de área de trabalho MSIX empacotado, com confiança total, e o ativa por meio da ID do Modelo de Usuário do Aplicativo. Não há suporte para hosts UWP/AppContainer verdadeiros. Veja https://github.com/microsoft/testfx/issues/9933. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Implanta um host de teste do Windows não empacotado (layout solto), como um aplicativo WinUI não empacotado, em um diretório isolado e o inicia a partir desse diretório. Na compilação do Windows, também registra um host de teste de área de trabalho MSIX empacotado, com confiança total, e o ativa por meio da ID do Modelo de Usuário do Aplicativo. Não há suporte para hosts UWP/AppContainer verdadeiros. Veja https://github.com/microsoft/testfx/issues/9933. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ru.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ru.xlf index 710c6154b2..bd5474fb5e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.ru.xlf @@ -7,15 +7,20 @@ Манифест упакованного приложения объявляет несколько приложений, и ни одно из них не соответствует однозначно исполняемому файлу "{0}". Идентификаторы пользовательской модели приложений-кандидатов: {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. Манифест упакованного приложения не объявляет допустимый элемент <Identity Name="..." Publisher="..." />. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - Развертывает неупакованный (со свободной компоновкой) тестовый узел Windows (например, неупакованный WinUI) в изолированный каталог и запускает его оттуда, а в сборке Windows регистрирует упакованный тестовый узел классической версии MSIX с полным доверием и активирует его по идентификатору пользовательской модели приложения. Настоящие узлы UWP/AppContainer не поддерживаются. Сведения: https://github.com/microsoft/testfx/issues/9933. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Развертывает неупакованный (со свободной компоновкой) тестовый узел Windows (например, неупакованный WinUI) в изолированный каталог и запускает его оттуда, а в сборке Windows регистрирует упакованный тестовый узел классической версии MSIX с полным доверием и активирует его по идентификатору пользовательской модели приложения. Настоящие узлы UWP/AppContainer не поддерживаются. Сведения: https://github.com/microsoft/testfx/issues/9933. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.tr.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.tr.xlf index c873524c98..ca2b8f7950 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.tr.xlf @@ -7,15 +7,20 @@ Paketlenmiş uygulama bildirimi birden çok uygulama bildiriyor ve bunların hiçbiri benzersiz olarak '{0}' yürütülebilir dosyasıyla eşleşmiyor. Aday Uygulama Kullanıcı Modeli Kimlikleri: {1}. + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. Paketlenmiş uygulama bildirimi geçerli bir <Identity Name="..." Publisher="..." /> öğesi belirtmiyor. - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - Paketlenmemiş (gevşek düzenli) bir Windows test konağını (örneğin, paketlenmemiş WinUI) yalıtılmış bir dizine dağıtır ve oradan başlatır ve — Windows derlemesinde — paketlenmiş, tam güvenilir bir MSIX masaüstü test konağını kaydeder ve onu Uygulama Kullanıcı Modeli Kimliği ile etkinleştirir. Gerçek UWP/AppContainer konakları desteklenmez. https://github.com/microsoft/testfx/issues/9933 bağlantısına bakın. - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + Paketlenmemiş (gevşek düzenli) bir Windows test konağını (örneğin, paketlenmemiş WinUI) yalıtılmış bir dizine dağıtır ve oradan başlatır ve — Windows derlemesinde — paketlenmiş, tam güvenilir bir MSIX masaüstü test konağını kaydeder ve onu Uygulama Kullanıcı Modeli Kimliği ile etkinleştirir. Gerçek UWP/AppContainer konakları desteklenmez. https://github.com/microsoft/testfx/issues/9933 bağlantısına bakın. + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.zh-Hans.xlf index dbb58cd9cf..bb2ae26631 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.zh-Hans.xlf @@ -7,15 +7,20 @@ 打包应用部件清单声明了多个应用程序,而没有一个与可执行文件 '{0}' 唯一匹配。候选应用程序用户模型 ID: {1}。 + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. 打包应用部件清单未声明有效的 <Identity Name="..." Publisher="..." /> 元素。 - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - 将非打包(松散布局)的 Windows 测试主机(例如,未打包的 WinUI)部署到隔离目录,并从该目录启动它;在 Windows 构建中,还会注册一个打包、完全信任的 MSIX 桌面测试主机,并通过应用程序用户模型 ID 激活它。不支持真正的 UWP/AppContainer 主机。请参阅 https://github.com/microsoft/testfx/issues/9933。 - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + 将非打包(松散布局)的 Windows 测试主机(例如,未打包的 WinUI)部署到隔离目录,并从该目录启动它;在 Windows 构建中,还会注册一个打包、完全信任的 MSIX 桌面测试主机,并通过应用程序用户模型 ID 激活它。不支持真正的 UWP/AppContainer 主机。请参阅 https://github.com/microsoft/testfx/issues/9933。 + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.zh-Hant.xlf index 0b18735871..4271492d85 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/Resources/xlf/ExtensionResources.zh-Hant.xlf @@ -7,15 +7,20 @@ 封裝的應用程式資訊清單會宣告多個應用程式,且沒有一個能唯一地符合可執行檔 '{0}'。候選應用程式使用者模型識別碼: {1}。 + + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + The packaged app manifest declares no application for the executable '{0}', so it describes a different application and activating it would target the wrong Application User Model ID. Declared application executables: {1}. + Do not localize the technology name {Locked="Application User Model ID"}. {0} is an executable path. {1} is a comma-separated list of executable paths. + The packaged app manifest does not declare a valid <Identity Name="..." Publisher="..." /> element. 封裝的應用程式清單未宣告有效的 <Identity Name="..." Publisher="..." /> 元素。 - Deploys a non-packaged (loose-layout) Windows test host (for example, unpackaged WinUI) to an isolated directory and launches it from there, and — in the Windows build — registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. - 將未封裝 (鬆散配置) 的 Windows 測試主機 (例如未封裝的 WinUI) 部署到隔離目錄,並從該處啟動它,然後在 Windows 組建中註冊封裝、完全信任的 MSIX 桌面測試主機,並透過應用程式使用者模型識別碼來啟用它。不支援真正的 UWP/AppContainer 主機。請參閱 https://github.com/microsoft/testfx/issues/9933。 - + Registers a packaged, full-trust MSIX desktop test host and activates it by Application User Model ID (Windows build), and — when opted in through TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER=always — deploys a non-packaged (loose-layout) Windows test host to an isolated directory and launches it from there. Enabled only for a packaged layout by default, so an unpackaged app is left on the default launch path. True UWP/AppContainer hosts are not supported. See https://github.com/microsoft/testfx/issues/9933. + 將未封裝 (鬆散配置) 的 Windows 測試主機 (例如未封裝的 WinUI) 部署到隔離目錄,並從該處啟動它,然後在 Windows 組建中註冊封裝、完全信任的 MSIX 桌面測試主機,並透過應用程式使用者模型識別碼來啟用它。不支援真正的 UWP/AppContainer 主機。請參閱 https://github.com/microsoft/testfx/issues/9933。 + Do not localize the environment variable name or its value {Locked="TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"}{Locked="always"}, nor the technology names {Locked="MSIX"}{Locked="Application User Model ID"}{Locked="Windows"}{Locked="UWP"}{Locked="AppContainer"}. Packaged app test host launcher diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/TestingPlatformBuilderHook.cs b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/TestingPlatformBuilderHook.cs index e1aaab5eb4..c94d5250e4 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/TestingPlatformBuilderHook.cs +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/TestingPlatformBuilderHook.cs @@ -6,14 +6,16 @@ namespace Microsoft.Testing.Extensions.PackagedApp; /// -/// This class is used by Microsoft.Testing.Platform.MSBuild to hook into the Testing Platform Builder to add Windows test host deployment support (non-packaged loose layouts such as unpackaged WinUI, and packaged, full-trust MSIX desktop apps launched by AUMID activation). +/// This class is used by Microsoft.Testing.Platform.MSBuild to hook into the Testing Platform Builder to add Windows test host launch support (packaged, full-trust MSIX desktop apps activated by AUMID, and — when opted in — non-packaged loose layouts deployed to an isolated directory). /// public static class TestingPlatformBuilderHook { /// - /// Adds Windows test host deployment support to the Testing Platform Builder: it deploys and - /// launches non-packaged (loose-layout) hosts, and — in the Windows build — registers and activates - /// packaged, full-trust MSIX desktop hosts by Application User Model ID (see https://github.com/microsoft/testfx/issues/9933). + /// Adds Windows test host launch support to the Testing Platform Builder: it registers and activates + /// packaged, full-trust MSIX desktop hosts by Application User Model ID in the Windows build (see + /// https://github.com/microsoft/testfx/issues/9933), and deploys and launches an opted-in + /// non-packaged (loose-layout) host. Because this hook runs for anyone who merely references the + /// package, the launcher stays disabled unless the test application is a packaged layout. /// /// The test application builder. /// The command line arguments. diff --git a/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs b/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs index 90ee952430..9af9f29f3d 100644 --- a/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs +++ b/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs @@ -12,8 +12,33 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer; /// public class UITestMethodAttribute : TestMethodAttribute { - private static bool s_isApplicationInitialized; - private static DispatcherQueue? s_applicationDispatcherQueue; + // How often the application-startup wait re-checks that the UI thread is still alive. Short enough + // that a failed startup is reported promptly, long enough not to spin. + private static readonly TimeSpan ThreadLivenessPollInterval = TimeSpan.FromMilliseconds(100); + + // Upper bound on how long to wait for the application to come up. Application.Start can block without + // ever invoking its callback (for example a modal dialog during XAML initialization), which neither an + // exception nor the thread dying would surface, so the wait is capped to keep a startup problem a test + // failure rather than a hung run. Generous because it covers first-run Windows App SDK resolution. + private static readonly TimeSpan ApplicationStartupTimeout = TimeSpan.FromMinutes(2); + + // Serializes the check-and-start below. Application.Start can only be called once per process, so + // without this two [UITestMethod]s running in parallel could both observe "not started yet" and each + // start an application. + private static readonly object InitializationLock = new(); + + // Written on the UI thread and read on the test thread, so all three are volatile: this runs on ARM64 + // as well as x64, where non-volatile reads are not guaranteed to observe the writes. + private static volatile bool s_isApplicationInitialized; + private static volatile DispatcherQueue? s_applicationDispatcherQueue; + + // Why bringing the application up failed, so that every later [UITestMethod] reports the same root + // cause instead of the generic "DispatcherQueue should not be null" message. The cause is stored + // rather than an ExceptionDispatchInfo because replaying one dispatch token from several test threads + // would mutate the stack trace of a single shared exception; each caller instead gets a fresh + // exception wrapping this one. Application.Start cannot meaningfully be retried in a process, so + // re-reporting is better than re-attempting. + private static volatile Exception? s_applicationInitializationFailure; /// /// Initializes a new instance of the class. @@ -93,33 +118,58 @@ public override async Task ExecuteAsync(ITestMethod testMethod) return s_applicationDispatcherQueue; } - if (s_isApplicationInitialized) + // Application.Start can only be called once per process, so the whole check-and-start has to be + // serialized: otherwise two [UITestMethod]s running in parallel can both see "not started yet". + lock (InitializationLock) { - return null; - } + if (s_applicationDispatcherQueue != null) + { + return s_applicationDispatcherQueue; + } - Type? applicationType = GetApplicationType(assembly); - if (applicationType == null) - { - return null; - } + // A previous attempt already failed to bring the application up, and Application.Start cannot + // be retried in the same process. Report that cause instead of letting the caller fall through + // to the generic "DispatcherQueue should not be null" message. A new exception is built per + // caller so concurrent tests never share (and mutate) one exception instance. + if (s_applicationInitializationFailure is { } cause) + { + // The cause's message is formatted into the text rather than relying on the inner + // exception alone: MSTest reports a failure using the exception's Message, so an + // InnerException would never be shown to the user. It is still attached for debuggers + // and for anyone inspecting the exception programmatically. + throw new InvalidOperationException( + string.Format(CultureInfo.CurrentCulture, FrameworkExtensionsMessages.WinUIApplicationInitializationAlreadyFailed, cause.Message), + cause); + } - // We need to initialize the SDK before calling Application.Start - try - { - // We need to execute all module initializers before doing any WinRT calls. - // This will cause the [ModuleInitializer]s to execute, if they haven't yet. - Type? id = applicationType.Assembly.GetType("Microsoft.WindowsAppSDK.Runtime.Identity"); - if (id != null) + if (s_isApplicationInitialized) + { + return null; + } + + Type? applicationType = GetApplicationType(assembly); + if (applicationType == null) + { + return null; + } + + // We need to initialize the SDK before calling Application.Start + try + { + // We need to execute all module initializers before doing any WinRT calls. + // This will cause the [ModuleInitializer]s to execute, if they haven't yet. + Type? id = applicationType.Assembly.GetType("Microsoft.WindowsAppSDK.Runtime.Identity"); + if (id != null) + { + _ = Activator.CreateInstance(id); + } + } + catch { - _ = Activator.CreateInstance(id); } - } - catch - { - } - return InitializeApplication(applicationType); + return InitializeApplication(applicationType); + } } private static DispatcherQueue? GetDispatcherQueue(Assembly assembly) @@ -162,15 +212,42 @@ void OnApplicationInitialized(ApplicationInitializationCallbackParams e) _ = Activator.CreateInstance(applicationType) as Application; s_applicationDispatcherQueue = dispatcher; - tsc.SetResult(dispatcher); + tsc.TrySetResult(dispatcher); } - catch + catch (Exception ex) { + // Never leave the wait below blocked. This used to swallow the exception, which left the + // TaskCompletionSource incomplete and hung the whole run on tsc.Task with no diagnostic at + // all. The common causes are a throwing Application constructor and — in an unpackaged app + // — the Windows App SDK runtime not being resolvable, which surfaces here as a COMException + // (REGDB_E_CLASSNOTREG). Propagate it so the test fails with the real cause. See issue #2784. + // + // Unwrap the reflection wrapper: MSTest reports a failure using the exception's Message, so + // leaving a TargetInvocationException in place would tell the user only "Exception has been + // thrown by the target of an invocation" and bury the real cause in the stack trace. + tsc.TrySetException(ex is TargetInvocationException { InnerException: { } inner } ? inner : ex); } } - var treadStart = new ThreadStart(() => Application.Start(OnApplicationInitialized)); - var uiThread = new Thread(treadStart) + var threadStart = new ThreadStart(() => + { + try + { + Application.Start(OnApplicationInitialized); + + // Application.Start normally pumps a message loop until the app exits, so reaching this + // point without the callback having completed the wait means the application never came up. + tsc.TrySetException(new InvalidOperationException(FrameworkExtensionsMessages.WinUIApplicationFailedToStart)); + } + catch (Exception ex) + { + // Application.Start can throw before it ever invokes the callback above (typically when the + // Windows App SDK runtime cannot be resolved). Without this the exception would be unhandled + // on this thread and the wait below would never be released. + tsc.TrySetException(ex); + } + }); + var uiThread = new Thread(threadStart) { Name = "UI Thread for Tests", @@ -181,9 +258,72 @@ void OnApplicationInitialized(ApplicationInitializationCallbackParams e) IsBackground = true, }; uiThread.Start(); - tsc.Task.Wait(); - return tsc.Task.Result; + // Wait for the application to come up, but never unconditionally. Two things can leave the wait + // incomplete and used to hang the whole run with no diagnostic at all (see issue #2784): + // - XAML tears this thread down for some native startup failures without surfacing a managed + // exception, so neither catch above runs. A dead thread therefore counts as a failure. + // - Startup can stall while the thread stays alive: Application.Start may block without ever + // invoking its callback (for example a modal dialog during XAML initialization), or the + // callback may block constructing the application. The overall timeout covers both. + // On success the callback completes the wait while the thread keeps pumping, so this costs at + // most one poll interval. + WaitForApplicationStartup(tsc, uiThread.Join, ApplicationStartupTimeout, ThreadLivenessPollInterval); + + try + { + // GetAwaiter().GetResult() rather than Wait()/Result so a failure surfaces as the original + // exception instead of an AggregateException wrapping it. + return tsc.Task.GetAwaiter().GetResult(); + } + catch (Exception ex) + { + // Remember why startup failed so later [UITestMethod]s report the same cause instead of a + // generic message. A bare 'throw' preserves the original stack. + s_applicationInitializationFailure = ex; + throw; + } + } + + /// + /// Waits for application startup to complete, and fails the wait rather than blocking forever when + /// the UI thread dies or startup stalls. + /// + /// + /// Separated from the thread it observes so that both failure paths can be covered by tests without a + /// real XAML application: they are the guards that keep a startup problem a test failure rather than + /// the hung run described in issue #2784, and neither is reproducible on demand from a test host. + /// + /// The result the startup completion carries. + /// Completed by the initialization callback once the application is up. + /// Waits the given interval for the UI thread to exit, returning whether it did. + /// How long startup may take before it is reported as stalled. + /// How long each liveness check waits for the UI thread to exit. + internal static void WaitForApplicationStartup( + TaskCompletionSource startupCompletion, + Func waitForUiThreadExit, + TimeSpan timeout, + TimeSpan pollInterval) + { + var startupTimer = Stopwatch.StartNew(); + while (!startupCompletion.Task.IsCompleted) + { + if (waitForUiThreadExit(pollInterval)) + { + startupCompletion.TrySetException(new InvalidOperationException(FrameworkExtensionsMessages.WinUIApplicationFailedToStart)); + return; + } + + if (startupTimer.Elapsed > timeout) + { + // The thread is still alive, so the application did not exit — it never finished coming + // up. Say that rather than reusing the "exited without initializing" message, which would + // point at the wrong cause. + startupCompletion.TrySetException(new TimeoutException( + string.Format(CultureInfo.CurrentCulture, FrameworkExtensionsMessages.WinUIApplicationStartupTimedOut, timeout))); + return; + } + } } } #endif diff --git a/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.resx b/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.resx index ab5b382a34..6381bdf397 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.resx +++ b/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.resx @@ -125,4 +125,16 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf index 9be8f5ed78..7eed9742cd 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue nesmí mít hodnotu null. Pokud chcete použít UITestMethodAttribute v desktopové aplikaci WinUI, nezapomeňte během inicializace testu nastavit statický UITestMethodAttribute.DispatcherQueue. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf index 8f767c5ac1..8a9bc3c97a 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue darf nicht null sein. Um UITestMethodAttribute in einer WinUI-Desktop-App zu verwenden, denken Sie daran, die statische UITestMethodAttribute.DispatcherQueue während der Testinitialisierung festzulegen. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf index 059f1ad97c..2881a0592e 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue no debe ser null. Para usar UITestMethodAttribute en una aplicación de escritorio WinUI, recuerde establecer el UITestMethodAttribute.DispatcherQueue estático durante la inicialización de la prueba. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf index 2621cebd23..782f4a531b 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue ne doit pas avoir la valeur null. Pour utiliser UITestMethodAttribute dans une application de bureau WinUI, n’oubliez pas de définir l’UITestMethodAttribute.DispatcherQueue statique pendant l’initialisation du test. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf index f1b21c8e22..082bab8152 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue non deve essere null. Per usare UITestMethodAttribute all'interno di un'app desktop WinUI, ricordarsi di impostare il parametro statico UITestMethodAttribute.DispatcherQueue durante l'inizializzazione del test. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf index 5c7aa7394d..348bc43b1f 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue を null にすることはできません。WinUI デスクトップ アプリ内で UITestMethodAttribute を使用するには、テストの初期化中に静的な UITestMethodAttribute.DispatcherQueue を設定してください。 Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf index bc909567ce..7d2dd55e39 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue는 null이 아니어야 합니다. WinUI 데스크톱 앱 내에서 UITestMethodAttribute를 사용하려면 테스트 초기화 중에 정적 UITestMethodAttribute.DispatcherQueue를 설정해야 합니다. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf index 317e4a6251..22620fad9d 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf @@ -12,6 +12,21 @@ Element UITestMethodAttribute.DispatcherQueue nie powinien mieć wartości null. Aby użyć atrybutu UITestMethodAttribute w aplikacji klasycznej WinUI, pamiętaj o ustawieniu statycznego atrybutu UITestMethodAttribute.DispatcherQueue podczas inicjowania testu. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf index dfc8212ecd..44effc1503 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue não deve ser null. Para usar o UITestMethodAttribute em um Aplicativo de Área de Trabalho do WinUI, lembre-se de definir a variável estática UITestMethodAttribute.DispatcherQueue durante a inicialização do teste. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf index 14dff4214b..dfc6cfb749 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf @@ -12,6 +12,21 @@ Параметр UITestMethodAttribute.DispatcherQueue не должен иметь значение null. Чтобы использовать параметр UITestMethodAttribute в классических приложениях WinUI, не забудьте задать статический параметр UITestMethodAttribute.DispatcherQueue во время инициализации теста. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf index cb8a73fe1c..03599258aa 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue null olmamalıdır. UITestMethodAttribute'ı bir WinUI Masaüstü Uygulamasında kullanmak için, test başlatma sırasında statik UITestMethodAttribute.DispatcherQueue'yu ayarlamayı unutmayın. Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf index 3ad5237ce3..44280e97e3 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue 不应为 null。若要在 WinUI 桌面应用中使用 UITestMethodAttribute,请在测试初始化期间设置静态 UITestMethodAttribute.DispatcherQueue。 Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf index 0a3be6874d..b2f36cd50a 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf @@ -12,6 +12,21 @@ UITestMethodAttribute.DispatcherQueue 不應為 null。若要在 WinUI 傳統型應用程式內使用 UITestMethodAttribute,請記得在測試初始化期間設定 static UITestMethodAttribute.DispatcherQueue。 Do not localize API names {Locked="UITestMethodAttribute.DispatcherQueue"}{Locked="UITestMethodAttribute"}, the product name {Locked="WinUI"}, or the C# keyword {Locked="null"}. + + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + The WinUI application under test exited without initializing. When running unpackaged, this usually means the Windows App SDK runtime could not be resolved for the process. + Do not localize the product names {Locked="WinUI"}{Locked="Windows App SDK"}. + + + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + The WinUI application under test failed to initialize earlier in this run, and Application.Start cannot be retried in the same process. The original failure was: {0} + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is the message of the original failure. + + + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + The WinUI application under test did not finish initializing within {0}. Application.Start was called but its initialization did not complete. + Do not localize the product name {Locked="WinUI"} or the API name {Locked="Application.Start"}. {0} is a timeout duration. + \ No newline at end of file diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/UnpackagedWinUITests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/UnpackagedWinUITests.cs new file mode 100644 index 0000000000..28909be74c --- /dev/null +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/UnpackagedWinUITests.cs @@ -0,0 +1,397 @@ +// 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.Platform.Acceptance.IntegrationTests; +using Microsoft.Testing.Platform.Acceptance.IntegrationTests.Helpers; +using Microsoft.Testing.Platform.Helpers; + +namespace MSTest.Acceptance.IntegrationTests; + +/// +/// End-to-end coverage for testing an unpackaged WinUI 3 app +/// (<WindowsPackageType>None</WindowsPackageType>) on Microsoft.Testing.Platform — the +/// scenario tracked by . Unlike +/// , which only checks that the WinUI-flavored MSTest assemblies load, these +/// assets reference the real Microsoft.WindowsAppSDK, so the produced apps are actual WinUI apps +/// with no package identity. +/// +/// +/// +/// The two hosting shapes are covered separately because they take different code paths: +/// +/// +/// +/// +/// Self-hosted — the WinUI app is itself the test host and has already called +/// Application.Start, so it publishes its dispatcher through +/// UITestMethodAttribute.DispatcherQueue. WinUITestTarget must not be used here: it +/// would make the attribute call Application.Start a second time in the same process. +/// +/// +/// +/// +/// WinUITestTarget — the test host is an ordinary executable and the attribute starts the +/// application itself. This is the path that owns application startup, and hence the one that can +/// fail while bringing it up. +/// +/// +/// +/// +/// Both assets are built with the dotnet muxer like every other acceptance asset, so these tests run on +/// any Windows leg. (Older Windows App SDK releases needed the MrtCore PRI MSBuild tasks that ship with +/// Visual Studio; the version pinned below builds fine without them.) +/// +/// +/// Every run is bounded by an explicit timeout, because the failure mode +/// guards against is +/// a hang, which would otherwise stall the job instead of failing it. +/// +/// +[TestClass] +[OSCondition(OperatingSystems.Windows, IgnoreMessage = "WinUI is Windows-only.")] +public sealed class UnpackagedWinUITests : AcceptanceTestBase +{ + private const string TargetFramework = "net8.0-windows10.0.19041.0"; + + // Self-contained deployment of the Windows App SDK needs an explicit RID; it also puts the build + // output under a RID-specific folder, which BuildAssetAsync accounts for. + private const string RuntimeIdentifier = "win-x64"; + + // The Windows App SDK version the assets build against, kept in one place so both assets stay in sync. + // Must stay at or above the release that builds without the Visual Studio MrtCore PRI tasks. + private const string WindowsAppSdkVersion = "1.8.251106002"; + private const string WindowsSdkBuildToolsVersion = "10.0.26100.7175"; + + private const string ThrowingConstructorMessage = "Application constructor failed on purpose"; + + // Bounds every child process so a regression of the deadlock fix in UITestMethodAttribute surfaces as + // a test failure instead of stalling the whole job. + private static readonly TimeSpan ExecutionTimeout = TimeSpan.FromMinutes(5); + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task SelfHostedUnpackagedWinUI_RunsTests_AndProcessExits() + { + const string AssetName = "SelfHostedWinUITests"; + + using TestAsset testAsset = await GenerateAssetAsync(AssetName, SelfHostedSourceCode); + string testHostDirectory = await BuildAssetAsync(AssetName, testAsset); + TestHostResult testHostResult = await ExecuteBoundedAsync(TestHost.LocateFrom(testHostDirectory, AssetName)); + + // Passing all three proves in a single run that: + // - the app has no package identity yet still hosts the platform (unpackaged works at all), + // - a plain [TestMethod] can call a Windows App SDK WinRT API, and + // - a [UITestMethod] reaches the UI thread through UITestMethodAttribute.DispatcherQueue. + testHostResult.AssertExitCodeIs(ExitCode.Success); + testHostResult.AssertOutputContainsSummary(failed: 0, passed: 3, skipped: 0); + + // Getting a result at all means the process exited rather than being killed by the timeout: + // Application.Start pumps a message loop that never returns, so the UI thread has to stay a + // background thread for the run to terminate (see https://github.com/microsoft/testfx/pull/9904). + } + + [TestMethod] + public async Task WinUITestTarget_WhenApplicationConstructorThrows_FailsInsteadOfHanging() + { + const string AssetName = "WinUITestTargetFailureTests"; + + // Regression test for the deadlock in UITestMethodAttribute.InitializeApplication: a failure while + // bringing the application up used to be swallowed, leaving the TaskCompletionSource incomplete so + // the blocking wait never returned and the run hung with no diagnostic at all. The same swallow hid + // a failed Windows App SDK bootstrap in an unpackaged app; a throwing constructor is the + // deterministic way to reach that catch block. + using TestAsset testAsset = await GenerateAssetAsync(AssetName, WinUITestTargetSourceCode); + string testHostDirectory = await BuildAssetAsync(AssetName, testAsset); + TestHostResult testHostResult = await ExecuteBoundedAsync(TestHost.LocateFrom(testHostDirectory, AssetName)); + + // The run has to finish and report a failed test rather than block forever, and the original + // exception message has to reach the output so the cause is diagnosable. Asserting the message + // (not just the exit code) is what proves the reflection wrapper is unwrapped: without that the + // user would only see "Exception has been thrown by the target of an invocation". + testHostResult.AssertExitCodeIs(ExitCode.AtLeastOneTestFailed); + testHostResult.AssertOutputContains(ThrowingConstructorMessage); + } + + /// + /// Runs the test host under . The failure these tests guard against is + /// a hang, and a bare cancellation surfaces only as TaskCanceledException from + /// WaitForExitAsync with no indication of what the app was doing, so the timeout is turned + /// into a message that names the likely cause instead. + /// + private async Task ExecuteBoundedAsync(TestHost testHost) + { + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + cancellation.CancelAfter(ExecutionTimeout); + try + { + return await testHost.ExecuteAsync(cancellationToken: cancellation.Token); + } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested && !TestContext.CancellationToken.IsCancellationRequested) + { + Assert.Fail( + $"The WinUI test host did not exit within {ExecutionTimeout}. It produced no result, which usually means it blocked during " + + "startup rather than while running tests - historically because an unpackaged app could not resolve the Windows App SDK " + + "runtime and its bootstrapper waited on a dialog. The asset is built Windows App SDK self-contained precisely to avoid " + + "that; check whether that setting still applies, and whether the agent can run a WinUI app at all."); + throw; // Unreachable: Assert.Fail always throws. + } + } + + private static Task GenerateAssetAsync(string assetName, string sourceCode) + => TestAsset.GenerateAssetAsync( + assetName, + sourceCode + .PatchCodeWithReplace("$AssetName$", assetName) + .PatchCodeWithReplace("$TargetFramework$", TargetFramework) + .PatchCodeWithReplace("$RuntimeIdentifier$", RuntimeIdentifier) + .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion) + .PatchCodeWithReplace("$WindowsAppSdkVersion$", WindowsAppSdkVersion) + .PatchCodeWithReplace("$WindowsSdkBuildToolsVersion$", WindowsSdkBuildToolsVersion) + .PatchCodeWithReplace("$ThrowingConstructorMessage$", ThrowingConstructorMessage)); + + /// + /// Builds the asset and returns the directory holding the produced executable. + /// + private async Task BuildAssetAsync(string assetName, TestAsset testAsset) + { + CancellationToken cancellationToken = TestContext.CancellationToken; + + string project = Path.Combine(testAsset.TargetAssetPath, $"{assetName}.csproj"); + DotnetMuxerResult buildResult = await DotnetCli.RunAsync( + $"build \"{project}\" -c Release", + workingDirectory: testAsset.TargetAssetPath, + failIfReturnValueIsNotZero: false, + // MrtCore's PRI indexer warns that MSTest's localized satellite assemblies carry no en-US + // default. It logs the PRI257/PRI263 codes inside the message text rather than as MSBuild + // warning codes, so neither NoWarn nor MSBuildWarningsAsMessages can target them (both were + // tried). The warning is benign for a test app and outside this repository's control, so drop + // -warnaserror for this build. + warnAsError: false, + cancellationToken: cancellationToken); + Assert.AreEqual(0, buildResult.ExitCode, $"Building the unpackaged WinUI asset failed.{Environment.NewLine}{buildResult}"); + + string testHostDirectory = Path.Combine(testAsset.TargetAssetPath, "bin", "Release", TargetFramework, RuntimeIdentifier); + Assert.IsTrue( + Directory.Exists(testHostDirectory), + $"Expected the built unpackaged WinUI app under '{testHostDirectory}'."); + + return testHostDirectory; + } + + /// + /// The self-hosted shape: the WinUI app owns the entry point, starts the platform from + /// OnLaunched, and publishes its own dispatcher queue for [UITestMethod]. + /// + private const string SelfHostedSourceCode = """ +#file $AssetName$.csproj + + + + Exe + $TargetFramework$ + 10.0.17763.0 + true + enable + + + None + false + + + $RuntimeIdentifier$ + true + + true + + + false + + + + + + + + + + + + + + + + + +#file UnitTestApp.xaml + + + + + + + + + + + +#file UnitTestApp.xaml.cs +using System; +using System.Linq; +using Microsoft.Testing.Platform.Builder; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; +using Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer; + +namespace $AssetName$; + +public partial class UnitTestApp : Application +{ + public UnitTestApp() => InitializeComponent(); + + protected override async void OnLaunched(LaunchActivatedEventArgs args) + { + // OnLaunched already runs on the UI thread, so take its dispatcher directly. No window is shown: + // [UITestMethod] only needs a dispatcher, and not creating one keeps the test host from depending + // on an interactive desktop. Using WinUITestTarget here instead would start a second application. + UITestMethodAttribute.DispatcherQueue = DispatcherQueue.GetForCurrentThread(); + + try + { + string[] cliArgs = Environment.GetCommandLineArgs().Skip(1).ToArray(); + ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(cliArgs); + builder.AddSelfRegisteredExtensions(cliArgs); + using ITestApplication app = await builder.BuildAsync(); + Environment.ExitCode = await app.RunAsync(); + } + finally + { + // The app is the test host, so it has to shut itself down once the run is over. + Exit(); + } + } +} + +#file UnitTest1.cs +using Microsoft.UI.Xaml.Controls; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer; + +namespace $AssetName$; + +[TestClass] +public class TestClass1 +{ + [TestMethod] + public void PlainTestMethod_Runs() + { + } + + [TestMethod] + public void PlainTestMethod_CanCallWindowsAppSdkWinRT() + { + // A plain [TestMethod], not a [UITestMethod]: Windows App SDK WinRT has to be usable from an + // ordinary test thread in a process with no package identity. + string runtimeInfo = Microsoft.Windows.ApplicationModel.WindowsAppRuntime.RuntimeInfo.AsString; + + Assert.IsFalse(string.IsNullOrEmpty(runtimeInfo)); + } + + [UITestMethod] + public void UITestMethod_RunsOnUIThread() + { + var grid = new Grid(); + + Assert.AreEqual(0, grid.MinWidth); + } +} +"""; + + /// + /// The WinUITestTarget shape: an ordinary test executable (the platform generates its entry point) + /// that points [UITestMethod] at an Application the attribute has to start itself. The + /// application's constructor throws, which is the deterministic way to exercise the failure path in + /// UITestMethodAttribute.InitializeApplication. + /// + private const string WinUITestTargetSourceCode = """ +#file $AssetName$.csproj + + + + Exe + $TargetFramework$ + 10.0.17763.0 + true + enable + + + None + false + + + $RuntimeIdentifier$ + true + + + true + + + + + + + + + + + + +#file UnitTest1.cs +using Microsoft.UI.Xaml; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer; + +// UITestMethodAttribute.DispatcherQueue is deliberately left unset so the attribute goes through +// WinUITestTarget and starts the application itself. +[assembly: WinUITestTarget(typeof($AssetName$.ThrowingApp))] + +namespace $AssetName$; + +public class ThrowingApp : Application +{ + public ThrowingApp() + => throw new System.InvalidOperationException("$ThrowingConstructorMessage$"); +} + +[TestClass] +public class TestClass1 +{ + [UITestMethod] + public void UITestMethod_CannotStartApplication() + { + } +} +"""; +} diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/WinUITests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/WinUITests.cs index 463b27d9df..763e0285fa 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/WinUITests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/WinUITests.cs @@ -7,6 +7,12 @@ namespace MSTest.Acceptance.IntegrationTests; +/// +/// Smoke coverage that a UseWinUI project resolves and loads the WinUI-flavored MSTest +/// assemblies and runs to completion. The asset deliberately does not reference +/// Microsoft.WindowsAppSDK, which keeps it buildable by the dotnet muxer on every leg; the real +/// WinUI end-to-end coverage lives in . +/// [TestClass] public sealed class WinUITests : AcceptanceTestBase { @@ -44,6 +50,13 @@ public override (string ID, string Name, string Code) GetAssetsToGenerate() => ( true $TargetFramework$ true + + None diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/PackagedAppDeploymentTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/PackagedAppDeploymentTests.cs index 0cc192e785..499af9df17 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/PackagedAppDeploymentTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/PackagedAppDeploymentTests.cs @@ -1,13 +1,22 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests; [TestClass] +// Both test methods share the single asset generated by TestAssetFixture, and one of them deploys (that +// is, enumerates and copies) that whole directory while the other writes a marker file into it. The +// assembly runs methods in parallel, so they must not overlap. +[DoNotParallelize] public sealed class PackagedAppDeploymentTests : AcceptanceTestBase { private const string AssetName = "PackagedAppDeploymentTest"; + // Mirrors PackagedAppTestHostLauncher.LauncherModeEnvironmentVariable, which is internal to the + // extension. It is part of the extension's documented contract, so asserting on the literal here + // also guards against renaming it without noticing the behavior change. + private const string LauncherModeEnvironmentVariable = "TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER"; + [DynamicData(nameof(TargetFrameworks.NetForDynamicData), typeof(TargetFrameworks))] [TestMethod] [OSCondition(ConditionMode.Include, OperatingSystems.Windows, IgnoreMessage = "Packaged Windows apps (UWP/WinUI) are a Windows-only scenario.")] @@ -22,7 +31,15 @@ public async Task PackagedAppDeployment_DeploysAndLaunchesTestHost_WithoutLocalP string markerPath = Path.Combine(testHost.DirectoryName, "deployment-basedir.txt"); TestHostResult testHostResult = await testHost.ExecuteAsync( - environmentVariables: new Dictionary { ["PACKAGEDAPP_BASEDIR_MARKER"] = markerPath }, + environmentVariables: new Dictionary + { + ["PACKAGEDAPP_BASEDIR_MARKER"] = markerPath, + + // This asset is a plain (non-packaged) layout, which the launcher leaves alone by + // default. 'always' is the documented opt-in that requests deploy-and-launch for a + // loose layout. + [LauncherModeEnvironmentVariable] = "always", + }, cancellationToken: TestContext.CancellationToken); // The test host is deployed elsewhere and launched through a handle that exposes no local @@ -31,11 +48,43 @@ public async Task PackagedAppDeployment_DeploysAndLaunchesTestHost_WithoutLocalP testHostResult.AssertExitCodeIs(ExitCode.Success); Assert.IsTrue(File.Exists(markerPath), $"Expected the deployed host to write its base directory to '{markerPath}'."); - string runtimeBaseDirectory = File.ReadAllText(markerPath).Trim().TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - string originalDirectory = testHost.DirectoryName.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - Assert.AreNotEqual(originalDirectory, runtimeBaseDirectory, "The test host must have been deployed to and launched from a different directory."); + Assert.AreNotEqual( + NormalizeDirectory(testHost.DirectoryName), + ReadMarkedDirectory(markerPath), + "The test host must have been deployed to and launched from a different directory."); } + [DynamicData(nameof(TargetFrameworks.NetForDynamicData), typeof(TargetFrameworks))] + [TestMethod] + [OSCondition(ConditionMode.Include, OperatingSystems.Windows, IgnoreMessage = "The launcher is only ever enabled on Windows, so there is nothing to opt out of elsewhere.")] + public async Task PackagedAppDeployment_WithNonPackagedLayoutAndNoOptIn_RunsInPlace(string currentTfm) + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, currentTfm); + string markerPath = Path.Combine(testHost.DirectoryName, "in-place-basedir.txt"); + + // No opt-in and no AppxManifest.xml in the layout: merely referencing the PackagedApp package + // must not change how the app runs. This is the guard for unpackaged apps (most notably + // unpackaged WinUI), which would otherwise pay for the test host controller process model and + // have their whole layout copied to a deployment directory on every run. + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new Dictionary { ["PACKAGEDAPP_BASEDIR_MARKER"] = markerPath }, + cancellationToken: TestContext.CancellationToken); + + testHostResult.AssertExitCodeIs(ExitCode.Success); + + Assert.IsTrue(File.Exists(markerPath), $"Expected the test host to write its base directory to '{markerPath}'."); + Assert.AreEqual( + NormalizeDirectory(testHost.DirectoryName), + ReadMarkedDirectory(markerPath), + "The test host must have run from its own output directory, without being deployed elsewhere."); + } + + private static string ReadMarkedDirectory(string markerPath) + => NormalizeDirectory(File.ReadAllText(markerPath).Trim()); + + private static string NormalizeDirectory(string directory) + => directory.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + public sealed class TestAssetFixture() : TestAssetFixtureBase() { private const string Sources = """ @@ -73,12 +122,12 @@ public class Startup { public static async Task Main(string[] args) { - // The deployed copy of this app reports the directory it is actually running from, so the - // acceptance test can confirm it was deployed-and-launched from a different location. Both the - // controller process (original directory) and the deployed test host (deployment directory) - // run this Main; the deployed host is launched later, so it is the last writer and the marker - // ends up pointing at the deployment directory. The marker path comes from the - // platform-forwarded environment. + // The app reports the directory it is actually running from, so the acceptance tests can tell + // whether it was deployed-and-launched elsewhere or ran in place. When the launcher is opted in, + // both the controller process (original directory) and the deployed test host (deployment + // directory) run this Main, and the deployed host is launched later, so it is the last writer. + // When the launcher stays out of the way there is a single process and the marker points at the + // app's own output directory. The marker path comes from the platform-forwarded environment. string? markerPath = Environment.GetEnvironmentVariable("PACKAGEDAPP_BASEDIR_MARKER"); if (!string.IsNullOrEmpty(markerPath)) { diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/UITestMethodStartupWaitTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/UITestMethodStartupWaitTests.cs new file mode 100644 index 0000000000..1a924d3ee0 --- /dev/null +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/UITestMethodStartupWaitTests.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#if WIN_UI +using AwesomeAssertions; + +using Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer; +using Microsoft.VisualStudio.TestTools.UnitTesting.Resources; + +using TestFramework.ForTestingMSTest; + +namespace MSTestAdapter.PlatformServices.UnitTests; + +/// +/// Covers the guards that keep a WinUI startup problem a test failure rather than the hung run described +/// in issue #2784. Neither failure is reproducible on demand from a test host - one needs XAML to tear +/// down the UI thread natively, the other needs startup to stall for minutes - so the decision is +/// exercised directly instead of through a real application. +/// +public class UITestMethodStartupWaitTests : TestContainer +{ + private static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(1); + + // A generous timeout, so that reaching it would mean the liveness guard failed to fire rather than + // the test racing the clock. + private static readonly TimeSpan UnreachableTimeout = TimeSpan.FromMinutes(5); + + public void WaitForApplicationStartup_WhenUIThreadExitsWithoutCompleting_ReportsThatTheApplicationFailedToStart() + { + TaskCompletionSource startupCompletion = new(); + + UITestMethodAttribute.WaitForApplicationStartup(startupCompletion, _ => true, UnreachableTimeout, PollInterval); + + startupCompletion.Task.IsFaulted.Should().BeTrue(); + startupCompletion.Task.Exception!.InnerException.Should().BeOfType() + .Which.Message.Should().Be(FrameworkExtensionsMessages.WinUIApplicationFailedToStart); + } + + public void WaitForApplicationStartup_WhenStartupStallsOnALiveThread_TimesOut() + { + TaskCompletionSource startupCompletion = new(); + + // The thread never exits and the callback never completes, which is what a stalled startup looks + // like: only the timeout can end this wait. + UITestMethodAttribute.WaitForApplicationStartup(startupCompletion, _ => false, TimeSpan.Zero, PollInterval); + + startupCompletion.Task.IsFaulted.Should().BeTrue(); + startupCompletion.Task.Exception!.InnerException.Should().BeOfType() + .Which.Message.Should().Be(string.Format( + CultureInfo.CurrentCulture, FrameworkExtensionsMessages.WinUIApplicationStartupTimedOut, TimeSpan.Zero)); + } + + public void WaitForApplicationStartup_WhenTheCallbackCompletesWhileWaiting_LeavesTheResultAlone() + { + TaskCompletionSource startupCompletion = new(); + object expectedResult = new(); + int polls = 0; + + // The application comes up on the third poll, as it does on the success path where the callback + // completes the wait while the UI thread keeps pumping. + bool WaitForUIThreadExit(TimeSpan _) + { + if (++polls == 3) + { + startupCompletion.SetResult(expectedResult); + } + + return false; + } + + UITestMethodAttribute.WaitForApplicationStartup(startupCompletion, WaitForUIThreadExit, UnreachableTimeout, PollInterval); + + startupCompletion.Task.IsCompletedSuccessfully.Should().BeTrue(); + startupCompletion.Task.Result.Should().BeSameAs(expectedResult); + } + + public void WaitForApplicationStartup_WhenStartupAlreadyCompleted_DoesNotWait() + { + TaskCompletionSource startupCompletion = new(); + object expectedResult = new(); + startupCompletion.SetResult(expectedResult); + + // A poll would mean the wait ran despite startup being done, and an already-completed wait must + // not be turned into a failure. + UITestMethodAttribute.WaitForApplicationStartup( + startupCompletion, + _ => throw new InvalidOperationException("The UI thread must not be polled once startup completed."), + TimeSpan.Zero, + PollInterval); + + startupCompletion.Task.Result.Should().BeSameAs(expectedResult); + } +} +#endif diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppxManifestInfoTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppxManifestInfoTests.cs index 6462b58457..70724c46d4 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppxManifestInfoTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppxManifestInfoTests.cs @@ -225,22 +225,34 @@ public void GetManifestPath_WithManifest_ReturnsPathWithoutParsing() } [TestMethod] - public void FindManifestPath_WhenManifestIsInAnAncestorDirectory_ReturnsTheNearestManifest() + public void FindManifestPath_WhenManifestIsInAnAncestorDirectoryAndDeclaresExecutable_ReturnsTheNearestManifest() { // Model a valid MSIX layout where the manifest sits at the package root but the executable // lives in a subdirectory (Application/@Executable = "bin\host.exe"). string root = Path.Combine(Path.GetTempPath(), "AppxManifestInfoTests", Guid.NewGuid().ToString("N")); string executableDirectory = Path.Combine(root, "bin"); + string executablePath = Path.Combine(executableDirectory, "host.exe"); Directory.CreateDirectory(executableDirectory); try { string manifestPath = Path.Combine(root, AppxManifestInfo.AppxManifestFileName); - File.WriteAllText(manifestPath, "not xml"); + File.WriteAllText( + manifestPath, + """ + + + + + + + + """); // GetManifestPath only probes the executable's own directory and must miss the ancestor // manifest, whereas FindManifestPath walks up and locates it. Assert.IsNull(AppxManifestInfo.GetManifestPath(executableDirectory)); Assert.AreEqual(manifestPath, AppxManifestInfo.FindManifestPath(executableDirectory)); + Assert.AreEqual(manifestPath, AppxManifestInfo.FindManifestPath(executableDirectory, executablePath)); } finally { @@ -263,6 +275,192 @@ public void FindManifestPath_WithoutAnyManifest_ReturnsNull() } } + // The launch path is handed the exact executable it must start, so a manifest that declares a + // *different* application next to it must not be attributed: ResolveApplication would then pick that + // sole entry and the launcher would activate the wrong Application User Model ID. Enablement has no + // executable to match, so it still attributes on the directory. + // Two applications declaring the same executable is genuinely ambiguous rather than a mismatch, so + // the error must name the candidate AUMIDs instead of claiming that nothing declares the executable. + [TestMethod] + public void ResolveApplication_WithSeveralApplicationsDeclaringTheSameExecutable_ReportsTheCandidates() + { + const string ManifestXml = """ + + + + + + + + + """; + + AppxManifestInfo info = ReadManifest(ManifestXml); + string manifestDirectory = Path.Combine(Path.GetTempPath(), "AppxManifestInfoTests", Guid.NewGuid().ToString("N")); + + InvalidOperationException exception = Assert.ThrowsExactly( + () => info.ResolveApplication(manifestDirectory, Path.Combine(manifestDirectory, "Host.exe"))); + + Assert.Contains($"{info.PackageFamilyName}!First", exception.Message); + Assert.Contains($"{info.PackageFamilyName}!Second", exception.Message); + } + + // The manifest beside the app is accepted without parsing (the common-case fast path), so resolution + // is the only thing standing between a mismatched manifest and the wrong AUMID: a layout holding + // Host.exe next to a manifest whose sole application declares Other.exe must not activate Other. + [TestMethod] + public void ResolveApplication_WithSameDirectoryManifestDeclaringADifferentExecutable_Throws() + { + const string ManifestXml = """ + + + + + + + + """; + + AppxManifestInfo info = ReadManifest(ManifestXml); + string manifestDirectory = Path.Combine(Path.GetTempPath(), "AppxManifestInfoTests", Guid.NewGuid().ToString("N")); + + InvalidOperationException exception = Assert.ThrowsExactly( + () => info.ResolveApplication(manifestDirectory, Path.Combine(manifestDirectory, "Host.exe"))); + + // Naming both the executable that was asked for and the one the manifest declares is what makes + // this failure actionable, so it is asserted rather than just the exception type. + Assert.Contains("Host.exe", exception.Message); + Assert.Contains("Other.exe", exception.Message); + } + + // A manifest that declares no executable at all cannot be validated, so the lenient behavior stays: + // this is the minimal manifest shape the packaged acceptance assets and most fixtures use. + [TestMethod] + public void ResolveApplication_WithoutDeclaredExecutable_FallsBackToTheSoleApplication() + { + AppxManifestInfo info = ReadManifest( + name: "Contoso.MyTestApp", + publisher: MicrosoftStorePublisher, + applicationId: "App"); + string manifestDirectory = Path.Combine(Path.GetTempPath(), "AppxManifestInfoTests", Guid.NewGuid().ToString("N")); + + AppxApplicationInfo? application = info.ResolveApplication(manifestDirectory, Path.Combine(manifestDirectory, "Host.exe")); + + Assert.IsNotNull(application); + Assert.AreEqual("App", application.Id); + } + + // A package may legally declare two applications whose executables share a file name in different + // subdirectories. The file name alone cannot tell them apart, so resolving by it would report an + // ambiguity and refuse to activate; the full path the launcher already validated does distinguish them. + [TestMethod] + public void ResolveApplication_WithSameFileNameInDifferentDirectories_ResolvesByFullPath() + { + const string ManifestXml = """ + + + + + + + + + """; + + AppxManifestInfo info = ReadManifest(ManifestXml); + string manifestDirectory = Path.Combine(Path.GetTempPath(), "AppxManifestInfoTests", Guid.NewGuid().ToString("N")); + + AppxApplicationInfo? application = info.ResolveApplication(manifestDirectory, Path.Combine(manifestDirectory, "bin2", "host.exe")); + + Assert.IsNotNull(application); + Assert.AreEqual("Second", application.Id); + + // The file-name-only overload cannot disambiguate these, which is why the full path is carried through. + Assert.ThrowsExactly(() => info.ResolveApplication("host.exe")); + } + + [TestMethod] + public void FindManifestPath_WhenAncestorManifestDeclaresADifferentExecutableInTheAppDirectory_MatchesOnlyForEnablement() + { + string root = Path.Combine(Path.GetTempPath(), "AppxManifestInfoTests", Guid.NewGuid().ToString("N")); + string executableDirectory = Path.Combine(root, "bin"); + Directory.CreateDirectory(executableDirectory); + try + { + string manifestPath = Path.Combine(root, AppxManifestInfo.AppxManifestFileName); + File.WriteAllText( + manifestPath, + """ + + + + + + + + """); + + // Enablement only knows the directory, and the manifest does place an application there. + Assert.AreEqual(manifestPath, AppxManifestInfo.FindManifestPath(executableDirectory)); + + // The launch path knows it was asked for host.exe, which this manifest does not declare. + Assert.IsNull(AppxManifestInfo.FindManifestPath(executableDirectory, Path.Combine(executableDirectory, "host.exe"))); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [TestMethod] + public void FindManifestPath_WhenAncestorManifestDoesNotMatchExecutable_ReturnsNull() + { + string root = Path.Combine(Path.GetTempPath(), "AppxManifestInfoTests", Guid.NewGuid().ToString("N")); + string executableDirectory = Path.Combine(root, "bin"); + Directory.CreateDirectory(executableDirectory); + try + { + string manifestPath = Path.Combine(root, AppxManifestInfo.AppxManifestFileName); + File.WriteAllText( + manifestPath, + """ + + + + + + + + """); + + Assert.IsNull(AppxManifestInfo.FindManifestPath(executableDirectory)); + Assert.IsNull(AppxManifestInfo.FindManifestPath(executableDirectory, Path.Combine(executableDirectory, "host.exe"))); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [TestMethod] + public void FindManifestPath_WhenAncestorManifestIsMalformed_ReturnsNull() + { + string root = Path.Combine(Path.GetTempPath(), "AppxManifestInfoTests", Guid.NewGuid().ToString("N")); + string executableDirectory = Path.Combine(root, "bin"); + Directory.CreateDirectory(executableDirectory); + try + { + File.WriteAllText(Path.Combine(root, AppxManifestInfo.AppxManifestFileName), "not xml"); + + Assert.IsNull(AppxManifestInfo.FindManifestPath(executableDirectory)); + Assert.IsNull(AppxManifestInfo.FindManifestPath(executableDirectory, Path.Combine(executableDirectory, "host.exe"))); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + [TestMethod] public void ResolveApplication_MatchesExecutableDeclaredWithASubdirectoryPath() { diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppTestHostLauncherTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppTestHostLauncherTests.cs index de65babcf2..4286c1f667 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppTestHostLauncherTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppTestHostLauncherTests.cs @@ -15,17 +15,119 @@ public sealed class PackagedAppTestHostLauncherTests private const string MicrosoftStorePublisher = "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"; private const string MicrosoftStorePublisherId = "8wekyb3d8bbwe"; + /// A minimal manifest that makes a layout classify as packaged. + private static readonly string PackagedManifestXml = BuildManifestXml("Contoso.MyTestApp", MicrosoftStorePublisher, "App"); + + // A layout without an AppxManifest.xml can be started with a plain Process.Start. Enabling the + // launcher would force the platform onto the test host controller (process restart) model and copy + // the layout to a deployment directory — pure overhead here, and most visible for an unpackaged + // WinUI test app that merely references this package. + [TestMethod] + public Task IsEnabledAsync_WithLooseLayout_IsDisabledSoTheDefaultLaunchPathIsKept() + => AssertIsEnabledAsync(expected: false, manifestXml: null, mode: null); + + // A packaged (MSIX) layout genuinely cannot be started with Process.Start, so the launcher takes + // over without the user having to configure anything. + [TestMethod] + [OSCondition(ConditionMode.Include, OperatingSystems.Windows, IgnoreMessage = "Packaged Windows apps are a Windows-only scenario; the launcher is unconditionally disabled elsewhere.")] + public Task IsEnabledAsync_WithPackagedLayout_IsEnabled() + => AssertIsEnabledAsync(expected: true, PackagedManifestXml, mode: null); + + // 'always' is how a consumer opts a non-packaged layout into deploy-and-launch. + [TestMethod] + [OSCondition(ConditionMode.Include, OperatingSystems.Windows, IgnoreMessage = "Packaged Windows apps are a Windows-only scenario; the launcher is unconditionally disabled elsewhere.")] + public Task IsEnabledAsync_WithLooseLayoutAndAlwaysMode_IsEnabled() + => AssertIsEnabledAsync(expected: true, manifestXml: null, mode: "always"); + + // 'never' is the escape hatch: it keeps the launcher out of the way even for a packaged layout. + [TestMethod] + public Task IsEnabledAsync_WithPackagedLayoutAndNeverMode_IsDisabled() + => AssertIsEnabledAsync(expected: false, PackagedManifestXml, mode: "never"); + + [TestMethod] + [OSCondition(ConditionMode.Include, OperatingSystems.Windows, IgnoreMessage = "Packaged Windows apps are a Windows-only scenario; the launcher is unconditionally disabled elsewhere.")] + public Task IsEnabledAsync_ModeIsCaseAndWhitespaceInsensitive() + => AssertIsEnabledAsync(expected: true, manifestXml: null, mode: " AlWaYs "); + + // A typo in an environment variable must not do anything beyond falling back to the default (probe + // the layout), and must never fail the run. Asserting against a packaged layout is what proves the + // probe actually ran: expecting false on a loose layout would be indistinguishable from an + // unrecognized mode short-circuiting straight to disabled. + [TestMethod] + [OSCondition(ConditionMode.Include, OperatingSystems.Windows, IgnoreMessage = "Packaged Windows apps are a Windows-only scenario; the launcher is unconditionally disabled elsewhere.")] + public Task IsEnabledAsync_WithUnrecognizedMode_FallsBackToProbingTheLayout() + => AssertIsEnabledAsync(expected: true, PackagedManifestXml, mode: "alwyas"); + [TestMethod] - public async Task IsEnabledAsync_IsEnabledOnlyOnWindows() + public Task IsEnabledAsync_WithUnrecognizedModeAndLooseLayout_IsDisabled() + => AssertIsEnabledAsync(expected: false, manifestXml: null, mode: "alwyas"); + + // The layout probe walks up from the app directory because Application/@Executable may point into a + // subdirectory. Ancestor manifests are accepted only when they describe the app directory, so an + // unrelated manifest far above (a shared build root, a CI staging directory) must not classify an + // ordinary test app as packaged and take over its run. + [TestMethod] + [OSCondition(ConditionMode.Include, OperatingSystems.Windows, IgnoreMessage = "Packaged Windows apps are a Windows-only scenario; the launcher is unconditionally disabled elsewhere.")] + public Task IsEnabledAsync_WithAncestorManifestDeclaringDeepExecutable_IsEnabled() + { + const int AppSubdirectoryDepth = 4; + return AssertIsEnabledForManifestAsync( + BuildManifestXml( + "Contoso.MyTestApp", + MicrosoftStorePublisher, + applicationId: "App", + executable: GetNestedExecutablePath(AppSubdirectoryDepth, "MyTestApp.exe")), + expected: true, + appSubdirectoryDepth: AppSubdirectoryDepth); + } + + [TestMethod] + public Task IsEnabledAsync_WithStrayAncestorManifest_IsDisabled() + => AssertIsEnabledForManifestAsync( + BuildManifestXml( + "Contoso.MyOtherApp", + MicrosoftStorePublisher, + applicationId: "App", + executable: "other\\MyTestApp.exe"), + expected: false, + appSubdirectoryDepth: 4); + + [TestMethod] + public Task IsEnabledAsync_WithMalformedAncestorManifest_IsDisabled() + => AssertIsEnabledForManifestAsync("not xml", expected: false, appSubdirectoryDepth: 4); + + // Regression test: the launcher passes AppContext.BaseDirectory, which ends with a directory + // separator, while Path.GetDirectoryName never returns one. Comparing them unnormalized silently + // failed to attribute any ancestor manifest, so enablement never fired in production even though + // the separator-free paths these tests build kept passing. + [TestMethod] + [OSCondition(ConditionMode.Include, OperatingSystems.Windows, IgnoreMessage = "Packaged Windows apps are a Windows-only scenario; the launcher is unconditionally disabled elsewhere.")] + public Task IsEnabledAsync_WithTrailingSeparatorOnAppDirectory_IsEnabled() { - var launcher = new PackagedAppTestHostLauncher(); + const int AppSubdirectoryDepth = 4; + return RunInTemporaryLayoutAsync( + BuildManifestXml( + "Contoso.MyTestApp", + MicrosoftStorePublisher, + applicationId: "App", + executable: GetNestedExecutablePath(AppSubdirectoryDepth, "MyTestApp.exe")), + async (_, appDirectory) => + { + var launcher = new PackagedAppTestHostLauncher(appDirectory + Path.DirectorySeparatorChar, static _ => null); - // Packaged Windows apps are Windows-only. On other operating systems the launcher must report - // itself disabled so it is never registered and the platform is not forced onto the controller - // (deploy-and-launch) host. This assertion runs on both Windows and non-Windows CI legs. - Assert.AreEqual(OperatingSystem.IsWindows(), await launcher.IsEnabledAsync()); + Assert.IsTrue(await launcher.IsEnabledAsync()); + }, + AppSubdirectoryDepth); } + // Packaged Windows apps are a Windows-only concept, so neither a packaged layout nor an explicit + // 'always' may register the launcher elsewhere: that would force every non-Windows run onto the + // controller host for a launcher that cannot work there. + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows, IgnoreMessage = "This asserts the non-Windows behavior.")] + public Task IsEnabledAsync_OnNonWindows_IsDisabledEvenForAPackagedLayoutAndAlwaysMode() + => AssertIsEnabledAsync(expected: false, PackagedManifestXml, mode: "always"); + [TestMethod] public async Task LaunchTestHostAsync_WithPackagedLayout_ThrowsWithApplicationUserModelId() { @@ -67,44 +169,121 @@ public async Task LaunchTestHostAsync_WithMultipleApplications_ReportsTheOneMatc Assert.Contains($"Contoso.MyTestApp_{MicrosoftStorePublisherId}!Second", exception.Message); } + [TestMethod] + public async Task LaunchTestHostAsync_WithAncestorManifestDeclaringDeepExecutable_ThrowsWithApplicationUserModelId() + { + const int AppSubdirectoryDepth = 4; + InvalidOperationException exception = await LaunchInLayoutContainingManifestAsync( + BuildManifestXml( + "Contoso.MyTestApp", + MicrosoftStorePublisher, + applicationId: "App", + executable: GetNestedExecutablePath(AppSubdirectoryDepth, "MyTestApp.exe")), + testHostFileName: "MyTestApp.exe", + appSubdirectoryDepth: AppSubdirectoryDepth); + + Assert.Contains($"Contoso.MyTestApp_{MicrosoftStorePublisherId}!App", exception.Message); + } + private static Task LaunchInLayoutContainingManifestAsync(string? applicationId) => LaunchInLayoutContainingManifestAsync( BuildManifestXml("Contoso.MyTestApp", MicrosoftStorePublisher, applicationId), testHostFileName: "MyTestApp.exe"); - private static async Task LaunchInLayoutContainingManifestAsync(string manifestXml, string testHostFileName) + private static async Task LaunchInLayoutContainingManifestAsync( + string manifestXml, + string testHostFileName, + int appSubdirectoryDepth = 0) { - string directory = Path.Combine(Path.GetTempPath(), "PackagedAppTestHostLauncherTests", Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(directory); - try - { - File.WriteAllText( - Path.Combine(directory, AppxManifestInfo.AppxManifestFileName), - manifestXml); + InvalidOperationException? exception = null; + await RunInTemporaryLayoutAsync(manifestXml, async (_, appDirectory) => + { var launcher = new PackagedAppTestHostLauncher(); // The executable does not need to exist: the packaged-layout check happens before any launch. - string fakeTestHost = Path.Combine(directory, testHostFileName); + string fakeTestHost = Path.Combine(appDirectory, testHostFileName); #pragma warning disable TPEXP // TestHostLaunchContext is experimental. var context = new TestHostLaunchContext(fakeTestHost, [], new Dictionary(), workingDirectory: null); - return await Assert.ThrowsExactlyAsync( + exception = await Assert.ThrowsExactlyAsync( () => launcher.LaunchTestHostAsync(context, CancellationToken.None)); #pragma warning restore TPEXP + }, + appSubdirectoryDepth); + + return exception!; + } + + /// + /// Asserts the launcher's enablement decision for a layout that does (or does not) contain an + /// AppxManifest.xml, under an explicit + /// value. The environment is stubbed rather than mutated so the assertion never depends on — nor + /// leaks into — the ambient environment of a parallel test run. + /// + private static Task AssertIsEnabledAsync(bool expected, string? manifestXml, string? mode) + => RunInTemporaryLayoutAsync(manifestXml, async (_, appDirectory) => + { + var launcher = new PackagedAppTestHostLauncher( + appDirectory, + name => name == PackagedAppTestHostLauncher.LauncherModeEnvironmentVariable ? mode : null); + + Assert.AreEqual(expected, await launcher.IsEnabledAsync()); + }); + + /// + /// Places a manifest at the layout root and the app + /// directory levels below it, then asserts whether the launcher's upward probe still finds it. + /// + private static Task AssertIsEnabledForManifestAsync(string manifestXml, bool expected, int appSubdirectoryDepth) + => RunInTemporaryLayoutAsync(manifestXml, async (_, appDirectory) => + { + var launcher = new PackagedAppTestHostLauncher(appDirectory, static _ => null); + + Assert.AreEqual(expected, await launcher.IsEnabledAsync()); + }, + appSubdirectoryDepth); + + /// + /// Runs against a throw-away layout, optionally containing an + /// AppxManifest.xml at its root so the layout classifies as packaged. The action receives the + /// layout root and the app directory, which sit levels + /// apart so the upward manifest probe can be exercised. Passing the directory explicitly (rather + /// than relying on the test run's own output directory) keeps these tests independent of where the + /// test host happens to run from. + /// + private static async Task RunInTemporaryLayoutAsync(string? manifestXml, Func action, int appSubdirectoryDepth = 0) + { + string root = Path.Combine(Path.GetTempPath(), "PackagedAppTestHostLauncherTests", Guid.NewGuid().ToString("N")); + string appDirectory = appSubdirectoryDepth == 0 + ? root + : Path.Combine(root, Path.Combine([.. Enumerable.Repeat("nested", appSubdirectoryDepth)])); + Directory.CreateDirectory(appDirectory); + try + { + if (manifestXml is not null) + { + File.WriteAllText(Path.Combine(root, AppxManifestInfo.AppxManifestFileName), manifestXml); + } + + await action(root, appDirectory); } finally { - Directory.Delete(directory, recursive: true); + Directory.Delete(root, recursive: true); } } private static string BuildManifestXml(string name, string publisher, string? applicationId) + => BuildManifestXml(name, publisher, applicationId, executable: null); + + private static string BuildManifestXml(string name, string publisher, string? applicationId, string? executable) { + string executableAttribute = executable is null ? string.Empty : $" Executable=\"{executable}\""; string applications = applicationId is null ? string.Empty : $""" - + """; @@ -116,6 +295,9 @@ private static string BuildManifestXml(string name, string publisher, string? ap """; } + + private static string GetNestedExecutablePath(int depth, string fileName) + => string.Join("\\", Enumerable.Repeat("nested", depth).Append(fileName)); } #endif