|
8 | 8 | import java.nio.file.Files; |
9 | 9 | import java.nio.file.Path; |
10 | 10 | import java.util.List; |
| 11 | +import java.util.regex.Matcher; |
| 12 | +import java.util.regex.Pattern; |
11 | 13 |
|
12 | 14 | import org.junit.jupiter.api.AfterAll; |
13 | 15 | import org.junit.jupiter.api.BeforeAll; |
14 | 16 | import org.junit.jupiter.api.Nested; |
15 | 17 | import org.junit.jupiter.api.Test; |
16 | 18 | import org.junit.jupiter.api.io.TempDir; |
17 | 19 | import org.testcontainers.containers.ContainerLaunchException; |
| 20 | +import org.testcontainers.containers.GenericContainer; |
| 21 | +import org.testcontainers.containers.Network; |
18 | 22 | import org.testcontainers.containers.PostgreSQLContainer; |
| 23 | +import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; |
19 | 24 | import org.testcontainers.utility.DockerImageName; |
20 | 25 |
|
21 | 26 | import de.cronn.assertions.validationfile.normalization.SimpleRegexReplacement; |
@@ -173,4 +178,34 @@ void testOtherPostgresVersion() { |
173 | 178 | compareActualWithValidationFile(schema); |
174 | 179 | } |
175 | 180 | } |
| 181 | + |
| 182 | + @Test |
| 183 | + void testConnectViaDockerContainerIpAddress() { |
| 184 | + String networkAlias = "postgres-db"; |
| 185 | + try (Network network = Network.newNetwork(); |
| 186 | + PostgreSQLContainer<?> postgresInNetworkContainer = createPostgresContainer(DockerImageName.parse("postgres:17.0")) |
| 187 | + .withNetwork(network) |
| 188 | + .withNetworkAliases(networkAlias)) { |
| 189 | + postgresInNetworkContainer.start(); |
| 190 | + |
| 191 | + String ipAddress = resolveHostname(network, networkAlias); |
| 192 | + |
| 193 | + String jdbcUrl = "jdbc:postgresql://%s/test-db".formatted(ipAddress); |
| 194 | + String schema = PostgresDump.dumpToString(jdbcUrl, USERNAME, PASSWORD); |
| 195 | + compareActualWithValidationFile(schema); |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + private String resolveHostname(Network network, String hostname) { |
| 200 | + try (GenericContainer<?> dnsContainer = new GenericContainer<>("alpine:3.20.3") |
| 201 | + .withNetwork(network) |
| 202 | + .withCommand("getent hosts " + hostname) |
| 203 | + .withStartupCheckStrategy(new OneShotStartupCheckStrategy())) { |
| 204 | + dnsContainer.start(); |
| 205 | + String logs = dnsContainer.getLogs(); |
| 206 | + Matcher matcher = Pattern.compile("(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+" + hostname + "\\s+" + hostname + "\\n").matcher(logs); |
| 207 | + assertThat(matcher.matches()).describedAs("Failed to parse '%s'", logs).isTrue(); |
| 208 | + return matcher.group(1); |
| 209 | + } |
| 210 | + } |
176 | 211 | } |
0 commit comments