From 94b6e23ac2eddf158099ff648fe40a6d3022c286 Mon Sep 17 00:00:00 2001 From: Dimitris Zenios Date: Sat, 31 Oct 2026 13:59:22 +0200 Subject: [PATCH 1/3] Start again on another port when a detected port is taken before the server binds it A detected port is free only until the server binds it, after initdb, and something else can take it in between. Builder.start() now tries up to 3 times, with a new port and temporary directory, when the failed port really is taken. A port or data directory set by the caller, or a failure with the port still free, fails as before. A failed start now closes the instance, releasing its lock and removing its data directory. --- .../postgres/embedded/EmbeddedPostgres.java | 49 +++++++++++++++---- .../embedded/EmbeddedPostgresTest.java | 37 ++++++++++++++ 2 files changed, 77 insertions(+), 9 deletions(-) diff --git a/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java b/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java index b49c6f42..3f2e35cb 100644 --- a/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java +++ b/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java @@ -167,7 +167,12 @@ public class EmbeddedPostgres implements Closeable dataDirectoryCustomizer.accept(dataDirectory); } - this.process = startPostmaster(); + try { + this.process = startPostmaster(); + } catch (IOException e) { + close(); + throw e; + } } public Process getProcess() { @@ -508,6 +513,8 @@ public static class Builder private final Map localeConfig = new HashMap<>(); private boolean builderCleanDataDirectory = true; private boolean builderRegisterShutdownHook = true; + private static final int START_ATTEMPTS = 3; + private int builderPort = 0; private final Map connectConfig = new HashMap<>(); private PgBinaryResolver pgBinaryResolver = DefaultPostgresBinaryResolver.INSTANCE; @@ -602,16 +609,40 @@ public Builder setDataDirectoryCustomizer(final Consumer dataDirectoryCust } public EmbeddedPostgres start() throws IOException { - if (builderPort == 0) - { - builderPort = detectPort(); + final boolean detectedPort = builderPort == 0; + final boolean temporaryDirectory = builderDataDirectory == null; + for (int attempt = 1; ; attempt++) { + if (detectedPort) { + builderPort = nextPort(); + } + if (temporaryDirectory) { + builderDataDirectory = Files.createTempDirectory("epg").toFile(); + } + try { + return new EmbeddedPostgres(parentDirectory, builderDataDirectory, builderCleanDataDirectory, builderRegisterShutdownHook, + config, localeConfig, builderPort, connectConfig, pgBinaryResolver, errRedirector, outRedirector, + pgStartupWait, overrideWorkingDirectory, dataDirectoryCustomizer); + } catch (IOException e) { + // A detected port is only free until the server binds it, after initdb: something else can take it + // in between. A failure with the port still free is not that, and is not worth waiting for again. + if (!detectedPort || !temporaryDirectory || attempt == START_ATTEMPTS || !isTaken(builderPort)) { + throw e; + } + LOG.warn("Port {} was taken before the server could bind it, starting again on another", builderPort); + } } - if (builderDataDirectory == null) { - builderDataDirectory = Files.createTempDirectory("epg").toFile(); + } + + int nextPort() throws IOException { + return detectPort(); + } + + private static boolean isTaken(int port) { + try (ServerSocket ignored = new ServerSocket(port)) { + return false; + } catch (IOException e) { + return true; } - return new EmbeddedPostgres(parentDirectory, builderDataDirectory, builderCleanDataDirectory, builderRegisterShutdownHook, - config, localeConfig, builderPort, connectConfig, pgBinaryResolver, errRedirector, outRedirector, - pgStartupWait, overrideWorkingDirectory, dataDirectoryCustomizer); } @Override diff --git a/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java b/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java index 7af761eb..cd092388 100644 --- a/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java +++ b/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java @@ -15,15 +15,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; +import java.net.ServerSocket; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -73,4 +78,36 @@ public void testEmbeddedPgCreationWithNestedDataDirectory() throws Exception } } } + + @Test + public void testDetectedPortTakenBeforeTheServerBindsItStartsOnAnother() throws Exception { + try (ServerSocket taken = new ServerSocket(0)) { + AtomicInteger detections = new AtomicInteger(); + EmbeddedPostgres.Builder builder = new EmbeddedPostgres.Builder() { + @Override + int nextPort() throws IOException { + return detections.getAndIncrement() == 0 ? taken.getLocalPort() : super.nextPort(); + } + }; + try (EmbeddedPostgres pg = builder.setPGStartupWait(Duration.ofSeconds(5)).start(); + Connection connection = pg.getPostgresDatabase().getConnection(); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("SELECT 1")) { + assertTrue(result.next()); + assertEquals(1, result.getInt(1)); + assertNotEquals(taken.getLocalPort(), pg.getPort()); + assertEquals(2, detections.get()); + } + } + } + + @Test + public void testAPortAskedForAndTakenFailsWithoutAnotherAttempt() throws Exception { + try (ServerSocket taken = new ServerSocket(0)) { + assertThrows(IOException.class, () -> EmbeddedPostgres.builder() + .setPort(taken.getLocalPort()) + .setPGStartupWait(Duration.ofSeconds(2)) + .start()); + } + } } From f1bfcc806c5c77601b947a201168c0ae58e0e712 Mon Sep 17 00:00:00 2001 From: Dimitris Zenios Date: Sat, 14 Nov 2026 18:25:25 +0200 Subject: [PATCH 2/3] Start again on another port when another instance's server answers on the detected one When another instance took the detected port first, this instance's postmaster cannot bind it and exits, but the other instance's server answers the readiness check: start() returned an instance whose connections reached another cluster, and closing it would not stop that server. The readiness check now also requires the server to serve this instance's data directory; one that does not fails the attempt at once, and the port being taken starts it again on another, as when anything else holds the port. --- .../postgres/embedded/EmbeddedPostgres.java | 23 ++++++++++++++ .../embedded/EmbeddedPostgresTest.java | 30 +++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java b/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java index 3f2e35cb..b137f27d 100644 --- a/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java +++ b/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java @@ -339,6 +339,7 @@ private void waitForServerStartup(StopWatch watch) throws IOException while (System.nanoTime() - start < maxWaitNs) { try { verifyReady(); + verifyOwnCluster(); LOG.info("{} postmaster startup finished in {}", instanceId, watch); return; } catch (final SQLException e) { @@ -356,6 +357,28 @@ private void waitForServerStartup(StopWatch watch) throws IOException throw new IOException("Gave up waiting for server to start after " + pgStartupWait.toMillis() + "ms", lastCause); } + /** + * The server answering on this instance's port must serve its data directory. When another instance took the port + * first, this one's postmaster could not bind it and exited, and the other's server answers instead: using it would + * run against another cluster, and closing this instance would not stop it. + */ + private void verifyOwnCluster() throws SQLException, IOException + { + final String served; + try (Connection c = getPostgresDatabase().getConnection() ; + Statement s = c.createStatement() ; + ResultSet rs = s.executeQuery("SHOW data_directory")) + { + if (!rs.next()) { + throw new IllegalStateException("expecting single row"); + } + served = rs.getString(1); + } + if (!new File(served).getCanonicalFile().equals(dataDirectory.getCanonicalFile())) { + throw new IOException("Port " + port + " is served by another cluster, of data directory " + served + ", not " + dataDirectory); + } + } + private void verifyReady() throws SQLException { final InetAddress localhost = InetAddress.getLoopbackAddress(); diff --git a/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java b/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java index cd092388..ea0aac55 100644 --- a/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java +++ b/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java @@ -101,6 +101,36 @@ int nextPort() throws IOException { } } + @Test + public void testDetectedPortServedByAnotherInstanceStartsOnAnotherAndLeavesItRunning() throws Exception { + try (EmbeddedPostgres other = EmbeddedPostgres.builder().start()) { + String otherDirectory = dataDirectory(other); + AtomicInteger detections = new AtomicInteger(); + EmbeddedPostgres.Builder builder = new EmbeddedPostgres.Builder() { + @Override + int nextPort() throws IOException { + return detections.getAndIncrement() == 0 ? other.getPort() : super.nextPort(); + } + }; + try (EmbeddedPostgres pg = builder.setPGStartupWait(Duration.ofSeconds(5)).start()) { + assertNotEquals(other.getPort(), pg.getPort()); + assertEquals(2, detections.get()); + assertNotEquals(otherDirectory, dataDirectory(pg)); + } + // The failed attempt did not stop the instance whose server answered on its port + assertEquals(otherDirectory, dataDirectory(other)); + } + } + + private static String dataDirectory(EmbeddedPostgres pg) throws Exception { + try (Connection connection = pg.getPostgresDatabase().getConnection(); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("SHOW data_directory")) { + assertTrue(result.next()); + return result.getString(1); + } + } + @Test public void testAPortAskedForAndTakenFailsWithoutAnotherAttempt() throws Exception { try (ServerSocket taken = new ServerSocket(0)) { From 26fb365b004d73d84f80571512e4fa5b45e23418 Mon Sep 17 00:00:00 2001 From: Dimitris Zenios Date: Mon, 23 Nov 2026 22:59:35 +0200 Subject: [PATCH 3/3] Retry only the server start, on the same data directory, and stop waiting once pg_ctl failed Per review: the retry moves from Builder.start() into startPostmaster(). When no port is set, a free port is chosen just before pg_ctl start; a failed start is stopped and started again on another port, on the same data directory, up to 3 times, so initdb, the temporary directory and the lock are not redone, and the shutdown hook is registered once, after the loop. A port set by the caller fails as before, without another attempt. waitForServerStartup() takes the pg_ctl process and fails as soon as pg_ctl failed, so a failed attempt takes milliseconds, not pgStartupWait. It connects only once pg_ctl -w start has exited: before that a connection can reach whatever else listens on the port and wait seconds for an answer. With retries this cheap, any failure is retried and isTaken() is gone. The data_directory check is part of the readiness query, the constructor cleans up on a RuntimeException too, and the tests no longer shorten pgStartupWait and check that a failed attempt is fast. --- .../postgres/embedded/EmbeddedPostgres.java | 146 +++++++++--------- .../embedded/EmbeddedPostgresTest.java | 35 +++-- 2 files changed, 94 insertions(+), 87 deletions(-) diff --git a/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java b/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java index b137f27d..76ac2888 100644 --- a/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java +++ b/src/main/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgres.java @@ -89,13 +89,15 @@ public class EmbeddedPostgres implements Closeable private static final String PG_SUPERUSER = "postgres"; private static final Duration DEFAULT_PG_STARTUP_WAIT = Duration.ofSeconds(10); private static final String LOCK_FILE_NAME = "epg-lock"; + private static final int START_ATTEMPTS = 3; private final File pgDir; private final Duration pgStartupWait; private final File dataDirectory, lockFile; private final UUID instanceId = UUID.randomUUID(); - private final int port; + private final PortChooser portChooser; + private int port; private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean closed = new AtomicBoolean(); @@ -117,14 +119,14 @@ public class EmbeddedPostgres implements Closeable PgBinaryResolver pgBinaryResolver, ProcessBuilder.Redirect errorRedirector, ProcessBuilder.Redirect outputRedirector) throws IOException { this(parentDirectory, dataDirectory, cleanDataDirectory, registerShutdownHook, postgresConfig, localeConfig, port, connectConfig, - pgBinaryResolver, errorRedirector, outputRedirector, DEFAULT_PG_STARTUP_WAIT, null, null); + pgBinaryResolver, errorRedirector, outputRedirector, DEFAULT_PG_STARTUP_WAIT, null, null, EmbeddedPostgres::detectPort); } EmbeddedPostgres(File parentDirectory, File dataDirectory, boolean cleanDataDirectory, boolean registerShutdownHook, Map postgresConfig, Map localeConfig, int port, Map connectConfig, PgBinaryResolver pgBinaryResolver, ProcessBuilder.Redirect errorRedirector, ProcessBuilder.Redirect outputRedirector, Duration pgStartupWait, - File overrideWorkingDirectory, Consumer dataDirectoryCustomizer) throws IOException + File overrideWorkingDirectory, Consumer dataDirectoryCustomizer, PortChooser portChooser) throws IOException { this.cleanDataDirectory = cleanDataDirectory; this.registerShutdownHook = registerShutdownHook; @@ -132,6 +134,7 @@ public class EmbeddedPostgres implements Closeable this.localeConfig = new HashMap<>(localeConfig); this.connectConfig = new HashMap<>(connectConfig); this.port = port; + this.portChooser = portChooser; this.pgDir = prepareBinaries(pgBinaryResolver, overrideWorkingDirectory); this.errorRedirector = errorRedirector; this.outputRedirector = outputRedirector; @@ -169,7 +172,7 @@ public class EmbeddedPostgres implements Closeable try { this.process = startPostmaster(); - } catch (IOException e) { + } catch (IOException | RuntimeException e) { close(); throw e; } @@ -277,6 +280,39 @@ private Process startPostmaster() throws IOException throw new IllegalStateException("Postmaster already started"); } + // A chosen port is only free until the server binds it, and something else can take it in between: then the + // server is started again, on the same data directory, on another port. A port set by the caller is not changed. + final boolean choosePort = port == 0; + Process pgCtl; + for (int attempt = 1; ; attempt++) { + if (choosePort) { + port = portChooser.choosePort(); + } + pgCtl = startPgCtl(); + try { + waitForServerStartup(watch, pgCtl); + break; + } catch (IOException e) { + if (!choosePort || attempt == START_ATTEMPTS) { + throw e; + } + LOG.warn("{} server did not start on port {} ({}), starting again on another", instanceId, port, e.getMessage()); + try { + pgCtl(dataDirectory, "stop"); + } catch (RuntimeException stopFailure) { + LOG.trace("No server to stop", stopFailure); + } + } + } + + if (registerShutdownHook) { + Runtime.getRuntime().addShutdownHook(newCloserThread()); + } + return pgCtl; + } + + private Process startPgCtl() throws IOException + { final List args = new ArrayList<>(); args.addAll(Arrays.asList( "-D", dataDirectory.getPath(), @@ -297,12 +333,6 @@ private Process startPostmaster() throws IOException } LOG.info("{} postmaster started as {} on port {}. Waiting up to {} for server startup to finish.", instanceId, postmaster.toString(), port, pgStartupWait); - - if (registerShutdownHook) { - Runtime.getRuntime().addShutdownHook(newCloserThread()); - } - - waitForServerStartup(watch); return postmaster; } @@ -331,20 +361,26 @@ private List createLocaleOptions() return localeOptions; } - private void waitForServerStartup(StopWatch watch) throws IOException + private void waitForServerStartup(StopWatch watch, Process pgCtl) throws IOException { Throwable lastCause = null; final long start = System.nanoTime(); final long maxWaitNs = TimeUnit.NANOSECONDS.convert(pgStartupWait.toMillis(), TimeUnit.MILLISECONDS); while (System.nanoTime() - start < maxWaitNs) { - try { - verifyReady(); - verifyOwnCluster(); - LOG.info("{} postmaster startup finished in {}", instanceId, watch); - return; - } catch (final SQLException e) { - lastCause = e; - LOG.trace("While waiting for server startup", e); + if (!pgCtl.isAlive() && pgCtl.exitValue() != 0) { + throw new IOException("pg_ctl failed with exit code " + pgCtl.exitValue(), lastCause); + } + // pg_ctl -w start exits once the server is ready, or once it failed, as on a taken port. Until then a + // connection can reach whatever else listens on the port, and wait seconds for an answer that never comes. + if (!pgCtl.isAlive()) { + try { + verifyReady(); + LOG.info("{} postmaster startup finished in {}", instanceId, watch); + return; + } catch (final SQLException e) { + lastCause = e; + LOG.trace("While waiting for server startup", e); + } } try { @@ -358,28 +394,11 @@ private void waitForServerStartup(StopWatch watch) throws IOException } /** - * The server answering on this instance's port must serve its data directory. When another instance took the port - * first, this one's postmaster could not bind it and exited, and the other's server answers instead: using it would - * run against another cluster, and closing this instance would not stop it. + * The server answering on this instance's port must also serve its data directory: the postmaster starts when it + * can bind any of its addresses, so another instance's server can still answer on the one connected to. Using it + * would run against another cluster, and closing this instance would not stop it. */ - private void verifyOwnCluster() throws SQLException, IOException - { - final String served; - try (Connection c = getPostgresDatabase().getConnection() ; - Statement s = c.createStatement() ; - ResultSet rs = s.executeQuery("SHOW data_directory")) - { - if (!rs.next()) { - throw new IllegalStateException("expecting single row"); - } - served = rs.getString(1); - } - if (!new File(served).getCanonicalFile().equals(dataDirectory.getCanonicalFile())) { - throw new IOException("Port " + port + " is served by another cluster, of data directory " + served + ", not " + dataDirectory); - } - } - - private void verifyReady() throws SQLException + private void verifyReady() throws SQLException, IOException { final InetAddress localhost = InetAddress.getLoopbackAddress(); try (Socket sock = new Socket()) { @@ -388,9 +407,10 @@ private void verifyReady() throws SQLException } catch (final IOException e) { throw new SQLException("connect failed", e); } + final String served; try (Connection c = getPostgresDatabase().getConnection() ; Statement s = c.createStatement() ; - ResultSet rs = s.executeQuery("SELECT 1")) + ResultSet rs = s.executeQuery("SELECT 1, current_setting('data_directory')")) { if (!rs.next()) { throw new IllegalStateException("expecting single row"); @@ -398,10 +418,14 @@ private void verifyReady() throws SQLException if (1 != rs.getInt(1)) { throw new IllegalStateException("expecting 1"); } + served = rs.getString(2); if (rs.next()) { throw new IllegalStateException("expecting single row"); } } + if (!new File(served).getCanonicalFile().equals(dataDirectory.getCanonicalFile())) { + throw new IOException("Port " + port + " is served by another cluster, of data directory " + served + ", not " + dataDirectory); + } } private Thread newCloserThread() @@ -536,8 +560,6 @@ public static class Builder private final Map localeConfig = new HashMap<>(); private boolean builderCleanDataDirectory = true; private boolean builderRegisterShutdownHook = true; - private static final int START_ATTEMPTS = 3; - private int builderPort = 0; private final Map connectConfig = new HashMap<>(); private PgBinaryResolver pgBinaryResolver = DefaultPostgresBinaryResolver.INSTANCE; @@ -632,42 +654,18 @@ public Builder setDataDirectoryCustomizer(final Consumer dataDirectoryCust } public EmbeddedPostgres start() throws IOException { - final boolean detectedPort = builderPort == 0; - final boolean temporaryDirectory = builderDataDirectory == null; - for (int attempt = 1; ; attempt++) { - if (detectedPort) { - builderPort = nextPort(); - } - if (temporaryDirectory) { - builderDataDirectory = Files.createTempDirectory("epg").toFile(); - } - try { - return new EmbeddedPostgres(parentDirectory, builderDataDirectory, builderCleanDataDirectory, builderRegisterShutdownHook, - config, localeConfig, builderPort, connectConfig, pgBinaryResolver, errRedirector, outRedirector, - pgStartupWait, overrideWorkingDirectory, dataDirectoryCustomizer); - } catch (IOException e) { - // A detected port is only free until the server binds it, after initdb: something else can take it - // in between. A failure with the port still free is not that, and is not worth waiting for again. - if (!detectedPort || !temporaryDirectory || attempt == START_ATTEMPTS || !isTaken(builderPort)) { - throw e; - } - LOG.warn("Port {} was taken before the server could bind it, starting again on another", builderPort); - } + if (builderDataDirectory == null) { + builderDataDirectory = Files.createTempDirectory("epg").toFile(); } + return new EmbeddedPostgres(parentDirectory, builderDataDirectory, builderCleanDataDirectory, builderRegisterShutdownHook, + config, localeConfig, builderPort, connectConfig, pgBinaryResolver, errRedirector, outRedirector, + pgStartupWait, overrideWorkingDirectory, dataDirectoryCustomizer, this::nextPort); } int nextPort() throws IOException { return detectPort(); } - private static boolean isTaken(int port) { - try (ServerSocket ignored = new ServerSocket(port)) { - return false; - } catch (IOException e) { - return true; - } - } - @Override public boolean equals(Object o) { if (this == o) { @@ -981,4 +979,8 @@ public void applyTo(ProcessBuilder builder, List arguments) { builder.command(command); } } + + interface PortChooser { + int choosePort() throws IOException; + } } diff --git a/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java b/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java index ea0aac55..95f9f223 100644 --- a/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java +++ b/src/test/java/io/zonky/test/db/postgres/embedded/EmbeddedPostgresTest.java @@ -28,6 +28,8 @@ import java.sql.ResultSet; import java.sql.Statement; import java.time.Duration; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; @@ -82,21 +84,25 @@ public void testEmbeddedPgCreationWithNestedDataDirectory() throws Exception @Test public void testDetectedPortTakenBeforeTheServerBindsItStartsOnAnother() throws Exception { try (ServerSocket taken = new ServerSocket(0)) { - AtomicInteger detections = new AtomicInteger(); + List detections = new ArrayList<>(); EmbeddedPostgres.Builder builder = new EmbeddedPostgres.Builder() { @Override int nextPort() throws IOException { - return detections.getAndIncrement() == 0 ? taken.getLocalPort() : super.nextPort(); + detections.add(System.nanoTime()); + return detections.size() == 1 ? taken.getLocalPort() : super.nextPort(); } }; - try (EmbeddedPostgres pg = builder.setPGStartupWait(Duration.ofSeconds(5)).start(); + try (EmbeddedPostgres pg = builder.start(); Connection connection = pg.getPostgresDatabase().getConnection(); Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT 1")) { assertTrue(result.next()); assertEquals(1, result.getInt(1)); assertNotEquals(taken.getLocalPort(), pg.getPort()); - assertEquals(2, detections.get()); + assertEquals(2, detections.size()); + // The failed attempt ends when pg_ctl fails, without waiting out the startup wait (10 s by default) + Duration failedAttempt = Duration.ofNanos(detections.get(1) - detections.get(0)); + assertTrue(failedAttempt.compareTo(Duration.ofSeconds(5)) < 0, "the failed attempt took " + failedAttempt); } } } @@ -112,7 +118,7 @@ int nextPort() throws IOException { return detections.getAndIncrement() == 0 ? other.getPort() : super.nextPort(); } }; - try (EmbeddedPostgres pg = builder.setPGStartupWait(Duration.ofSeconds(5)).start()) { + try (EmbeddedPostgres pg = builder.start()) { assertNotEquals(other.getPort(), pg.getPort()); assertEquals(2, detections.get()); assertNotEquals(otherDirectory, dataDirectory(pg)); @@ -122,22 +128,21 @@ int nextPort() throws IOException { } } - private static String dataDirectory(EmbeddedPostgres pg) throws Exception { - try (Connection connection = pg.getPostgresDatabase().getConnection(); - Statement statement = connection.createStatement(); - ResultSet result = statement.executeQuery("SHOW data_directory")) { - assertTrue(result.next()); - return result.getString(1); - } - } - @Test public void testAPortAskedForAndTakenFailsWithoutAnotherAttempt() throws Exception { try (ServerSocket taken = new ServerSocket(0)) { assertThrows(IOException.class, () -> EmbeddedPostgres.builder() .setPort(taken.getLocalPort()) - .setPGStartupWait(Duration.ofSeconds(2)) .start()); } } + + private static String dataDirectory(EmbeddedPostgres pg) throws Exception { + try (Connection connection = pg.getPostgresDatabase().getConnection(); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("SHOW data_directory")) { + assertTrue(result.next()); + return result.getString(1); + } + } }