testcontainers / testcontainers-dotnet

A library to support tests with throwaway instances of Docker containers for all compatible .NET Standard versions.
https://dotnet.testcontainers.org
MIT License
3.82k stars 278 forks source link

[Enhancement]: extension method to throw on errors for the MsSqlContainer #1280

Open riezebosch opened 1 month ago

riezebosch commented 1 month ago

Problem

When setting up an environment for integration tests I found out that I was lacking feedback because the ExecScriptAsync silently fails.

Solution

I've created this small extension method to enhance the ExecScriptAsync a little:

public static async Task<ExecResult> ThrowOnError(this Task<ExecResult> task)
{
    var result = await task;
    if (result.ExitCode != 0)
    {
        throw new Exception(result.Stderr);
    }
    return result;
}

Benefit

It makes working with query (in your integration tests) a bit easier because you get immediate feedback:

await connection.ExecScriptAsync($"""
                                  CREATE TABLE {table} (
                                    Id int NOT NULL PRIMARY KEY IDENTITY(1, 1),
                                    Data varchar(8001)
                                  );
                                  """).ThrowOnError();

Output:

System.Exception: Msg 131, Level 15, State 2, Server 85186a74865e, Line 3

System.Exception
Msg 131, Level 15, State 2, Server 85186a74865e, Line 3
The size (8001) given to the column 'Data' exceeds the maximum allowed for any data type (8000).

Alternatives

make the ExecScriptAsync fail or have an overload to do so.

Would you like to help contributing this enhancement?

Yes