Skip to content
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#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
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 @@ -40,6 +40,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 CountdownEvent _incomingRequestCounter = new(1);
private bool? _isTrxEnabled;
private bool _isDisposed;
Expand All @@ -55,6 +56,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();
PlatformServiceProvider.Instance.AdapterTraceLogger = new MTPTraceLogger(_loggerFactory.CreateLogger("mstest-trace"));
_gracefulStopCapability.NotifyTestExecutionPending();

Expand Down Expand Up @@ -187,7 +191,13 @@ private async Task RunTestsAsync(RunTestExecutionRequest request, IMessageBus me
runSettings.SettingsXml,
runContext.TestRunDirectory,
handle.ToAdapterMessageLogger(),
settings => new MtpTestResultRecorder(messageBus, this, sessionUid, IsTrxEnabled, settings),
settings => new MtpTestResultRecorder(
messageBus,
this,
sessionUid,
IsTrxEnabled,
settings,
_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,44 +28,181 @@ internal sealed class MtpTestResultRecorder : ITestResultRecorder
private readonly SessionUid _sessionUid;
private readonly bool _isTrxEnabled;
private readonly MSTestSettings _settings;
private readonly TestExecutionActivityBroker? _testExecutionActivityBroker;
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)
public MtpTestResultRecorder(
IMessageBus messageBus,
IDataProducer dataProducer,
SessionUid sessionUid,
bool isTrxEnabled,
MSTestSettings settings)
: this(messageBus, dataProducer, sessionUid, isTrxEnabled, settings, testExecutionActivityBroker: null)
{
}

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

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 (occurrence is null && _testExecutionActivityBroker?.Reserve(testNode) is { } reservation)
Comment thread
Evangelink marked this conversation as resolved.
Resolved
{
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);
}

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)
{
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 @@ -112,6 +112,7 @@ 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.
await _testResultRecorder.RecordStartAsync(currentTest).ConfigureAwait(false);
unitTestElement.ExecutionActivityLease = currentTest.ExecutionActivityLease;

DateTimeOffset startTime = DateTimeOffset.Now;

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

TestTools.UnitTesting.TestResult[] unitTestResult;
if (usesAppDomains || Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
DateTimeOffset endTime;
try
{
if (usesAppDomains || Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
#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.
// In addition to app domains, if we are STA thread (e.g, because runsettings setting ExecutionApartmentState to STA), we want to preserve that.
// If we await, we could end up in a thread pool thread, which is not what we want.
// 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);
// When app domains support is dropped, we can finally always be calling the async version.
// In addition to app domains, if we are STA thread (e.g, because runsettings setting ExecutionApartmentState to STA), we want to preserve that.
// If we await, we could end up in a thread pool thread, which is not what we want.
// 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);
#pragma warning restore VSTHRD103 // Call async methods when in an async method
}
else
{
unitTestResult = await testRunner.RunSingleTestAsync(unitTestElement, testContextProperties, lifecycleContextProperties, remotingMessageLogger).ConfigureAwait(false);
}
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
}
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
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
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ internal sealed partial class TestMethodRunner
/// TestMethod referred by the above test element.
/// </summary>
private readonly TestMethodInfo _testMethodInfo;
private readonly ITestExecutionActivityLease? _executionActivityLease;

/// <summary>
/// Cached <see cref="ReflectionTestMethodInfo"/> wrapper reused across all data rows of a
Expand All @@ -66,6 +67,15 @@ internal sealed partial class TestMethodRunner
/// The test context.
/// </param>
public TestMethodRunner(TestMethodInfo testMethodInfo, TestMethod testMethod, ITestContext testContext)
: this(testMethodInfo, testMethod, testContext, executionActivityLease: null)
{
}

internal TestMethodRunner(
TestMethodInfo testMethodInfo,
TestMethod testMethod,
ITestContext testContext,
ITestExecutionActivityLease? executionActivityLease)
{
DebugEx.Assert(testMethodInfo != null, "testMethodInfo should not be null");
DebugEx.Assert(testMethod != null, "testMethod should not be null");
Expand All @@ -74,6 +84,7 @@ public TestMethodRunner(TestMethodInfo testMethodInfo, TestMethod testMethod, IT
_testMethodInfo = testMethodInfo;
_test = testMethod;
_testContext = testContext;
_executionActivityLease = executionActivityLease;
}

/// <summary>
Expand All @@ -92,7 +103,7 @@ internal async Task<TestResult[]> ExecuteAsync(string? initializationLogs, strin

// The engine-level span for the whole test method: it wraps test initialize, the body, test cleanup and any
// data-row expansion, so the platform's test-case span gains an explanation of where the time went.
using IMSTestActivity? activity = MSTestInstrumentation.IsEnabled
using IMSTestActivity? activity = _executionActivityLease is null && MSTestInstrumentation.IsEnabled
? MSTestInstrumentation.StartActivity(
MSTestInstrumentation.ActivityNames.TestMethod,
[
Expand Down
Loading
Loading