Skip to content

Commit

Permalink
map testcontainers to random available host port (#5462)
Browse files Browse the repository at this point in the history
  • Loading branch information
StevenMassaro committed Jan 12, 2024
1 parent c83f582 commit 1f41d6a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
6 changes: 6 additions & 0 deletions liquibase-extension-testing/pom.xml
Expand Up @@ -90,6 +90,12 @@
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.29</version>
<scope>compile</scope>
</dependency>

</dependencies>

Expand Down
Expand Up @@ -12,6 +12,7 @@
import liquibase.extension.testing.testsystem.core.DB2TestSystem;
import liquibase.util.CollectionUtil;
import liquibase.util.StringUtil;
import org.springframework.test.util.TestSocketUtils;
import org.testcontainers.containers.JdbcDatabaseContainer;

import java.util.*;
Expand Down Expand Up @@ -116,6 +117,7 @@ protected void mapPorts(JdbcDatabaseContainer container) {
return returnValue;
}, false);

boolean shouldMapToRandomHostPort = ports == null;
if (ports == null) {
final List<Integer> exposedPorts = container.getExposedPorts();
ports = new int[exposedPorts.size()];
Expand All @@ -128,7 +130,11 @@ protected void mapPorts(JdbcDatabaseContainer container) {
if (ports != null) {
List<PortBinding> portBindings = new ArrayList<>();
for (int port : ports) {
portBindings.add(new PortBinding(Ports.Binding.bindPort(port), new ExposedPort(port)));
int hostPort = port;
if (shouldMapToRandomHostPort) {
hostPort = TestSocketUtils.findAvailableTcpPort();
}
portBindings.add(new PortBinding(Ports.Binding.bindPort(hostPort), new ExposedPort(port)));
}

container.withCreateContainerCmdModifier((Consumer<CreateContainerCmd>) cmd ->
Expand Down

0 comments on commit 1f41d6a

Please sign in to comment.