From eb512ee2dc1a91b54f6d49af996193e045085df7 Mon Sep 17 00:00:00 2001 From: petruki <31597636+petruki@users.noreply.github.com> Date: Sun, 13 Aug 2023 13:35:00 -0700 Subject: [PATCH 1/2] Improved ClientRemoteService cohesion - removed Singleton --- .../switcherapi/client/SwitcherExecutor.java | 9 +- .../client/SwitcherProperties.java | 6 +- .../switcherapi/client/model/Switcher.java | 2 +- .../service/local/SwitcherLocalService.java | 13 +- .../client/service/remote/ClientRemote.java | 24 +++ .../service/remote/ClientRemoteService.java | 32 +-- .../service/remote/SwitcherRemoteService.java | 13 +- .../client/SwitcherApiMock2Test.java | 54 +----- .../client/SwitcherApiMockTest.java | 183 +++++------------- .../SwitcherSnapshotAutoUpdateTest.java | 30 ++- .../client/remote/ClientRemoteTest.java | 79 ++++++++ .../client/remote/ClientWSTest.java | 50 ++--- .../client/utils/SnapshotWatcherTest.java | 35 ++-- .../utils/SnapshotWatcherWorkerTest.java | 8 +- .../switcherapi/fixture/CountDownHelper.java | 25 +++ .../fixture/MockWebServerHelper.java | 134 +++++++++++++ 16 files changed, 393 insertions(+), 304 deletions(-) create mode 100644 src/main/java/com/github/switcherapi/client/service/remote/ClientRemote.java create mode 100644 src/test/java/com/github/switcherapi/client/remote/ClientRemoteTest.java create mode 100644 src/test/java/com/github/switcherapi/fixture/CountDownHelper.java create mode 100644 src/test/java/com/github/switcherapi/fixture/MockWebServerHelper.java diff --git a/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java b/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java index 2b30b3dd..74fcc560 100644 --- a/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java +++ b/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java @@ -4,6 +4,7 @@ import java.util.Map; import java.util.Set; +import com.github.switcherapi.client.service.remote.ClientRemote; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -75,17 +76,17 @@ public abstract class SwitcherExecutor { */ public abstract long getSnapshotVersion(); - protected boolean checkSnapshotVersion(final Domain domain) { + protected boolean checkSnapshotVersion(ClientRemote clientRemote, final Domain domain) { final String environment = SwitcherContextBase.contextStr(ContextKey.ENVIRONMENT); if (logger.isDebugEnabled()) { logger.debug(String.format("verifying snapshot version - environment: %s", environment)); } - return ClientRemoteService.getInstance().checkSnapshotVersion(domain.getVersion()); + return clientRemote.checkSnapshotVersion(domain.getVersion()); } - protected Domain initializeSnapshotFromAPI() { + protected Domain initializeSnapshotFromAPI(ClientRemote clientRemote) { final String environment = SwitcherContextBase.contextStr(ContextKey.ENVIRONMENT); if (logger.isDebugEnabled()) { @@ -93,7 +94,7 @@ protected Domain initializeSnapshotFromAPI() { } try { - final Snapshot snapshot = ClientRemoteService.getInstance().resolveSnapshot(); + final Snapshot snapshot = clientRemote.resolveSnapshot(); final String snapshotLocation = SwitcherContextBase.contextStr(ContextKey.SNAPSHOT_LOCATION); if (snapshotLocation != null) { diff --git a/src/main/java/com/github/switcherapi/client/SwitcherProperties.java b/src/main/java/com/github/switcherapi/client/SwitcherProperties.java index 9a433b03..5bba3efd 100644 --- a/src/main/java/com/github/switcherapi/client/SwitcherProperties.java +++ b/src/main/java/com/github/switcherapi/client/SwitcherProperties.java @@ -134,7 +134,7 @@ public String getEnvironment() { } public void setEnvironment(String environment) { - if (!StringUtils.isBlank(environment)) { + if (StringUtils.isNotBlank(environment)) { this.environment = environment; } else { this.environment = DEFAULT_ENV; @@ -162,7 +162,7 @@ public String getRegexTimeout() { } public void setRegexTimeout(String regexTimeout) { - if (!StringUtils.isBlank(regexTimeout)) { + if (StringUtils.isNotBlank(regexTimeout)) { this.regexTimeout = regexTimeout; } else { this.regexTimeout = DEFAULT_REGEX_TIMEOUT; @@ -222,7 +222,7 @@ public String getTimeoutMs() { } public void setTimeoutMs(String timeoutMs) { - if (!StringUtils.isBlank(timeoutMs)) { + if (StringUtils.isNotBlank(timeoutMs)) { this.timeoutMs = timeoutMs; } else { this.timeoutMs = DEFAULT_TIMEOUT_MS; diff --git a/src/main/java/com/github/switcherapi/client/model/Switcher.java b/src/main/java/com/github/switcherapi/client/model/Switcher.java index 4f0fb9b7..881dc029 100644 --- a/src/main/java/com/github/switcherapi/client/model/Switcher.java +++ b/src/main/java/com/github/switcherapi/client/model/Switcher.java @@ -45,7 +45,7 @@ public final class Switcher extends SwitcherBuilder { * Use {@link SwitcherContext#getSwitcher(String)} to create this object. * * @param switcherKey name of the key created - * @param context configuration object containing all information to start using switchers + * @param context client context in which the switcher will be executed (local/remote) */ public Switcher(final String switcherKey, final SwitcherExecutor context) { this.switcherKey = switcherKey; diff --git a/src/main/java/com/github/switcherapi/client/service/local/SwitcherLocalService.java b/src/main/java/com/github/switcherapi/client/service/local/SwitcherLocalService.java index f51c001c..3160b14f 100644 --- a/src/main/java/com/github/switcherapi/client/service/local/SwitcherLocalService.java +++ b/src/main/java/com/github/switcherapi/client/service/local/SwitcherLocalService.java @@ -9,6 +9,8 @@ import com.github.switcherapi.client.model.Switcher; import com.github.switcherapi.client.model.criteria.Domain; import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.service.remote.ClientRemote; +import com.github.switcherapi.client.service.remote.ClientRemoteService; import com.github.switcherapi.client.utils.SnapshotEventHandler; import com.github.switcherapi.client.utils.SnapshotLoader; import org.apache.commons.lang3.StringUtils; @@ -26,10 +28,13 @@ public class SwitcherLocalService extends SwitcherExecutor { private static final Logger logger = LogManager.getLogger(SwitcherLocalService.class); + + private final ClientRemote clientRemote; private Domain domain; public SwitcherLocalService() { + this.clientRemote = new ClientRemoteService(); this.init(); } @@ -44,13 +49,13 @@ public void init() { final boolean snapshotAutoload = SwitcherContextBase.contextBol(ContextKey.SNAPSHOT_AUTO_LOAD); if (StringUtils.isBlank(snapshotLocation) && snapshotAutoload) { - this.domain = this.initializeSnapshotFromAPI(); + this.domain = this.initializeSnapshotFromAPI(this.clientRemote); } else if (StringUtils.isNotBlank(snapshotLocation)) { try { this.domain = SnapshotLoader.loadSnapshot(snapshotLocation, environment); } catch (IOException e) { if (snapshotAutoload) { - this.domain = this.initializeSnapshotFromAPI(); + this.domain = this.initializeSnapshotFromAPI(this.clientRemote); } } } @@ -74,12 +79,12 @@ public CriteriaResponse executeCriteria(final Switcher switcher) { @Override public boolean checkSnapshotVersion() { - return super.checkSnapshotVersion(this.domain); + return super.checkSnapshotVersion(this.clientRemote, this.domain); } @Override public void updateSnapshot() { - this.domain = super.initializeSnapshotFromAPI(); + this.domain = super.initializeSnapshotFromAPI(this.clientRemote); } @Override diff --git a/src/main/java/com/github/switcherapi/client/service/remote/ClientRemote.java b/src/main/java/com/github/switcherapi/client/service/remote/ClientRemote.java new file mode 100644 index 00000000..fd631d71 --- /dev/null +++ b/src/main/java/com/github/switcherapi/client/service/remote/ClientRemote.java @@ -0,0 +1,24 @@ +package com.github.switcherapi.client.service.remote; + +import com.github.switcherapi.client.exception.SwitcherException; +import com.github.switcherapi.client.model.Switcher; +import com.github.switcherapi.client.model.criteria.Snapshot; +import com.github.switcherapi.client.model.criteria.SwitchersCheck; +import com.github.switcherapi.client.model.response.CriteriaResponse; + +import java.util.Set; + +/** + * @author Roger Floriano (petruki) + * @since 2023-07-12 + */ +public interface ClientRemote { + + CriteriaResponse executeCriteria(final Switcher switcher); + + Snapshot resolveSnapshot() throws SwitcherException; + + boolean checkSnapshotVersion(final long version); + + SwitchersCheck checkSwitchers(final Set switchers); +} diff --git a/src/main/java/com/github/switcherapi/client/service/remote/ClientRemoteService.java b/src/main/java/com/github/switcherapi/client/service/remote/ClientRemoteService.java index 30993caf..ea0d5aba 100644 --- a/src/main/java/com/github/switcherapi/client/service/remote/ClientRemoteService.java +++ b/src/main/java/com/github/switcherapi/client/service/remote/ClientRemoteService.java @@ -24,7 +24,7 @@ * @author Roger Floriano (petruki) * @since 2019-12-24 */ -public class ClientRemoteService { +public class ClientRemoteService implements ClientRemote { private final ClientWS clientWs; @@ -33,25 +33,12 @@ public class ClientRemoteService { private enum TokenStatus { VALID, INVALID, SILENT } - - private enum Singleton { - INSTANCE; - - private final ClientRemoteService instance = new ClientRemoteService(); - - public ClientRemoteService getInstance() { - return this.instance; - } - } - private ClientRemoteService() { + public ClientRemoteService() { this.clientWs = new ClientWSImpl(); } - - public static ClientRemoteService getInstance() { - return Singleton.INSTANCE.getInstance(); - } - + + @Override public CriteriaResponse executeCriteria(final Switcher switcher) { final TokenStatus tokenStatus = this.isTokenValid(); @@ -69,13 +56,15 @@ public CriteriaResponse executeCriteria(final Switcher switcher) { } } + @Override public Snapshot resolveSnapshot() throws SwitcherException { this.auth(this.isTokenValid()); return this.clientWs.resolveSnapshot( Optional.of(this.authResponse).orElseGet(AuthResponse::new).getToken()); } - + + @Override public boolean checkSnapshotVersion(final long version) { this.auth(this.isTokenValid()); @@ -84,7 +73,8 @@ public boolean checkSnapshotVersion(final long version) { return snapshotVersionResponse.isUpdated(); } - + + @Override public SwitchersCheck checkSwitchers(final Set switchers) { final TokenStatus tokenStatus = this.isTokenValid(); @@ -141,8 +131,4 @@ private void setSilentModeExpiration() throws SwitcherInvalidDateTimeArgumentExc } } - public void clearAuthResponse() { - this.authResponse = null; - } - } diff --git a/src/main/java/com/github/switcherapi/client/service/remote/SwitcherRemoteService.java b/src/main/java/com/github/switcherapi/client/service/remote/SwitcherRemoteService.java index 04a2c30a..f180fcd3 100644 --- a/src/main/java/com/github/switcherapi/client/service/remote/SwitcherRemoteService.java +++ b/src/main/java/com/github/switcherapi/client/service/remote/SwitcherRemoteService.java @@ -27,9 +27,12 @@ public class SwitcherRemoteService extends SwitcherExecutor { private static final Logger logger = LogManager.getLogger(SwitcherRemoteService.class); private final SwitcherLocalService switcherOffline; + + private final ClientRemote clientRemote; public SwitcherRemoteService() { this.switcherOffline = new SwitcherLocalService(); + this.clientRemote = new ClientRemoteService(); } @Override @@ -39,7 +42,7 @@ public CriteriaResponse executeCriteria(final Switcher switcher) { } try { - final CriteriaResponse response = ClientRemoteService.getInstance().executeCriteria(switcher); + final CriteriaResponse response = this.clientRemote.executeCriteria(switcher); if (logger.isDebugEnabled()) { logger.debug(String.format("[Online] response: %s", response)); @@ -70,16 +73,16 @@ private CriteriaResponse executeSilentCriteria(final Switcher switcher, public boolean checkSnapshotVersion() { if (StringUtils.isNotBlank(SwitcherContextBase.contextStr(ContextKey.SNAPSHOT_LOCATION)) && this.switcherOffline.getDomain() != null) { - return super.checkSnapshotVersion(this.switcherOffline.getDomain()); + return super.checkSnapshotVersion(this.clientRemote, this.switcherOffline.getDomain()); } - super.initializeSnapshotFromAPI(); + super.initializeSnapshotFromAPI(this.clientRemote); return Boolean.TRUE; } @Override public void updateSnapshot() { - this.switcherOffline.setDomain(super.initializeSnapshotFromAPI()); + this.switcherOffline.setDomain(super.initializeSnapshotFromAPI(this.clientRemote)); } @Override @@ -88,7 +91,7 @@ public void checkSwitchers(final Set switchers) { logger.debug(String.format("switchers: %s", switchers)); } - final SwitchersCheck response = ClientRemoteService.getInstance().checkSwitchers(switchers); + final SwitchersCheck response = this.clientRemote.checkSwitchers(switchers); if (response.getNotFound() != null && response.getNotFound().length > 0) { throw new SwitchersValidationException(Arrays.toString(response.getNotFound())); } diff --git a/src/test/java/com/github/switcherapi/client/SwitcherApiMock2Test.java b/src/test/java/com/github/switcherapi/client/SwitcherApiMock2Test.java index 967d1988..783b123b 100644 --- a/src/test/java/com/github/switcherapi/client/SwitcherApiMock2Test.java +++ b/src/test/java/com/github/switcherapi/client/SwitcherApiMock2Test.java @@ -3,11 +3,7 @@ import com.github.switcherapi.Switchers; import com.github.switcherapi.client.exception.SwitcherRemoteException; import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.remote.ClientWSImpl; -import com.github.switcherapi.client.service.remote.ClientRemoteService; -import com.github.switcherapi.client.utils.SwitcherUtils; -import mockwebserver3.MockResponse; -import mockwebserver3.MockWebServer; +import com.github.switcherapi.fixture.MockWebServerHelper; import mockwebserver3.QueueDispatcher; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -15,34 +11,28 @@ import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.Date; import static org.junit.jupiter.api.Assertions.assertThrows; -class SwitcherApiMock2Test { - - private static MockWebServer mockBackEnd; +class SwitcherApiMock2Test extends MockWebServerHelper { @BeforeAll static void setup() throws IOException { - mockBackEnd = new MockWebServer(); - mockBackEnd.start(); - ((QueueDispatcher) mockBackEnd.getDispatcher()).setFailFast(true); - - Switchers.loadProperties(); - Switchers.configure(ContextBuilder.builder().url(String.format("http://localhost:%s", mockBackEnd.getPort()))); - Switchers.initializeClient(); + MockWebServerHelper.setupMockServer(); + + Switchers.loadProperties(); + Switchers.configure(ContextBuilder.builder().url(String.format("http://localhost:%s", mockBackEnd.getPort()))); + Switchers.initializeClient(); } @AfterAll static void tearDown() throws IOException { - mockBackEnd.shutdown(); + MockWebServerHelper.tearDownMockServer(); } @BeforeEach void resetSwitcherContextState() { ((QueueDispatcher) mockBackEnd.getDispatcher()).clear(); - ClientRemoteService.getInstance().clearAuthResponse(); Switchers.configure(ContextBuilder.builder() .offlineMode(false) @@ -55,34 +45,6 @@ void resetSwitcherContextState() { Switchers.initializeClient(); } - - /** - * @see ClientWSImpl#auth() - * - * @param secondsAhead time to expire the token - * @return Generated mock /auth response - */ - private MockResponse generateMockAuth(int secondsAhead) { - return new MockResponse() - .setBody(String.format("{ \"token\": \"%s\", \"exp\": \"%s\" }", - "mocked_token", SwitcherUtils.addTimeDuration(secondsAhead + "s", new Date()).getTime()/1000)) - .addHeader("Content-Type", "application/json"); - } - - /** - * @see ClientWSImpl#isAlive() - * - * @param code HTTP status - * @return Generated mock /check response - */ - private MockResponse generateStatusResponse(String code) { - return new MockResponse().setStatus(String.format("HTTP/1.1 %s", code)); - - } - - private void givenResponse(MockResponse response) { - ((QueueDispatcher) mockBackEnd.getDispatcher()).enqueueResponse(response); - } @Test void shouldReturnError_componentNotRegistered() { diff --git a/src/test/java/com/github/switcherapi/client/SwitcherApiMockTest.java b/src/test/java/com/github/switcherapi/client/SwitcherApiMockTest.java index 9c586c19..1114b30e 100644 --- a/src/test/java/com/github/switcherapi/client/SwitcherApiMockTest.java +++ b/src/test/java/com/github/switcherapi/client/SwitcherApiMockTest.java @@ -1,20 +1,16 @@ package com.github.switcherapi.client; import com.github.switcherapi.Switchers; -import com.github.switcherapi.client.exception.*; +import com.github.switcherapi.client.exception.SwitcherException; +import com.github.switcherapi.client.exception.SwitcherRemoteException; +import com.github.switcherapi.client.exception.SwitcherSnapshotWriteException; +import com.github.switcherapi.client.exception.SwitchersValidationException; import com.github.switcherapi.client.model.Entry; import com.github.switcherapi.client.model.StrategyValidator; import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.model.criteria.Criteria; -import com.github.switcherapi.client.model.criteria.Snapshot; -import com.github.switcherapi.client.model.criteria.SwitchersCheck; -import com.github.switcherapi.client.remote.ClientWSImpl; -import com.github.switcherapi.client.service.remote.ClientRemoteService; -import com.github.switcherapi.client.utils.SnapshotLoader; -import com.github.switcherapi.client.utils.SwitcherUtils; -import com.google.gson.Gson; -import mockwebserver3.MockResponse; -import mockwebserver3.MockWebServer; +import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.fixture.CountDownHelper; +import com.github.switcherapi.fixture.MockWebServerHelper; import mockwebserver3.QueueDispatcher; import org.apache.commons.lang3.StringUtils; import org.glassfish.jersey.internal.guava.Sets; @@ -25,32 +21,25 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) -class SwitcherApiMockTest { +class SwitcherApiMockTest extends MockWebServerHelper { private static final String RESOURCES_PATH = Paths.get(StringUtils.EMPTY).toAbsolutePath() + "/src/test/resources"; private static final String SNAPSHOTS_LOCAL = Paths.get(StringUtils.EMPTY).toAbsolutePath() + "/src/test/resources/snapshot"; - private static MockWebServer mockBackEnd; - @BeforeAll static void setup() throws IOException { Files.deleteIfExists(Paths.get(RESOURCES_PATH + "/not_accessible")); Files.deleteIfExists(Paths.get(RESOURCES_PATH + "/new_folder/generated_on_new_folder.json")); Files.deleteIfExists(Paths.get(RESOURCES_PATH + "/new_folder")); Files.deleteIfExists(Paths.get(RESOURCES_PATH + "/generated_mock_default.json")); - - mockBackEnd = new MockWebServer(); - mockBackEnd.start(); - ((QueueDispatcher) mockBackEnd.getDispatcher()).setFailFast(true); + + MockWebServerHelper.setupMockServer(); Switchers.loadProperties(); Switchers.configure(ContextBuilder.builder().url(String.format("http://localhost:%s", mockBackEnd.getPort()))); @@ -59,7 +48,7 @@ static void setup() throws IOException { @AfterAll static void tearDown() throws IOException { - mockBackEnd.shutdown(); + MockWebServerHelper.tearDownMockServer(); //clean generated outputs SwitcherContext.stopWatchingSnapshot(); @@ -71,7 +60,6 @@ static void tearDown() throws IOException { @BeforeEach void resetSwitcherContextState() { ((QueueDispatcher) mockBackEnd.getDispatcher()).clear(); - ClientRemoteService.getInstance().clearAuthResponse(); Switchers.configure(ContextBuilder.builder() .offlineMode(false) @@ -85,98 +73,6 @@ void resetSwitcherContextState() { Switchers.initializeClient(); } - /** - * @see ClientWSImpl#auth() - * - * @param secondsAhead time to expire the token - * @return Generated mock /auth response - */ - private MockResponse generateMockAuth(int secondsAhead) { - return new MockResponse() - .setBody(String.format("{ \"token\": \"%s\", \"exp\": \"%s\" }", - "mocked_token", SwitcherUtils.addTimeDuration(secondsAhead + "s", new Date()).getTime()/1000)) - .addHeader("Content-Type", "application/json"); - } - - /** - * @see ClientWSImpl#executeCriteriaService(Switcher, String) - * - * @param result returned by the criteria execution - * @param reason if want to display along with the result - * @return Generated mock /criteria response - */ - private MockResponse generateCriteriaResponse(String result, boolean reason) { - String response; - if (reason) - response = "{ \"result\": \"%s\", \"reason\": \"Success\" }"; - else - response = "{ \"result\": \"%s\" }"; - - return new MockResponse() - .setBody(String.format(response, result)) - .addHeader("Content-Type", "application/json"); - } - - /** - * @see ClientWSImpl#isAlive() - * - * @param code HTTP status - * @return Generated mock /check response - */ - private MockResponse generateStatusResponse(String code) { - return new MockResponse().setStatus(String.format("HTTP/1.1 %s", code)); - } - - /** - * @see ClientWSImpl#checkSnapshotVersion(long, String) - * - * @param status is true when snapshot version is updated - * @return Generated mock /criteria/snapshot_check response - */ - private MockResponse generateCheckSnapshotVersionResponse(String status) { - return new MockResponse() - .setBody(String.format("{ \"status\": \"%s\" }", status)) - .addHeader("Content-Type", "application/json"); - } - - /** - * @see ClientWSImpl#resolveSnapshot(String) - * - * @return Generated mock /graphql response based on src/test/resources/default.json - */ - private MockResponse generateSnapshotResponse() { - final Snapshot mockedSnapshot = new Snapshot(); - final Criteria criteria = new Criteria(); - criteria.setDomain(SnapshotLoader.loadSnapshot(RESOURCES_PATH + "/default.json")); - mockedSnapshot.setData(criteria); - - Gson gson = new Gson(); - return new MockResponse() - .setBody(gson.toJson(mockedSnapshot)) - .addHeader("Content-Type", "application/json"); - } - - /** - * @see ClientWSImpl#checkSwitchers(Set, String) - * - * @param switchersNotFound Switcher Keys forced to be not found - * @return Generated mock /criteria/check_switchers - */ - private MockResponse generateCheckSwitchersResponse(Set switchersNotFound) { - SwitchersCheck switchersCheckNotFound = new SwitchersCheck(); - switchersCheckNotFound.setNotFound( - switchersNotFound.toArray(new String[0])); - - Gson gson = new Gson(); - return new MockResponse() - .setBody(gson.toJson(switchersCheckNotFound)) - .addHeader("Content-Type", "application/json"); - } - - private void givenResponse(MockResponse response) { - ((QueueDispatcher) mockBackEnd.getDispatcher()).enqueueResponse(response); - } - @Test void shouldReturnTrue() { //auth @@ -220,7 +116,7 @@ void shouldHideExecutionReason() { //test assertTrue(switcher.isItOn(entries)); assertNotNull(switcher.getHistoryExecution()); - assertNull(switcher.getHistoryExecution().stream().findFirst().get().getReason()); + assertNull(switcher.getHistoryExecution().stream().findFirst().orElseGet(CriteriaResponse::new).getReason()); } @Test @@ -241,8 +137,9 @@ void shouldShowExecutionReason() { //test assertTrue(switcher.isItOn(entries)); assertNotNull(switcher.getHistoryExecution()); - assertNotNull(switcher.getHistoryExecution().stream().findFirst().get().getReason()); - assertEquals(switcher.getSwitcherKey(), switcher.getHistoryExecution().stream().findFirst().get().getSwitcherKey()); + assertNotNull(switcher.getHistoryExecution().stream().findFirst().orElseGet(CriteriaResponse::new).getReason()); + assertEquals(switcher.getSwitcherKey(), + switcher.getHistoryExecution().stream().findFirst().orElseGet(CriteriaResponse::new).getSwitcherKey()); } @Test @@ -267,7 +164,7 @@ void shouldReturnError_unauthorizedAPIAccess() { } @Test - void shouldReturnTrue_silentMode() throws InterruptedException { + void shouldReturnTrue_silentMode() { //given Switchers.configure(ContextBuilder.builder() .snapshotLocation(SNAPSHOTS_LOCAL) @@ -285,9 +182,8 @@ void shouldReturnTrue_silentMode() throws InterruptedException { //test Switcher switcher = Switchers.getSwitcher(Switchers.USECASE11); assertTrue(switcher.isItOn()); - - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(2, TimeUnit.SECONDS); + + CountDownHelper.wait(2); //isAlive - service unavailable givenResponse(generateStatusResponse("503")); @@ -300,7 +196,7 @@ void shouldReturnTrue_silentMode() throws InterruptedException { } @Test - void shouldReturnTrue_tokenExpired() throws InterruptedException { + void shouldReturnTrue_tokenExpired() { //auth givenResponse(generateMockAuth(2)); @@ -311,9 +207,8 @@ void shouldReturnTrue_tokenExpired() throws InterruptedException { //test assertTrue(switcher.isItOn()); - - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(2, TimeUnit.SECONDS); + + CountDownHelper.wait(2); //auth givenResponse(generateMockAuth(2)); @@ -334,7 +229,7 @@ void shouldValidateAndUpdateSnapshot() { givenResponse(generateCheckSnapshotVersionResponse("false")); //graphql - givenResponse(generateSnapshotResponse()); + givenResponse(generateSnapshotResponse(RESOURCES_PATH)); //test Switchers.configure(ContextBuilder.builder().snapshotLocation(RESOURCES_PATH)); @@ -345,6 +240,23 @@ void shouldValidateAndUpdateSnapshot() { }); } + @Test + void shouldValidateAndNotUpdateSnapshot() { + //auth + givenResponse(generateMockAuth(10)); + + //criteria/snapshot_check + givenResponse(generateCheckSnapshotVersionResponse("true")); + + //test + Switchers.configure(ContextBuilder.builder().snapshotLocation(RESOURCES_PATH)); + + assertDoesNotThrow(() -> { + Switchers.initializeClient(); + assertTrue(Switchers.validateSnapshot()); + }); + } + @Test void shouldSkipValidateSnapshot() { //given @@ -369,7 +281,7 @@ void shouldLookupForSnapshot() { givenResponse(generateMockAuth(10)); //graphql - givenResponse(generateSnapshotResponse()); + givenResponse(generateSnapshotResponse(RESOURCES_PATH)); //test assertDoesNotThrow(Switchers::initializeClient); @@ -407,7 +319,7 @@ void shouldLookupForSnapshot_whenNotAutoLoad() { givenResponse(generateMockAuth(10)); //graphql - givenResponse(generateSnapshotResponse()); + givenResponse(generateSnapshotResponse(RESOURCES_PATH)); //test assertDoesNotThrow(Switchers::validateSnapshot); @@ -431,7 +343,7 @@ void shouldValidateAndLoadSnapshot_whenOffline() { givenResponse(generateCheckSnapshotVersionResponse("false")); //graphql - givenResponse(generateSnapshotResponse()); + givenResponse(generateSnapshotResponse(RESOURCES_PATH)); //test assertDoesNotThrow(Switchers::validateSnapshot); @@ -478,7 +390,7 @@ void shouldNotLookupForSnapshot_invalidLocation() { givenResponse(generateMockAuth(10)); //graphql - givenResponse(generateSnapshotResponse()); + givenResponse(generateSnapshotResponse(RESOURCES_PATH)); //test assertThrows(SwitcherSnapshotWriteException.class, Switchers::initializeClient); @@ -506,7 +418,7 @@ void shouldNotLookupForSnapshot_invalidFolderLocation() { givenResponse(generateMockAuth(10)); //graphql - givenResponse(generateSnapshotResponse()); + givenResponse(generateSnapshotResponse(RESOURCES_PATH)); //test assertThrows(SwitcherSnapshotWriteException.class, Switchers::initializeClient); @@ -563,7 +475,7 @@ void shouldNotValidateSwitchers_serviceUnavailable() { } @Test - void shouldReturnTrue_withThrottle() throws InterruptedException { + void shouldReturnTrue_withThrottle() { // First call givenResponse(generateMockAuth(10)); //auth givenResponse(generateCriteriaResponse("true", false)); //criteria @@ -584,9 +496,8 @@ void shouldReturnTrue_withThrottle() throws InterruptedException { // Async call givenResponse(generateMockAuth(10)); //auth givenResponse(generateCriteriaResponse("true", false)); //criteria - - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(1, TimeUnit.SECONDS); + + CountDownHelper.wait(1); assertTrue(switcher.isItOn()); } diff --git a/src/test/java/com/github/switcherapi/client/SwitcherSnapshotAutoUpdateTest.java b/src/test/java/com/github/switcherapi/client/SwitcherSnapshotAutoUpdateTest.java index 994324d7..58813edc 100644 --- a/src/test/java/com/github/switcherapi/client/SwitcherSnapshotAutoUpdateTest.java +++ b/src/test/java/com/github/switcherapi/client/SwitcherSnapshotAutoUpdateTest.java @@ -5,9 +5,9 @@ import com.github.switcherapi.client.model.criteria.Domain; import com.github.switcherapi.client.model.criteria.Snapshot; import com.github.switcherapi.client.remote.ClientWSImpl; -import com.github.switcherapi.client.service.remote.ClientRemoteService; import com.github.switcherapi.client.utils.SnapshotLoader; import com.github.switcherapi.client.utils.SwitcherUtils; +import com.github.switcherapi.fixture.CountDownHelper; import com.google.gson.Gson; import mockwebserver3.MockResponse; import mockwebserver3.MockWebServer; @@ -19,8 +19,6 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.util.Date; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -51,7 +49,7 @@ static void setup() throws IOException { } @AfterAll - static void tearDown() throws IOException, InterruptedException { + static void tearDown() throws IOException { mockBackEnd.shutdown(); //clean generated outputs @@ -59,14 +57,12 @@ static void tearDown() throws IOException, InterruptedException { Files.deleteIfExists(Paths.get(SNAPSHOTS_LOCAL + "/generated_mock_default_3.json")); Files.deleteIfExists(Paths.get(SNAPSHOTS_LOCAL + "/generated_mock_default_4.json")); - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(10, TimeUnit.SECONDS); + CountDownHelper.wait(10); } @BeforeEach void resetSwitcherContextState() { ((QueueDispatcher) mockBackEnd.getDispatcher()).clear(); - ClientRemoteService.getInstance().clearAuthResponse(); SwitcherContextBase.terminateSnapshotAutoUpdateWorker(); } @@ -138,7 +134,7 @@ private void givenResponse(MockResponse response) { @Test @Order(1) - void shouldUpdateSnapshot_offline() throws InterruptedException { + void shouldUpdateSnapshot_offline() { //given givenSnapshotUpdateResponse(false); @@ -155,14 +151,13 @@ void shouldUpdateSnapshot_offline() throws InterruptedException { assertEquals(1, Switchers.getSnapshotVersion()); //test - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(2, TimeUnit.SECONDS); + CountDownHelper.wait(2); assertEquals(2, Switchers.getSnapshotVersion()); } @Test @Order(2) - void shouldUpdateSnapshot_online() throws InterruptedException { + void shouldUpdateSnapshot_online() { //given givenSnapshotUpdateResponse(false); @@ -179,14 +174,13 @@ void shouldUpdateSnapshot_online() throws InterruptedException { assertEquals(1, Switchers.getSnapshotVersion()); //test - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(2, TimeUnit.SECONDS); + CountDownHelper.wait(2); assertEquals(2, Switchers.getSnapshotVersion()); } @Test @Order(3) - void shouldNotUpdateSnapshot_whenNoUpdateAvailable() throws InterruptedException { + void shouldNotUpdateSnapshot_whenNoUpdateAvailable() { //given givenSnapshotUpdateResponse(true); @@ -203,14 +197,13 @@ void shouldNotUpdateSnapshot_whenNoUpdateAvailable() throws InterruptedException assertEquals(1, Switchers.getSnapshotVersion()); //test - still the same version - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(1, TimeUnit.SECONDS); + CountDownHelper.wait(1); assertEquals(1, Switchers.getSnapshotVersion()); } @Test @Order(4) - void shouldUpdateSnapshot_online_inMemory() throws InterruptedException { + void shouldUpdateSnapshot_online_inMemory() { //given givenResponse(generateMockAuth()); //auth givenResponse(generateSnapshotResponse("default_outdated.json")); //graphql @@ -230,8 +223,7 @@ void shouldUpdateSnapshot_online_inMemory() throws InterruptedException { assertEquals(1, Switchers.getSnapshotVersion()); //test - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(2, TimeUnit.SECONDS); + CountDownHelper.wait(2); assertEquals(2, Switchers.getSnapshotVersion()); } diff --git a/src/test/java/com/github/switcherapi/client/remote/ClientRemoteTest.java b/src/test/java/com/github/switcherapi/client/remote/ClientRemoteTest.java new file mode 100644 index 00000000..d4c42fe1 --- /dev/null +++ b/src/test/java/com/github/switcherapi/client/remote/ClientRemoteTest.java @@ -0,0 +1,79 @@ +package com.github.switcherapi.client.remote; + +import com.github.switcherapi.Switchers; +import com.github.switcherapi.client.ContextBuilder; +import com.github.switcherapi.client.model.Switcher; +import com.github.switcherapi.client.model.criteria.SwitchersCheck; +import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.service.remote.ClientRemote; +import com.github.switcherapi.client.service.remote.ClientRemoteService; +import com.github.switcherapi.client.service.remote.SwitcherRemoteService; +import com.github.switcherapi.fixture.MockWebServerHelper; +import mockwebserver3.QueueDispatcher; +import org.glassfish.jersey.internal.guava.Sets; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ClientRemoteTest extends MockWebServerHelper { + + private ClientRemote clientRemote; + + @BeforeAll + static void setup() throws IOException { + MockWebServerHelper.setupMockServer(); + + Switchers.loadProperties(); + Switchers.configure(ContextBuilder.builder().url(String.format("http://localhost:%s", mockBackEnd.getPort()))); + Switchers.initializeClient(); + } + + @AfterAll + static void tearDown() throws IOException { + MockWebServerHelper.tearDownMockServer(); + } + + @BeforeEach + void resetSwitcherContextState() { + clientRemote = new ClientRemoteService(); + ((QueueDispatcher) mockBackEnd.getDispatcher()).clear(); + + Switchers.configure(ContextBuilder.builder().timeoutMs(null)); + Switchers.initializeClient(); + } + + @Test + void shouldExecuteCriteria() { + //given + givenResponse(generateMockAuth(100)); + givenResponse(generateCriteriaResponse("true", false)); + + Switcher switcher = new Switcher("KEY", new SwitcherRemoteService()); + + //test + CriteriaResponse actual = clientRemote.executeCriteria(switcher); + assertTrue(actual.isItOn()); + } + + @Test + void shouldCheckSwitchers() { + //given + final Set switcherKeys = Sets.newHashSet(); + switcherKeys.add("KEY"); + + givenResponse(generateMockAuth(100)); + givenResponse(generateCheckSwitchersResponse(switcherKeys)); + + //test + SwitchersCheck actual = clientRemote.checkSwitchers(switcherKeys); + assertEquals(1, actual.getNotFound().length); + } + +} diff --git a/src/test/java/com/github/switcherapi/client/remote/ClientWSTest.java b/src/test/java/com/github/switcherapi/client/remote/ClientWSTest.java index bcc7b53d..121ced1b 100644 --- a/src/test/java/com/github/switcherapi/client/remote/ClientWSTest.java +++ b/src/test/java/com/github/switcherapi/client/remote/ClientWSTest.java @@ -2,9 +2,7 @@ import com.github.switcherapi.Switchers; import com.github.switcherapi.client.ContextBuilder; -import com.github.switcherapi.client.service.remote.ClientRemoteService; -import mockwebserver3.MockResponse; -import mockwebserver3.MockWebServer; +import com.github.switcherapi.fixture.MockWebServerHelper; import mockwebserver3.QueueDispatcher; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -12,30 +10,15 @@ import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -class ClientWSTest { - - private static MockWebServer mockBackEnd; - - private void givenResponse(MockResponse response) { - ((QueueDispatcher) mockBackEnd.getDispatcher()).enqueueResponse(response); - } - - private MockResponse generateTimeOut(int timeoutMs) { - return new MockResponse() - .setResponseCode(200) - .setHeadersDelay(timeoutMs, TimeUnit.MILLISECONDS); - } +class ClientWSTest extends MockWebServerHelper { @BeforeAll static void setup() throws IOException { - mockBackEnd = new MockWebServer(); - mockBackEnd.start(); - ((QueueDispatcher) mockBackEnd.getDispatcher()).setFailFast(true); + MockWebServerHelper.setupMockServer(); Switchers.loadProperties(); Switchers.configure(ContextBuilder.builder().url(String.format("http://localhost:%s", mockBackEnd.getPort()))); @@ -44,46 +27,36 @@ static void setup() throws IOException { @AfterAll static void tearDown() throws IOException { - mockBackEnd.shutdown(); + MockWebServerHelper.tearDownMockServer(); } @BeforeEach void resetSwitcherContextState() { ((QueueDispatcher) mockBackEnd.getDispatcher()).clear(); - ClientRemoteService.getInstance().clearAuthResponse(); - - Switchers.configure(ContextBuilder.builder() - .offlineMode(false) - .snapshotLocation(null) - .snapshotSkipValidation(false) - .environment("default") - .silentMode(null) - .snapshotAutoLoad(false) - .snapshotAutoUpdateInterval(null) - .timeoutMs(null)); + Switchers.configure(ContextBuilder.builder().timeoutMs(null)); Switchers.initializeClient(); } @Test void shouldBeAlive() { // given - var clientWS = new ClientWSImpl(); + ClientWS clientWS = new ClientWSImpl(); givenResponse(generateTimeOut(100)); // test - var response = clientWS.isAlive(); + boolean response = clientWS.isAlive(); assertTrue(response); } @Test void shouldTimeOut() { // given - var clientWS = new ClientWSImpl(); + ClientWS clientWS = new ClientWSImpl(); givenResponse(generateTimeOut(3500)); // test - var response = clientWS.isAlive(); + boolean response = clientWS.isAlive(); assertFalse(response); } @@ -95,11 +68,12 @@ void shouldExtendTimeOut() { Switchers.initializeClient(); - var clientWS = new ClientWSImpl(); + ClientWS clientWS = new ClientWSImpl(); givenResponse(generateTimeOut(3500)); // test - var response = clientWS.isAlive(); + boolean response = clientWS.isAlive(); assertTrue(response); } + } diff --git a/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherTest.java b/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherTest.java index 2ff5fd4a..e3ed1161 100644 --- a/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherTest.java +++ b/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherTest.java @@ -5,6 +5,7 @@ import com.github.switcherapi.client.model.Switcher; import com.github.switcherapi.client.model.criteria.Criteria; import com.github.switcherapi.client.model.criteria.Snapshot; +import com.github.switcherapi.fixture.CountDownHelper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.lang3.StringUtils; @@ -21,8 +22,6 @@ import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -72,13 +71,13 @@ static void generateFixture() { SnapshotLoader.saveSnapshot(mockedSnapshot, SNAPSHOTS_LOCAL, "generated_watcher_default"); } - void changeFixture(boolean domainStatus) { + void changeFixture() { final Snapshot mockedSnapshot = new Snapshot(); final Criteria criteria = new Criteria(); criteria.setDomain(SnapshotLoader.loadSnapshot(SNAPSHOTS_LOCAL + "/snapshot_watcher.json")); mockedSnapshot.setData(criteria); - criteria.getDomain().setActivated(domainStatus); + criteria.getDomain().setActivated(false); final Gson gson = new GsonBuilder().setPrettyPrinting().create(); writeFixture(gson.toJson(mockedSnapshot)); @@ -98,39 +97,35 @@ void writeFixture(String content) { } @Test - void shouldNotReloadDomainAfterChangingSnapshot() throws InterruptedException { + void shouldNotReloadDomainAfterChangingSnapshot() { Switcher switcher = SwitchersBase.getSwitcher(SwitchersBase.USECASE11); //initial value is true assertTrue(switcher.isItOn()); - - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(1, TimeUnit.SECONDS); + + CountDownHelper.wait(1); SwitchersBase.stopWatchingSnapshot(); - this.changeFixture(false); - - waiter = new CountDownLatch(1); - waiter.await(2, TimeUnit.SECONDS); + this.changeFixture(); + + CountDownHelper.wait(2); //snapshot file updated - does not change as the watcher has been terminated assertTrue(switcher.isItOn()); } @Test - void shouldReloadDomainAfterChangingSnapshot() throws InterruptedException { + void shouldReloadDomainAfterChangingSnapshot() { Switcher switcher = SwitchersBase.getSwitcher(SwitchersBase.USECASE11); //initial value is true assertTrue(switcher.isItOn()); + + CountDownHelper.wait(1); - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(1, TimeUnit.SECONDS); - - this.changeFixture(false); - - waiter = new CountDownLatch(1); - waiter.await(2, TimeUnit.SECONDS); + this.changeFixture(); + + CountDownHelper.wait(2); //snapshot file updated - triggered domain reload assertFalse(switcher.isItOn()); diff --git a/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherWorkerTest.java b/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherWorkerTest.java index 9580bcc7..ff07e8da 100644 --- a/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherWorkerTest.java +++ b/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherWorkerTest.java @@ -3,13 +3,12 @@ import com.github.switcherapi.SwitchersBase; import com.github.switcherapi.client.ContextBuilder; import com.github.switcherapi.client.service.WorkerName; +import com.github.switcherapi.fixture.CountDownHelper; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.nio.file.Paths; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -37,13 +36,12 @@ void assertWorker(boolean exists) { } @Test - void shouldStartAndKillWorker() throws InterruptedException { + void shouldStartAndKillWorker() { SwitchersBase.watchSnapshot(); assertWorker(true); SwitchersBase.stopWatchingSnapshot(); - CountDownLatch waiter = new CountDownLatch(1); - waiter.await(2, TimeUnit.SECONDS); + CountDownHelper.wait(2); assertWorker(false); } diff --git a/src/test/java/com/github/switcherapi/fixture/CountDownHelper.java b/src/test/java/com/github/switcherapi/fixture/CountDownHelper.java new file mode 100644 index 00000000..66936faa --- /dev/null +++ b/src/test/java/com/github/switcherapi/fixture/CountDownHelper.java @@ -0,0 +1,25 @@ +package com.github.switcherapi.fixture; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class CountDownHelper { + + private static final Logger logger = LogManager.getLogger(CountDownHelper.class); + + public static void wait(int seconds) { + try { + CountDownLatch waiter = new CountDownLatch(1); + boolean finished = waiter.await(seconds, TimeUnit.SECONDS); + + if (!finished) { + logger.error("Countdown failed"); + } + } catch (InterruptedException e) { + logger.error(e.getMessage(), e); + } + } +} diff --git a/src/test/java/com/github/switcherapi/fixture/MockWebServerHelper.java b/src/test/java/com/github/switcherapi/fixture/MockWebServerHelper.java new file mode 100644 index 00000000..d92bc5b5 --- /dev/null +++ b/src/test/java/com/github/switcherapi/fixture/MockWebServerHelper.java @@ -0,0 +1,134 @@ +package com.github.switcherapi.fixture; + +import com.github.switcherapi.client.model.Switcher; +import com.github.switcherapi.client.model.criteria.Criteria; +import com.github.switcherapi.client.model.criteria.Snapshot; +import com.github.switcherapi.client.model.criteria.SwitchersCheck; +import com.github.switcherapi.client.remote.ClientWSImpl; +import com.github.switcherapi.client.utils.SnapshotLoader; +import com.github.switcherapi.client.utils.SwitcherUtils; +import com.google.gson.Gson; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.QueueDispatcher; + +import java.io.IOException; +import java.util.Date; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +public class MockWebServerHelper { + + protected static MockWebServer mockBackEnd; + + protected static void setupMockServer() throws IOException { + mockBackEnd = new MockWebServer(); + mockBackEnd.start(); + ((QueueDispatcher) mockBackEnd.getDispatcher()).setFailFast(true); + } + + protected static void tearDownMockServer() throws IOException { + mockBackEnd.shutdown(); + } + + protected void givenResponse(MockResponse response) { + ((QueueDispatcher) mockBackEnd.getDispatcher()).enqueueResponse(response); + } + + protected MockResponse generateTimeOut(int timeoutMs) { + return new MockResponse() + .setResponseCode(200) + .setHeadersDelay(timeoutMs, TimeUnit.MILLISECONDS); + } + + /** + * @see ClientWSImpl#auth() + * + * @param secondsAhead which the token will expire + * @return Generated mock /auth response + */ + protected MockResponse generateMockAuth(int secondsAhead) { + return new MockResponse() + .setBody(String.format("{ \"token\": \"%s\", \"exp\": \"%s\" }", + "mocked_token", SwitcherUtils.addTimeDuration(secondsAhead + "s", new Date()).getTime()/1000)) + .addHeader("Content-Type", "application/json"); + } + + /** + * @see ClientWSImpl#resolveSnapshot(String) + * + * @return Generated mock /graphql response based on src/test/resources/default.json + */ + protected MockResponse generateSnapshotResponse(String resourcesPath) { + final Snapshot mockedSnapshot = new Snapshot(); + final Criteria criteria = new Criteria(); + criteria.setDomain(SnapshotLoader.loadSnapshot(resourcesPath + "/default.json")); + mockedSnapshot.setData(criteria); + + Gson gson = new Gson(); + return new MockResponse() + .setBody(gson.toJson(mockedSnapshot)) + .addHeader("Content-Type", "application/json"); + } + + /** + * @see ClientWSImpl#checkSnapshotVersion(long, String) + * + * @param status is true when snapshot version is updated + * @return Generated mock /criteria/snapshot_check response + */ + protected MockResponse generateCheckSnapshotVersionResponse(String status) { + return new MockResponse() + .setBody(String.format("{ \"status\": \"%s\" }", status)) + .addHeader("Content-Type", "application/json"); + } + + /** + * @see ClientWSImpl#isAlive() + * + * @param code HTTP status + * @return Generated mock /check response + */ + protected MockResponse generateStatusResponse(String code) { + return new MockResponse().setStatus(String.format("HTTP/1.1 %s", code)); + + } + + /** + * @see ClientWSImpl#executeCriteriaService(Switcher, String) + * + * @param result returned by the criteria execution + * @param reason if you want to display along with the result + * @return Generated mock /criteria response + */ + protected MockResponse generateCriteriaResponse(String result, boolean reason) { + String response; + if (reason) { + response = "{ \"result\": \"%s\", \"reason\": \"Success\" }"; + } else { + response = "{ \"result\": \"%s\" }"; + } + + return new MockResponse() + .setBody(String.format(response, result)) + .addHeader("Content-Type", "application/json"); + } + + /** + * @see ClientWSImpl#checkSwitchers(Set, String) + * + * @param switchersNotFound Switcher Keys forced to be not found + * @return Generated mock /criteria/check_switchers + */ + protected MockResponse generateCheckSwitchersResponse(Set switchersNotFound) { + SwitchersCheck switchersCheckNotFound = new SwitchersCheck(); + switchersCheckNotFound.setNotFound( + switchersNotFound.toArray(new String[0])); + + Gson gson = new Gson(); + return new MockResponse() + .setBody(gson.toJson(switchersCheckNotFound)) + .addHeader("Content-Type", "application/json"); + } + +} From 4d91a68a2d8f016f1d48e0823d4c4f441bbf86a0 Mon Sep 17 00:00:00 2001 From: petruki <31597636+petruki@users.noreply.github.com> Date: Sun, 13 Aug 2023 13:39:14 -0700 Subject: [PATCH 2/2] Removed unused import --- .../switcherapi/client/SwitcherExecutor.java | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java b/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java index 74fcc560..3ffef8d6 100644 --- a/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java +++ b/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java @@ -1,13 +1,5 @@ package com.github.switcherapi.client; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import com.github.switcherapi.client.service.remote.ClientRemote; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import com.github.switcherapi.client.exception.SwitcherRemoteException; import com.github.switcherapi.client.exception.SwitcherSnapshotWriteException; import com.github.switcherapi.client.model.ContextKey; @@ -15,9 +7,15 @@ import com.github.switcherapi.client.model.criteria.Domain; import com.github.switcherapi.client.model.criteria.Snapshot; import com.github.switcherapi.client.model.response.CriteriaResponse; -import com.github.switcherapi.client.service.remote.ClientRemoteService; +import com.github.switcherapi.client.service.remote.ClientRemote; import com.github.switcherapi.client.utils.SnapshotEventHandler; import com.github.switcherapi.client.utils.SnapshotLoader; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; /** * The Executor provides an API to handle Remote and Local functionalities that