Skip to content
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
#nullable enable
Microsoft.VisualStudio.TestTools.UnitTesting.MtpTestResultRecorder.MtpTestResultRecorder(Microsoft.Testing.Platform.Messages.IMessageBus! messageBus, Microsoft.Testing.Platform.Extensions.Messages.IDataProducer! dataProducer, Microsoft.Testing.Platform.TestHost.SessionUid sessionUid, bool isTrxEnabled, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! settings, Microsoft.Testing.Platform.Telemetry.TestExecutionActivityBroker? testExecutionActivityBroker) -> void
Microsoft.VisualStudio.TestTools.UnitTesting.MtpTestResultRecorder.MtpTestResultRecorder(Microsoft.Testing.Platform.Messages.IMessageBus! messageBus, Microsoft.Testing.Platform.Extensions.Messages.IDataProducer! dataProducer, Microsoft.Testing.Platform.TestHost.SessionUid sessionUid, bool isTrxEnabled, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! settings, System.Action<Microsoft.VisualStudio.TestTools.UnitTesting.TestResult!>! stageResultFiles) -> void
Microsoft.VisualStudio.TestTools.UnitTesting.MtpTestResultRecorder.MtpTestResultRecorder(Microsoft.Testing.Platform.Messages.IMessageBus! messageBus, Microsoft.Testing.Platform.Extensions.Messages.IDataProducer! dataProducer, Microsoft.Testing.Platform.TestHost.SessionUid sessionUid, bool isTrxEnabled, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! settings, System.Action<Microsoft.VisualStudio.TestTools.UnitTesting.TestResult!>! stageResultFiles, Microsoft.Testing.Platform.Telemetry.TestExecutionActivityBroker? testExecutionActivityBroker) -> void
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#nullable enable
Microsoft.VisualStudio.TestTools.UnitTesting.MtpTestResultRecorder.MtpTestResultRecorder(Microsoft.Testing.Platform.Messages.IMessageBus! messageBus, Microsoft.Testing.Platform.Extensions.Messages.IDataProducer! dataProducer, Microsoft.Testing.Platform.TestHost.SessionUid sessionUid, bool isTrxEnabled, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! settings, Microsoft.Testing.Platform.Telemetry.TestExecutionActivityBroker? testExecutionActivityBroker) -> void
Comment thread
Evangelink marked this conversation as resolved.
Resolved
abstract Microsoft.Testing.Extensions.RunSettingsCommandLineOptionsProviderBase.EnvironmentVariablesNotSupportedOnBrowserError.get -> string!
abstract Microsoft.Testing.Extensions.RunSettingsConfigurationProviderBase.DisplayName.get -> string!
abstract Microsoft.Testing.Extensions.RunSettingsConfigurationProviderBase.ReadRunSettings(Microsoft.Testing.Platform.CommandLine.CommandLineParseResult! commandLineParseResult) -> string?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,13 @@ internal static void TryEnable(IServiceProvider serviceProvider)

