Skip to content

Commit 7b8c60f

Browse files
authored
Support env variables for dotnet test (MTP) (#50810)
1 parent fb270b3 commit 7b8c60f

File tree

9 files changed

+123
-2
lines changed

9 files changed

+123
-2
lines changed

src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
using System.Collections.Immutable;
45
using System.CommandLine;
56
using System.Diagnostics.CodeAnalysis;
67
using Microsoft.DotNet.Cli.Commands.Test.Terminal;
@@ -41,7 +42,10 @@ private int RunInternal(ParseResult parseResult, bool isHelp)
4142
ValidationUtility.ValidateSolutionOrProjectOrDirectoryOrModulesArePassedCorrectly(parseResult);
4243

4344
int degreeOfParallelism = GetDegreeOfParallelism(parseResult);
44-
var testOptions = new TestOptions(IsHelp: isHelp, IsDiscovery: parseResult.HasOption(MicrosoftTestingPlatformOptions.ListTestsOption));
45+
var testOptions = new TestOptions(
46+
IsHelp: isHelp,
47+
IsDiscovery: parseResult.HasOption(MicrosoftTestingPlatformOptions.ListTestsOption),
48+
EnvironmentVariables: parseResult.GetValue(CommonOptions.EnvOption) ?? ImmutableDictionary<string, string>.Empty);
4549

4650
InitializeOutput(degreeOfParallelism, parseResult, testOptions);
4751

src/Cli/dotnet/Commands/Test/MTP/Options.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
namespace Microsoft.DotNet.Cli.Commands.Test;
55

6-
internal record TestOptions(bool IsHelp, bool IsDiscovery);
6+
internal record TestOptions(bool IsHelp, bool IsDiscovery, IReadOnlyDictionary<string, string> EnvironmentVariables);
77

88
internal record PathOptions(string? ProjectPath, string? SolutionPath, string? ResultsDirectoryPath, string? ConfigFilePath, string? DiagnosticOutputDirectoryPath);
99

src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,12 @@ private ProcessStartInfo CreateProcessStartInfo()
140140
processStartInfo.Environment[entry.Key] = value;
141141
}
142142

