Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,9 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable<TestCase> tests, IRunCo

try
{
await Task.WhenAll(tasks);
// Ensure we can abandon currently running tasks on cancellation, rather than waiting for them to complete.
// They will still run on background but we won't await them.
await Task.WhenAny(Task.WhenAll(tasks), _testRunCancellationToken.AsTask());
Copy link
Member

Choose a reason for hiding this comment

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

I would make the Task.WhenAny(task, cancellationToken.AsTask()) part as the helper instead. Also, could we - if not already done - get some blessing from runtime? I saw multiple different suggestions for this online.

}
catch (Exception ex)
{
Expand All @@ -485,12 +487,16 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable<TestCase> tests, IRunCo
// Queue the non parallel set
if (nonParallelizableTestSet != null)
{
await ExecuteTestsWithTestRunnerAsync(nonParallelizableTestSet, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains);
// Ensure we can abandon currently running tasks on cancellation, rather than waiting for them to complete.
// They will still run on background but we won't await them.
await Task.WhenAny(ExecuteTestsWithTestRunnerAsync(nonParallelizableTestSet, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains), _testRunCancellationToken.AsTask());
}
}
else
{
await ExecuteTestsWithTestRunnerAsync(testsToRun, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains);
// Ensure we can abandon currently running tasks on cancellation, rather than waiting for them to complete.
// They will still run on background but we won't await them.
await Task.WhenAny(ExecuteTestsWithTestRunnerAsync(testsToRun, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains), _testRunCancellationToken.AsTask());
}

if (PlatformServiceProvider.Instance.IsGracefulStopRequested)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// 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.VisualStudio.TestPlatform.MSTest.TestAdapter;

internal static class TestRunCancellationTokenExtensions
{
/// <summary>
/// Wraps the cancellation token into a task that will complete when cancellation is requested, so we can combine it with Task.WhenAny, to abandon other tasks in the background.
/// </summary>
// Returns Task but is not doing any async work, and we should not await getting the Task.
#pragma warning disable VSTHRD200 // Use "Async" suffix for async methods
public static Task AsTask(this TestRunCancellationToken? testRunCancellationToken)
#pragma warning restore VSTHRD200 // Use "Async" suffix for async methods
{
var cancellationSource = new TaskCompletionSource<object>();
testRunCancellationToken?.Register(() => cancellationSource.TrySetCanceled());

return cancellationSource.Task;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,15 @@ public sealed class AbortionTests : AcceptanceTestBase<AbortionTests.TestAssetFi

[TestMethod]
[DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
public async Task AbortWithCTRLPlusC_CancellingTests(string tfm)
public async Task AbortWithCTRLPlusC_CancellingParallelTests(string tfm)
=> await AbortWithCTRLPlusC_CancellingTests(tfm, parallelize: true);

[TestMethod]
[DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
public async Task AbortWithCTRLPlusC_CancellingNonParallelTests(string tfm)
=> await AbortWithCTRLPlusC_CancellingTests(tfm, parallelize: false);

internal async Task AbortWithCTRLPlusC_CancellingTests(string tfm, bool parallelize)
{
// We expect the same semantic for Linux, the test setup is not cross and we're using specific
// Windows API because this gesture is not easy xplat.
Expand All @@ -25,17 +33,45 @@ public async Task AbortWithCTRLPlusC_CancellingTests(string tfm)

var testHost = TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm);

string? parameters = null;
if (parallelize)
{
// Providing runSettings even with Parallelize Workers = 1, will "enable" parallelization and will run via different path.
// So providing the settings only to the parallel run.
string runSettingsPath = Path.Combine(testHost.DirectoryName, $"{(parallelize ? "parallel" : "serial")}.runsettings");
File.WriteAllText(runSettingsPath, $"""
<RunSettings>
<MSTest>
<Parallelize>
<Workers>{(parallelize ? 0 : 1)}</Workers>
<Scope>MethodLevel</Scope>
</Parallelize>
</MSTest>
</RunSettings>
""");
parameters = $"--settings {runSettingsPath}";
}

string fileCreationPath = Path.Combine(testHost.DirectoryName, "fileCreation");
File.WriteAllText(fileCreationPath, string.Empty);
Copy link
Member Author

Choose a reason for hiding this comment

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

This was unblocking the loop below, so as soon as we started the app we cancelled tests before any test ever had a chance to run.

So this test was testing almost nothing.


TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new()
TestHostResult testHostResult = await testHost.ExecuteAsync(parameters, environmentVariables: new()
{
["FILE_DIRECTORY"] = fileCreationPath,
});

testHostResult.AssertExitCodeIs(ExitCodes.TestSessionAborted);
// To ensure we don't cancel right away, so tests have chance to run, and block our
// cancellation if we do it wrong.
testHostResult.AssertOutputContains("Waiting for file creation.");
if (parallelize)
{
testHostResult.AssertOutputContains("Test Parallelization enabled for");
}
else
{
testHostResult.AssertOutputDoesNotContain("Test Parallelization enabled for");
}

testHostResult.AssertOutputMatchesRegex("Canceling the test session.*");
Copy link
Member Author

Choose a reason for hiding this comment

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

Now we abort so fast that this does not have a chance to write to screen.

testHostResult.AssertExitCodeIs(ExitCodes.TestSessionAborted);
}

public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder)
Expand Down Expand Up @@ -92,6 +128,7 @@ public static async Task<int> Main(string[] args)
}
else
{
Console.WriteLine("Waiting for file creation.");
Thread.Sleep(1000);
}
}
Expand Down Expand Up @@ -131,12 +168,18 @@ public async Task TestA()
var fireCtrlCTask = Task.Run(() =>
{
// Delay for a short period before firing CTRL+C to simulate some processing time
Task.Delay(1000).Wait();
File.WriteAllText(Environment.GetEnvironmentVariable("FILE_DIRECTORY")!, string.Empty);
});

// Start a task that represents the infinite delay, which should be canceled
await Task.Delay(Timeout.Infinite, TestContext.CancellationTokenSource.Token);
// Wait for 10s, and after that kill the process.
// When we cancel by CRTL+C we do non-graceful teardown so the Environment.Exit should never be reached,
// because the test process already terminated.
//
// If we do reach it, we will see 11111 exit code, and it will fail the test assertion, because we did not cancel.
// (If we don't exit here, the process will happily run to completion after 10 seconds, but will still report
// cancelled exit code, so that is why we are more aggressive here.)
await Task.Delay(10_000);
Environment.Exit(11111);
}
}
""";
Expand Down
Loading