Skip to content

Commit cb58053

Browse files
EvangelinkCopilot
andauthored
Await canceled MSTest workers and share the compatibility fixture (#12288)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 680411e commit cb58053

4 files changed

Lines changed: 122 additions & 24 deletions

File tree

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.DependencyGraphExecution.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,8 @@ private async Task ExecuteChunksInTopologicalOrderAsync(
106106
bool usesAppDomains,
107107
int parallelWorkers)
108108
{
109+
_testRunCancellationToken?.ThrowIfCancellationRequested();
110+
109111
int chunkCount = graph.ParallelChunks.Length;
110112
int[] pendingPrerequisites = new int[chunkCount];
111113
var dependents = new List<int>[chunkCount];
@@ -147,10 +149,9 @@ private async Task ExecuteChunksInTopologicalOrderAsync(
147149
var resourceLockManager = new ResourceLockManager();
148150
var tasks = new List<Task>(effectiveWorkers);
149151

152+
// Once workers are scheduled, let them observe cancellation so we always await their completion.
150153
for (int worker = 0; worker < effectiveWorkers; worker++)
151154
{
152-
_testRunCancellationToken?.ThrowIfCancellationRequested();
153-
154155
tasks.Add(_taskFactory(async () =>
155156
{
156157
try

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.ParallelExecution.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,11 @@ .. parallelizableTestSet
8888
var tasks = new List<Task>();
8989
var resourceLockManager = new ResourceLockManager();
9090

91+
_testRunCancellationToken?.ThrowIfCancellationRequested();
92+
93+
// Once workers are scheduled, let them observe cancellation so we always await their completion.
9194
for (int i = 0; i < parallelWorkers; i++)
9295
{
93-
_testRunCancellationToken?.ThrowIfCancellationRequested();
94-
9596
tasks.Add(_taskFactory(async () =>
9697
{
9798
try

‎test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using AwesomeAssertions;
5+
using AwesomeAssertions.Execution;
56

67
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter;
78
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution;
@@ -509,6 +510,87 @@ public async Task RunTestsForMultipleSourcesShouldRunEachTestJustOnce()
509510

510511
#region Parallel tests
511512

513+
public Task RunTests_CancelledWhileStartingParallelWorkers_WaitsForScheduledWorkers()
514+
=> RunTestsCancelledWhileStartingWorkersAsync(withDependencies: false);
515+
516+
public Task RunTests_CancelledWhileStartingDependencyWorkers_WaitsForScheduledWorkers()
517+
=> RunTestsCancelledWhileStartingWorkersAsync(withDependencies: true);
518+
519+
private async Task RunTestsCancelledWhileStartingWorkersAsync(bool withDependencies)
520+
{
521+
UnitTestElement[] tests = ToUnitTestElements(
522+
GetTestCase(typeof(DummyTestClassForParallelize), nameof(DummyTestClassForParallelize.TestMethod1)),
523+
GetTestCase(typeof(DummyTestClassForParallelize2), nameof(DummyTestClassForParallelize2.TestMethod1)));
524+
if (withDependencies)
525+
{
526+
tests[1].Dependencies =
527+
[
528+
new TestDependencyInfo(typeof(DummyTestClassForParallelize).FullName, nameof(DummyTestClassForParallelize.TestMethod1), proceedOnFailure: false),
529+
];
530+
}
531+
532+
_runContext.MockRunSettings.Setup(rs => rs.SettingsXml).Returns(
533+
"""
534+
<RunSettings>
535+
<RunConfiguration>
536+
<DisableAppDomain>True</DisableAppDomain>
537+
</RunConfiguration>
538+
<MSTest>
539+
<Parallelize>
540+
<Workers>2</Workers>
541+
<Scope>MethodLevel</Scope>
542+
</Parallelize>
543+
</MSTest>
544+
</RunSettings>
545+
""");
546+
MSTestSettings.PopulateSettings(_runContext.RunSettings?.SettingsXml, _mockMessageLogger.Object.ToAdapterMessageLogger(), null);
547+
548+
var releaseWorker = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
549+
int scheduledWorkers = 0;
550+
var manager = new TestExecutionManager(action =>
551+
{
552+
if (++scheduledWorkers == 1)
553+
{
554+
_cancellationToken.Cancel();
555+
return releaseWorker.Task;
556+
}
557+
558+
return action();
559+
});
560+
Task run = manager.RunTestsAsync(
561+
tests,
562+
CurrentDeploymentContext,
563+
_frameworkHandle.ToAdapterMessageLogger(),
564+
TestResultRecorder,
565+
new TestElementFilterProvider(_runContext),
566+
_cancellationToken);
567+
568+
using var assertions = new AssertionScope();
569+
try
570+
{
571+
scheduledWorkers.Should().BeGreaterThan(0);
572+
run.IsCompleted.Should().BeFalse("cancellation must not abandon an already scheduled worker");
573+
}
574+
finally
575+
{
576+
releaseWorker.TrySetResult(true);
577+
}
578+
579+
const int WorkerCleanupTimeoutMilliseconds = 60_000;
580+
if (await Task.WhenAny(run, Task.Delay(WorkerCleanupTimeoutMilliseconds)) != run)
581+
{
582+
throw new TimeoutException("Parallel workers did not finish after their release.");
583+
}
584+
585+
Func<Task> completeRun = () => run;
586+
await completeRun.Should().NotThrowAsync();
587+
588+
scheduledWorkers.Should().Be(2);
589+
_frameworkHandle.TestCaseStartList.Should().BeEmpty();
590+
_frameworkHandle.ResultsList.Should().BeEmpty();
591+
_frameworkHandle.TestCaseEndList.Should().BeEmpty();
592+
}
593+
512594
public async Task RunTestsForTestShouldRunTestsInParallelWhenEnabledInRunsettings()
513595
{
514596
TestCase testCase11 = GetTestCase(typeof(DummyTestClassForParallelize), "TestMethod1");

‎test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/CompatibilityPolyfillTests.cs‎

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,20 @@ namespace Microsoft.Testing.Platform.MSBuild.UnitTests;
1010
[TestClass]
1111
public sealed class CompatibilityPolyfillTests
1212
{
13+
// The polyfills are stateless; keep one assembly alive until all parallel cases have finished.
14+
private static CompatibilityAssembly? s_compatibilityAssembly;
15+
16+
[ClassInitialize]
17+
public static void InitializeCompatibilityAssembly(TestContext _)
18+
=> s_compatibilityAssembly = new();
19+
20+
[ClassCleanup]
21+
public static void CleanupCompatibilityAssembly()
22+
{
23+
s_compatibilityAssembly?.Dispose();
24+
s_compatibilityAssembly = null;
25+
}
26+
1327
[TestMethod]
1428
[DataRow(0, false, 0, 0, "0")]
1529
[DataRow(0, true, 0, 0, "^0")]
@@ -21,7 +35,7 @@ public sealed class CompatibilityPolyfillTests
2135
[DataRow(11, false, 10, 11, "11")]
2236
public void Index_OffsetsAndFormatting_PreserveOrigin(int value, bool fromEnd, int length, int expectedOffset, string expectedText)
2337
{
24-
using CompatibilityAssembly assembly = new();
38+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
2539
Type type = assembly.GetRequiredType("System.Index");
2640
object index = CreateIndex(type, value, fromEnd);
2741
object equal = CreateIndex(type, value, fromEnd);
@@ -46,7 +60,7 @@ public void Index_OffsetsAndFormatting_PreserveOrigin(int value, bool fromEnd, i
4660
[DataRow(int.MinValue)]
4761
public void Index_NegativeValues_AreRejectedByConstructorAndFactories(int value)
4862
{
49-
using CompatibilityAssembly assembly = new();
63+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
5064
Type type = assembly.GetRequiredType("System.Index");
5165
Action[] create =
5266
[
@@ -65,7 +79,7 @@ public void Index_NegativeValues_AreRejectedByConstructorAndFactories(int value)
6579
[TestMethod]
6680
public void Index_FactoriesAndConversion_PreserveStartAndEndSemantics()
6781
{
68-
using CompatibilityAssembly assembly = new();
82+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
6983
Type type = assembly.GetRequiredType("System.Index");
7084
object start = type.GetProperty("Start")!.GetValue(null)!;
7185
object end = type.GetProperty("End")!.GetValue(null)!;
@@ -90,7 +104,7 @@ public void Index_FactoriesAndConversion_PreserveStartAndEndSemantics()
90104
[DataRow(10, false, 0, true, 10, 10, 0)]
91105
public void Range_OffsetsAndLength_RespectBothBounds(int start, bool startFromEnd, int end, bool endFromEnd, int length, int expectedOffset, int expectedLength)
92106
{
93-
using CompatibilityAssembly assembly = new();
107+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
94108
Type indexType = assembly.GetRequiredType("System.Index");
95109
Type rangeType = assembly.GetRequiredType("System.Range");
96110
object startIndex = CreateIndex(indexType, start, startFromEnd);
@@ -114,7 +128,7 @@ public void Range_OffsetsAndLength_RespectBothBounds(int start, bool startFromEn
114128
[DataRow(11, true, 0, true, 10)]
115129
public void Range_OutOfBoundsOrReversed_ReportsLength(int start, bool startFromEnd, int end, bool endFromEnd, int length)
116130
{
117-
using CompatibilityAssembly assembly = new();
131+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
118132
Type indexType = assembly.GetRequiredType("System.Index");
119133
Type rangeType = assembly.GetRequiredType("System.Range");
120134
object range = Invoke(rangeType.GetConstructor([indexType, indexType])!, null, CreateIndex(indexType, start, startFromEnd), CreateIndex(indexType, end, endFromEnd))!;
@@ -128,7 +142,7 @@ public void Range_OutOfBoundsOrReversed_ReportsLength(int start, bool startFromE
128142
[TestMethod]
129143
public void Range_Factories_PreserveEndpointsAndValueEquality()
130144
{
131-
using CompatibilityAssembly assembly = new();
145+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
132146
Type indexType = assembly.GetRequiredType("System.Index");
133147
Type rangeType = assembly.GetRequiredType("System.Range");
134148
object startAt = Invoke(rangeType.GetMethod("StartAt")!, null, CreateIndex(indexType, 3, true))!;
@@ -148,7 +162,7 @@ public void Range_Factories_PreserveEndpointsAndValueEquality()
148162
[TestMethod]
149163
public void BackwardCompatibility_ContainsAndAppendJoin_PreserveLegacyContracts()
150164
{
151-
using CompatibilityAssembly assembly = new();
165+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
152166
Type type = assembly.GetRequiredType("Polyfills.Polyfill");
153167
MethodInfo containsCharacter = type.GetMethod("Contains", [typeof(string), typeof(char)])!;
154168
MethodInfo containsText = type.GetMethod("Contains", [typeof(string), typeof(string), typeof(StringComparison)])!;
@@ -175,7 +189,7 @@ public void BackwardCompatibility_ContainsAndAppendJoin_PreserveLegacyContracts(
175189
[TestMethod]
176190
public void BackwardCompatibility_Deconstruct_PreservesBothComponents()
177191
{
178-
using CompatibilityAssembly assembly = new();
192+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
179193
Type type = assembly.GetRequiredType("Polyfills.Polyfill");
180194
MethodInfo deconstruct = type.GetMethods().Single(method => method.Name == "Deconstruct" && method.IsGenericMethodDefinition).MakeGenericMethod(typeof(string), typeof(int));
181195
object?[] arguments = [new KeyValuePair<string, int>("answer", 42), null, null];
@@ -189,7 +203,7 @@ public void BackwardCompatibility_Deconstruct_PreservesBothComponents()
189203
[TestMethod]
190204
public async Task BackwardCompatibility_CopyToAsync_TransfersFromCurrentPositionAndHonorsCancellation()
191205
{
192-
using CompatibilityAssembly assembly = new();
206+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
193207
MethodInfo copy = assembly.GetRequiredType("Polyfills.Polyfill").GetMethod("CopyToAsync", [typeof(Stream), typeof(Stream), typeof(CancellationToken)])!;
194208
using MemoryStream source = new([0, 255, 1, 13, 10, 128], writable: false);
195209
source.Position = 2;
@@ -209,7 +223,7 @@ public async Task BackwardCompatibility_CopyToAsync_TransfersFromCurrentPosition
209223
[TestMethod]
210224
public async Task BackwardCompatibility_SaveAsync_PreservesXmlAndHonorsCancellation()
211225
{
212-
using CompatibilityAssembly assembly = new();
226+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
213227
MethodInfo save = assembly.GetRequiredType("Polyfills.Polyfill").GetMethod("SaveAsync", [typeof(XDocument), typeof(Stream), typeof(SaveOptions), typeof(CancellationToken)])!;
214228
var document = XDocument.Parse("<root><item id=\"7\">value</item></root>");
215229
using MemoryStream destination = new();
@@ -233,7 +247,7 @@ public async Task BackwardCompatibility_SaveAsync_PreservesXmlAndHonorsCancellat
233247
[DataRow("System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute", "ParameterName", "result", false)]
234248
public void CompatibilityAttributes_StringPayloads_PreserveCompilerMetadata(string fullName, string propertyName, string payload, bool inherited)
235249
{
236-
using CompatibilityAssembly assembly = new();
250+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
237251
Type type = assembly.GetRequiredType(fullName);
238252
object attribute = Invoke(type.GetConstructor([typeof(string)])!, null, payload)!;
239253
AttributeUsageAttribute usage = type.GetCustomAttribute<AttributeUsageAttribute>()!;
@@ -268,7 +282,7 @@ public void CompatibilityAttributes_StringPayloads_PreserveCompilerMetadata(stri
268282
[DataRow("System.Diagnostics.CodeAnalysis.DoesNotReturnIfAttribute", "ParameterValue", true)]
269283
public void CompatibilityAttributes_ConditionalNullability_PreservesBothBooleanStates(string fullName, string propertyName, bool condition)
270284
{
271-
using CompatibilityAssembly assembly = new();
285+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
272286
Type type = assembly.GetRequiredType(fullName);
273287
object attribute = Invoke(type.GetConstructor([typeof(bool)])!, null, condition)!;
274288
AttributeUsageAttribute usage = type.GetCustomAttribute<AttributeUsageAttribute>()!;
@@ -281,7 +295,7 @@ public void CompatibilityAttributes_ConditionalNullability_PreservesBothBooleanS
281295
[TestMethod]
282296
public void CompatibilityAttributes_MemberLists_PreserveOverloadsAndConditions()
283297
{
284-
using CompatibilityAssembly assembly = new();
298+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
285299
Type memberType = assembly.GetRequiredType("System.Diagnostics.CodeAnalysis.MemberNotNullAttribute");
286300
object single = Invoke(memberType.GetConstructor([typeof(string)])!, null, "_first")!;
287301
string[] names = ["_first", "_second"];
@@ -304,7 +318,7 @@ public void CompatibilityAttributes_MemberLists_PreserveOverloadsAndConditions()
304318
[TestMethod]
305319
public void CompatibilityAttributes_InterpolatedArgumentsAndPriority_PreserveBindingInputs()
306320
{
307-
using CompatibilityAssembly assembly = new();
321+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
308322
Type argumentType = assembly.GetRequiredType("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute");
309323
object single = Invoke(argumentType.GetConstructor([typeof(string)])!, null, "receiver")!;
310324
string[] arguments = ["receiver", "provider"];
@@ -329,7 +343,7 @@ public void CompatibilityAttributes_InterpolatedArgumentsAndPriority_PreserveBin
329343
[DataRow("UnsupportedOSPlatformGuardAttribute")]
330344
public void CompatibilityAttributes_PlatformAnnotations_PreserveVersionAndOptionalMessage(string name)
331345
{
332-
using CompatibilityAssembly assembly = new();
346+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
333347
Type type = assembly.GetRequiredType($"System.Runtime.Versioning.{name}");
334348
object attribute = Invoke(type.GetConstructor([typeof(string)])!, null, "windows10.0.19041.0")!;
335349
Assert.AreEqual("windows10.0.19041.0", type.GetProperty("PlatformName")!.GetValue(attribute));
@@ -355,7 +369,7 @@ public void CompatibilityAttributes_PlatformAnnotations_PreserveVersionAndOption
355369
[TestMethod]
356370
public void CompatibilityAttributes_SuppressionAndDynamicMembers_PreserveAllMetadata()
357371
{
358-
using CompatibilityAssembly assembly = new();
372+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
359373
Type suppressionType = assembly.GetRequiredType("System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute");
360374
object suppression = Invoke(suppressionType.GetConstructor([typeof(string), typeof(string)])!, null, "Trimming", "IL2026")!;
361375
Assert.AreEqual("Trimming", suppressionType.GetProperty("Category")!.GetValue(suppression));
@@ -378,7 +392,7 @@ public void CompatibilityAttributes_SuppressionAndDynamicMembers_PreserveAllMeta
378392
[TestMethod]
379393
public void CompatibilityException_PreservesMessagesAndInnerException()
380394
{
381-
using CompatibilityAssembly assembly = new();
395+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
382396
Type type = assembly.GetRequiredType("System.Diagnostics.UnreachableException");
383397
var defaultException = (Exception)Invoke(type.GetConstructor(Type.EmptyTypes)!, null)!;
384398
var messageException = (Exception)Invoke(type.GetConstructor([typeof(string)])!, null, "custom unreachable")!;
@@ -395,7 +409,7 @@ public void CompatibilityException_PreservesMessagesAndInnerException()
395409
[TestMethod]
396410
public void OperatingSystemCompatibility_UsesActualRuntimePlatform()
397411
{
398-
using CompatibilityAssembly assembly = new();
412+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
399413
Type type = assembly.GetRequiredType("Polyfills.Polyfill");
400414
foreach (string platform in new[] { "Wasi", "Android", "IOS", "TvOS", "Browser" })
401415
{
@@ -407,7 +421,7 @@ public void OperatingSystemCompatibility_UsesActualRuntimePlatform()
407421
[TestMethod]
408422
public void Ensure_NotEmpty_ValidatesNullEmptyAndNonemptyCollectionShapes()
409423
{
410-
using CompatibilityAssembly assembly = new();
424+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
411425
MethodInfo method = assembly.GetRequiredType("Polyfills.Ensure").GetMethods()
412426
.Single(candidate => candidate.Name == "NotEmpty" && candidate.IsGenericMethodDefinition)
413427
.MakeGenericMethod(typeof(int));
@@ -431,7 +445,7 @@ public void Ensure_NotEmpty_ValidatesNullEmptyAndNonemptyCollectionShapes()
431445
[TestMethod]
432446
public void Ensure_StringGuards_PreserveInputAndDistinguishEmptyFromWhitespace()
433447
{
434-
using CompatibilityAssembly assembly = new();
448+
CompatibilityAssembly assembly = s_compatibilityAssembly!;
435449
Type type = assembly.GetRequiredType("Polyfills.Ensure");
436450
MethodInfo notEmpty = type.GetMethod("NotEmpty", [typeof(string), typeof(string)])!;
437451
MethodInfo notNullOrWhitespace = type.GetMethod("NotNullOrWhiteSpace")!;

0 commit comments

Comments
 (0)