From f9f2f9ad7a3510e246de1e4bffaee0de113cca3a Mon Sep 17 00:00:00 2001 From: holomekc <30546982+holomekc@users.noreply.github.com> Date: Mon, 1 Apr 2024 10:26:14 +0200 Subject: [PATCH] feat: Update to Wiremock 3.5.2 spotless --- .../wiremock/core/ProxyHandler.java | 2 +- .../wiremock/core/WireMockApp.java | 252 ++++++++-------- .../responsetemplating/helpers/JWTHelper.java | 175 ++++++----- .../wiremock/jetty/JettyHttpServer.java | 1 - .../wiremock/jetty11/Jetty11HttpServer.java | 8 +- .../wiremock/core/ProxyHandlerTest.java | 282 ++++++++++-------- .../webhooks/WebhooksRegistrationTest.java | 3 - 7 files changed, 395 insertions(+), 328 deletions(-) diff --git a/src/main/java/com/github/tomakehurst/wiremock/core/ProxyHandler.java b/src/main/java/com/github/tomakehurst/wiremock/core/ProxyHandler.java index 6857a20f0e..9b75ce1fb4 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/core/ProxyHandler.java +++ b/src/main/java/com/github/tomakehurst/wiremock/core/ProxyHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2023 Thomas Akehurst + * Copyright (C) 2023-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java b/src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java index 5ec263cb34..635a5bf8c5 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java +++ b/src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java @@ -104,38 +104,38 @@ public WireMockApp(Options options, Container container) { this.settingsStore = stores.getSettingsStore(); extensions = - new Extensions( - options.getDeclaredExtensions(), - this, - options, - stores, - options.filesRoot().child(FILES_ROOT)); + new Extensions( + options.getDeclaredExtensions(), + this, + options, + stores, + options.filesRoot().child(FILES_ROOT)); extensions.load(); Map customMatchers = - extensions.ofType(RequestMatcherExtension.class); + extensions.ofType(RequestMatcherExtension.class); requestJournal = - options.requestJournalDisabled() - ? new DisabledRequestJournal() - : new StoreBackedRequestJournal( - options.maxRequestJournalEntries().orElse(null), - customMatchers, - stores.getRequestJournalStore()); + options.requestJournalDisabled() + ? new DisabledRequestJournal() + : new StoreBackedRequestJournal( + options.maxRequestJournalEntries().orElse(null), + customMatchers, + stores.getRequestJournalStore()); scenarios = new InMemoryScenarios(stores.getScenariosStore()); stubMappings = - new StoreBackedStubMappings( - stores.getStubStore(), - scenarios, - customMatchers, - extensions.ofType(ResponseDefinitionTransformer.class), - extensions.ofType(ResponseDefinitionTransformerV2.class), - stores.getFilesBlobStore(), - List.copyOf(extensions.ofType(StubLifecycleListener.class).values())); + new StoreBackedStubMappings( + stores.getStubStore(), + scenarios, + customMatchers, + extensions.ofType(ResponseDefinitionTransformer.class), + extensions.ofType(ResponseDefinitionTransformerV2.class), + stores.getFilesBlobStore(), + List.copyOf(extensions.ofType(StubLifecycleListener.class).values())); nearMissCalculator = new NearMissCalculator(stubMappings, requestJournal, scenarios); recorder = - new Recorder(this, extensions, stores.getFilesBlobStore(), stores.getRecorderStateStore()); + new Recorder(this, extensions, stores.getFilesBlobStore(), stores.getRecorderStateStore()); globalSettingsListeners = List.copyOf(extensions.ofType(GlobalSettingsListener.class).values()); this.mappingsLoaderExtensions = extensions.ofType(MappingsLoaderExtension.class); @@ -143,12 +143,18 @@ public WireMockApp(Options options, Container container) { loadDefaultMappings(); } - public WireMockApp(boolean browserProxyingEnabled, MappingsLoader defaultMappingsLoader, - Map mappingsLoaderExtensions, MappingsSaver mappingsSaver, - boolean requestJournalDisabled, Integer maxRequestJournalEntries, - Map transformers, - Map v2transformers, Map requestMatchers, - FileSource rootFileSource, Container container) { + public WireMockApp( + boolean browserProxyingEnabled, + MappingsLoader defaultMappingsLoader, + Map mappingsLoaderExtensions, + MappingsSaver mappingsSaver, + boolean requestJournalDisabled, + Integer maxRequestJournalEntries, + Map transformers, + Map v2transformers, + Map requestMatchers, + FileSource rootFileSource, + Container container) { this.proxyHandler = new ProxyHandler(this); @@ -160,119 +166,121 @@ public WireMockApp(boolean browserProxyingEnabled, MappingsLoader defaultMapping this.mappingsSaver = mappingsSaver; this.settingsStore = stores.getSettingsStore(); requestJournal = - requestJournalDisabled - ? new DisabledRequestJournal() - : new StoreBackedRequestJournal( - maxRequestJournalEntries, requestMatchers, stores.getRequestJournalStore()); + requestJournalDisabled + ? new DisabledRequestJournal() + : new StoreBackedRequestJournal( + maxRequestJournalEntries, requestMatchers, stores.getRequestJournalStore()); scenarios = new InMemoryScenarios(stores.getScenariosStore()); stubMappings = - new StoreBackedStubMappings( - stores.getStubStore(), - scenarios, - requestMatchers, - transformers, - v2transformers, - stores.getFilesBlobStore(), - Collections.emptyList()); + new StoreBackedStubMappings( + stores.getStubStore(), + scenarios, + requestMatchers, + transformers, + v2transformers, + stores.getFilesBlobStore(), + Collections.emptyList()); this.container = container; nearMissCalculator = new NearMissCalculator(stubMappings, requestJournal, scenarios); recorder = - new Recorder(this, extensions, stores.getFilesBlobStore(), stores.getRecorderStateStore()); + new Recorder(this, extensions, stores.getFilesBlobStore(), stores.getRecorderStateStore()); globalSettingsListeners = Collections.emptyList(); loadDefaultMappings(); } public AdminRequestHandler buildAdminRequestHandler() { AdminRoutes adminRoutes = - AdminRoutes.forServer(extensions.ofType(AdminApiExtension.class).values(), stores); + AdminRoutes.forServer(extensions.ofType(AdminApiExtension.class).values(), stores); return new AdminRequestHandler( - adminRoutes, - this, - new BasicResponseRenderer(), - options.getAdminAuthenticator(), - options.getHttpsRequiredForAdminApi(), - getAdminRequestFilters(), - getV2AdminRequestFilters(), - options.getDataTruncationSettings()); + adminRoutes, + this, + new BasicResponseRenderer(), + options.getAdminAuthenticator(), + options.getHttpsRequiredForAdminApi(), + getAdminRequestFilters(), + getV2AdminRequestFilters(), + options.getDataTruncationSettings()); } public StubRequestHandler buildStubRequestHandler() { Map postServeActions = extensions.ofType(PostServeAction.class); - Map concatenatedMap = new HashMap<>(extensions.ofType(ServeEventListener.class)); + Map concatenatedMap = + new HashMap<>(extensions.ofType(ServeEventListener.class)); concatenatedMap.put("wiremock-gui", new GuiServeEventListener()); - Map serveEventListeners = Collections.unmodifiableMap(concatenatedMap); + Map serveEventListeners = + Collections.unmodifiableMap(concatenatedMap); BrowserProxySettings browserProxySettings = options.browserProxySettings(); final com.github.tomakehurst.wiremock.http.client.HttpClientFactory httpClientFactory = - extensions - .ofType(com.github.tomakehurst.wiremock.http.client.HttpClientFactory.class) - .values() - .stream() - .findFirst() - .orElse(options.httpClientFactory()); + extensions + .ofType(com.github.tomakehurst.wiremock.http.client.HttpClientFactory.class) + .values() + .stream() + .findFirst() + .orElse(options.httpClientFactory()); final HttpClient reverseProxyClient = - httpClientFactory.buildHttpClient(options, true, Collections.emptyList(), true); + httpClientFactory.buildHttpClient(options, true, Collections.emptyList(), true); final HttpClient forwardProxyClient = - httpClientFactory.buildHttpClient( - options, - browserProxySettings.trustAllProxyTargets(), - browserProxySettings.trustAllProxyTargets() - ? Collections.emptyList() - : browserProxySettings.trustedProxyTargets(), - false); + httpClientFactory.buildHttpClient( + options, + browserProxySettings.trustAllProxyTargets(), + browserProxySettings.trustAllProxyTargets() + ? Collections.emptyList() + : browserProxySettings.trustedProxyTargets(), + false); return new StubRequestHandler( - this, - new StubResponseRenderer( - options.getStores().getFilesBlobStore(), - settingsStore, - new ProxyResponseRenderer( - options.shouldPreserveHostHeader(), - options.proxyHostHeader(), - settingsStore, - options.getStubCorsEnabled(), - options.getSupportedProxyEncodings(), - reverseProxyClient, - forwardProxyClient), - List.copyOf(extensions.ofType(ResponseTransformer.class).values()), - List.copyOf(extensions.ofType(ResponseTransformerV2.class).values())), - this, - postServeActions, - serveEventListeners, - requestJournal, - getStubRequestFilters(), - getV2StubRequestFilters(), - options.getStubRequestLoggingDisabled(), - options.getDataTruncationSettings(), - options.getNotMatchedRendererFactory().apply(extensions)); + this, + new StubResponseRenderer( + options.getStores().getFilesBlobStore(), + settingsStore, + new ProxyResponseRenderer( + options.shouldPreserveHostHeader(), + options.proxyHostHeader(), + settingsStore, + options.getStubCorsEnabled(), + options.getSupportedProxyEncodings(), + reverseProxyClient, + forwardProxyClient), + List.copyOf(extensions.ofType(ResponseTransformer.class).values()), + List.copyOf(extensions.ofType(ResponseTransformerV2.class).values())), + this, + postServeActions, + serveEventListeners, + requestJournal, + getStubRequestFilters(), + getV2StubRequestFilters(), + options.getStubRequestLoggingDisabled(), + options.getDataTruncationSettings(), + options.getNotMatchedRendererFactory().apply(extensions)); } private List getAdminRequestFilters() { return extensions.ofType(RequestFilter.class).values().stream() - .filter(RequestFilter::applyToAdmin) - .collect(Collectors.toList()); + .filter(RequestFilter::applyToAdmin) + .collect(Collectors.toList()); } private List getV2AdminRequestFilters() { return extensions.ofType(RequestFilterV2.class).values().stream() - .filter(RequestFilterV2::applyToAdmin) - .collect(Collectors.toList()); + .filter(RequestFilterV2::applyToAdmin) + .collect(Collectors.toList()); } private List getStubRequestFilters() { return extensions.ofType(RequestFilter.class).values().stream() - .filter(RequestFilter::applyToStubs) - .collect(Collectors.toList()); + .filter(RequestFilter::applyToStubs) + .collect(Collectors.toList()); } private List getV2StubRequestFilters() { return extensions.ofType(RequestFilterV2.class).values().stream() - .filter(RequestFilterV2::applyToStubs) - .collect(Collectors.toList()); + .filter(RequestFilterV2::applyToStubs) + .collect(Collectors.toList()); } private void loadDefaultMappings() { @@ -291,11 +299,11 @@ public ServeEvent serveStubFor(ServeEvent initialServeEvent) { ServeEvent serveEvent = stubMappings.serveFor(initialServeEvent); if (serveEvent.isNoExactMatch() - && browserProxyingEnabled - && serveEvent.getRequest().isBrowserProxyRequest() - && getGlobalSettings().getSettings().getProxyPassThrough()) { + && browserProxyingEnabled + && serveEvent.getRequest().isBrowserProxyRequest() + && getGlobalSettings().getSettings().getProxyPassThrough()) { return ServeEvent.ofUnmatched( - serveEvent.getRequest(), ResponseDefinition.browserProxy(serveEvent.getRequest())); + serveEvent.getRequest(), ResponseDefinition.browserProxy(serveEvent.getRequest())); } return serveEvent; @@ -318,13 +326,13 @@ public void addStubMapping(StubMapping stubMapping) { @Override public void removeStubMapping(StubMapping stubMapping) { stubMappings - .get(stubMapping.getId()) - .ifPresent( - stubToDelete -> { - if (stubToDelete.shouldBePersisted()) { - mappingsSaver.remove(stubToDelete); - } - }); + .get(stubMapping.getId()) + .ifPresent( + stubToDelete -> { + if (stubToDelete.shouldBePersisted()) { + mappingsSaver.remove(stubToDelete); + } + }); stubMappings.removeMapping(stubMapping); @@ -419,7 +427,7 @@ public GetServeEventsResult getServeEvents(ServeEventQuery query) { return GetServeEventsResult.requestJournalEnabled(LimitAndOffsetPaginator.none(serveEvents)); } catch (RequestJournalDisabledException e) { return GetServeEventsResult.requestJournalDisabled( - LimitAndOffsetPaginator.none(requestJournal.getAllServeEvents())); + LimitAndOffsetPaginator.none(requestJournal.getAllServeEvents())); } } @@ -451,10 +459,10 @@ public FindRequestsResult findRequestsMatching(RequestPattern requestPattern) { public FindRequestsResult findUnmatchedRequests() { try { List requests = - requestJournal.getAllServeEvents().stream() - .filter(ServeEvent::isNoExactMatch) - .map(ServeEvent::getRequest) - .collect(Collectors.toList()); + requestJournal.getAllServeEvents().stream() + .filter(ServeEvent::isNoExactMatch) + .map(ServeEvent::getRequest) + .collect(Collectors.toList()); return FindRequestsResult.withRequests(requests); } catch (RequestJournalDisabledException e) { return FindRequestsResult.withRequestJournalDisabled(); @@ -472,17 +480,19 @@ public FindServeEventsResult removeServeEventsMatching(RequestPattern requestPat } @Override - public FindServeEventsResult removeServeEventsForStubsMatchingMetadata(StringValuePattern metadataPattern) { - return new FindServeEventsResult(requestJournal.removeServeEventsForStubsMatchingMetadata(metadataPattern)); + public FindServeEventsResult removeServeEventsForStubsMatchingMetadata( + StringValuePattern metadataPattern) { + return new FindServeEventsResult( + requestJournal.removeServeEventsForStubsMatchingMetadata(metadataPattern)); } @Override public FindNearMissesResult findNearMissesForUnmatchedRequests() { List nearMisses = new ArrayList<>(); List unmatchedServeEvents = - requestJournal.getAllServeEvents().stream() - .filter(ServeEvent::isNoExactMatch) - .collect(Collectors.toList()); + requestJournal.getAllServeEvents().stream() + .filter(ServeEvent::isNoExactMatch) + .collect(Collectors.toList()); for (ServeEvent serveEvent : unmatchedServeEvents) { nearMisses.addAll(nearMissCalculator.findNearestTo(serveEvent.getRequest())); @@ -622,7 +632,8 @@ public RecordingStatusResult getRecordingStatus() { @Override public ListStubMappingsResult findAllStubsByMetadata(StringValuePattern pattern) { - return new ListStubMappingsResult(LimitAndOffsetPaginator.none(stubMappings.findByMetadata(pattern))); + return new ListStubMappingsResult( + LimitAndOffsetPaginator.none(stubMappings.findByMetadata(pattern))); } @Override @@ -636,7 +647,8 @@ public void removeStubsByMetadata(StringValuePattern pattern) { @Override public void importStubs(StubImport stubImport) { List mappings = stubImport.getMappings(); - StubImport.Options importOptions = getFirstNonNull(stubImport.getImportOptions(), StubImport.Options.DEFAULTS); + StubImport.Options importOptions = + getFirstNonNull(stubImport.getImportOptions(), StubImport.Options.DEFAULTS); for (int i = mappings.size() - 1; i >= 0; i--) { StubMapping mapping = mappings.get(i); diff --git a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/JWTHelper.java b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/JWTHelper.java index 7ccb77ea3d..09ddd3af5f 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/JWTHelper.java +++ b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/JWTHelper.java @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2024 Thomas Akehurst + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers; import com.fasterxml.jackson.core.type.TypeReference; @@ -6,9 +21,6 @@ import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; -import org.bouncycastle.jce.provider.BouncyCastleProvider; - -import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.security.Key; import java.security.KeyFactory; @@ -18,88 +30,93 @@ import java.util.Base64; import java.util.HashMap; import java.util.Map; +import javax.crypto.spec.SecretKeySpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; public class JWTHelper extends HandlebarsHelper { - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - @Override - public Object apply(Object context, Options options) throws IOException { - String signAlgo = options.hash("algo", SignatureAlgorithm.RS256.name()); - String key = options.hash("key", null); - String claims = options.hash("claims", null); - String payload = options.hash("payload", null); - String header = options.hash("header", null); - - try { - return createJWT(SignatureAlgorithm.valueOf(signAlgo), key, jsonToMap(claims), payload, jsonToMap(header)); - } catch (Exception e) { - return this.handleError(e.getMessage(), e); - } + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + @Override + public Object apply(Object context, Options options) throws IOException { + String signAlgo = options.hash("algo", SignatureAlgorithm.RS256.name()); + String key = options.hash("key", null); + String claims = options.hash("claims", null); + String payload = options.hash("payload", null); + String header = options.hash("header", null); + + try { + return createJWT( + SignatureAlgorithm.valueOf(signAlgo), key, jsonToMap(claims), payload, jsonToMap(header)); + } catch (Exception e) { + return this.handleError(e.getMessage(), e); } + } - private Map jsonToMap(String json) { - if (json == null) { - return new HashMap<>(); - } - - try { - return OBJECT_MAPPER.readValue(json, new TypeReference>() { - }); - } catch (IOException e) { - handleError("Could not parse json for JWTHelper", e); - return new HashMap<>(); - } + private Map jsonToMap(String json) { + if (json == null) { + return new HashMap<>(); } - private String createJWT(SignatureAlgorithm signatureAlgorithm, final String apiKey, - final Map claims, - final String payload, - final Map header) throws NoSuchAlgorithmException, InvalidKeySpecException { - - if (signatureAlgorithm == null) { - signatureAlgorithm = SignatureAlgorithm.NONE; - } - - final JwtBuilder jwtBuilder = Jwts.builder(); - - if (signatureAlgorithm != SignatureAlgorithm.NONE) { - - if (apiKey == null || apiKey.trim().isEmpty()) { - throw new IllegalStateException("key must not be empty in case algo is defined"); - } - - byte[] apiKeyBytes = Base64.getDecoder().decode(apiKey); - - Key key; - switch (signatureAlgorithm.getFamilyName()) { - case "HMAC": - key = new SecretKeySpec(apiKeyBytes, signatureAlgorithm.getJcaName()); - break; - case "ECDSA": - final KeyFactory ecdsaKf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider()); - key = ecdsaKf.generatePrivate(new PKCS8EncodedKeySpec(apiKeyBytes)); - break; - case "RSA": - default: - final KeyFactory rsaKf = KeyFactory.getInstance(signatureAlgorithm.getFamilyName()); - key = rsaKf.generatePrivate(new PKCS8EncodedKeySpec(apiKeyBytes)); - break; - } - - jwtBuilder.signWith(key, signatureAlgorithm); - } - - if (claims != null && !claims.isEmpty()) { - jwtBuilder.setClaims(claims); - } else if (payload != null) { - jwtBuilder.setPayload(payload); - } - - if (header != null && !header.isEmpty()) { - jwtBuilder.setHeader(header); - } - - return jwtBuilder.compact(); + try { + return OBJECT_MAPPER.readValue(json, new TypeReference>() {}); + } catch (IOException e) { + handleError("Could not parse json for JWTHelper", e); + return new HashMap<>(); + } + } + + private String createJWT( + SignatureAlgorithm signatureAlgorithm, + final String apiKey, + final Map claims, + final String payload, + final Map header) + throws NoSuchAlgorithmException, InvalidKeySpecException { + + if (signatureAlgorithm == null) { + signatureAlgorithm = SignatureAlgorithm.NONE; } + + final JwtBuilder jwtBuilder = Jwts.builder(); + + if (signatureAlgorithm != SignatureAlgorithm.NONE) { + + if (apiKey == null || apiKey.trim().isEmpty()) { + throw new IllegalStateException("key must not be empty in case algo is defined"); + } + + byte[] apiKeyBytes = Base64.getDecoder().decode(apiKey); + + Key key; + switch (signatureAlgorithm.getFamilyName()) { + case "HMAC": + key = new SecretKeySpec(apiKeyBytes, signatureAlgorithm.getJcaName()); + break; + case "ECDSA": + final KeyFactory ecdsaKf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider()); + key = ecdsaKf.generatePrivate(new PKCS8EncodedKeySpec(apiKeyBytes)); + break; + case "RSA": + default: + final KeyFactory rsaKf = KeyFactory.getInstance(signatureAlgorithm.getFamilyName()); + key = rsaKf.generatePrivate(new PKCS8EncodedKeySpec(apiKeyBytes)); + break; + } + + jwtBuilder.signWith(key, signatureAlgorithm); + } + + if (claims != null && !claims.isEmpty()) { + jwtBuilder.setClaims(claims); + } else if (payload != null) { + jwtBuilder.setPayload(payload); + } + + if (header != null && !header.isEmpty()) { + jwtBuilder.setHeader(header); + } + + return jwtBuilder.compact(); + } } diff --git a/src/main/java/com/github/tomakehurst/wiremock/jetty/JettyHttpServer.java b/src/main/java/com/github/tomakehurst/wiremock/jetty/JettyHttpServer.java index bfee50461d..144f25da0e 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/jetty/JettyHttpServer.java +++ b/src/main/java/com/github/tomakehurst/wiremock/jetty/JettyHttpServer.java @@ -24,7 +24,6 @@ import com.github.tomakehurst.wiremock.http.HttpServer; import com.github.tomakehurst.wiremock.http.StubRequestHandler; import com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener; -import com.github.tomakehurst.wiremock.jetty.websockets.WebSocketEndpoint; import com.github.tomakehurst.wiremock.servlet.*; import java.io.IOException; import java.net.Socket; diff --git a/src/main/java/com/github/tomakehurst/wiremock/jetty11/Jetty11HttpServer.java b/src/main/java/com/github/tomakehurst/wiremock/jetty11/Jetty11HttpServer.java index c91b87a0ce..b6e67c6816 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/jetty11/Jetty11HttpServer.java +++ b/src/main/java/com/github/tomakehurst/wiremock/jetty11/Jetty11HttpServer.java @@ -376,10 +376,10 @@ private ServletContextHandler addAdminContext( // wiremock-gui Include websocket into admin context JakartaWebSocketServletContainerInitializer.configure( - adminContext, - (servletContext, serverContainer) -> { - serverContainer.addEndpoint(WebSocketEndpoint.class); - }); + adminContext, + (servletContext, serverContainer) -> { + serverContainer.addEndpoint(WebSocketEndpoint.class); + }); decorateAdminServiceContextAfterConfig(adminContext); diff --git a/src/test/java/com/github/tomakehurst/wiremock/core/ProxyHandlerTest.java b/src/test/java/com/github/tomakehurst/wiremock/core/ProxyHandlerTest.java index 5649050c59..95a63b9667 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/core/ProxyHandlerTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/core/ProxyHandlerTest.java @@ -1,185 +1,227 @@ +/* + * Copyright (C) 2024 Thomas Akehurst + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.github.tomakehurst.wiremock.core; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.github.tomakehurst.wiremock.admin.model.SingleStubMappingResult; import com.github.tomakehurst.wiremock.http.ResponseDefinition; import com.github.tomakehurst.wiremock.stubbing.StubMapping; -import org.junit.Assert; +import java.util.UUID; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.UUID; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - /** * @author Christopher Holomek */ public class ProxyHandlerTest { - private ProxyHandler proxyHandler; - private static final UUID EXISTING_UUID_IS_PROXY = UUID.randomUUID(); - private static final UUID EXISTING_UUID_IS_PROXY_BINARY = UUID.randomUUID(); - private static final UUID EXISTING_UUID_IS_NO_PROXY = UUID.randomUUID(); - private static final UUID NOT_EXISTING_UUID = UUID.randomUUID(); - - - @BeforeEach - public void before() { - final Admin admin = mock(Admin.class); - - this.proxyHandler = new ProxyHandler(admin); + private ProxyHandler proxyHandler; + private static final UUID EXISTING_UUID_IS_PROXY = UUID.randomUUID(); + private static final UUID EXISTING_UUID_IS_PROXY_BINARY = UUID.randomUUID(); + private static final UUID EXISTING_UUID_IS_NO_PROXY = UUID.randomUUID(); + private static final UUID NOT_EXISTING_UUID = UUID.randomUUID(); - when(admin.getStubMapping(ProxyHandlerTest.EXISTING_UUID_IS_PROXY)).thenReturn(new SingleStubMappingResult( - ProxyHandlerTest.this.createDefaultStubMapping(ProxyHandlerTest.EXISTING_UUID_IS_PROXY, true))); + @BeforeEach + public void before() { + final Admin admin = mock(Admin.class); - when(admin.getStubMapping(ProxyHandlerTest.EXISTING_UUID_IS_PROXY_BINARY)).thenReturn(new SingleStubMappingResult( - ProxyHandlerTest.this.createBinaryStubMapping())); + this.proxyHandler = new ProxyHandler(admin); - when(admin.getStubMapping(ProxyHandlerTest.EXISTING_UUID_IS_NO_PROXY)).thenReturn(new SingleStubMappingResult( - ProxyHandlerTest.this.createDefaultStubMapping(ProxyHandlerTest.EXISTING_UUID_IS_NO_PROXY, false))); + when(admin.getStubMapping(ProxyHandlerTest.EXISTING_UUID_IS_PROXY)) + .thenReturn( + new SingleStubMappingResult( + ProxyHandlerTest.this.createDefaultStubMapping( + ProxyHandlerTest.EXISTING_UUID_IS_PROXY, true))); - when(admin.getStubMapping(ProxyHandlerTest.NOT_EXISTING_UUID)).thenReturn(new SingleStubMappingResult(null)); - } + when(admin.getStubMapping(ProxyHandlerTest.EXISTING_UUID_IS_PROXY_BINARY)) + .thenReturn(new SingleStubMappingResult(ProxyHandlerTest.this.createBinaryStubMapping())); - @Test - public void testClear() { - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + when(admin.getStubMapping(ProxyHandlerTest.EXISTING_UUID_IS_NO_PROXY)) + .thenReturn( + new SingleStubMappingResult( + ProxyHandlerTest.this.createDefaultStubMapping( + ProxyHandlerTest.EXISTING_UUID_IS_NO_PROXY, false))); - // first we need to disable proxy so that we have something to remove - this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY); + when(admin.getStubMapping(ProxyHandlerTest.NOT_EXISTING_UUID)) + .thenReturn(new SingleStubMappingResult(null)); + } - Assertions.assertFalse(this.proxyHandler.getConfig().isEmpty()); + @Test + public void testClear() { + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - this.proxyHandler.clear(); + // first we need to disable proxy so that we have something to remove + this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY); - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - } + Assertions.assertFalse(this.proxyHandler.getConfig().isEmpty()); + this.proxyHandler.clear(); - @Test - public void testRemoveProxyConfig() { - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + } - // first we need to disable proxy so that we have something to remove - this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY); + @Test + public void testRemoveProxyConfig() { + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - Assertions.assertFalse(this.proxyHandler.getConfig().isEmpty()); + // first we need to disable proxy so that we have something to remove + this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY); - this.proxyHandler.removeProxyConfig(EXISTING_UUID_IS_PROXY); + Assertions.assertFalse(this.proxyHandler.getConfig().isEmpty()); - Assertions.assertFalse(this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY.toString())); - } + this.proxyHandler.removeProxyConfig(EXISTING_UUID_IS_PROXY); - @Test - public void testDisableProxy() { - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + Assertions.assertFalse( + this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY.toString())); + } - // first we need to disable proxy so that we have something to remove - this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY); + @Test + public void testDisableProxy() { + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - Assertions.assertTrue(this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY.toString())); - } + // first we need to disable proxy so that we have something to remove + this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY); - @Test - public void testDisableNoProxyMapping() { - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + Assertions.assertTrue( + this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY.toString())); + } - // first we need to disable proxy so that we have something to remove - this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_NO_PROXY); + @Test + public void testDisableNoProxyMapping() { + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - Assertions.assertFalse(this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_NO_PROXY.toString())); - } + // first we need to disable proxy so that we have something to remove + this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_NO_PROXY); - @Test - public void testDisableNoMapping() { - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + Assertions.assertFalse( + this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_NO_PROXY.toString())); + } - // first we need to disable proxy so that we have something to remove - this.proxyHandler.disableProxyUrl(NOT_EXISTING_UUID); + @Test + public void testDisableNoMapping() { + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - Assertions.assertFalse(this.proxyHandler.getConfig().containsKey(NOT_EXISTING_UUID.toString())); - } + // first we need to disable proxy so that we have something to remove + this.proxyHandler.disableProxyUrl(NOT_EXISTING_UUID); - @Test - public void testEnableProxy() { - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + Assertions.assertFalse(this.proxyHandler.getConfig().containsKey(NOT_EXISTING_UUID.toString())); + } - // first we need to disable proxy so that we have something to remove - this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY); + @Test + public void testEnableProxy() { + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - Assertions.assertTrue(this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY.toString())); + // first we need to disable proxy so that we have something to remove + this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY); - final String url = this.proxyHandler.getConfig().get(EXISTING_UUID_IS_PROXY.toString()); + Assertions.assertTrue( + this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY.toString())); - Assertions.assertEquals("http://localhost:8080", url); + final String url = this.proxyHandler.getConfig().get(EXISTING_UUID_IS_PROXY.toString()); - this.proxyHandler.enableProxyUrl(EXISTING_UUID_IS_PROXY); + Assertions.assertEquals("http://localhost:8080", url); - Assertions.assertFalse(this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY.toString())); - } + this.proxyHandler.enableProxyUrl(EXISTING_UUID_IS_PROXY); - @Test - public void testEnableNoProxyMapping() { - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + Assertions.assertFalse( + this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY.toString())); + } - this.proxyHandler.enableProxyUrl(EXISTING_UUID_IS_NO_PROXY); + @Test + public void testEnableNoProxyMapping() { + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - Assertions.assertFalse(this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_NO_PROXY.toString())); - } + this.proxyHandler.enableProxyUrl(EXISTING_UUID_IS_NO_PROXY); - @Test - public void testEnableNoMapping() { - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + Assertions.assertFalse( + this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_NO_PROXY.toString())); + } - this.proxyHandler.enableProxyUrl(NOT_EXISTING_UUID); + @Test + public void testEnableNoMapping() { + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - Assertions.assertFalse(this.proxyHandler.getConfig().containsKey(NOT_EXISTING_UUID.toString())); - } + this.proxyHandler.enableProxyUrl(NOT_EXISTING_UUID); - @Test - public void testBinary() { - Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); + Assertions.assertFalse(this.proxyHandler.getConfig().containsKey(NOT_EXISTING_UUID.toString())); + } - // first we need to disable proxy so that we have something to remove - this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY_BINARY); + @Test + public void testBinary() { + Assertions.assertTrue(this.proxyHandler.getConfig().isEmpty()); - Assertions.assertTrue(this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY_BINARY.toString())); + // first we need to disable proxy so that we have something to remove + this.proxyHandler.disableProxyUrl(EXISTING_UUID_IS_PROXY_BINARY); - final String url = this.proxyHandler.getConfig().get(EXISTING_UUID_IS_PROXY_BINARY.toString()); + Assertions.assertTrue( + this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY_BINARY.toString())); - Assertions.assertEquals("http://localhost:8080", url); + final String url = this.proxyHandler.getConfig().get(EXISTING_UUID_IS_PROXY_BINARY.toString()); - this.proxyHandler.enableProxyUrl(EXISTING_UUID_IS_PROXY_BINARY); + Assertions.assertEquals("http://localhost:8080", url); - Assertions.assertFalse(this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY_BINARY.toString())); - } + this.proxyHandler.enableProxyUrl(EXISTING_UUID_IS_PROXY_BINARY); - private StubMapping createDefaultStubMapping(final UUID id, final boolean isProxy) { - final StubMapping stubMapping = new StubMapping(); - final String proxyUrl = isProxy ? "http://localhost:8080" : null; - final ResponseDefinition responseDefinition = new ResponseDefinition(200, "test", "test", null, null, null, null, null, null, null, - null, - proxyUrl, null, null, null, null, null); + Assertions.assertFalse( + this.proxyHandler.getConfig().containsKey(EXISTING_UUID_IS_PROXY_BINARY.toString())); + } - stubMapping.setResponse(responseDefinition); - stubMapping.setId(id); + private StubMapping createDefaultStubMapping(final UUID id, final boolean isProxy) { + final StubMapping stubMapping = new StubMapping(); + final String proxyUrl = isProxy ? "http://localhost:8080" : null; + final ResponseDefinition responseDefinition = + new ResponseDefinition( + 200, "test", "test", null, null, null, null, null, null, null, null, null, proxyUrl, + null, null, null, null, null); - return stubMapping; - } + stubMapping.setResponse(responseDefinition); + stubMapping.setId(id); - private StubMapping createBinaryStubMapping() { - final StubMapping stubMapping = new StubMapping(); - final ResponseDefinition responseDefinition = new ResponseDefinition(200, "test", new byte[0], null, null, null, null, null, null, - null, - null, - "http://localhost:8080", null, null, null, null, null); + return stubMapping; + } - stubMapping.setResponse(responseDefinition); - stubMapping.setId(EXISTING_UUID_IS_PROXY_BINARY); + private StubMapping createBinaryStubMapping() { + final StubMapping stubMapping = new StubMapping(); + final ResponseDefinition responseDefinition = + new ResponseDefinition( + 200, + "test", + new byte[0], + null, + null, + null, + null, + null, + null, + null, + null, + null, + "http://localhost:8080", + null, + null, + null, + null, + null); - return stubMapping; - } + stubMapping.setResponse(responseDefinition); + stubMapping.setId(EXISTING_UUID_IS_PROXY_BINARY); -} \ No newline at end of file + return stubMapping; + } +} diff --git a/src/test/java/com/github/tomakehurst/wiremock/extension/webhooks/WebhooksRegistrationTest.java b/src/test/java/com/github/tomakehurst/wiremock/extension/webhooks/WebhooksRegistrationTest.java index 73941a37e4..01a2f46566 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/extension/webhooks/WebhooksRegistrationTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/extension/webhooks/WebhooksRegistrationTest.java @@ -22,11 +22,8 @@ import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.standalone.WireMockServerRunner; -import com.github.tomakehurst.wiremock.testsupport.TestNotifier; - import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test;