From 05bdaee0ac5516af164fcf00c96b6803e1c67b96 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 09:28:51 +1000 Subject: [PATCH] Add ProcessId to IEnvironment --- .../Builder/TestApplication.cs | 5 ++--- .../Helpers/System/IEnvironment.cs | 2 ++ .../Helpers/System/SystemEnvironment.cs | 2 ++ .../Hosts/ServerTestHost.cs | 2 +- .../Hosts/TestHostBuilder.cs | 9 +++------ .../Hosts/TestHostControllersTestHost.cs | 19 +++++++++---------- .../DotnetTest/DotnetTestConnection.cs | 6 ++---- .../ServerMode/JsonRpc/PassiveNode.cs | 8 ++++---- 8 files changed, 25 insertions(+), 28 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index b676230b177..aea7efebe87 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -125,8 +125,7 @@ private static async Task LogInformationAsync( await logger.LogInformationAsync("Logging mode: " + (syncWrite ? "synchronous" : "asynchronous")).ConfigureAwait(false); await logger.LogInformationAsync($"Logging level: {loggerLevel}").ConfigureAwait(false); await logger.LogInformationAsync($"CreateBuilderAsync entry time: {createBuilderEntryTime}").ConfigureAwait(false); - using IProcess currentProcess = processHandler.GetCurrentProcess(); - await logger.LogInformationAsync($"PID: {currentProcess.Id}").ConfigureAwait(false); + await logger.LogInformationAsync($"PID: {environment.ProcessId}").ConfigureAwait(false); #if NETCOREAPP string runtimeInformation = $"{RuntimeInformation.RuntimeIdentifier} - {RuntimeInformation.FrameworkDescription}"; @@ -237,7 +236,7 @@ private static void AttachDebuggerIfNeeded(SystemEnvironment environment, System if (environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_WAIT_ATTACH_DEBUGGER) == "1") { IProcess currentProcess = systemProcess.GetCurrentProcess(); - console.WriteLine($"Waiting for debugger to attach... Process Id: {currentProcess.Id}, Name: {currentProcess.Name}"); + console.WriteLine($"Waiting for debugger to attach... Process Id: {environment.ProcessId}, Name: {currentProcess.Name}"); while (!Debugger.IsAttached) { diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IEnvironment.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IEnvironment.cs index b44afb73776..dfcab15fbbe 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IEnvironment.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IEnvironment.cs @@ -11,6 +11,8 @@ internal interface IEnvironment string NewLine { get; } + int ProcessId { get; } + string OsVersion { get; } #if NETCOREAPP diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemEnvironment.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemEnvironment.cs index a7ea4efe62a..5723b9cfa5f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemEnvironment.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemEnvironment.cs @@ -12,6 +12,8 @@ internal sealed class SystemEnvironment : IEnvironment public string NewLine => Environment.NewLine; + public int ProcessId => Environment.ProcessId; + public string OsVersion => Environment.OSVersion.ToString(); #if NETCOREAPP diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index bc5168c5c57..84874e82965 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -405,7 +405,7 @@ private async Task HandleRequestCoreAsync(RequestMessage message, RpcInv INamedFeatureCapability? namedFeatureCapability = ServiceProvider.GetTestFrameworkCapabilities().GetCapability(); return new InitializeResponseArgs( - ProcessId: ServiceProvider.GetProcessHandler().GetCurrentProcess().Id, + ProcessId: ServiceProvider.GetEnvironment().ProcessId, ServerInfo: new ServerInfo("test-anywhere", Version: ProtocolVersion), Capabilities: new ServerCapabilities( new ServerTestingCapabilities( diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 5091f98f92a..2b54e29887f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -329,7 +329,7 @@ await LogTestHostCreatedAsync( return toolsTestHost; } - var pushOnlyProtocol = new DotnetTestConnection(commandLineHandler, processHandler, environment, _testApplicationModuleInfo, testApplicationCancellationTokenSource); + var pushOnlyProtocol = new DotnetTestConnection(commandLineHandler, environment, _testApplicationModuleInfo, testApplicationCancellationTokenSource); await pushOnlyProtocol.AfterCommonServiceSetupAsync().ConfigureAwait(false); if (pushOnlyProtocol.IsServerMode) { @@ -388,7 +388,7 @@ await LogTestHostCreatedAsync( passiveNode = new PassiveNode( messageHandlerFactory, testApplicationCancellationTokenSource, - processHandler, + systemEnvironment, systemMonitorAsyncFactory, loggerFactory.CreateLogger()); } @@ -433,7 +433,6 @@ await LogTestHostCreatedAsync( // If we're under test controllers and currently we're inside the started test host we connect to the out of process // test controller manager. NamedPipeClient? testControllerConnection = await ConnectToTestHostProcessMonitorIfAvailableAsync( - processHandler, testApplicationCancellationTokenSource, loggerFactory.CreateLogger(nameof(ConnectToTestHostProcessMonitorIfAvailableAsync)), testHostControllerInfo, @@ -522,7 +521,6 @@ await LogTestHostCreatedAsync( } private static async Task ConnectToTestHostProcessMonitorIfAvailableAsync( - IProcessHandler processHandler, CTRLPlusCCancellationTokenSource testApplicationCancellationTokenSource, ILogger logger, TestHostControllerInfo testHostControllerInfo, @@ -556,9 +554,8 @@ await LogTestHostCreatedAsync( await logger.LogDebugAsync($"Connected to named pipe '{pipeName}'").ConfigureAwait(false); // Send the PID - using IProcess currentProcess = processHandler.GetCurrentProcess(); await client.RequestReplyAsync( - new TestHostProcessPIDRequest(currentProcess.Id), + new TestHostProcessPIDRequest(environment.ProcessId), testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); return client; } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index 5ed3207de12..42965ff6b46 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -76,9 +76,8 @@ protected override async Task InternalRunAsync() IConfiguration configuration = ServiceProvider.GetConfiguration(); try { - using IProcess currentProcess = process.GetCurrentProcess(); - int currentPID = currentProcess.Id; - string processIdString = currentPID.ToString(CultureInfo.InvariantCulture); + int currentPid = environment.ProcessId; + string processIdString = currentPid.ToString(CultureInfo.InvariantCulture); ExecutableInfo executableInfo = testApplicationModuleInfo.GetCurrentExecutableInfo(); await _logger.LogDebugAsync($"Test host controller process info: {executableInfo}").ConfigureAwait(false); @@ -92,7 +91,7 @@ protected override async Task InternalRunAsync() // Prepare the environment variables used by the test host string processCorrelationId = Guid.NewGuid().ToString("N"); - await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPID} '{processCorrelationId}'").ConfigureAwait(false); + await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPid} '{processCorrelationId}'").ConfigureAwait(false); NamedPipeServer testHostControllerIpc = new( $"MONITORTOHOST_{Guid.NewGuid():N}", @@ -115,10 +114,10 @@ protected override async Task InternalRunAsync() { EnvironmentVariables = { - { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPID}", processCorrelationId }, - { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PARENTPID}_{currentPID}", processIdString }, - { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_SKIPEXTENSION}_{currentPID}", "1" }, - { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PIPENAME}_{currentPID}", testHostControllerIpc.PipeName.Name }, + { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPid}", processCorrelationId }, + { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PARENTPID}_{currentPid}", processIdString }, + { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_SKIPEXTENSION}_{currentPid}", "1" }, + { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PIPENAME}_{currentPid}", testHostControllerIpc.PipeName.Name }, }, #if !NETCOREAPP UseShellExecute = false, @@ -230,9 +229,9 @@ protected override async Task InternalRunAsync() // Launch the test host process string testHostProcessStartupTime = _clock.UtcNow.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture); #pragma warning disable CA1416 // Validate platform compatibility - processStartInfo.EnvironmentVariables.Add($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPID}", testHostProcessStartupTime); + processStartInfo.EnvironmentVariables.Add($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPid}", testHostProcessStartupTime); #pragma warning restore CA1416 - await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPID} '{testHostProcessStartupTime}'").ConfigureAwait(false); + await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPid} '{testHostProcessStartupTime}'").ConfigureAwait(false); #pragma warning disable CA1416 // Validate platform compatibility await _logger.LogDebugAsync($"Starting test host process '{processStartInfo.FileName}' with args '{processStartInfo.Arguments}'").ConfigureAwait(false); #pragma warning restore CA1416 diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index d69a7c0220e..faeea63c183 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -20,7 +20,6 @@ internal sealed class DotnetTestConnection : IPushOnlyProtocol, IDisposable { private readonly CommandLineHandler _commandLineHandler; - private readonly IProcessHandler _processHandler; private readonly IEnvironment _environment; private readonly ITestApplicationModuleInfo _testApplicationModuleInfo; private readonly ITestApplicationCancellationTokenSource _cancellationTokenSource; @@ -29,10 +28,9 @@ internal sealed class DotnetTestConnection : IPushOnlyProtocol, public static string InstanceId { get; } = Guid.NewGuid().ToString("N"); - public DotnetTestConnection(CommandLineHandler commandLineHandler, IProcessHandler processHandler, IEnvironment environment, ITestApplicationModuleInfo testApplicationModuleInfo, ITestApplicationCancellationTokenSource cancellationTokenSource) + public DotnetTestConnection(CommandLineHandler commandLineHandler, IEnvironment environment, ITestApplicationModuleInfo testApplicationModuleInfo, ITestApplicationCancellationTokenSource cancellationTokenSource) { _commandLineHandler = commandLineHandler; - _processHandler = processHandler; _environment = environment; _testApplicationModuleInfo = testApplicationModuleInfo; _cancellationTokenSource = cancellationTokenSource; @@ -97,7 +95,7 @@ public async Task IsCompatibleProtocolAsync(string hostType) string supportedProtocolVersions = ProtocolConstants.Version; HandshakeMessage handshakeMessage = new(new Dictionary { - { HandshakeMessagePropertyNames.PID, _processHandler.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture) }, + { HandshakeMessagePropertyNames.PID, _environment.ProcessId.ToString(CultureInfo.InvariantCulture) }, { HandshakeMessagePropertyNames.Architecture, RuntimeInformation.ProcessArchitecture.ToString() }, { HandshakeMessagePropertyNames.Framework, RuntimeInformation.FrameworkDescription }, { HandshakeMessagePropertyNames.OS, RuntimeInformation.OSDescription }, diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs index 9bd65b99085..931755233fa 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs @@ -11,7 +11,7 @@ internal sealed class PassiveNode : IDisposable { private readonly IMessageHandlerFactory _messageHandlerFactory; private readonly ITestApplicationCancellationTokenSource _testApplicationCancellationTokenSource; - private readonly IProcessHandler _processHandler; + private readonly IEnvironment _environment; private readonly ILogger _logger; private readonly IAsyncMonitor _messageMonitor; private IMessageHandler? _messageHandler; @@ -19,13 +19,13 @@ internal sealed class PassiveNode : IDisposable public PassiveNode( IMessageHandlerFactory messageHandlerFactory, ITestApplicationCancellationTokenSource testApplicationCancellationTokenSource, - IProcessHandler processHandler, + IEnvironment environment, IAsyncMonitorFactory asyncMonitorFactory, ILogger logger) { _messageHandlerFactory = messageHandlerFactory; _testApplicationCancellationTokenSource = testApplicationCancellationTokenSource; - _processHandler = processHandler; + _environment = environment; _messageMonitor = asyncMonitorFactory.Create(); _logger = logger; } @@ -61,7 +61,7 @@ public async Task ConnectAsync() var requestMessage = (RequestMessage)message; var responseObject = new InitializeResponseArgs( - ProcessId: _processHandler.GetCurrentProcess().Id, + ProcessId: _environment.ProcessId, ServerInfo: new ServerInfo("test-anywhere", Version: PlatformVersion.Version), Capabilities: new ServerCapabilities( new ServerTestingCapabilities(