-
-
Notifications
You must be signed in to change notification settings - Fork 341
feat: Add Task<ExecResult> extension method ThrowOnFailure
#1448
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
HofmeisterAn
merged 1 commit into
develop
from
feature/add-exec-result-extensions-throw-on-failure
May 17, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | ||
| } | ||
|
|
||
| return exceptionInfo.ToString(); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could've used |
||
|
|
||
| var execResult = await execTask | ||
| .ConfigureAwait(false); | ||
|
|
||
| if (Array.IndexOf(successExitCodes, execResult.ExitCode) < 0) | ||
| { | ||
| throw new ExecFailedException(execResult); | ||
| } | ||
|
|
||
| return execResult; | ||
| } | ||
| } | ||
| } | ||
50 changes: 50 additions & 0 deletions
50
tests/Testcontainers.Platform.Linux.Tests/ExecFailedExceptionTest.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } |
50 changes: 50 additions & 0 deletions
50
tests/Testcontainers.Platform.Linux.Tests/ExecResultExtensionsTest.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?