Skip to content

Add test for dotnet test with UseAppHost=false in MTP #50109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
108 changes: 108 additions & 0 deletions src/Cli/dotnet/Commands/Test/TestApplication.cs
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot Please revert the changes in TestApplication.cs

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverted all changes in TestApplication.cs as requested. Changes reverted in commit 628f1b7.

Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

using System.Diagnostics;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using Microsoft.DotNet.Cli.Commands.Test.IPC;
using Microsoft.DotNet.Cli.Commands.Test.IPC.Models;
using Microsoft.DotNet.Cli.Commands.Test.IPC.Serializers;
Expand Down Expand Up @@ -54,6 +55,16 @@ public async Task<int> RunAsync(TestOptions testOptions)

private ProcessStartInfo CreateProcessStartInfo(TestOptions testOptions)
{
// Check for architecture mismatch when UseAppHost=false
if (ShouldValidateArchitectureForUseAppHostFalse())
{
var archMismatchError = ValidateArchitectureCompatibility();
if (archMismatchError != null)
{
throw new GracefulException(archMismatchError);
}
}

var processStartInfo = new ProcessStartInfo
{
// We should get correct RunProperties right away.
Expand Down Expand Up @@ -368,6 +379,103 @@ public override string ToString()
return builder.ToString();
}

private bool ShouldValidateArchitectureForUseAppHostFalse()
{
// Check if UseAppHost=false (RunArguments starts with "exec")
return !string.IsNullOrEmpty(Module.RunProperties.RunArguments) &&
Module.RunProperties.RunArguments.TrimStart().StartsWith("exec ", StringComparison.OrdinalIgnoreCase);
}

private string ValidateArchitectureCompatibility()
{
// Extract the requested architecture from MSBuild args
string requestedArch = GetRequestedArchitecture();
if (string.IsNullOrEmpty(requestedArch))
{
// No architecture specified, no validation needed
return null;
}

// Get current muxer architecture
string currentArch = GetCurrentMuxerArchitecture();

// Normalize architecture names for comparison
string normalizedRequested = NormalizeArchitectureName(requestedArch);
string normalizedCurrent = NormalizeArchitectureName(currentArch);

if (!string.Equals(normalizedRequested, normalizedCurrent, StringComparison.OrdinalIgnoreCase))
{
return $"The current .NET host does not support the requested target architecture '{requestedArch}'. " +
$"The current host is running '{currentArch}' architecture. " +
$"When UseAppHost is false, the target architecture must match the current .NET host architecture.";
}

return null;
}

private string GetRequestedArchitecture()
{
// Look for architecture in MSBuild args
foreach (var arg in _buildOptions.MSBuildArgs)
{
if (arg.StartsWith("--property:RuntimeIdentifier=", StringComparison.OrdinalIgnoreCase) ||
arg.StartsWith("-property:RuntimeIdentifier=", StringComparison.OrdinalIgnoreCase) ||
arg.StartsWith("/property:RuntimeIdentifier=", StringComparison.OrdinalIgnoreCase) ||
arg.StartsWith("-p:RuntimeIdentifier=", StringComparison.OrdinalIgnoreCase) ||
arg.StartsWith("/p:RuntimeIdentifier=", StringComparison.OrdinalIgnoreCase))
{
var rid = arg.Split('=', 2)[1];
return ExtractArchitectureFromRid(rid);
}
}

// Also check UnmatchedTokens for --arch parameter
for (int i = 0; i < _buildOptions.UnmatchedTokens.Count - 1; i++)
{
if (_buildOptions.UnmatchedTokens[i] == "--arch" || _buildOptions.UnmatchedTokens[i] == "-a")
{
return _buildOptions.UnmatchedTokens[i + 1];
}
}

return null;
}

private static string ExtractArchitectureFromRid(string rid)
{
// RID format is typically os-arch (e.g., linux-x64, win-x86, osx-arm64)
var parts = rid.Split('-');
if (parts.Length >= 2)
{
return parts[^1]; // Last part is the architecture
}
return rid; // Fallback to the entire string
}

private static string GetCurrentMuxerArchitecture()
{
return RuntimeInformation.ProcessArchitecture switch
{
Architecture.X64 => "x64",
Architecture.X86 => "x86",
Architecture.Arm => "arm",
Architecture.Arm64 => "arm64",
_ => RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant()
};
}

private static string NormalizeArchitectureName(string arch)
{
return arch.ToLowerInvariant() switch
{
"amd64" => "x64",
"x86_64" => "x64",
"arm64" => "arm64",
"aarch64" => "arm64",
_ => arch.ToLowerInvariant()
};
}

public void Dispose()
{
foreach (var namedPipeServer in _testAppPipeConnections)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using Microsoft.Testing.Platform.Builder;
using Microsoft.Testing.Platform.Capabilities.TestFramework;
using Microsoft.Testing.Platform.Extensions.Messages;
using Microsoft.Testing.Platform.Extensions.TestFramework;

var testApplicationBuilder = await TestApplication.CreateBuilderAsync(args);

testApplicationBuilder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_, __) => new DummyTestAdapter());

