// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Pipes;
using System.Text.Json;
using Aspire.Hosting.Dcp.Process;
using Aspire.Hosting.Tests.Utils;
using Microsoft.AspNetCore.InternalTesting;
namespace Aspire.Hosting.Tests.Dcp;
[Trait("Partition", "4")]
public class ProcessUtilTests(ITestOutputHelper outputHelper)
{
[Fact]
public async Task Run_WaitsForOutputCallbacksToFinishBeforeCompleting()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var callbackStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseCallback = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var processStarted = new TaskCompletionSource<System.Diagnostics.Process>(TaskCreationOptions.RunContinuationsAsynchronously);
var spec = CreateSingleLineOutputProcessSpec(workspace, output =>
{
// File-based apps can emit SDK build diagnostics before their own output.
if (output != "final-line")
{
return;
}
callbackStarted.TrySetResult();
releaseCallback.Task.GetAwaiter().GetResult();
}, pid => processStarted.TrySetResult(System.Diagnostics.Process.GetProcessById(pid)));
var (pendingProcessResult, processDisposable) = ProcessUtil.Run(spec);
await using (processDisposable)
{
using var process = await processStarted.Task.DefaultTimeout(TestConstants.LongTimeoutDuration);
try
{
await callbackStarted.Task.DefaultTimeout(TestConstants.LongTimeoutDuration);
// Observe actual process exit while its output callback is still blocked.
await process.WaitForExitAsync().DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.False(pendingProcessResult.IsCompleted);
}
finally
{
releaseCallback.TrySetResult();
}
var result = await pendingProcessResult.DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.Equal(0, result.ExitCode);
}
}
[Fact]
public async Task Run_IncludesCapturedOutputInNonZeroExitException()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var (pendingProcessResult, processDisposable) = ProcessUtil.Run(CreateFailingProcessSpec(workspace, ["stdout-final-line", "stderr-final-line"], emitSecondLineToStderr: true));
await using (processDisposable)
{
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => pendingProcessResult).DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.Contains("returned non-zero exit code 1", exception.Message);
Assert.Contains("stdout-final-line", exception.Message);
Assert.Contains("stderr-final-line", exception.Message);
}
}
[Fact]
public async Task Run_ReturnsCapturedOutputInProcessResult_WhenRetentionEnabled()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var spec = CreateFailingProcessSpec(
workspace,
["stdout-final-line", "stderr-final-line"],
emitSecondLineToStderr: true,
throwOnNonZeroReturnCode: false,
retainedOutputLineCount: ProcessSpec.DefaultRetainedOutputLineCount);
var (pendingProcessResult, processDisposable) = ProcessUtil.Run(spec);
await using (processDisposable)
{
var processResult = await pendingProcessResult.DefaultTimeout(TestConstants.LongTimeoutDuration);
var normalizedOutput = processResult.ProcessOutput.Select(static line => line.TrimEnd()).ToArray();
Assert.Equal(1, processResult.ExitCode);
Assert.Equal(2, processResult.TotalProcessOutputLineCount);
Assert.Equal(2, processResult.ProcessOutput.Count);
Assert.Contains("stdout-final-line", normalizedOutput);
Assert.Contains("stderr-final-line", normalizedOutput);
}
}
[Fact]
public async Task Run_PassesArgumentListToProcess()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var appPath = DotnetFileAppProcess.WriteApp(workspace.WorkspaceRoot.FullName, "argument-list.cs", """
#:sdk Microsoft.NET.Sdk
Console.WriteLine(args[0]);
""");
var outputLines = new List<string>();
var spec = DotnetFileAppProcess.CreateDcpProcessSpec(appPath, ["argument-list-value"], onOutputData: outputLines.Add);
var (pendingProcessResult, processDisposable) = ProcessUtil.Run(spec);
await using (processDisposable)
{
var result = await pendingProcessResult.DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.Equal(0, result.ExitCode);
Assert.Contains("argument-list-value", outputLines);
}
}
[Fact]
public async Task Run_IncludesArgumentListInNonZeroExitException()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var appPath = DotnetFileAppProcess.WriteApp(workspace.WorkspaceRoot.FullName, "argument-list-failure.cs", """
#:sdk Microsoft.NET.Sdk
Environment.Exit(7);
""");
var spec = DotnetFileAppProcess.CreateDcpProcessSpec(
appPath,
["failure-argument", "failure argument", "quote\"argument", ""],
throwOnNonZeroReturnCode: true);
var (pendingProcessResult, processDisposable) = ProcessUtil.Run(spec);
await using (processDisposable)
{
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => pendingProcessResult).DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.Contains("returned non-zero exit code 7", exception.Message);
Assert.Contains("failure-argument", exception.Message);
Assert.Contains("-- failure-argument \"failure argument\" \"quote\\\"argument\" \"\"", exception.Message);
}
}
[Fact]
public async Task Run_ResolvesExecutableNameFromPathBeforeStartingProcess()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var appPath = DotnetFileAppProcess.WriteApp(workspace.WorkspaceRoot.FullName, "path-executable.cs", """
#:sdk Microsoft.NET.Sdk
Console.WriteLine("path-executable-output");
""");
var dotnetPath = DotnetFileAppProcess.ResolvedExecutablePath;
var dotnetDirectory = Path.GetDirectoryName(dotnetPath);
var dotnetExecutableName = Path.GetFileName(dotnetPath);
var outputLines = new List<string>();
var spec = new ProcessSpec(dotnetExecutableName)
{
ArgumentList = DotnetFileAppProcess.CreateArguments(appPath),
EnvironmentVariables = new Dictionary<string, string>
{
["PATH"] = dotnetDirectory ?? string.Empty
},
OnOutputData = outputLines.Add,
ThrowOnNonZeroReturnCode = false,
ResolveExecutablePath = true
};
var (pendingProcessResult, processDisposable) = ProcessUtil.Run(spec);
await using (processDisposable)
{
var result = await pendingProcessResult.DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.Equal(0, result.ExitCode);
Assert.Contains("path-executable-output", outputLines);
}
}
[Fact]
public void Run_Throws_WhenArgumentsAndArgumentListAreSpecified()
{
var spec = new ProcessSpec("dotnet")
{
Arguments = "--version",
ArgumentList = ["--info"],
ThrowOnNonZeroReturnCode = false
};
var exception = Assert.Throws<ArgumentException>(() => ProcessUtil.Run(spec));
Assert.StartsWith("Specify either Arguments or ArgumentList, not both.", exception.Message);
Assert.Equal("processSpec", exception.ParamName);
}
[Fact]
public async Task Run_TruncatesCapturedOutputToLast50LinesInNonZeroExitException()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var lines = Enumerable.Range(1, 52).Select(i => $"line-{i}").ToArray();
var (pendingProcessResult, processDisposable) = ProcessUtil.Run(CreateFailingProcessSpec(workspace, lines));
await using (processDisposable)
{
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => pendingProcessResult).DefaultTimeout(TestConstants.LongTimeoutDuration);
var outputLines = exception.Message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
var normalizedOutputLines = outputLines.Select(static line => line.TrimEnd()).ToArray();
Assert.Contains("Command output truncated: showing last 50 of 52 lines.", exception.Message);
Assert.DoesNotContain("line-1", outputLines);
Assert.DoesNotContain("line-2", outputLines);
Assert.Contains("line-3", normalizedOutputLines);
Assert.Contains("line-52", normalizedOutputLines);
}
}
[Fact]
public async Task Run_PreservesLegacyLineInputAndOutput()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var app = DotnetFileAppProcess.WriteApp(workspace.Path, "legacy-lines.cs", """
#:sdk Microsoft.NET.Sdk
var input = await Console.In.ReadToEndAsync().ConfigureAwait(false);
Console.WriteLine(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(input)));
Console.Write("\nfirst\r\n\nsecond\rthird\nlast");
""");
var lines = new List<string>();
var spec = new ProcessSpec(DotnetFileAppProcess.ResolvedExecutablePath)
{
ArgumentList = DotnetFileAppProcess.CreateArguments(app),
OnOutputData = lines.Add,
StandardInputContent = "test input"
};
var (pending, disposable) = ProcessUtil.Run(spec);
await using (disposable)
{
var result = await pending.DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.Equal(0, result.ExitCode);
Assert.Equal(new[] { Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("test input" + Environment.NewLine)), "first", "second", "third", "last" }, lines);
}
}
[Theory]
[InlineData(0, false)]
[InlineData(0, true)]
[InlineData(17, false)]
[InlineData(17, true)]
public async Task Run_InputFailure_PreservesNaturalExitAndLateOutput(int exitCode, bool throwOnNonZeroReturnCode)
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var (executable, arguments) = await DotnetFileAppProcess.CreateInputRejectingProcessAsync(workspace.Path, exitCode.ToString(), TestContext.Current.CancellationToken);
int? stoppedExitCode = null;
var (pending, disposable) = ProcessUtil.Run(new ProcessSpec(executable)
{
ArgumentList = arguments,
StandardInputContent = new string('x', 2_000_000),
ThrowOnNonZeroReturnCode = throwOnNonZeroReturnCode,
RetainedOutputLineCount = 10,
OnStop = code => stoppedExitCode = code
});
await using (disposable)
{
if (exitCode == 0)
{
await Assert.ThrowsAsync<IOException>(() => pending).DefaultTimeout(TestConstants.LongTimeoutDuration);
}
else if (throwOnNonZeroReturnCode)
{
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => pending).DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.Contains("returned non-zero exit code 17", exception.Message);
Assert.Contains("stdout-after-input-closed", exception.Message);
Assert.Contains("stderr-after-input-closed", exception.Message);
}
else
{
var result = await pending.DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.Equal(exitCode, result.ExitCode);
Assert.Equal(2, result.TotalProcessOutputLineCount);
Assert.Equal(["stderr-after-input-closed", "stdout-after-input-closed"], result.ProcessOutput.Order().ToArray());
}
Assert.Equal(exitCode, stoppedExitCode);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Run_InputFailure_StopsLiveProcessAndReportsOriginalError(bool throwOnNonZeroReturnCode)
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var (executable, arguments) = await DotnetFileAppProcess.CreateInputRejectingProcessAsync(workspace.Path, "wait", TestContext.Current.CancellationToken);
var startedPid = 0;
int? stoppedExitCode = null;
var (pending, disposable) = ProcessUtil.Run(new ProcessSpec(executable)
{
ArgumentList = arguments,
StandardInputContent = new string('x', 2_000_000),
ThrowOnNonZeroReturnCode = throwOnNonZeroReturnCode,
OnStart = pid => startedPid = pid,
OnStop = code => stoppedExitCode = code
});
await using (disposable)
{
using var child = System.Diagnostics.Process.GetProcessById(startedPid);
await Assert.ThrowsAsync<IOException>(() => pending).DefaultTimeout(TestConstants.LongTimeoutDuration);
Assert.True(child.HasExited);
Assert.True(stoppedExitCode is not null and not 0);
}
}
[Theory]
[InlineData(0, false, false)]
[InlineData(17, false, false)]
[InlineData(17, true, false)]
[InlineData(17, false, true)]
public Task Run_ExitedProcessWithDescendantHoldingInput_SettlesInputAndPreservesResult(
int exitCode, bool throwOnNonZeroReturnCode, bool disposeAfterRootExit)
=> RunWithDescendantHoldingStreamsAsync(
holdStandardInput: true, hasStandardInput: true, exitCode, throwOnNonZeroReturnCode, disposeAfterRootExit);
[Theory]
[InlineData(0, false)]
[InlineData(17, false)]
[InlineData(17, true)]
public Task Run_InputFailureWithDescendantHoldingOutput_PreservesResultAndDiagnostics(
int exitCode, bool throwOnNonZeroReturnCode)
=> RunWithDescendantHoldingStreamsAsync(
holdStandardInput: false, hasStandardInput: true, exitCode, throwOnNonZeroReturnCode, disposeAfterRootExit: false);
[Fact]
public Task Run_ExitedProcessWithDescendantHoldingOutput_BoundsDrain()
=> RunWithDescendantHoldingStreamsAsync(
holdStandardInput: false, hasStandardInput: false, exitCode: 0, throwOnNonZeroReturnCode: false, disposeAfterRootExit: false);
private async Task RunWithDescendantHoldingStreamsAsync(
bool holdStandardInput, bool hasStandardInput, int exitCode, bool throwOnNonZeroReturnCode, bool disposeAfterRootExit)
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
// Unix named pipes use path-limited domain sockets under the temp directory.
var pipeName = Guid.NewGuid().ToString("N")[..16];
await using var descendantPipe = new NamedPipeServerStream(
pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
var (executable, arguments) = await DotnetFileAppProcess.CreateDescendantHoldingStreamsProcessAsync(
workspace.Path, pipeName, holdStandardInput, hasStandardInput, exitCode, TestContext.Current.CancellationToken);
var stdout = new ConcurrentQueue<string>();
var stderr = new ConcurrentQueue<string>();
Process? root = null;
Process? descendant = null;
int? stoppedExitCode = null;
var (pending, disposable) = ProcessUtil.Run(new ProcessSpec(executable)
{
ArgumentList = arguments,
StandardInputContent = hasStandardInput ? new string('x', 2_000_000) : null,
ThrowOnNonZeroReturnCode = throwOnNonZeroReturnCode,
RetainedOutputLineCount = 10,
OnStart = pid => root = Process.GetProcessById(pid),
OnStop = code => stoppedExitCode = code,
OnOutputData = stdout.Enqueue,
OnErrorData = stderr.Enqueue
});
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TestConstants.LongTimeoutDuration);
await descendantPipe.WaitForConnectionAsync(timeout.Token);
using var reader = new StreamReader(descendantPipe, leaveOpen: true);
var descendantId = await reader.ReadLineAsync(timeout.Token);
Assert.NotNull(descendantId);
descendant = Process.GetProcessById(int.Parse(descendantId));
Assert.False(descendant.HasExited);
Assert.NotNull(root);
await root.WaitForExitAsync(timeout.Token);
if (disposeAfterRootExit)
{
await disposable.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(20), timeout.Token);
}
if (exitCode == 0 && hasStandardInput)
{
await Assert.ThrowsAsync<IOException>(() => pending.WaitAsync(TimeSpan.FromSeconds(20), timeout.Token));
}
else if (throwOnNonZeroReturnCode)
{
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => pending.WaitAsync(TimeSpan.FromSeconds(20), timeout.Token));
Assert.Contains("returned non-zero exit code 17", exception.Message);
Assert.Contains("root-stdout", exception.Message);
Assert.Contains("root-stderr-without-newline", exception.Message);
}
else
{
var result = await pending.WaitAsync(TimeSpan.FromSeconds(20), timeout.Token);
Assert.Equal(exitCode, result.ExitCode);
Assert.Equal(2, result.TotalProcessOutputLineCount);
Assert.Equal(["root-stderr-without-newline", "root-stdout"], result.ProcessOutput.Order().ToArray());
}
Assert.Equal(exitCode, stoppedExitCode);
Assert.Equal(["root-stdout"], stdout.ToArray());
Assert.Equal(["root-stderr-without-newline"], stderr.ToArray());
Assert.False(descendant.HasExited);
}
finally
{
if (descendantPipe.IsConnected)
{
try
{
await descendantPipe.WriteAsync(new byte[] { 1 });
}
catch (IOException)
{
// The descendant may already have exited after an earlier test failure.
}
}
if (descendant is not null)
{
try
{
await descendant.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10));
}
catch (TimeoutException)
{
if (!descendant.HasExited)
{
descendant.Kill();
}
}
descendant.Dispose();
}
await disposable.DisposeAsync();
root?.Dispose();
}
}
private static ProcessSpec CreateSingleLineOutputProcessSpec(TemporaryWorkspace workspace, Action<string> onOutputData, Action<int> onStart)
{
var appPath = DotnetFileAppProcess.WriteApp(workspace.WorkspaceRoot.FullName, "single-line.cs", """
#:sdk Microsoft.NET.Sdk
Console.WriteLine("final-line");
""");
return DotnetFileAppProcess.CreateDcpProcessSpec(appPath, onOutputData: onOutputData, onStart: onStart);
}
private static ProcessSpec CreateFailingProcessSpec(
TemporaryWorkspace workspace,
string[] lines,
bool emitSecondLineToStderr = false,
bool throwOnNonZeroReturnCode = true,
int? retainedOutputLineCount = null)
{
var appPath = DotnetFileAppProcess.WriteApp(workspace.WorkspaceRoot.FullName, "failing.cs", $$"""
#:sdk Microsoft.NET.Sdk
var lines = new[] { {{string.Join(", ", lines.Select(static line => JsonSerializer.Serialize(line)))}} };
var emitSecondLineToStderr = {{JsonSerializer.Serialize(emitSecondLineToStderr)}};
for (var i = 0; i < lines.Length; i++)
{
if (emitSecondLineToStderr && i == 1)
{
Console.Error.WriteLine(lines[i]);
}
else
{
Console.WriteLine(lines[i]);
}
}
Environment.Exit(1);
""");
return DotnetFileAppProcess.CreateDcpProcessSpec(
appPath,
throwOnNonZeroReturnCode: throwOnNonZeroReturnCode,
retainedOutputLineCount: retainedOutputLineCount);
}
}