143+
// Env variables specified on command line override those specified in launch profile:
144+
foreach (var (name, value) in TestOptions.EnvironmentVariables)
145+
{
146+
processStartInfo.Environment[name] = value;
147+
}
148+
143149
if (!_buildOptions.NoLaunchProfileArguments &&
144150
!string.IsNullOrEmpty(Module.LaunchSettings.CommandLineArgs))
145151
{

src/Cli/dotnet/Commands/Test/TestCommandParser.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ private static Command GetTestingPlatformCliCommand()
246246
command.Options.Add(MicrosoftTestingPlatformOptions.MaxParallelTestModulesOption);
247247
command.Options.Add(MicrosoftTestingPlatformOptions.MinimumExpectedTestsOption);
248248
command.Options.Add(CommonOptions.ArchitectureOption);
249+
command.Options.Add(CommonOptions.EnvOption);
249250
command.Options.Add(CommonOptions.PropertiesOption);
250251
command.Options.Add(MicrosoftTestingPlatformOptions.ConfigurationOption);
251252
command.Options.Add(MicrosoftTestingPlatformOptions.FrameworkOption);
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
using Microsoft.Testing.Platform.Builder;
2+
using Microsoft.Testing.Platform.Capabilities.TestFramework;
3+
using Microsoft.Testing.Platform.Extensions.Messages;
4+
using Microsoft.Testing.Platform.Extensions.TestFramework;
5+
6+
var testApplicationBuilder = await TestApplication.CreateBuilderAsync(args);
7+
8+
testApplicationBuilder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_, __) => new DummyTestAdapter());
9+
10+
using var testApplication = await testApplicationBuilder.BuildAsync();
11+
return await testApplication.RunAsync();
12+
13+
public class DummyTestAdapter : ITestFramework, IDataProducer
14+
{
15+
public string Uid => nameof(DummyTestAdapter);
16+
17+
public string Version => "2.0.0";
18+
19+
public string DisplayName => nameof(DummyTestAdapter);
20+
21+
public string Description => nameof(DummyTestAdapter);
22+
23+
public Task<bool> IsEnabledAsync() => Task.FromResult(true);
24+
25+
public Type[] DataTypesProduced => new[] {
26+
typeof(TestNodeUpdateMessage)
27+
};
28+
29+
public Task<CreateTestSessionResult> CreateTestSessionAsync(CreateTestSessionContext context)
30+
=> Task.FromResult(new CreateTestSessionResult() { IsSuccess = true });
31+
32+
public Task<CloseTestSessionResult> CloseTestSessionAsync(CloseTestSessionContext context)
33+
=> Task.FromResult(new CloseTestSessionResult() { IsSuccess = true });
34+
35+
public async Task ExecuteRequestAsync(ExecuteRequestContext context)
36+
{
37+
var envVariableValue = Environment.GetEnvironmentVariable("DUMMY_TEST_ENV_VAR") ?? "NOT SET";
38+
await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, new TestNode()
39+
{
40+
Uid = "Test1",
41+
DisplayName = "Test1",
42+
Properties = new PropertyBag(new FailedTestNodeStateProperty($"DUMMY_TEST_ENV_VAR is '{envVariableValue}'")),
43+
}));
44+
45+
context.Complete();
46+
}
47+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"profiles": {
3+
"ConsoleApp25": {
4+
"commandName": "Project",
5+
"environmentVariables": {
6+
"DUMMY_TEST_ENV_VAR": "FROM_LAUNCHSETTINGS"
7+
}
8+
}
9+
}
10+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), testAsset.props))\testAsset.props" />
3+
4+
<PropertyGroup>
5+
<TargetFramework>$(CurrentTargetFramework)</TargetFramework>
6+
<OutputType>Exe</OutputType>
7+
8+
<ImplicitUsings>enable</ImplicitUsings>
9+
<Nullable>enable</Nullable>
10+
11+
<ManagePackageVersionsCentrally>false</ManagePackageVersionsCentrally>
12+
<IsTestingPlatformApplication>true</IsTestingPlatformApplication>
13+
</PropertyGroup>
14+
15+
<ItemGroup>
16+
<PackageReference Include="Microsoft.Testing.Platform" Version="$(MicrosoftTestingPlatformVersion)" />
17+
</ItemGroup>
18+
</Project>
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"test": {
3+
"runner": "Microsoft.Testing.Platform"
4+
}
5+
}

test/dotnet.Tests/CommandTests/Test/GivenDotnetTestBuildsAndRunsTests.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,5 +476,35 @@ at Microsoft.DotNet.Cli.Commands.Test.TestApplicationActionQueue.Read(BuildOptio
476476
result.StdOut.Contains("Test run completed with non-success exit code: 1 (see: https://aka.ms/testingplatform/exitcodes)");
477477
}
478478
}
479+
480+
[Theory]
481+
[InlineData(TestingConstants.Debug)]
482+
[InlineData(TestingConstants.Release)]
483+
public void RunTestProjectWithEnvVariable(string configuration)
484+
{
485+
TestAsset testInstance = _testAssetsManager.CopyTestAsset("TestProjectShowingEnvVariable", Guid.NewGuid().ToString())
486+
.WithSource();
487+
488+
CommandResult result = new DotnetTestCommand(Log, disableNewOutput: false)
489+
.WithWorkingDirectory(testInstance.Path)
490+
.Execute(
491+
MicrosoftTestingPlatformOptions.ConfigurationOption.Name, configuration,
492+
CommonOptions.EnvOption.Name, "DUMMY_TEST_ENV_VAR=ENV_VAR_CMD_LINE");
493+
494+
if (!TestContext.IsLocalized())
495+
{
496+
result.StdOut
497+
.Should().Contain("Using launch settings from")
498+
.And.Contain($"Properties{Path.DirectorySeparatorChar}launchSettings.json...")
499+
.And.Contain("Test run summary: Failed!")
500+
.And.Contain("total: 1")
501+
.And.Contain("succeeded: 0")
502+
.And.Contain("failed: 1")
503+
.And.Contain("skipped: 0")
504+
.And.Contain("DUMMY_TEST_ENV_VAR is 'ENV_VAR_CMD_LINE'");
505+
}
506+
507+
result.ExitCode.Should().Be(ExitCodes.AtLeastOneTestFailed);
508+
}
479509
}
480510
}

0 commit comments

Comments
 (0)