Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions src/Testcontainers/Containers/ExecFailedException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
namespace DotNet.Testcontainers.Containers
{
using System;
using System.Linq;
using System.Text;
using JetBrains.Annotations;

/// <summary>
/// Represents an exception that is thrown when executing a command inside a
/// running container fails.
/// </summary>
[PublicAPI]
public sealed class ExecFailedException : Exception
{
private static readonly string[] LineEndings = new[] { "\r\n", "\n" };

/// <summary>
/// Initializes a new instance of the <see cref="ExecFailedException" /> class.
/// </summary>
/// <param name="execResult">The result of the failed command execution.</param>
public ExecFailedException(ExecResult execResult)
: base(CreateMessage(execResult))
{
ExecResult = execResult;
}

/// <summary>
/// Gets the result of the failed command execution inside the container.
/// </summary>
public ExecResult ExecResult { get; }

private static string CreateMessage(ExecResult execResult)
{
var exceptionInfo = new StringBuilder(256);
exceptionInfo.Append($"Process exited with code {execResult.ExitCode}.");

if (!string.IsNullOrEmpty(execResult.Stdout))
{
var stdoutLines = execResult.Stdout
.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries)
.Select(line => " " + line);

exceptionInfo.AppendLine();
exceptionInfo.AppendLine(" Stdout: ");
exceptionInfo.Append(string.Join(Environment.NewLine, stdoutLines));
}

if (!string.IsNullOrEmpty(execResult.Stderr))
{
var stderrLines = execResult.Stderr
.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries)
.Select(line => " " + line);

exceptionInfo.AppendLine();
exceptionInfo.AppendLine(" Stderr: ");
exceptionInfo.Append(string.Join(Environment.NewLine, stderrLines));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why combine StringBuilder with linq?

}

return exceptionInfo.ToString();
}
}
}
33 changes: 33 additions & 0 deletions src/Testcontainers/Containers/ExecResultExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
namespace DotNet.Testcontainers.Containers
{
using System;
using System.Threading.Tasks;

/// <summary>
/// Extension methods for working with <see cref="ExecResult" /> instances.
/// </summary>
public static class ExecResultExtensions
{
/// <summary>
/// Awaits the <see cref="Task{ExecResult}" /> and throws an exception if the result's exit code is not successful.
/// </summary>
/// <param name="execTask">The task returning an <see cref="ExecResult" />.</param>
/// <param name="successExitCodes">A list of exit codes that should be treated as successful. If none are provided, only exit code <c>0</c> is treated as successful.</param>
/// <returns>The <see cref="ExecResult" /> if the exit code is in the list of success exit codes.</returns>
/// <exception cref="ExecFailedException">Thrown if the exit code is not in the list of success exit codes.</exception>
public static async Task<ExecResult> ThrowOnFailure(this Task<ExecResult> execTask, params long[] successExitCodes)
{
successExitCodes = successExitCodes == null || successExitCodes.Length == 0 ? new long[] { 0 } : successExitCodes;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could've used successExitCodes?.Any() here


var execResult = await execTask
.ConfigureAwait(false);

if (Array.IndexOf(successExitCodes, execResult.ExitCode) < 0)
{
throw new ExecFailedException(execResult);
}

return execResult;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
namespace Testcontainers.Tests;

public sealed class ExecFailedExceptionTest
{
public static readonly List<TheoryDataRow<ExecResult, string>> ExecResultTestData
= new List<TheoryDataRow<ExecResult, string>>
{
new TheoryDataRow<ExecResult, string>
(
new ExecResult("Stdout\nStdout", "Stderr\nStderr", 1),
"Process exited with code 1." + Environment.NewLine +
" Stdout: " + Environment.NewLine +
" Stdout" + Environment.NewLine +
" Stdout" + Environment.NewLine +
" Stderr: " + Environment.NewLine +
" Stderr" + Environment.NewLine +
" Stderr"
),
new TheoryDataRow<ExecResult, string>
(
new ExecResult("Stdout\nStdout", string.Empty, 1),
"Process exited with code 1." + Environment.NewLine +
" Stdout: " + Environment.NewLine +
" Stdout" + Environment.NewLine +
" Stdout"
),
new TheoryDataRow<ExecResult, string>
(
new ExecResult(string.Empty, "Stderr\nStderr", 1),
"Process exited with code 1." + Environment.NewLine +
" Stderr: " + Environment.NewLine +
" Stderr" + Environment.NewLine +
" Stderr"
),
new TheoryDataRow<ExecResult, string>
(
new ExecResult(string.Empty, string.Empty, 1),
"Process exited with code 1."
),
};

[Theory]
[MemberData(nameof(ExecResultTestData))]
public void ExecFailedExceptionCreatesExpectedMessage(ExecResult execResult, string message)
{
var exception = new ExecFailedException(execResult);
Assert.Equal(execResult, exception.ExecResult);
Assert.Equal(message, exception.Message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
namespace Testcontainers.Tests;

public sealed class ExecResultExtensionsTest : IAsyncLifetime
{
private readonly IContainer _container = new ContainerBuilder()
.WithImage(CommonImages.Alpine)
.WithCommand(CommonCommands.SleepInfinity)
.Build();

public async ValueTask InitializeAsync()
{
await _container.StartAsync()
.ConfigureAwait(false);
}

public ValueTask DisposeAsync()
{
return _container.DisposeAsync();
}

[Fact]
public async Task ExecAsyncShouldSucceedWhenCommandReturnsZeroExitCode()
{
// Given
var command = new[] { "true" };

// When
var exception = await Record.ExceptionAsync(() => _container.ExecAsync(command, TestContext.Current.CancellationToken).ThrowOnFailure())
.ConfigureAwait(true);

// Then
Assert.Null(exception);
}

[Fact]
public async Task ExecAsyncShouldThrowExecFailedExceptionWhenCommandFails()
{
// Given
var command = new[] { "/bin/sh", "-c", "echo out; echo err >&2; exit 1" };

// When
var exception = await Assert.ThrowsAsync<ExecFailedException>(() => _container.ExecAsync(command, TestContext.Current.CancellationToken).ThrowOnFailure())
.ConfigureAwait(true);

// Then
Assert.Equal(1, exception.ExecResult.ExitCode);
Assert.Equal("out", exception.ExecResult.Stdout.Trim());
Assert.Equal("err", exception.ExecResult.Stderr.Trim());
}
}