using var testApplication = await testApplicationBuilder.BuildAsync();
return await testApplication.RunAsync();

public class DummyTestAdapter : ITestFramework, IDataProducer
{
public string Uid => nameof(DummyTestAdapter);

public string Version => "2.0.0";

public string DisplayName => nameof(DummyTestAdapter);

public string Description => nameof(DummyTestAdapter);

public Task<bool> IsEnabledAsync() => Task.FromResult(true);

public Type[] DataTypesProduced => [];

public Task<CreateTestSessionResult> CreateTestSessionAsync(CreateTestSessionContext context)
=> Task.FromResult(new CreateTestSessionResult() { IsSuccess = true });

public Task<CloseTestSessionResult> CloseTestSessionAsync(CloseTestSessionContext context)
=> Task.FromResult(new CloseTestSessionResult() { IsSuccess = true });

public Task ExecuteRequestAsync(ExecuteRequestContext context)
{
// Simple dummy test that always passes
context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(
context.Request.Session.SessionUid,
new TestNode()
{
Uid = "dummy_test_1",
DisplayName = "Dummy Test 1",
Properties = new PropertyBag()
}));

context.MessageBus.PublishAsync(this, new TestResultMessage(
context.Request.Session.SessionUid,
new PassedTestResult()
{
Uid = "dummy_test_1",
DisplayName = "Dummy Test 1",
Duration = TimeSpan.FromMilliseconds(1)
}));

context.Complete();
return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), testAsset.props))\testAsset.props" />

<PropertyGroup>
<TargetFramework>$(CurrentTargetFramework)</TargetFramework>
<OutputType>Exe</OutputType>
<UseAppHost>false</UseAppHost>

<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<GenerateProgramFile>false</GenerateProgramFile>
<ManagePackageVersionsCentrally>false</ManagePackageVersionsCentrally>
<IsTestingPlatformApplication>true</IsTestingPlatformApplication>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Testing.Platform" Version="$(MicrosoftTestingPlatformVersion)" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Xml.Linq;
using Microsoft.DotNet.Cli.Commands;
using Microsoft.DotNet.Cli.Commands.Test;
using CommandResult = Microsoft.DotNet.Cli.Utils.CommandResult;
Expand Down Expand Up @@ -374,5 +375,33 @@ public void RunningWithGlobalPropertyShouldProperlyPropagate(string configuratio

result.ExitCode.Should().Be(ExitCodes.Success);
}

[Fact]
public void RunMTPProjectWithUseAppHostFalseAndArchMismatch_ShouldFailWithProperError()
{
TestAsset testInstance = _testAssetsManager.CopyTestAsset("TestProjectWithTests", Guid.NewGuid().ToString())
.WithSource()
.WithProjectChanges(project =>
{
// Modify the project to use UseAppHost=false
var ns = project.Root!.Name.Namespace;
var propertyGroup = project.Root.Elements(ns + "PropertyGroup").First();
propertyGroup.Add(new XElement(ns + "UseAppHost", "false"));
});

// Call test with wrong architecture
CommandResult result = new DotnetTestCommand(Log, disableNewOutput: false)
.WithWorkingDirectory(testInstance.Path)
.Execute("--arch", "wrongArchitecture");

// Verify proper error is shown for architecture mismatch
if (!TestContext.IsLocalized())
{
// Should provide clear error about architecture mismatch when UseAppHost=false
result.StdOut.Should().Contain("architecture");
}

result.ExitCode.Should().Be(ExitCodes.GenericFailure);
}
}
}
Loading