|
| 1 | +namespace DotNet.Testcontainers.Tests.Unit |
| 2 | +{ |
| 3 | + using System; |
| 4 | + using System.Threading.Tasks; |
| 5 | + using DotNet.Testcontainers.Builders; |
| 6 | + using DotNet.Testcontainers.Commons; |
| 7 | + using DotNet.Testcontainers.Configurations; |
| 8 | + using DotNet.Testcontainers.Containers; |
| 9 | + using Xunit; |
| 10 | + |
| 11 | + public sealed class WaitUntilExternalTcpPortIsAvailable : IAsyncLifetime |
| 12 | + { |
| 13 | + private const ushort ListeningPort = 49152; |
| 14 | + |
| 15 | + private const ushort MappedPort = 49153; |
| 16 | + |
| 17 | + private const ushort UnmappedPort = 49154; |
| 18 | + |
| 19 | + private readonly IContainer _container = new ContainerBuilder() |
| 20 | + .WithImage(CommonImages.Socat) |
| 21 | + .WithCommand("-v") |
| 22 | + .WithCommand($"TCP-LISTEN:{ListeningPort},crlf,reuseaddr,fork") |
| 23 | + .WithCommand("EXEC:cat") |
| 24 | + .WithPortBinding(ListeningPort, true) |
| 25 | + .WithPortBinding(MappedPort, true) |
| 26 | + .WithWaitStrategy(Wait.ForUnixContainer().UntilExternalTcpPortIsAvailable(ListeningPort)) |
| 27 | + .Build(); |
| 28 | + |
| 29 | + public async ValueTask InitializeAsync() |
| 30 | + { |
| 31 | + await _container.StartAsync() |
| 32 | + .ConfigureAwait(false); |
| 33 | + } |
| 34 | + |
| 35 | + public ValueTask DisposeAsync() |
| 36 | + { |
| 37 | + return _container.DisposeAsync(); |
| 38 | + } |
| 39 | + |
| 40 | + [Fact] |
| 41 | + public async Task SucceedsWhenPortIsMappedAndListening() |
| 42 | + { |
| 43 | + // Given |
| 44 | + var waitStrategy = new UntilExternalTcpPortIsAvailable(ListeningPort); |
| 45 | + |
| 46 | + // When |
| 47 | + var success = await waitStrategy.UntilAsync(_container) |
| 48 | + .ConfigureAwait(true); |
| 49 | + |
| 50 | + // Then |
| 51 | + Assert.True(success); |
| 52 | + } |
| 53 | + |
| 54 | + [Fact] |
| 55 | + public async Task SucceedsWhenPortIsMappedButNotListening() |
| 56 | + { |
| 57 | + // Given |
| 58 | + var waitStrategy = new UntilExternalTcpPortIsAvailable(MappedPort); |
| 59 | + |
| 60 | + // When |
| 61 | + var success = await waitStrategy.UntilAsync(_container) |
| 62 | + .ConfigureAwait(true); |
| 63 | + |
| 64 | + // Then |
| 65 | + Assert.True(success); |
| 66 | + } |
| 67 | + |
| 68 | + [Fact] |
| 69 | + public Task ThrowsWhenPortIsNotMapped() |
| 70 | + { |
| 71 | + var waitStrategy = new UntilExternalTcpPortIsAvailable(UnmappedPort); |
| 72 | + return Assert.ThrowsAsync<InvalidOperationException>(() => waitStrategy.UntilAsync(_container)); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments