|
| 1 | +using DotNet.Testcontainers.Containers; |
| 2 | +using Npgsql; |
| 3 | +using System; |
| 4 | +using System.Diagnostics; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Testcontainers.PostgreSql; |
| 7 | + |
| 8 | +namespace NpgsqlBenchmark.Helpers |
| 9 | +{ |
| 10 | + internal static class ContainerHelpers |
| 11 | + { |
| 12 | + /// <summary> |
| 13 | + /// Wait untill container start |
| 14 | + /// </summary> |
| 15 | + public static async ValueTask WaitContainerStateRunningAsync(this DockerContainer dockerContainer, TimeSpan timeout) |
| 16 | + { |
| 17 | + var sw = Stopwatch.StartNew(); |
| 18 | + while (true) |
| 19 | + { |
| 20 | + if (dockerContainer.State == TestcontainersStates.Running) |
| 21 | + { |
| 22 | + break; |
| 23 | + } |
| 24 | + |
| 25 | + if (sw.Elapsed >= timeout) |
| 26 | + { |
| 27 | + throw new Exception($"Container start timeout ({timeout}) exceeded, benchmark stopped, current container state is {dockerContainer.State}."); |
| 28 | + } |
| 29 | + |
| 30 | + await Task.Delay(100); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Wait until the container responds to at least one request |
| 36 | + /// </summary> |
| 37 | + public static async ValueTask WaitResponseAsync(this PostgreSqlContainer container, TimeSpan timeout) |
| 38 | + { |
| 39 | + var sw = Stopwatch.StartNew(); |
| 40 | + while (true) |
| 41 | + { |
| 42 | + if (sw.Elapsed >= timeout) |
| 43 | + { |
| 44 | + throw new Exception($"Postgres has not responded to any queries in {timeout}. Container state {container.State}"); |
| 45 | + } |
| 46 | + |
| 47 | + var connectionString = container.GetConnectionString(); |
| 48 | + try |
| 49 | + { |
| 50 | + await using (var conn = new NpgsqlConnection(connectionString)) |
| 51 | + { |
| 52 | + await conn.OpenAsync(); |
| 53 | + await using var command = conn.CreateCommand(); |
| 54 | + command.CommandText = "SELECT 1"; |
| 55 | + var result = await command.ExecuteScalarAsync(); |
| 56 | + if (result is int value && value == 1) |
| 57 | + { |
| 58 | + break; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + catch |
| 63 | + { |
| 64 | + // игнорим |
| 65 | + } |
| 66 | + |
| 67 | + await Task.Delay(100); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments