|
| 1 | +using DotNet.Testcontainers.Builders; |
| 2 | +using DotNet.Testcontainers.Containers; |
| 3 | +using Xunit; |
| 4 | + |
| 5 | +namespace NimblePros.SampleToDo.FunctionalTests.ClassFixtures; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// This class ensures that an SMTP server is running and shared between all tests in a specified class. |
| 9 | +/// </summary> |
| 10 | +public class SmtpServerFixture : IAsyncLifetime |
| 11 | +{ |
| 12 | + private const string SmtpServerImageName = "jijiechen/papercut:latest"; |
| 13 | + private const int SmtpServerListenPort = 25; |
| 14 | + |
| 15 | + private IContainer? _container; |
| 16 | + |
| 17 | + public async Task InitializeAsync() |
| 18 | + { |
| 19 | + _container = new ContainerBuilder() |
| 20 | + .WithName(Guid.NewGuid().ToString("D")) |
| 21 | + .WithImage(SmtpServerImageName) |
| 22 | + .WithPortBinding(SmtpServerListenPort, SmtpServerListenPort) |
| 23 | + .WithWaitStrategy( |
| 24 | + Wait |
| 25 | + .ForUnixContainer() |
| 26 | + .UntilMessageIsLogged("Server Ready", o => o.WithTimeout(TimeSpan.FromSeconds(30)))) |
| 27 | + .Build(); |
| 28 | + |
| 29 | + await _container.StartAsync().ConfigureAwait(false); |
| 30 | + } |
| 31 | + |
| 32 | + public async Task DisposeAsync() |
| 33 | + { |
| 34 | + if (_container != null) |
| 35 | + { |
| 36 | + await _container.StopAsync().ConfigureAwait(false); |
| 37 | + await _container.DisposeAsync().ConfigureAwait(false); |
| 38 | + _container = null; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Ensures that the container is running and healthy. |
| 44 | + /// </summary> |
| 45 | + /// <exception cref="InvalidOperationException"> |
| 46 | + /// Thrown when the SMTP server container was not created or is not running. |
| 47 | + /// This could be due to Docker not running or issues with the container image. |
| 48 | + /// In such cases, verify that Docker is running correctly. |
| 49 | + /// </exception> |
| 50 | + public void EnsureContainerIsRunning() |
| 51 | + { |
| 52 | + if (_container == null) |
| 53 | + { |
| 54 | + throw new InvalidOperationException("SMTP server container was not created. Ensure Docker is running and the container image is correct."); |
| 55 | + } |
| 56 | + |
| 57 | + if (_container.State != TestcontainersStates.Running) |
| 58 | + { |
| 59 | + throw new InvalidOperationException("The SMTP server container is not running. Please verify that the SMTP server image is correctly configured and that Docker is functioning properly."); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments