|
| 1 | +using System.Data.Common; |
| 2 | +using DotNet.Testcontainers.Builders; |
| 3 | +using DotNet.Testcontainers.Containers; |
| 4 | + |
| 5 | +namespace HealthChecks.SurrealDb.Tests; |
| 6 | + |
| 7 | +public class SurrealDbContainerFixture : IAsyncLifetime |
| 8 | +{ |
| 9 | + private const string Registry = "docker.io"; |
| 10 | + |
| 11 | + private const string Image = "surrealdb/surrealdb"; |
| 12 | + |
| 13 | + private const string Tag = "v2.3.7"; |
| 14 | + |
| 15 | + private const int Port = 8000; |
| 16 | + |
| 17 | + private const string Username = "root"; |
| 18 | + |
| 19 | + private const string Password = "root"; |
| 20 | + |
| 21 | + public IContainer? Container { get; private set; } |
| 22 | + |
| 23 | + public string GetConnectionString() |
| 24 | + { |
| 25 | + if (Container is null) |
| 26 | + { |
| 27 | + throw new InvalidOperationException("The test container was not initialized."); |
| 28 | + } |
| 29 | + |
| 30 | + string endpoint = new UriBuilder("http", Container.Hostname, Container.GetMappedPublicPort(Port)).ToString(); |
| 31 | + |
| 32 | + var builder = new DbConnectionStringBuilder |
| 33 | + { |
| 34 | + { "Server", endpoint }, |
| 35 | + { "Username", Username }, |
| 36 | + { "Password", Password } |
| 37 | + }; |
| 38 | + |
| 39 | + return builder.ConnectionString; |
| 40 | + } |
| 41 | + |
| 42 | + public async Task InitializeAsync() => Container = await CreateContainerAsync(); |
| 43 | + |
| 44 | + public Task DisposeAsync() => Container?.DisposeAsync().AsTask() ?? Task.CompletedTask; |
| 45 | + |
| 46 | + private static async Task<IContainer> CreateContainerAsync() |
| 47 | + { |
| 48 | + var waitStrategy = Wait |
| 49 | + .ForUnixContainer() |
| 50 | + .UntilHttpRequestIsSucceeded(x => x.ForPath("/health").ForPort(Port)); |
| 51 | + |
| 52 | + var container = new ContainerBuilder() |
| 53 | + .WithImage($"{Registry}/{Image}:{Tag}") |
| 54 | + .WithPortBinding(Port, true) |
| 55 | + .WithCommand("start", "--user", Username, "--pass", Password, "memory") |
| 56 | + .WithWaitStrategy(waitStrategy) |
| 57 | + .Build(); |
| 58 | + |
| 59 | + await container.StartAsync(); |
| 60 | + |
| 61 | + return container; |
| 62 | + } |
| 63 | +} |
0 commit comments