From c931b23f296d8201925cb8904babf161b5d4d24d Mon Sep 17 00:00:00 2001 From: Nick Wiedenbrueck Date: Wed, 2 Oct 2019 18:07:03 +0200 Subject: [PATCH] Fix port conflict when running multiple unit tests in parallel --- .../hoverfly/junit/api/HoverflyClient.java | 59 ------ .../junit/api/HoverflyClientFactory.java | 12 ++ .../api/HoverflyOkHttpClientFactory.java | 75 ++++++++ .../specto/hoverfly/junit/core/Hoverfly.java | 168 ++++++++++-------- .../core/config/HoverflyConfigValidator.java | 20 --- ...a => HoverflyOkHttpClientFactoryTest.java} | 10 +- .../junit/core/HoverflyConfigTest.java | 2 - .../hoverfly/junit/core/HoverflyTest.java | 30 ++-- .../config/HoverflyConfigValidatorTest.java | 12 +- 9 files changed, 207 insertions(+), 181 deletions(-) create mode 100644 src/main/java/io/specto/hoverfly/junit/api/HoverflyClientFactory.java create mode 100644 src/main/java/io/specto/hoverfly/junit/api/HoverflyOkHttpClientFactory.java rename src/test/java/io/specto/hoverfly/junit/api/{HoverflyClientTest.java => HoverflyOkHttpClientFactoryTest.java} (87%) diff --git a/src/main/java/io/specto/hoverfly/junit/api/HoverflyClient.java b/src/main/java/io/specto/hoverfly/junit/api/HoverflyClient.java index 7f1d652c..88054fa4 100644 --- a/src/main/java/io/specto/hoverfly/junit/api/HoverflyClient.java +++ b/src/main/java/io/specto/hoverfly/junit/api/HoverflyClient.java @@ -7,7 +7,6 @@ import io.specto.hoverfly.junit.api.view.DiffView; import io.specto.hoverfly.junit.api.view.HoverflyInfoView; import io.specto.hoverfly.junit.api.view.StateView; -import io.specto.hoverfly.junit.core.HoverflyConstants; import io.specto.hoverfly.junit.core.HoverflyMode; import io.specto.hoverfly.junit.core.model.Journal; import io.specto.hoverfly.junit.core.model.Request; @@ -94,62 +93,4 @@ public interface HoverflyClient { */ boolean getHealth(); - /** - * Static factory method for creating a {@link Builder} - * @return a builder for HoverflyClient - */ - static Builder custom() { - return new Builder(); - } - - /** - * Static factory method for default Hoverfly client - * @return a default HoverflyClient - */ - static HoverflyClient createDefault() { - return new Builder().build(); - } - - /** - * HTTP client builder for Hoverfly admin API - */ - class Builder { - - private String scheme = HoverflyConstants.HTTP; - private String host = HoverflyConstants.LOCALHOST; - private int port = HoverflyConstants.DEFAULT_ADMIN_PORT; - private String authToken = null; - - Builder() { - } - - public Builder scheme(String scheme) { - this.scheme = scheme; - return this; - } - - public Builder host(String host) { - this.host = host; - return this; - } - - public Builder port(int port) { - this.port = port; - return this; - } - - /** - * Get token from environment variable "HOVERFLY_AUTH_TOKEN" to authenticate with admin API - * @return this Builder for further customizations - */ - public Builder withAuthToken() { - this.authToken = System.getenv(HoverflyConstants.HOVERFLY_AUTH_TOKEN); - return this; - } - - public HoverflyClient build() { - return new OkHttpHoverflyClient(scheme, host, port, authToken); - } - } - } diff --git a/src/main/java/io/specto/hoverfly/junit/api/HoverflyClientFactory.java b/src/main/java/io/specto/hoverfly/junit/api/HoverflyClientFactory.java new file mode 100644 index 00000000..5e851a4c --- /dev/null +++ b/src/main/java/io/specto/hoverfly/junit/api/HoverflyClientFactory.java @@ -0,0 +1,12 @@ +package io.specto.hoverfly.junit.api; + +import io.specto.hoverfly.junit.core.config.HoverflyConfiguration; + +/** + * Factory for creating {@link HoverflyClient}s + */ +public interface HoverflyClientFactory { + + HoverflyClient createHoverflyClient(HoverflyConfiguration hoverflyConfig); + +} diff --git a/src/main/java/io/specto/hoverfly/junit/api/HoverflyOkHttpClientFactory.java b/src/main/java/io/specto/hoverfly/junit/api/HoverflyOkHttpClientFactory.java new file mode 100644 index 00000000..16bde567 --- /dev/null +++ b/src/main/java/io/specto/hoverfly/junit/api/HoverflyOkHttpClientFactory.java @@ -0,0 +1,75 @@ +package io.specto.hoverfly.junit.api; + +import io.specto.hoverfly.junit.core.HoverflyConstants; +import io.specto.hoverfly.junit.core.config.HoverflyConfiguration; + +public class HoverflyOkHttpClientFactory implements HoverflyClientFactory { + + public HoverflyClient createHoverflyClient(HoverflyConfiguration hoverflyConfig) { + return custom() + .scheme(hoverflyConfig.getScheme()) + .host(hoverflyConfig.getHost()) + .port(hoverflyConfig.getAdminPort()) + .withAuthToken() + .build(); + } + + /** + * Static factory method for creating a {@link Builder} + * @return a builder for HoverflyClient + */ + static Builder custom() { + return new Builder(); + } + + /** + * Static factory method for default Hoverfly client + * @return a default HoverflyClient + */ + static HoverflyClient createDefault() { + return new Builder().build(); + } + + /** + * HTTP client builder for Hoverfly admin API + */ + static class Builder { + + private String scheme = HoverflyConstants.HTTP; + private String host = HoverflyConstants.LOCALHOST; + private int port = HoverflyConstants.DEFAULT_ADMIN_PORT; + private String authToken = null; + + Builder() { + } + + public Builder scheme(String scheme) { + this.scheme = scheme; + return this; + } + + public Builder host(String host) { + this.host = host; + return this; + } + + public Builder port(int port) { + this.port = port; + return this; + } + + /** + * Get token from environment variable "HOVERFLY_AUTH_TOKEN" to authenticate with admin API + * @return this Builder for further customizations + */ + public Builder withAuthToken() { + this.authToken = System.getenv(HoverflyConstants.HOVERFLY_AUTH_TOKEN); + return this; + } + + public HoverflyClient build() { + return new OkHttpHoverflyClient(scheme, host, port, authToken); + } + } + +} diff --git a/src/main/java/io/specto/hoverfly/junit/core/Hoverfly.java b/src/main/java/io/specto/hoverfly/junit/core/Hoverfly.java index e32b9ae7..58642327 100644 --- a/src/main/java/io/specto/hoverfly/junit/core/Hoverfly.java +++ b/src/main/java/io/specto/hoverfly/junit/core/Hoverfly.java @@ -15,6 +15,7 @@ import java.io.File; import java.io.IOException; import java.io.OutputStream; +import java.net.ServerSocket; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; @@ -37,6 +38,8 @@ import com.fasterxml.jackson.databind.ObjectWriter; import io.specto.hoverfly.junit.api.HoverflyClient; import io.specto.hoverfly.junit.api.HoverflyClientException; +import io.specto.hoverfly.junit.api.HoverflyClientFactory; +import io.specto.hoverfly.junit.api.HoverflyOkHttpClientFactory; import io.specto.hoverfly.junit.api.model.ModeArguments; import io.specto.hoverfly.junit.api.view.DiffView; import io.specto.hoverfly.junit.api.view.HoverflyInfoView; @@ -83,7 +86,8 @@ public class Hoverfly implements AutoCloseable { private final HoverflyMode hoverflyMode; private final ProxyConfigurer proxyConfigurer; private final SslConfigurer sslConfigurer = new SslConfigurer(); - private final HoverflyClient hoverflyClient; + private final HoverflyClientFactory hoverflyClientFactory; + private HoverflyClient hoverflyClient; private final TempFileManager tempFileManager = new TempFileManager(); private StartedProcess startedProcess; @@ -100,14 +104,8 @@ public class Hoverfly implements AutoCloseable { public Hoverfly(HoverflyConfig hoverflyConfigBuilder, HoverflyMode hoverflyMode) { hoverflyConfig = hoverflyConfigBuilder.build(); this.proxyConfigurer = new ProxyConfigurer(hoverflyConfig); - this.hoverflyClient = HoverflyClient.custom() - .scheme(hoverflyConfig.getScheme()) - .host(hoverflyConfig.getHost()) - .port(hoverflyConfig.getAdminPort()) - .withAuthToken() - .build(); this.hoverflyMode = hoverflyMode; - + this.hoverflyClientFactory = new HoverflyOkHttpClientFactory(); } /** @@ -139,7 +137,10 @@ public void start() { if (!hoverflyConfig.isRemoteInstance()) { startHoverflyProcess(); - } else { + } + this.hoverflyClient = hoverflyClientFactory.createHoverflyClient(hoverflyConfig); + + if (hoverflyConfig.isRemoteInstance()) { resetJournal(); } @@ -152,7 +153,7 @@ public void start() { } if (hoverflyConfig.getProxyCaCertificate().isPresent()) { - sslConfigurer.setDefaultSslContext(hoverflyConfig.getProxyCaCertificate().get()); + sslConfigurer.setDefaultSslContext(hoverflyConfig.getProxyCaCertificate().get()); } else if (StringUtils.isNotBlank(hoverflyConfig.getSslCertificatePath())) { sslConfigurer.setDefaultSslContext(hoverflyConfig.getSslCertificatePath()); } else { @@ -163,81 +164,90 @@ public void start() { } private void startHoverflyProcess() { - checkPortInUse(hoverflyConfig.getProxyPort()); - checkPortInUse(hoverflyConfig.getAdminPort()); + synchronized (Hoverfly.class) { - final SystemConfig systemConfig = new SystemConfigFactory(hoverflyConfig).createSystemConfig(); + if (hoverflyConfig.getProxyPort() == 0) { + hoverflyConfig.setProxyPort(findUnusedPort()); + } + if (hoverflyConfig.getAdminPort() == 0) { + hoverflyConfig.setAdminPort(findUnusedPort()); + } + checkPortInUse(hoverflyConfig.getProxyPort()); + checkPortInUse(hoverflyConfig.getAdminPort()); - if (hoverflyConfig.getBinaryLocation() != null) { - tempFileManager.setBinaryLocation(hoverflyConfig.getBinaryLocation()); - } - Path binaryPath = tempFileManager.copyHoverflyBinary(systemConfig); + final SystemConfig systemConfig = new SystemConfigFactory(hoverflyConfig).createSystemConfig(); - LOGGER.info("Executing binary at {}", binaryPath); - final List commands = new ArrayList<>(); - commands.add(binaryPath.toString()); + if (hoverflyConfig.getBinaryLocation() != null) { + tempFileManager.setBinaryLocation(hoverflyConfig.getBinaryLocation()); + } + Path binaryPath = tempFileManager.copyHoverflyBinary(systemConfig); - if (!hoverflyConfig.getCommands().isEmpty()) { - commands.addAll(hoverflyConfig.getCommands()); - } - commands.add("-pp"); - commands.add(String.valueOf(hoverflyConfig.getProxyPort())); - commands.add("-ap"); - commands.add(String.valueOf(hoverflyConfig.getAdminPort())); - - if (StringUtils.isNotBlank(hoverflyConfig.getSslCertificatePath())) { - tempFileManager.copyClassPathResource(hoverflyConfig.getSslCertificatePath(), "ca.crt"); - commands.add("-cert"); - commands.add("ca.crt"); - } - if (StringUtils.isNotBlank(hoverflyConfig.getSslKeyPath())) { - tempFileManager.copyClassPathResource(hoverflyConfig.getSslKeyPath(), "ca.key"); - commands.add("-key"); - commands.add("ca.key"); - } - if (hoverflyConfig.isPlainHttpTunneling()) { - commands.add("-plain-http-tunneling"); - } + LOGGER.info("Executing binary at {}", binaryPath); + final List commands = new ArrayList<>(); + commands.add(binaryPath.toString()); - if (hoverflyConfig.isWebServer()) { - commands.add("-webserver"); - } + if (!hoverflyConfig.getCommands().isEmpty()) { + commands.addAll(hoverflyConfig.getCommands()); + } + commands.add("-pp"); + commands.add(String.valueOf(hoverflyConfig.getProxyPort())); + commands.add("-ap"); + commands.add(String.valueOf(hoverflyConfig.getAdminPort())); + + if (StringUtils.isNotBlank(hoverflyConfig.getSslCertificatePath())) { + tempFileManager.copyClassPathResource(hoverflyConfig.getSslCertificatePath(), "ca.crt"); + commands.add("-cert"); + commands.add("ca.crt"); + } + if (StringUtils.isNotBlank(hoverflyConfig.getSslKeyPath())) { + tempFileManager.copyClassPathResource(hoverflyConfig.getSslKeyPath(), "ca.key"); + commands.add("-key"); + commands.add("ca.key"); + } + if (hoverflyConfig.isPlainHttpTunneling()) { + commands.add("-plain-http-tunneling"); + } - if (hoverflyConfig.isTlsVerificationDisabled()) { - commands.add("-tls-verification=false"); - } + if (hoverflyConfig.isWebServer()) { + commands.add("-webserver"); + } - if (hoverflyConfig.getHoverflyLogger().isPresent()) { - commands.add("-logs"); - commands.add("json"); - } + if (hoverflyConfig.isTlsVerificationDisabled()) { + commands.add("-tls-verification=false"); + } - if (hoverflyConfig.getLogLevel().isPresent()) { - commands.add("-log-level"); - commands.add(hoverflyConfig.getLogLevel().get().name().toLowerCase()); - } + if (hoverflyConfig.getHoverflyLogger().isPresent()) { + commands.add("-logs"); + commands.add("json"); + } - if (hoverflyConfig.isMiddlewareEnabled()) { - final String path = hoverflyConfig.getLocalMiddleware().getPath(); - final String scriptName = path.contains(File.separator) ? path.substring(path.lastIndexOf(File.separator) + 1) : path; - tempFileManager.copyClassPathResource(path, scriptName); - commands.add("-middleware"); - commands.add(hoverflyConfig.getLocalMiddleware().getBinary() + " " + scriptName); - } + if (hoverflyConfig.getLogLevel().isPresent()) { + commands.add("-log-level"); + commands.add(hoverflyConfig.getLogLevel().get().name().toLowerCase()); + } - if (StringUtils.isNotBlank(hoverflyConfig.getUpstreamProxy())) { - commands.add("-upstream-proxy"); - commands.add(hoverflyConfig.getUpstreamProxy()); - } + if (hoverflyConfig.isMiddlewareEnabled()) { + final String path = hoverflyConfig.getLocalMiddleware().getPath(); + final String scriptName = path.contains(File.separator) ? path.substring(path.lastIndexOf(File.separator) + 1) : path; + tempFileManager.copyClassPathResource(path, scriptName); + commands.add("-middleware"); + commands.add(hoverflyConfig.getLocalMiddleware().getBinary() + " " + scriptName); + } - try { - startedProcess = new ProcessExecutor() - .command(commands) - .redirectOutput(hoverflyConfig.getHoverflyLogger().map(LoggingOutputStream::new).orElse(System.out)) - .directory(tempFileManager.getTempDirectory().toFile()) - .start(); - } catch (IOException e) { - throw new IllegalStateException("Could not start Hoverfly process", e); + if (StringUtils.isNotBlank(hoverflyConfig.getUpstreamProxy())) { + commands.add("-upstream-proxy"); + commands.add(hoverflyConfig.getUpstreamProxy()); + } + + try { + startedProcess = new ProcessExecutor() + .command(commands) + .redirectOutput(hoverflyConfig.getHoverflyLogger().map(LoggingOutputStream::new).orElse(System.out)) + .directory(tempFileManager.getTempDirectory().toFile()) + .start(); + } catch (IOException e) { + throw new IllegalStateException("Could not start Hoverfly process", e); + } } } @@ -505,6 +515,16 @@ private void persistSimulation(Path path, Simulation simulation) throws IOExcept JSON_PRETTY_PRINTER.writeValue(path.toFile(), simulation); } + /** + * Looks for an unused port on the current machine + */ + private int findUnusedPort() { + try (final ServerSocket serverSocket = new ServerSocket(0)) { + return serverSocket.getLocalPort(); + } catch (IOException e) { + throw new RuntimeException("Cannot find available port", e); + } + } /** * Blocks until the Hoverfly process becomes healthy, otherwise time out diff --git a/src/main/java/io/specto/hoverfly/junit/core/config/HoverflyConfigValidator.java b/src/main/java/io/specto/hoverfly/junit/core/config/HoverflyConfigValidator.java index 75ef0e7b..e66feaec 100644 --- a/src/main/java/io/specto/hoverfly/junit/core/config/HoverflyConfigValidator.java +++ b/src/main/java/io/specto/hoverfly/junit/core/config/HoverflyConfigValidator.java @@ -47,15 +47,7 @@ HoverflyConfiguration validate(HoverflyConfiguration hoverflyConfig) { if (isKeyBlank && !isCertBlank || !isKeyBlank && isCertBlank) { throw new IllegalArgumentException("Both SSL key and certificate files are required to override the default Hoverfly SSL."); } - // Validate proxy port - if (hoverflyConfig.getProxyPort() == 0) { - hoverflyConfig.setProxyPort(findUnusedPort()); - } - // Validate admin port - if (hoverflyConfig.getAdminPort() == 0) { - hoverflyConfig.setAdminPort(findUnusedPort()); - } } // Check proxy CA cert exists @@ -66,18 +58,6 @@ HoverflyConfiguration validate(HoverflyConfiguration hoverflyConfig) { return hoverflyConfig; } - - /** - * Looks for an unused port on the current machine - */ - private static int findUnusedPort() { - try (final ServerSocket serverSocket = new ServerSocket(0)) { - return serverSocket.getLocalPort(); - } catch (IOException e) { - throw new RuntimeException("Cannot find available port", e); - } - } - private void checkResourceOnClasspath(String resourceName) { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Optional.ofNullable(classLoader.getResource(resourceName)) diff --git a/src/test/java/io/specto/hoverfly/junit/api/HoverflyClientTest.java b/src/test/java/io/specto/hoverfly/junit/api/HoverflyOkHttpClientFactoryTest.java similarity index 87% rename from src/test/java/io/specto/hoverfly/junit/api/HoverflyClientTest.java rename to src/test/java/io/specto/hoverfly/junit/api/HoverflyOkHttpClientFactoryTest.java index 08512a37..8fe0c78e 100644 --- a/src/test/java/io/specto/hoverfly/junit/api/HoverflyClientTest.java +++ b/src/test/java/io/specto/hoverfly/junit/api/HoverflyOkHttpClientFactoryTest.java @@ -13,7 +13,7 @@ import static io.specto.hoverfly.junit.dsl.ResponseCreators.success; import static org.assertj.core.api.Assertions.assertThat; -public class HoverflyClientTest { +public class HoverflyOkHttpClientFactoryTest { @Rule @@ -30,7 +30,7 @@ public void shouldBeAbleToCreateNewInstanceOfHoverflyClient() { .get("/api/health") .willReturn(success()) )); - HoverflyClient hoverflyClient = HoverflyClient.custom() + HoverflyClient hoverflyClient = HoverflyOkHttpClientFactory.custom() .port(9999) .build(); @@ -46,7 +46,7 @@ public void shouldBeAbleToCreateHoverflyClientWithAuthToken() { .header("Authorization", "Bearer some-token") .willReturn(success()) )); - HoverflyClient hoverflyClient = HoverflyClient.custom() + HoverflyClient hoverflyClient = HoverflyOkHttpClientFactory.custom() .host("remote.host") .port(12345) .withAuthToken() @@ -62,9 +62,9 @@ public void shouldCreateDefaultClient() { .get("/api/health") .willReturn(success()) )); - HoverflyClient defaultClient = HoverflyClient.createDefault(); + HoverflyClient defaultClient = HoverflyOkHttpClientFactory.createDefault(); assertThat(defaultClient.getHealth()).isTrue(); } -} \ No newline at end of file +} diff --git a/src/test/java/io/specto/hoverfly/junit/core/HoverflyConfigTest.java b/src/test/java/io/specto/hoverfly/junit/core/HoverflyConfigTest.java index 59afe70b..1e88536a 100644 --- a/src/test/java/io/specto/hoverfly/junit/core/HoverflyConfigTest.java +++ b/src/test/java/io/specto/hoverfly/junit/core/HoverflyConfigTest.java @@ -28,8 +28,6 @@ public void shouldHaveDefaultSettings() { assertThat(configs.getHost()).isEqualTo("localhost"); assertThat(configs.getScheme()).isEqualTo("http"); assertThat(configs.isWebServer()).isFalse(); - assertThat(configs.getAdminPort()).isGreaterThan(0); - assertThat(configs.getProxyPort()).isGreaterThan(0); assertThat(configs.getSslCertificatePath()).isNull(); assertThat(configs.getSslKeyPath()).isNull(); diff --git a/src/test/java/io/specto/hoverfly/junit/core/HoverflyTest.java b/src/test/java/io/specto/hoverfly/junit/core/HoverflyTest.java index db436063..f240c6bd 100644 --- a/src/test/java/io/specto/hoverfly/junit/core/HoverflyTest.java +++ b/src/test/java/io/specto/hoverfly/junit/core/HoverflyTest.java @@ -10,8 +10,10 @@ import com.google.common.io.Resources; import io.specto.hoverfly.junit.api.HoverflyClient; import io.specto.hoverfly.junit.api.HoverflyClientException; +import io.specto.hoverfly.junit.api.HoverflyClientFactory; import io.specto.hoverfly.junit.api.model.ModeArguments; import io.specto.hoverfly.junit.api.view.HoverflyInfoView; +import io.specto.hoverfly.junit.core.config.HoverflyConfiguration; import io.specto.hoverfly.junit.core.config.LocalHoverflyConfig; import io.specto.hoverfly.junit.core.config.LogLevel; import io.specto.hoverfly.junit.core.model.DelaySettings; @@ -228,7 +230,6 @@ public void shouldCombineAndImportMultipleSimulationSources() throws Exception { } - @Test public void shouldThrowExceptionWhenExportSimulationWithoutPath() { @@ -397,9 +398,9 @@ public void shouldResetJournalWhenUsingARemoteHoverflyInstance() { public void shouldResetSimulationJournalAndStateWhenCallingReset() { hoverfly = new Hoverfly(SIMULATE); - HoverflyClient hoverflyClient = createMockHoverflyClient(hoverfly); when(hoverflyClient.getHealth()).thenReturn(true); + hoverfly.start(); hoverfly.reset(); @@ -409,7 +410,7 @@ public void shouldResetSimulationJournalAndStateWhenCallingReset() { } @Test - public void shouldCopySslCertAndKeyToTempFolderIfPresent () { + public void shouldCopySslCertAndKeyToTempFolderIfPresent() { // Given hoverfly = new Hoverfly(localConfigs() .sslCertificatePath("ssl/ca.crt") @@ -426,13 +427,13 @@ public void shouldCopySslCertAndKeyToTempFolderIfPresent () { } @Test - public void shouldCopyMiddlewareScriptToTempFolderIfLocalMiddlewareEnabled () { + public void shouldCopyMiddlewareScriptToTempFolderIfLocalMiddlewareEnabled() { String rawFilename = "middleware.py"; String path = "middleware" + File.separator + rawFilename; // Given hoverfly = new Hoverfly(localConfigs() - .localMiddleware("python", path), SIMULATE); + .localMiddleware("python", path), SIMULATE); TempFileManager tempFileManager = spy(TempFileManager.class); Whitebox.setInternalState(hoverfly, "tempFileManager", tempFileManager); @@ -460,10 +461,13 @@ public void shouldCopyHoverflyBinaryToTempFolderOnStart() { } @Test - public void shouldValidateHoverflyConfigBeforeStart() { + public void shouldFindUnusedPortWhenStarted() { hoverfly = new Hoverfly(SIMULATE); + assertThat(hoverfly.getHoverflyConfig().getProxyPort()).isZero(); + assertThat(hoverfly.getHoverflyConfig().getAdminPort()).isZero(); + hoverfly.start(); assertThat(hoverfly.getHoverflyConfig().getProxyPort()).isNotZero(); assertThat(hoverfly.getHoverflyConfig().getAdminPort()).isNotZero(); } @@ -566,20 +570,20 @@ public void shouldSetModeArgumentsForCaptureMode() { @Test public void shouldResetModeWithModeArguments() { hoverfly = new Hoverfly(localConfigs().captureAllHeaders().enableStatefulCapture(), CAPTURE); - HoverflyClient hoverflyClient = createMockHoverflyClient(hoverfly); + when(hoverflyClient.getHealth()).thenReturn(true); + hoverfly.start(); hoverfly.resetMode(CAPTURE); final ArgumentCaptor arguments = ArgumentCaptor.forClass(ModeArguments.class); - verify(hoverflyClient).setMode(eq(HoverflyMode.CAPTURE), arguments.capture()); + verify(hoverflyClient, times(2)).setMode(eq(HoverflyMode.CAPTURE), arguments.capture()); assertThat(arguments.getValue().isStateful()).isTrue(); assertThat(arguments.getValue().getHeadersWhitelist()).containsOnly("*"); } - @Test public void shouldSetUpstreamProxy() { hoverfly = new Hoverfly(localConfigs().upstreamProxy(new InetSocketAddress("127.0.0.1", 8900)), SIMULATE); @@ -595,7 +599,9 @@ public void shouldTolerateFailureOnResetJournal() { hoverfly = new Hoverfly(SIMULATE); HoverflyClient hoverflyClient = createMockHoverflyClient(hoverfly); + when(hoverflyClient.getHealth()).thenReturn(true); doThrow(HoverflyClientException.class).when(hoverflyClient).deleteJournal(); + hoverfly.start(); hoverfly.resetJournal(); @@ -620,7 +626,9 @@ public void shouldTolerateFailureOnResetDiff() { // given hoverfly = new Hoverfly(DIFF); HoverflyClient hoverflyClient = createMockHoverflyClient(hoverfly); + when(hoverflyClient.getHealth()).thenReturn(true); doThrow(HoverflyClientException.class).when(hoverflyClient).cleanDiffs(); + hoverfly.start(); // when hoverfly.resetDiffs(); @@ -711,7 +719,9 @@ public void tearDown() { private HoverflyClient createMockHoverflyClient(Hoverfly hoverfly) { HoverflyClient hoverflyClient = mock(HoverflyClient.class); - Whitebox.setInternalState(hoverfly, "hoverflyClient", hoverflyClient); + HoverflyClientFactory clientFactory = mock(HoverflyClientFactory.class); + when(clientFactory.createHoverflyClient(any(HoverflyConfiguration.class))).thenReturn(hoverflyClient); + Whitebox.setInternalState(hoverfly, "hoverflyClientFactory", clientFactory); return hoverflyClient; } diff --git a/src/test/java/io/specto/hoverfly/junit/core/config/HoverflyConfigValidatorTest.java b/src/test/java/io/specto/hoverfly/junit/core/config/HoverflyConfigValidatorTest.java index 22b30576..cd8578c8 100644 --- a/src/test/java/io/specto/hoverfly/junit/core/config/HoverflyConfigValidatorTest.java +++ b/src/test/java/io/specto/hoverfly/junit/core/config/HoverflyConfigValidatorTest.java @@ -29,16 +29,6 @@ public void shouldProvideDefaultPortForRemoteHoverflyInstanceIfNotConfigured() { assertThat(validated.getAdminPort()).isEqualTo(8888); } - @Test - public void shouldAssignPortForLocalHoverflyInstanceIfNotConfigured() { - - HoverflyConfiguration validated = localConfigs().build(); - - - assertThat(validated.getProxyPort()).isNotZero(); - assertThat(validated.getAdminPort()).isNotZero(); - } - @Test public void shouldThrowExceptionIfOnlySslKeyIsConfigured() { @@ -99,4 +89,4 @@ public void shouldThrowExceptionIfProxyCaCertDoesNotExist() { .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Resource not found with name: some-cert.pem"); } -} \ No newline at end of file +}