MSTestInstrumentation.SetActivityFactory((name, tags)
// A non-ambient span is required, not an optimization - see the remarks on MSTestInstrumentation.
// Because the span is not ambient it cannot pick a parent up from the ambient context either, so it
// is parented explicitly to the same test-framework span the platform's test-case spans use, which
// keeps everything in one trace.
=> otelService.StartNonAmbientActivity(name, tags, otelService.TestFrameworkActivity?.Id) is { } platformActivity
// Inherit the current ambient activity when one exists: under canonical execution this makes the
// test initialize/cleanup spans children of the test activity, while assembly/class fixtures still
// inherit the test-framework activity.
=> otelService.StartNonAmbientActivity(
name,
tags,
parentId: otelService.HasCurrentActivity ? null : otelService.TestFrameworkActivity?.Id) is { } platformActivity
? new MSTestPlatformActivity(platformActivity)
: null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ internal sealed class MSTestTestFramework : ITestFramework, IDataProducer, IDisp
private readonly PlatformServicesConfigurationAdapter _configuration;
private readonly ILoggerFactory _loggerFactory;
private readonly MSTestGracefulStopTestExecutionCapability _gracefulStopCapability;
private readonly TestExecutionActivityBroker? _testExecutionActivityBroker;
private readonly string _resultFilesStagingDirectory;
private readonly CountdownEvent _incomingRequestCounter = new(1);
private int _nextResultFileStagingDirectory;
Expand All @@ -59,6 +60,9 @@ public MSTestTestFramework(MSTestExtension extension, Func<IEnumerable<Assembly>
_configuration = new(serviceProvider.GetConfiguration());
_loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
_gracefulStopCapability = (MSTestGracefulStopTestExecutionCapability)capabilities.GetCapability<IGracefulStopTestExecutionCapability>()!;
_testExecutionActivityBroker =
(serviceProvider.GetService(typeof(ITestApplicationProcessExitCode)) as TestApplicationResult)?
.CreateTestExecutionActivityBroker();
_resultFilesStagingDirectory = Path.Combine(
serviceProvider.GetConfiguration().GetTestResultDirectory(),
$".mstest-{Guid.NewGuid():N}"[..16]);
Expand Down Expand Up @@ -196,7 +200,14 @@ private async Task RunTestsAsync(RunTestExecutionRequest request, IMessageBus me
runSettings.SettingsXml,
runContext.TestRunDirectory,
handle.ToAdapterMessageLogger(),
settings => new MtpTestResultRecorder(messageBus, this, sessionUid, IsTrxEnabled, settings, StageResultFiles),
settings => new MtpTestResultRecorder(
messageBus,
this,
sessionUid,
IsTrxEnabled,
settings,
StageResultFiles,
_testExecutionActivityBroker),
new MtpTestElementFilterProvider(runContext),
_configuration,
new TestSourceHandler(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using Microsoft.Testing.Platform.Extensions.Messages;
using Microsoft.Testing.Platform.Messages;
using Microsoft.Testing.Platform.Telemetry;
using Microsoft.Testing.Platform.TestHost;
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter;
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers;
Expand All @@ -27,52 +28,210 @@ internal sealed class MtpTestResultRecorder : ITestResultRecorder
private readonly SessionUid _sessionUid;
private readonly bool _isTrxEnabled;
private readonly MSTestSettings _settings;
private readonly TestExecutionActivityBroker? _testExecutionActivityBroker;
private readonly Action<FrameworkTestResult> _stageResultFiles;
private readonly Dictionary<UnitTestElement, Occurrence> _occurrences = [];
#if NET9_0_OR_GREATER
private readonly Lock _syncRoot = new();
#else
private readonly object _syncRoot = new();
#endif

public MtpTestResultRecorder(IMessageBus messageBus, IDataProducer dataProducer, SessionUid sessionUid, bool isTrxEnabled, MSTestSettings settings)
: this(messageBus, dataProducer, sessionUid, isTrxEnabled, settings, static _ => { })
public MtpTestResultRecorder(
IMessageBus messageBus,
IDataProducer dataProducer,
SessionUid sessionUid,
bool isTrxEnabled,
MSTestSettings settings)
: this(messageBus, dataProducer, sessionUid, isTrxEnabled, settings, static _ => { }, testExecutionActivityBroker: null)
{
}

public MtpTestResultRecorder(IMessageBus messageBus, IDataProducer dataProducer, SessionUid sessionUid, bool isTrxEnabled, MSTestSettings settings, Action<FrameworkTestResult> stageResultFiles)
public MtpTestResultRecorder(
IMessageBus messageBus,
IDataProducer dataProducer,
SessionUid sessionUid,
bool isTrxEnabled,
MSTestSettings settings,
Action<FrameworkTestResult> stageResultFiles)
: this(messageBus, dataProducer, sessionUid, isTrxEnabled, settings, stageResultFiles, testExecutionActivityBroker: null)
{
}

internal MtpTestResultRecorder(
IMessageBus messageBus,
IDataProducer dataProducer,
SessionUid sessionUid,
bool isTrxEnabled,
MSTestSettings settings,
TestExecutionActivityBroker? testExecutionActivityBroker)
: this(messageBus, dataProducer, sessionUid, isTrxEnabled, settings, static _ => { }, testExecutionActivityBroker)
{
}

internal MtpTestResultRecorder(
IMessageBus messageBus,
IDataProducer dataProducer,
SessionUid sessionUid,
bool isTrxEnabled,
MSTestSettings settings,
Action<FrameworkTestResult> stageResultFiles,
TestExecutionActivityBroker? testExecutionActivityBroker)
{
_messageBus = messageBus;
_dataProducer = dataProducer;
_sessionUid = sessionUid;
_isTrxEnabled = isTrxEnabled;
_settings = settings;
_testExecutionActivityBroker = testExecutionActivityBroker;
_stageResultFiles = stageResultFiles;
}

void ITestResultRecorder.PrepareResults(UnitTestElement testElement, FrameworkTestResult[] results)
{
lock (_syncRoot)
{
if (_occurrences.TryGetValue(testElement, out Occurrence? occurrence))
{
occurrence.RemainingResults = results.Length;
}
}
}

public Task RecordStartAsync(UnitTestElement testElement)
public async Task RecordStartAsync(UnitTestElement testElement)
{
TestNode testNode = MSTestTestNodeConverter.ToInProgressTestNode(testElement, _isTrxEnabled);
return PublishAsync(testNode);
Occurrence? occurrence;
lock (_syncRoot)
{
_occurrences.TryGetValue(testElement, out occurrence);
}

TestExecutionActivityReservation? discardedReservation = null;
if (testElement.SupportsExecutionActivityLease
&& occurrence is null
&& _testExecutionActivityBroker?.Reserve(testNode) is { } reservation)
{
var candidate = new Occurrence(reservation);
lock (_syncRoot)
{
if (_occurrences.TryGetValue(testElement, out occurrence))
{
discardedReservation = reservation;
}
else
{
_occurrences.Add(testElement, candidate);
occurrence = candidate;
}
}
}

if (discardedReservation is not null)
{
discardedReservation.RecordExecutionEnd(DateTimeOffset.UtcNow);
discardedReservation.CompleteWithoutResult();
}

if (occurrence is not null)
{
testElement.ExecutionActivityLease = occurrence.Lease;
testNode.Properties.Add(new TestExecutionActivityProperty(occurrence.Reservation, isFinalResult: false));
}

await PublishAsync(testNode).ConfigureAwait(false);
occurrence?.Reservation.Activate();
}

public Task RecordEmptyResultAsync(UnitTestElement testElement)
=> PublishAsync(MSTestTestNodeConverter.ToEmptyResultTestNode(testElement, _isTrxEnabled));
public async Task RecordEmptyResultAsync(UnitTestElement testElement)
{
TestNode testNode = MSTestTestNodeConverter.ToEmptyResultTestNode(testElement, _isTrxEnabled);
Occurrence? occurrence = TakeOccurrence(testElement, isResult: true);
if (occurrence is not null)
{
occurrence.Reservation.RecordExecutionEnd(DateTimeOffset.UtcNow);
testNode.Properties.Add(new TestExecutionActivityProperty(occurrence.Reservation, isFinalResult: true));
}

await PublishAsync(testNode).ConfigureAwait(false);
}

public async Task<bool> RecordResultAsync(UnitTestElement testElement, FrameworkTestResult unitTestResult, DateTimeOffset startTime, DateTimeOffset endTime)
{
var outcome = UnitTestOutcomeHelper.ToTestOutcome(unitTestResult.Outcome, _settings);
bool isFailed = outcome == TestOutcome.Failed;
Occurrence? occurrence = TakeOccurrence(testElement, isResult: true);

// Mirror TestResultRecorderExtensions: a NotFound result is not reported while hot reload is enabled.
if (outcome != TestOutcome.NotFound || !RuntimeContext.IsHotReloadEnabled)
{
_stageResultFiles(unitTestResult);
TestNode testNode = MSTestTestNodeConverter.ToResultTestNode(testElement, unitTestResult, startTime, endTime, _isTrxEnabled, _settings);
if (occurrence is not null)
{
occurrence.Reservation.RecordExecutionEnd(endTime);
testNode.Properties.Add(new TestExecutionActivityProperty(occurrence.Reservation, occurrence.IsFinalResult));
}

await PublishAsync(testNode).ConfigureAwait(false);
}
else if (occurrence is not null)
{
occurrence.Reservation.RecordExecutionEnd(endTime);
if (occurrence.IsFinalResult)
{
occurrence.Reservation.CompleteWithoutResult();
}
}

return isFailed;
}

private Task PublishAsync(TestNode testNode)
=> _messageBus.PublishAsync(_dataProducer, new TestNodeUpdateMessage(_sessionUid, testNode));

private Occurrence? TakeOccurrence(UnitTestElement testElement, bool isResult)
{
lock (_syncRoot)
{
if (!_occurrences.TryGetValue(testElement, out Occurrence? occurrence))
{
return null;
}

if (isResult)
{
occurrence.RemainingResults = Math.Max(0, occurrence.RemainingResults - 1);
occurrence.IsFinalResult = occurrence.RemainingResults == 0;
}

if (occurrence.IsFinalResult)
{
_occurrences.Remove(testElement);
testElement.ExecutionActivityLease = null;
}

return occurrence;
}
}

private sealed class Occurrence(TestExecutionActivityReservation reservation)
{
public TestExecutionActivityReservation Reservation { get; } = reservation;

public ITestExecutionActivityLease Lease { get; } = new MSTestExecutionActivityLease(reservation);

public int RemainingResults { get; set; } = 1;

public bool IsFinalResult { get; set; }
}

private sealed class MSTestExecutionActivityLease(TestExecutionActivityReservation reservation) : ITestExecutionActivityLease
{
public IDisposable? Enter()
=> reservation.Enter();

public void RecordExecutionEnd(DateTimeOffset endTime)
=> reservation.RecordExecutionEnd(endTime);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ private async Task ExecuteTestsWithDependencyGraphAsync(
TestFailureException = new InvalidOperationException(brokenTest.CycleMessage),
};

brokenTest.Element.SupportsExecutionActivityLease = !usesAppDomains;
await _testResultRecorder.RecordStartAsync(brokenTest.Element).ConfigureAwait(false);

// Selected but never run, so the class-cleanup countdown still owes this test its decrement.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ await ReportSkippedDependentAsync(

// Report through the neutral recorder using the element itself; the adapter-side recorder resolves
// the host test case (preserving host-injected TCM / data-collector properties) with full fidelity.
currentTest.SupportsExecutionActivityLease = !usesAppDomains;
await _testResultRecorder.RecordStartAsync(currentTest).ConfigureAwait(false);
unitTestElement.ExecutionActivityLease = currentTest.ExecutionActivityLease;

DateTimeOffset startTime = DateTimeOffset.Now;

Expand All @@ -125,7 +127,8 @@ await ReportSkippedDependentAsync(
Dictionary<string, object?> testContextProperties = GetTestContextProperties(tcmProperties, sourceLevelParameters, unitTestElement);

TestTools.UnitTesting.TestResult[] unitTestResult;
if (usesAppDomains || Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
DateTimeOffset endTime;
try
{
#pragma warning disable VSTHRD103 // Call async methods when in an async method - We cannot do right now because we are crossing app domains.
// When app domains support is dropped, we can finally always be calling the async version.
Expand All @@ -134,21 +137,22 @@ await ReportSkippedDependentAsync(
// Alternatively, if we want to use RunSingleTestAsync for the case of STA, we should have:
// 1. A custom single threaded synchronization context that keeps us in STA.
// 2. Use ConfigureAwait(true).
unitTestResult = testRunner.RunSingleTest(unitTestElement, testContextProperties, lifecycleContextProperties, remotingMessageLogger);
unitTestResult = usesAppDomains || Thread.CurrentThread.GetApartmentState() == ApartmentState.STA
? testRunner.RunSingleTest(unitTestElement, testContextProperties, lifecycleContextProperties, remotingMessageLogger)
: await testRunner.RunSingleTestAsync(unitTestElement, testContextProperties, lifecycleContextProperties, remotingMessageLogger).ConfigureAwait(false);
#pragma warning restore VSTHRD103 // Call async methods when in an async method
}
else
finally
{
unitTestResult = await testRunner.RunSingleTestAsync(unitTestElement, testContextProperties, lifecycleContextProperties, remotingMessageLogger).ConfigureAwait(false);
endTime = DateTimeOffset.Now;
unitTestElement.ExecutionActivityLease?.RecordExecutionEnd(endTime);
}

if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsInfoEnabled)
{
PlatformServiceProvider.Instance.AdapterTraceLogger.Info("Executed test {0}", unitTestElement.TestMethod.Name);
}

DateTimeOffset endTime = DateTimeOffset.Now;

dependencyCoordinator?.RecordOutcome(currentTest, AllPassed(unitTestResult));

await SendTestResultsAsync(currentTest, unitTestResult, startTime, endTime, _testResultRecorder).ConfigureAwait(false);
Expand Down Expand Up @@ -203,6 +207,7 @@ private async Task ReportSkippedDependentAsync(
dependencyCoordinator.RecordNotRun(test);

DateTimeOffset now = DateTimeOffset.Now;
test.SupportsExecutionActivityLease = !usesAppDomains;
await _testResultRecorder.RecordStartAsync(test).ConfigureAwait(false);

// The test was selected, so it is counted in the class-cleanup countdown even though it is not going
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ private async Task<TestResult[]> ExecuteTestAsync(ITestContext executionContext,
if (capturedContext is null)
{
using (TestContextImplementation.SetCurrentTestContext(executionContext as TestContext))
using (_executionActivityLease?.Enter())
{
testMethodInfo.TestContext = executionContext;
results = await _testMethodInfo.Executor.ExecuteAsync(testMethodInfo).ConfigureAwait(false);
Expand All @@ -44,6 +45,7 @@ private async Task<TestResult[]> ExecuteTestAsync(ITestContext executionContext,
try
{
using (TestContextImplementation.SetCurrentTestContext(executionContext as TestContext))
using (_executionActivityLease?.Enter())
{
testMethodInfo.TestContext = executionContext;
tcs.SetResult(await _testMethodInfo.Executor.ExecuteAsync(testMethodInfo).ConfigureAwait(false));
Expand Down
Loading
Loading