diff --git a/CI.md b/CI.md index 93834cde4..26d6ecb87 100644 --- a/CI.md +++ b/CI.md @@ -86,8 +86,8 @@ level**. What the Java 11 CI job validates: - The project compiles and all tests pass when Maven runs on JDK 11. -- Dependencies that require JDK 11 at runtime (e.g. WireMock 3.x, - Logback 1.4+, RESTEasy 4.x) do not break the build environment. +- Dependencies that require JDK 11 at runtime (e.g. Logback 1.4+, + RESTEasy 4.x) do not break the build environment. It does **not** mean the output bytecode is compiled to Java 11 level. diff --git a/core/pom.xml b/core/pom.xml index 68d0353ba..55d77ad40 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -72,10 +72,6 @@ commons-io commons-io - - com.github.tomakehurst - wiremock - ch.qos.logback logback-classic diff --git a/core/pom_OSSRH_NOTINUSE.xml b/core/pom_OSSRH_NOTINUSE.xml index d67a870b2..11eaeb9ec 100644 --- a/core/pom_OSSRH_NOTINUSE.xml +++ b/core/pom_OSSRH_NOTINUSE.xml @@ -86,10 +86,6 @@ commons-io commons-io - - com.github.tomakehurst - wiremock - ch.qos.logback logback-classic diff --git a/core/src/main/java/org/jsmart/zerocode/core/domain/MockStep.java b/core/src/main/java/org/jsmart/zerocode/core/domain/MockStep.java index 120b240a0..cdd2f5ad8 100644 --- a/core/src/main/java/org/jsmart/zerocode/core/domain/MockStep.java +++ b/core/src/main/java/org/jsmart/zerocode/core/domain/MockStep.java @@ -24,7 +24,7 @@ public class MockStep { private final String url; private final JsonNode request; private final JsonNode response; - private final JsonNode assertions; //<-- In case the wiremock or simulator mock throws a status code etc + private final JsonNode assertions; //<-- In case the simulator mock throws a status code etc // derived value i.e. body as JSON string private String body; diff --git a/core/src/main/java/org/jsmart/zerocode/core/engine/executor/httpapi/HttpApiExecutorImpl.java b/core/src/main/java/org/jsmart/zerocode/core/engine/executor/httpapi/HttpApiExecutorImpl.java index f54dc6b84..b4be298d9 100644 --- a/core/src/main/java/org/jsmart/zerocode/core/engine/executor/httpapi/HttpApiExecutorImpl.java +++ b/core/src/main/java/org/jsmart/zerocode/core/engine/executor/httpapi/HttpApiExecutorImpl.java @@ -3,13 +3,11 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; -import com.google.inject.name.Named; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; import java.io.IOException; import java.util.HashMap; import javax.ws.rs.core.MultivaluedMap; -import org.jsmart.zerocode.core.domain.MockSteps; import org.jsmart.zerocode.core.domain.Response; import org.jsmart.zerocode.core.httpclient.BasicHttpClient; import org.jsmart.zerocode.core.utils.SmartUtils; @@ -19,7 +17,6 @@ import static org.apache.commons.lang3.StringUtils.isEmpty; import static org.jsmart.zerocode.core.engine.mocker.RestEndPointMocker.createWithLocalMock; import static org.jsmart.zerocode.core.engine.mocker.RestEndPointMocker.createWithVirtuosoMock; -import static org.jsmart.zerocode.core.engine.mocker.RestEndPointMocker.createWithWireMock; import static org.jsmart.zerocode.core.utils.SmartUtils.prettyPrintJson; public class HttpApiExecutorImpl implements HttpApiExecutor { @@ -38,10 +35,6 @@ public HttpApiExecutorImpl(BasicHttpClient httpClient, ObjectMapper objectMapper @Inject private SmartUtils smartUtils; - @Inject(optional = true) - @Named("mock.api.port") - private int mockPort; - @Override public String execute(String httpUrl, String methodName, String requestJson) throws Exception { @@ -106,23 +99,7 @@ private Response deriveZeroCodeResponseFrom(int responseStatus, } private boolean completedMockingEndPoints(String httpUrl, String requestJson, String methodName, Object bodyContent) throws java.io.IOException { - if (httpUrl.contains("/$MOCK") && methodName.equals("$USE.WIREMOCK")) { - - MockSteps mockSteps = smartUtils.getMapper().readValue(requestJson, MockSteps.class); - - if (mockPort > 0) { - createWithWireMock(mockSteps, mockPort); - - LOGGER.debug("#SUCCESS: End points simulated via wiremock."); - - return true; - } - - LOGGER.error("\n\n#DISABLED: Mocking was not activated as there was no port configured in the properties file. \n\n " + - "Usage: e.g. in your file provide- \n " + - "mock.api.port=8888\n\n"); - return false; - } else if (httpUrl.contains("/$MOCK") && methodName.equals("$USE.VIRTUOSO")) { + if (httpUrl.contains("/$MOCK") && methodName.equals("$USE.VIRTUOSO")) { LOGGER.debug("\n#body:\n" + bodyContent); //read the content of the "request". This contains the complete rest API. diff --git a/core/src/main/java/org/jsmart/zerocode/core/engine/mocker/HandlebarsLocalDateHelper.java b/core/src/main/java/org/jsmart/zerocode/core/engine/mocker/HandlebarsLocalDateHelper.java deleted file mode 100644 index f3bbfeec7..000000000 --- a/core/src/main/java/org/jsmart/zerocode/core/engine/mocker/HandlebarsLocalDateHelper.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.jsmart.zerocode.core.engine.mocker; - -import com.github.jknack.handlebars.Options; -import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.DateOffset; -import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.HandlebarsHelper; - -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.Date; - -public class HandlebarsLocalDateHelper extends HandlebarsHelper { - public Object apply(Object context, Options options) { - String offset = options.hash("offset", null); - Date date = new Date(); - if (offset != null) { - date = (new DateOffset(offset)).shift(date); - } - return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().format(DateTimeFormatter.ISO_DATE_TIME); - } -} diff --git a/core/src/main/java/org/jsmart/zerocode/core/engine/mocker/RestEndPointMocker.java b/core/src/main/java/org/jsmart/zerocode/core/engine/mocker/RestEndPointMocker.java index e6304bcd3..b6e93c975 100644 --- a/core/src/main/java/org/jsmart/zerocode/core/engine/mocker/RestEndPointMocker.java +++ b/core/src/main/java/org/jsmart/zerocode/core/engine/mocker/RestEndPointMocker.java @@ -1,204 +1,20 @@ package org.jsmart.zerocode.core.engine.mocker; -import com.fasterxml.jackson.databind.JsonNode; -import com.github.jknack.handlebars.Helper; -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.client.MappingBuilder; -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.client.WireMock; -import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer; -import com.github.tomakehurst.wiremock.matching.UrlPattern; -import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.lang3.StringUtils; -import org.jsmart.zerocode.core.domain.MockStep; -import org.jsmart.zerocode.core.domain.MockSteps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; - public class RestEndPointMocker { private static final Logger LOGGER = LoggerFactory.getLogger(RestEndPointMocker.class); - public static WireMockServer wireMockServer; - - public static Boolean shouldBuildStrictUrlMatcherForAllUrls = false; - - private static boolean hasMoreThanOneStubForSameUrlPath(List urls) { - Set urlPathsSet = urls.stream() - .map(u -> (u.contains("?")) ? u.substring(0, u.indexOf("?")) : u) // remove query params for comparison - .collect(Collectors.toSet()); - return urlPathsSet.size() != urls.size(); - } - - public static void createWithWireMock(MockSteps mockSteps, int mockPort) { - - restartWireMock(mockPort); - - List urls = mockSteps.getMocks() - .stream() - .map(MockStep::getUrl) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - if (urls.size() != 0 && hasMoreThanOneStubForSameUrlPath(urls)) { - shouldBuildStrictUrlMatcherForAllUrls = true; - } - LOGGER.debug("Going to build strict url matcher - {}",shouldBuildStrictUrlMatcherForAllUrls); - mockSteps.getMocks().forEach(mockStep -> { - JsonNode jsonNodeResponse = mockStep.getResponse(); - JsonNode jsonNodeBody = jsonNodeResponse.get("body"); - String jsonBodyRequest = (jsonNodeBody != null) ? jsonNodeBody.toString() : jsonNodeResponse.get("xmlBody").asText(); - - - if ("GET".equals(mockStep.getOperation())) { - LOGGER.debug("*****WireMock- Mocking the GET endpoint"); - givenThat(createGetRequestBuilder(mockStep) - .willReturn(responseBuilder(mockStep, jsonBodyRequest))); - LOGGER.debug("WireMock- Mocking the GET endpoint -done- *****"); - } else if ("POST".equals(mockStep.getOperation())) { - LOGGER.debug("*****WireMock- Mocking the POST endpoint"); - givenThat(createPostRequestBuilder(mockStep) - .willReturn(responseBuilder(mockStep, jsonBodyRequest))); - LOGGER.debug("WireMock- Mocking the POST endpoint -done-*****"); - } else if ("PUT".equals(mockStep.getOperation())) { - LOGGER.debug("*****WireMock- Mocking the PUT endpoint"); - givenThat(createPutRequestBuilder(mockStep) - .willReturn(responseBuilder(mockStep, jsonBodyRequest))); - LOGGER.debug("WireMock- Mocking the PUT endpoint -done-*****"); - } else if ("PATCH".equals(mockStep.getOperation())) { - LOGGER.debug("*****WireMock- Mocking the PATCH endpoint"); - givenThat(createPatchRequestBuilder(mockStep) - .willReturn(responseBuilder(mockStep, jsonBodyRequest))); - LOGGER.debug("WireMock- Mocking the PATCH endpoint -done-*****"); - } else if ("DELETE".equals(mockStep.getOperation())) { - LOGGER.debug("*****WireMock- Mocking the DELETE endpoint"); - givenThat(createDeleteRequestBuilder(mockStep) - .willReturn(responseBuilder(mockStep, jsonBodyRequest))); - LOGGER.debug("WireMock- Mocking the DELETE endpoint -done-*****"); - } - - }); - } - - public static void restartWireMock(int dynamicPort) { - if (wireMockServer != null) { - /* - * Stop the wireMock server if it is running previously due to any other tests. - */ - wireMockServer.stop(); - } - wireMockServer = new WireMockServer( - wireMockConfig() - .extensions(new ResponseTemplateTransformer(true, getWiremockHelpers())) - .port(dynamicPort)); // <-- Strange - wireMockServer.start(); - WireMock.configureFor("localhost", dynamicPort); // <-- Repetition of PORT was needed, this is a wireMock bug - } - - private static Map getWiremockHelpers() { - Map helperMap = new HashedMap(); - helperMap.put("localdatetime", new HandlebarsLocalDateHelper()); - return helperMap; - } - - public static void stopWireMockServer() { - if (null != wireMockServer) { - wireMockServer.stop(); - wireMockServer = null; - LOGGER.debug("Scenario: All mockings done via WireMock server. Dependant end points executed. Stopped WireMock."); - } - } - - private static MappingBuilder createDeleteRequestBuilder(MockStep mockStep) { - final MappingBuilder requestBuilder = delete(buildUrlPattern(mockStep.getUrl())); - return createRequestBuilderWithHeaders(mockStep, requestBuilder); - } - - private static MappingBuilder createPatchRequestBuilder(MockStep mockStep) { - final MappingBuilder requestBuilder = patch(buildUrlPattern(mockStep.getUrl())); - return createRequestBuilderWithHeaders(mockStep, requestBuilder); - } - - private static MappingBuilder createPutRequestBuilder(MockStep mockStep) { - final MappingBuilder requestBuilder = put(buildUrlPattern(mockStep.getUrl())); - return createRequestBuilderWithHeaders(mockStep, requestBuilder); - } - - private static MappingBuilder createPostRequestBuilder(MockStep mockStep) { - final MappingBuilder requestBuilder = post(buildUrlPattern(mockStep.getUrl())); - return createRequestBuilderWithHeaders(mockStep, requestBuilder); - } - - private static MappingBuilder createGetRequestBuilder(MockStep mockStep) { - final MappingBuilder requestBuilder = get(buildUrlPattern(mockStep.getUrl())); - return createRequestBuilderWithHeaders(mockStep, requestBuilder); - } - - private static UrlPattern buildUrlPattern(String url) { - // if url pattern doesn't have query params and shouldBuildStrictUrlMatcher is true, then match url regardless query parameters - if (url != null && !url.contains("?") && !shouldBuildStrictUrlMatcherForAllUrls) { - LOGGER.debug("Going to build lenient matcher for url={}",url); - return urlPathEqualTo(url); - } else { // if url pattern has query params then match url strictly including query params - LOGGER.debug("Going to build strict matcher for url={}",url); - return urlEqualTo(url); - } - } - - private static MappingBuilder createRequestBuilderWithHeaders(MockStep mockStep, MappingBuilder requestBuilder) { - - final String bodyJson = mockStep.getBody(); - // ----------------------------------------------- - // read request body and set to request builder - // ----------------------------------------------- - if (StringUtils.isNotEmpty(bodyJson)) { - requestBuilder.withRequestBody(equalToJson(bodyJson)); - } - - final Map headersMap = mockStep.getHeadersMap(); - // ----------------------------------------------- - // read request headers and set to request builder - // ----------------------------------------------- - if (headersMap.size() > 0) { - for (Object key : headersMap.keySet()) { - requestBuilder.withHeader((String) key, equalTo((String) headersMap.get(key))); - } - } - return requestBuilder; - } - - private static ResponseDefinitionBuilder responseBuilder(MockStep mockStep, String jsonBodyRequest) { - ResponseDefinitionBuilder responseBuilder = aResponse() - .withStatus(mockStep.getResponse().get("status").asInt()); - JsonNode headers = mockStep.getResponse().get("headers"); - JsonNode contentType = headers != null ? headers.get("Content-Type") : null; - responseBuilder = contentType != null ? - responseBuilder.withHeader("Content-Type", contentType.textValue()).withBody(jsonBodyRequest) : - responseBuilder.withBody(jsonBodyRequest); - - return responseBuilder; - } - public static int createWithLocalMock(String endPointJsonApi) { if (StringUtils.isNotEmpty(endPointJsonApi)) { - // read this json into virtuoso. + // read this json into simulator. } return 200; } - public static WireMockServer getWireMockServer() { - return wireMockServer; - } - /* * This is working code, whenever you put the virtuoso dependency here, you can uncomment this block. */ diff --git a/core/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeMultiStepsScenarioRunnerImpl.java b/core/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeMultiStepsScenarioRunnerImpl.java index 2580c9ccf..3c9a6c260 100644 --- a/core/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeMultiStepsScenarioRunnerImpl.java +++ b/core/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeMultiStepsScenarioRunnerImpl.java @@ -22,7 +22,6 @@ import org.jsmart.zerocode.core.domain.builders.ZeroCodeIoWriteBuilder; import org.jsmart.zerocode.core.engine.assertion.FieldAssertionMatcher; import org.jsmart.zerocode.core.engine.executor.ApiServiceExecutor; -import static org.jsmart.zerocode.core.engine.mocker.RestEndPointMocker.wireMockServer; import org.jsmart.zerocode.core.engine.preprocessor.ScenarioExecutionState; import org.jsmart.zerocode.core.engine.preprocessor.StepExecutionState; import org.jsmart.zerocode.core.engine.preprocessor.ZeroCodeAssertionsProcessor; @@ -142,8 +141,6 @@ public synchronized boolean runScenario(ScenarioSpec scenario, RunNotifier notif ioWriterBuilder.result(resultReportBuilder.build()); } - stopIfWireMockServerRunning(); - ioWriterBuilder.printToFile(scenario.getScenarioName() + correlLogger.getCorrelationId() + ".json"); if (wasExecSuccessful) { @@ -540,14 +537,6 @@ public void overrideApplicationContext(String applicationContext) { this.applicationContext = applicationContext; } - private void stopIfWireMockServerRunning() { - if (null != wireMockServer) { - wireMockServer.stop(); - wireMockServer = null; - LOGGER.debug("Scenario: All mockings done via WireMock server. Dependant end points executed. Stopped WireMock."); - } - } - private int deriveScenarioLoopTimes(ScenarioSpec scenario) { int scenarioLoopTimes = scenario.getLoop() == null ? 1 : scenario.getLoop(); int parameterSize = getParameterSize(scenario.getParameterized()); diff --git a/core/src/main/java/org/jsmart/zerocode/core/zzignored/mocking/WireMockJsonContentTesting.java b/core/src/main/java/org/jsmart/zerocode/core/zzignored/mocking/WireMockJsonContentTesting.java deleted file mode 100644 index 26dd1e591..000000000 --- a/core/src/main/java/org/jsmart/zerocode/core/zzignored/mocking/WireMockJsonContentTesting.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.jsmart.zerocode.core.zzignored.mocking; - -import com.github.tomakehurst.wiremock.client.WireMock; -import com.github.tomakehurst.wiremock.junit.WireMockRule; - -import org.junit.Rule; -import org.junit.Test; -import org.skyscreamer.jsonassert.JSONAssert; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.givenThat; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; - -public class WireMockJsonContentTesting { - @Rule - public WireMockRule rule = new WireMockRule(9073); - - @Test - public void bioViaJson() throws Exception{ - String jsonBodyRequest = "{\n" + - " \"id\": \"303021\",\n" + - " \"names\": [\n" + - " {\n" + - " \"firstName\": \"You First\",\n" + - " \"lastName\": \"Me Last\"\n" + - " }\n" + - " ]\n" + - "}"; - - givenThat(WireMock.get(urlEqualTo("/id-services/id-services/person/id/p_id_009/bio/default")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", APPLICATION_JSON) - .withBody(jsonBodyRequest))); - - Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://localhost:9073/id-services/id-services/person/id/p_id_009/bio/default"); - Response response = target.request().get(); - final String respBodyAsString = response.readEntity(String.class); - JSONAssert.assertEquals(jsonBodyRequest, respBodyAsString, true); - - System.out.println("### bio response from mapping: \n" + respBodyAsString); - } -} \ No newline at end of file diff --git a/core/src/test/java/org/jsmart/zerocode/core/domain/MockStepTest.java b/core/src/test/java/org/jsmart/zerocode/core/domain/MockStepTest.java deleted file mode 100644 index 51a6d3cf9..000000000 --- a/core/src/test/java/org/jsmart/zerocode/core/domain/MockStepTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.jsmart.zerocode.core.domain; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.jsmart.zerocode.core.di.provider.ObjectMapperProvider; -import org.jsmart.zerocode.core.utils.SmartUtils; -import org.junit.Test; - -import java.util.HashMap; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -/** - * See also: - * RestEndPointMockerTest.java - for integration tests. - * - */ -public class MockStepTest { - - private ObjectMapper objectMapper = new ObjectMapperProvider().get(); - - @Test - public void testSerDeSer() throws Exception { - final String aMock = SmartUtils.readJsonAsString("unit_test_files/wiremock/test_mock_step.json"); - - final MockStep mockStep = objectMapper.readValue(aMock, MockStep.class); - - assertThat(mockStep.getOperation(), is("GET")); - assertThat(mockStep.getResponse().get("status").asInt(), is(200)); - assertThat(mockStep.getResponse().get("status").intValue(), is(200)); - assertThat(mockStep.getResponse().get("status").toString(), is("200")); - - } - - @Test - public void testSerDeSer_headers() throws Exception { - final String aMock = SmartUtils.readJsonAsString("unit_test_files/wiremock/test_mock_step_request_headers.json"); - - final MockStep mockStep = objectMapper.readValue(aMock, MockStep.class); - - assertThat(mockStep.getOperation(), is("GET")); - assertThat(mockStep.getRequest().get("headers").toString(), is("{\"key\":\"key-001\",\"secret\":\"secret-001\"}")); - - HashMap headersMap = (HashMap)objectMapper.readValue(mockStep.getRequest().get("headers").toString(), HashMap.class); - assertThat(headersMap.get("key"), is("key-001")); - assertThat(headersMap.get("secret"), is("secret-001")); - - } - - @Test - public void testSerDeSer_body() throws Exception { - final String aMock = SmartUtils.readJsonAsString("unit_test_files/wiremock/test_mock_step_request_body.json"); - - final MockStep mockStep = objectMapper.readValue(aMock, MockStep.class); - - assertThat(mockStep.getOperation(), is("GET")); - assertThat(mockStep.getRequest().get("body").toString(), - is("{\"name\":\"Emma\",\"age\":33,\"address\":{\"line1\":\"address line 1\",\"line2\":\"address line 2\"}}")); - - // The followings are not needed as WireMock will accept the full JSON body as it is - HashMap bodyAsMap = (HashMap)objectMapper.readValue(mockStep.getRequest().get("body").toString(), HashMap.class); - assertThat(bodyAsMap.get("name"), is("Emma")); - assertThat(((HashMap)bodyAsMap.get("address")).get("line1"), is("address line 1")); - - } -} \ No newline at end of file diff --git a/core/src/test/java/org/jsmart/zerocode/core/engine/mocker/RestEndPointMockerTest.java b/core/src/test/java/org/jsmart/zerocode/core/engine/mocker/RestEndPointMockerTest.java deleted file mode 100644 index 308b93282..000000000 --- a/core/src/test/java/org/jsmart/zerocode/core/engine/mocker/RestEndPointMockerTest.java +++ /dev/null @@ -1,408 +0,0 @@ -package org.jsmart.zerocode.core.engine.mocker; - - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.tomakehurst.wiremock.client.MappingBuilder; -import com.github.tomakehurst.wiremock.client.WireMock; -import com.github.tomakehurst.wiremock.junit.WireMockRule; -import com.google.inject.AbstractModule; -import jakarta.inject.Inject; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.jsmart.zerocode.core.di.main.ApplicationMainModule; -import org.jsmart.zerocode.core.domain.MockStep; -import org.jsmart.zerocode.core.domain.MockSteps; -import org.jsmart.zerocode.core.domain.ScenarioSpec; -import org.jsmart.zerocode.core.guice.ZeroCodeGuiceTestRule; -import org.jsmart.zerocode.core.utils.SmartUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.skyscreamer.jsonassert.JSONAssert; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; -import java.util.Map; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; -import static com.github.tomakehurst.wiremock.client.WireMock.equalToXml; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.givenThat; -import static com.github.tomakehurst.wiremock.client.WireMock.patch; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.jsmart.zerocode.core.engine.mocker.RestEndPointMocker.createWithWireMock; -import static org.jsmart.zerocode.core.engine.mocker.RestEndPointMocker.getWireMockServer; - -public class RestEndPointMockerTest { - @Rule - public ZeroCodeGuiceTestRule guiceRule = new ZeroCodeGuiceTestRule(this, RestEndPointMockerTest.ZeroCodeTestModule.class); - - public static class ZeroCodeTestModule extends AbstractModule { - @Override - protected void configure() { - ApplicationMainModule applicationMainModule = new ApplicationMainModule("config_hosts_test.properties"); - - /* Finally install the main module */ - install(applicationMainModule); - } - } - - @Inject - SmartUtils smartUtils; - - @Inject - private ObjectMapper objectMapper; - - @Rule - public WireMockRule rule = new WireMockRule(9073); - - RestEndPointMocker restEndPointMocker; - String jsonDocumentAsString; - ScenarioSpec scenarioDeserialized; - MockSteps mockSteps; - - @Before - public void beforeMethod() throws Exception { - restEndPointMocker = new RestEndPointMocker(); - - WireMock.configureFor(9073); - - jsonDocumentAsString = smartUtils.getJsonDocumentAsString("integration_test_files/wiremock_integration/wiremock_end_point_json_body.json"); - scenarioDeserialized = objectMapper.readValue(jsonDocumentAsString, ScenarioSpec.class); - mockSteps = smartUtils.getMapper().readValue(scenarioDeserialized.getSteps().get(0).getRequest().toString(), MockSteps.class); - - } - - @Test - public void willDeserializeA_VanilaFlow() throws Exception { - - assertThat(scenarioDeserialized, notNullValue()); - assertThat(scenarioDeserialized.getSteps().size(), is(1)); - assertThat(scenarioDeserialized.getScenarioName(), containsString("create_mocks")); - - MockSteps mockSteps = smartUtils.getMapper().readValue(scenarioDeserialized.getSteps().get(0).getRequest().toString(), MockSteps.class); - - assertThat(mockSteps.getMocks().get(0).getName(), containsString("Mock the Get Person")); - assertThat(mockSteps.getMocks().get(1).getName(), containsString("Mock the POST Person")); - assertThat(mockSteps.getMocks().get(2).getName(), containsString("Mock the PATCH Person")); - - MockStep mockStepGET = mockSteps.getMocks().get(0); - assertThat(mockStepGET.getOperation(), is("GET")); - assertThat(mockStepGET.getResponse().get("status").asInt(), is(200)); - assertThat(mockStepGET.getResponse().get("status").intValue(), is(200)); - assertThat(mockStepGET.getResponse().get("status").toString(), is("200")); - JSONAssert.assertEquals(mockSteps.getMocks().get(0).getResponse().get("body").toString(), - "{\n" + - " \"id\": \"p001\",\n" + - " \"source\": {\n" + - " \"code\": \"GOOGLE.UK\"\n" + - " }\n" + - " }", - - true); - - } - - @Test - public void willMockASimpleGetEndPoint() throws Exception { - - final MockStep mockStep = mockSteps.getMocks().get(0); - String jsonBodyRequest = mockStep.getResponse().get("body").toString(); - - WireMock.configureFor(9073); - givenThat(get(urlEqualTo(mockStep.getUrl())) - .willReturn(aResponse() - .withStatus(mockStep.getResponse().get("status").asInt()) - .withHeader("Content-Type", APPLICATION_JSON) - .withBody(jsonBodyRequest))); - - Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://localhost:9073" + mockStep.getUrl()); - Response response = target.request().get(); - final String respBodyAsString = response.readEntity(String.class); - JSONAssert.assertEquals(jsonBodyRequest, respBodyAsString, true); - - System.out.println("### zerocode: \n" + respBodyAsString); - - } - - @Test - public void willMockRequest_withAnyQueryParameters() throws Exception { - - int WIRE_MOCK_TEST_PORT = 9077; - - final MockStep mockGetRequest = mockSteps.getMocks().get(0); - String respBody = mockGetRequest.getResponse().get("body").toString(); - - createWithWireMock(mockSteps, WIRE_MOCK_TEST_PORT); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:" + WIRE_MOCK_TEST_PORT + mockGetRequest.getUrl() + "?param1=value1¶m2=value2"); - request.addHeader("key", "key-007"); - request.addHeader("secret", "secret-007"); - HttpResponse response = httpClient.execute(request); - - final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); - System.out.println("### response: \n" + responseBodyActual); - System.out.print(response); - - assertThat(response.getStatusLine().getStatusCode(), is(200)); - JSONAssert.assertEquals(respBody, responseBodyActual, true); - - Assert.assertEquals("Content-Type", response.getEntity().getContentType().getName()); - Assert.assertEquals("application/json", response.getEntity().getContentType().getValue()); - - getWireMockServer().stop(); - } - - @Test - public void willMockAPostRequest() throws Exception { - - final MockStep mockPost = mockSteps.getMocks().get(1); - String jsonBodyResponse = mockPost.getResponse().get("body").toString(); - - final String bodyJson = mockPost.getRequest().get("body").toString(); //"{ \"id\" : \"p002\" }"; - stubFor(post(urlEqualTo(mockPost.getUrl())) - .withRequestBody(equalToJson(bodyJson)) - .willReturn(aResponse() - .withStatus(mockPost.getResponse().get("status").asInt()) - .withHeader("Content-Type", APPLICATION_JSON) - .withBody(jsonBodyResponse))); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost request = new HttpPost("http://localhost:9073" + mockPost.getUrl()); - request.addHeader("Content-Type", "application/json"); - StringEntity entity = new StringEntity(bodyJson); - request.setEntity(entity); - HttpResponse response = httpClient.execute(request); - - final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); - System.out.println("### response: \n" + responseBodyActual); - - assertThat(response.getStatusLine().getStatusCode(), is(201)); - JSONAssert.assertEquals(jsonBodyResponse, responseBodyActual, true); - - } - - @Test - public void willMockAPATCHRequest() throws Exception { - - final MockStep mockPatch = mockSteps.getMocks().get(2); - String jsonBodyResponse = mockPatch.getResponse().get("body").toString(); // { "id": "cust345", "message": "email updated" } - - final String bodyJson = mockPatch.getRequest().get("body").toString(); // { "email": "new_email_to_update@gmail.com" } - stubFor(patch(urlEqualTo(mockPatch.getUrl())) - .withRequestBody(equalToJson(bodyJson)) - .willReturn(aResponse() - .withStatus(mockPatch.getResponse().get("status").asInt()) - .withHeader("Content-Type", APPLICATION_JSON) - .withBody(jsonBodyResponse))); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPatch request = new HttpPatch("http://localhost:9073" + mockPatch.getUrl()); - request.addHeader("Content-Type", "application/json"); - StringEntity entity = new StringEntity(bodyJson); - request.setEntity(entity); - HttpResponse response = httpClient.execute(request); - - final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); - System.out.println("### response: \n" + responseBodyActual); - - assertThat(response.getStatusLine().getStatusCode(), is(200)); - JSONAssert.assertEquals(jsonBodyResponse, responseBodyActual, true); - - } - - @Test - public void willMockADELETERequest() throws Exception { - - final MockStep mockDelete = mockSteps.getMocks().get(3); - - stubFor(delete(urlEqualTo(mockDelete.getUrl())) - .willReturn(aResponse() - .withStatus(mockDelete.getResponse().get("status").asInt()) - .withHeader("Content-Type", APPLICATION_JSON))); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpDelete request = new HttpDelete("http://localhost:9073" + mockDelete.getUrl()); - request.addHeader("Content-Type", "application/json"); - HttpResponse response = httpClient.execute(request); - - assertThat(response.getStatusLine().getStatusCode(), is(204)); - - } - - @Test - public void willMockRequest_jsonBody() throws Exception { - - int WIRE_MOCK_TEST_PORT = 9077; - - final MockStep mockPost = mockSteps.getMocks().get(1); - final String reqBody = mockPost.getRequest().get("body").toString(); //"{ \"id\" : \"p002\" }"; - String respBody = mockPost.getResponse().get("body").toString(); - - createWithWireMock(mockSteps, WIRE_MOCK_TEST_PORT); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost request = new HttpPost("http://localhost:" + WIRE_MOCK_TEST_PORT + mockPost.getUrl()); - request.addHeader("Content-Type", "application/json"); - StringEntity entity = new StringEntity(reqBody); - request.setEntity(entity); - HttpResponse response = httpClient.execute(request); - - final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); - System.out.println("### response: \n" + responseBodyActual); - - assertThat(response.getStatusLine().getStatusCode(), is(201)); - JSONAssert.assertEquals(respBody, responseBodyActual, true); - - getWireMockServer().stop(); - } - - @Test - public void willMockRequest_respond_with_contentType() throws Exception { - - int WIRE_MOCK_TEST_PORT = 9077; - - final MockStep mockGetRequest = mockSteps.getMocks().get(0); - String respBody = mockGetRequest.getResponse().get("body").toString(); - - createWithWireMock(mockSteps, WIRE_MOCK_TEST_PORT); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:" + WIRE_MOCK_TEST_PORT + mockGetRequest.getUrl()); - request.addHeader("key", "key-007"); - request.addHeader("secret", "secret-007"); - HttpResponse response = httpClient.execute(request); - - final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); - System.out.println("### response: \n" + responseBodyActual); - - assertThat(response.getStatusLine().getStatusCode(), is(200)); - JSONAssert.assertEquals(respBody, responseBodyActual, true); - - Assert.assertEquals("Content-Type", response.getEntity().getContentType().getName()); - Assert.assertEquals("application/json", response.getEntity().getContentType().getValue()); - - getWireMockServer().stop(); - } - - // -------------------------------------------------------------- - // ISSUE-202 - https://github.com/authorjapps/zerocode/issues/202 - // - xmlBody for SOAP mocking - // - Fixed by - arunvelusamyd - // -------------------------------------------------------------- - @Test - public void willMockRequest_xmlBody() throws Exception { - int WIRE_MOCK_TEST_PORT = 9077; - - String jsonDocumentAsString = smartUtils.getJsonDocumentAsString("integration_test_files/wiremock_integration/wiremock_end_point_soap_xml_body.json"); - ScenarioSpec scenarioDeserialized = objectMapper.readValue(jsonDocumentAsString, ScenarioSpec.class); - MockSteps mockSteps = smartUtils.getMapper().readValue(scenarioDeserialized.getSteps().get(0).getRequest().toString(), MockSteps.class); - - final MockStep mockPost = mockSteps.getMocks().get(0); - - createWithWireMock(mockSteps, WIRE_MOCK_TEST_PORT); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost request = new HttpPost("http://localhost:" + WIRE_MOCK_TEST_PORT + mockPost.getUrl()); - HttpResponse response = httpClient.execute(request); - - final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); - System.out.println("### response: \n" + responseBodyActual); - - assertThat(response.getStatusLine().getStatusCode(), is(200)); - assertThat(responseBodyActual, containsString("It is a tablet computers designed, developed and marketed by Apple.")); - - getWireMockServer().stop(); - } - - @Test - public void willMockAGetRequestWith_headers() throws Exception { - - final MockStep mockGetStep = mockSteps.getMocks().get(0); - final Map headersMap = mockGetStep.getHeadersMap(); - - final MappingBuilder requestBuilder = get(urlEqualTo(mockGetStep.getUrl())); - - // read request headers and set to request builder - if (headersMap.size() > 0) { - for (Object key : headersMap.keySet()) { - requestBuilder.withHeader((String) key, equalTo((String) headersMap.get(key))); - } - } - - String jsonBodyResponse = mockGetStep.getResponse().get("body").toString(); - - stubFor(requestBuilder - .willReturn(aResponse() - .withStatus(mockGetStep.getResponse().get("status").asInt()) - //.withHeader("Content-Type", APPLICATION_JSON) - .withBody(jsonBodyResponse))); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:9073" + mockGetStep.getUrl()); - request.addHeader("key", "key-007"); - request.addHeader("secret", "secret-007"); - - HttpResponse response = httpClient.execute(request); - final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); - System.out.println("### response: \n" + responseBodyActual); - - assertThat(response.getStatusLine().getStatusCode(), is(200)); - JSONAssert.assertEquals(jsonBodyResponse, responseBodyActual, true); - - } - - @Test - public void willMockASoapEndPoint() throws Exception { - - WireMock.configureFor(9073); - - String soapRequest = smartUtils.getJsonDocumentAsString("unit_test_files/soap_stub/soap_request.xml"); - - final MappingBuilder requestBuilder = post(urlEqualTo("/samples/testcomplete12/webservices/Service.asmx")); - requestBuilder.withRequestBody(equalToXml(soapRequest)); - requestBuilder.withHeader("Content-Type", equalTo("application/soap+xml; charset=utf-8")); - - String soapResponseExpected = smartUtils.getJsonDocumentAsString("unit_test_files/soap_stub/soap_response.xml"); - stubFor(requestBuilder - .willReturn(aResponse() - .withStatus(200) - //.withHeader("Content-Type", APPLICATION_JSON) - .withBody(soapResponseExpected))); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost request = new HttpPost("http://localhost:9073" + "/samples/testcomplete12/webservices/Service.asmx"); - request.addHeader("Content-Type", "application/soap+xml; charset=utf-8"); - StringEntity entity = new StringEntity(soapRequest); - request.setEntity(entity); - HttpResponse response = httpClient.execute(request); - - final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); - - assertThat(responseBodyActual, is(soapResponseExpected)); - } - -} \ No newline at end of file diff --git a/core/src/test/java/org/jsmart/zerocode/core/httpclient/BasicHttpClientTest.java b/core/src/test/java/org/jsmart/zerocode/core/httpclient/BasicHttpClientTest.java index 60d0deb75..806288e10 100644 --- a/core/src/test/java/org/jsmart/zerocode/core/httpclient/BasicHttpClientTest.java +++ b/core/src/test/java/org/jsmart/zerocode/core/httpclient/BasicHttpClientTest.java @@ -1,7 +1,5 @@ package org.jsmart.zerocode.core.httpclient; -import com.github.tomakehurst.wiremock.client.WireMock; -import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URISyntaxException; import java.util.HashMap; @@ -9,33 +7,18 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; -import org.hamcrest.CoreMatchers; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.givenThat; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNot.not; public class BasicHttpClientTest { private BasicHttpClient basicHttpClient; private Map header; - @Rule - public WireMockRule rule = new WireMockRule(9073); - @Before public void setUp() { basicHttpClient = new BasicHttpClient(); @@ -133,87 +116,4 @@ public void test_multipart_without_file() throws IOException { basicHttpClient.createFileUploadRequestBuilder("http://test-url", "POST", "{\"modelStorage\":\"DB\",\"sketchingAlgorithm\":\"UPDATE\"}"); } - @Test - public void willMockUTF16Response() throws Exception { - WireMock.configureFor(9073); - givenThat(get(urlEqualTo("/charset/utf16")) - .willReturn(aResponse() - .withStatus(200) - // ------------------------------------------------------------------------ - // If you make the value charset=UTF-8, the test will fail, that means - // When server is sending UTF-16 encoded chars, it should also set the - // charset to UTF-16 e.g. "application/json; charset=UTF-16", if not set - // by the server, the framework will default to UTF-8 and will not be able - // to interpret the chars as expected - // ------------------------------------------------------------------------ - .withHeader("Content-Type", "application/json; charset=UTF-16") - // ------------------------------------------------------------------------ - // "This is utf-16 text" is utf-16 encoded and converted to base64. - // Reference Link: https://www.base64encode.org/ - // ------------------------------------------------------------------------ - .withBase64Body("//5UAGgAaQBzACAAaQBzACAAdQB0AGYALQAxADYAIAB0AGUAeAB0AA=="))); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:9073" + "/charset/utf16"); - - CloseableHttpResponse response = httpClient.execute(request); - - BasicHttpClient basicHttpClient = new BasicHttpClient(); - String responseBodyActual = (String) basicHttpClient.handleResponse(response).getEntity(); - assertThat(responseBodyActual, CoreMatchers.is("This is utf-16 text")); - - // -------------------------------------- - // Now set to UTF-8 and see the assertion - // -------------------------------------- - givenThat(get(urlEqualTo("/charset/utf16")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/json; charset=UTF-8") - .withBase64Body("//5UAGgAaQBzACAAaQBzACAAdQB0AGYALQAxADYAIAB0AGUAeAB0AA=="))); - response = httpClient.execute(request); - responseBodyActual = (String) basicHttpClient.handleResponse(response).getEntity(); - assertThat(responseBodyActual, not("This is utf-16 text")); - } - - @Test - public void willMockUTF8Response() throws Exception { - - final String response = "utf-8 encoded text"; - WireMock.configureFor(9073); - givenThat(get(urlEqualTo("/charset/utf8")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/json; charset=UTF-8") - .withBody(response))); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:9073" + "/charset/utf8"); - - CloseableHttpResponse closeableHttpResponse = httpClient.execute(request); - - BasicHttpClient basicHttpClient = new BasicHttpClient(); - final String responseBodyActual = (String) basicHttpClient.handleResponse(closeableHttpResponse).getEntity(); - assertThat(responseBodyActual, CoreMatchers.is(response)); - } - - @Test - public void willMockDefaultResponseEncoding() throws Exception { - - final String response = "utf-8 encoded text"; - WireMock.configureFor(9073); - givenThat(get(urlEqualTo("/charset/none")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", APPLICATION_JSON) - .withBody(response))); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:9073" + "/charset/none"); - - CloseableHttpResponse closeableHttpResponse = httpClient.execute(request); - - BasicHttpClient basicHttpClient = new BasicHttpClient(); - final String responseBodyActual = (String) basicHttpClient.handleResponse(closeableHttpResponse).getEntity(); - assertThat(responseBodyActual, CoreMatchers.is(response)); - } } \ No newline at end of file diff --git a/core/src/test/java/org/jsmart/zerocode/core/httpclient/ssl/SslTrustHttpClientTest.java b/core/src/test/java/org/jsmart/zerocode/core/httpclient/ssl/SslTrustHttpClientTest.java deleted file mode 100644 index 7cd2bcedc..000000000 --- a/core/src/test/java/org/jsmart/zerocode/core/httpclient/ssl/SslTrustHttpClientTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.jsmart.zerocode.core.httpclient.ssl; - -import com.github.tomakehurst.wiremock.WireMockServer; -import java.net.SocketTimeoutException; -import java.util.HashMap; -import javax.ws.rs.core.Response; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class SslTrustHttpClientTest { - - @Mock - CloseableHttpClient httpClient; - - @InjectMocks - SslTrustHttpClient sslTrustHttpClient; - - static String basePath; - static String fullPath; - static int port = 8383; - - static WireMockServer mockServer = new WireMockServer(port); - - public static final int SERVER_DELAY = 2000; - public static final int MAX_IMPLICIT_WAIT_HIGH = 3000; - public static final int MAX_IMPLICIT_WAIT_LOW = 1500; - - @BeforeClass - public static void setUpWireMock() throws Exception { - basePath = "http://localhost:" + port; - String path = "/delay/ids/1"; - fullPath = basePath + path; - - mockServer.start(); - - mockServer.stubFor( - get(urlEqualTo(path)) - .willReturn(aResponse() - .withStatus(200) - .withFixedDelay(SERVER_DELAY) - )); - - } - - @AfterClass - public static void tearDown() { - mockServer.shutdown(); - } - - @Ignore("TODO-- unit test. Already Covered in the integration tests") - @Test - public void testNulPointerNotThrown_emptyBody() throws Exception { - CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class); - HttpUriRequest mockHttpUriRequest = mock(HttpUriRequest.class); - when(httpClient.execute(any())).thenReturn(mockResponse); - //when(requestBuilder.build()).thenReturn(mockHttpUriRequest); - - // when(httpClient.execute(anyString(), anyString(), anyMap(), anyMap(), anyObject())) - // .thenReturn(mockResponse); - Response actualResponse = sslTrustHttpClient.execute("url", - "GET", - new HashMap(), - new HashMap(), - "aBody"); - System.out.println("" + actualResponse); - } - - @Test - public void testImplicitDelay() throws Exception { - SslTrustHttpClient sslTrustHttpClient = new SslTrustHttpClient(); - sslTrustHttpClient.setImplicitWait(MAX_IMPLICIT_WAIT_HIGH); //Ok - More than the implicit - - CloseableHttpClient httpClient = sslTrustHttpClient.createHttpClient(); - - HttpGet request = new HttpGet(fullPath); - HttpResponse response = httpClient.execute(request); - - assertThat(response.getStatusLine().getStatusCode(), is(200)); - } - - @Test(expected = SocketTimeoutException.class) - public void testImplicitDelay_timeout() throws Exception { - SslTrustHttpClient sslTrustHttpClient = new SslTrustHttpClient(); - sslTrustHttpClient.setImplicitWait(MAX_IMPLICIT_WAIT_LOW); //Timeout - Less than the implicit - - CloseableHttpClient httpClient = sslTrustHttpClient.createHttpClient(); - - HttpGet request = new HttpGet(fullPath); - HttpResponse response = httpClient.execute(request); - } - - @Test - public void testImplicitDelay_noConfig() throws Exception { - SslTrustHttpClient sslTrustHttpClient = new SslTrustHttpClient(); - //sslTrustHttpClient.setImplicitWait(none); //not configured - - CloseableHttpClient httpClient = sslTrustHttpClient.createHttpClient(); - - HttpGet request = new HttpGet(fullPath); - HttpResponse response = httpClient.execute(request); - assertThat(response.getStatusLine().getStatusCode(), is(200)); - } -} \ No newline at end of file diff --git a/core/src/test/java/org/jsmart/zerocode/core/runner/retry/RetryTestCases.java b/core/src/test/java/org/jsmart/zerocode/core/runner/retry/RetryTestCases.java deleted file mode 100644 index 7673e87cf..000000000 --- a/core/src/test/java/org/jsmart/zerocode/core/runner/retry/RetryTestCases.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.jsmart.zerocode.core.runner.retry; - -import org.jsmart.zerocode.core.domain.JsonTestCase; -import org.jsmart.zerocode.core.domain.TargetEnv; -import org.jsmart.zerocode.core.tests.customrunner.TestOnlyZeroCodeUnitRunner; -import org.junit.Test; -import org.junit.runner.RunWith; - -@TargetEnv("dev_test.properties") -@RunWith(TestOnlyZeroCodeUnitRunner.class) -public class RetryTestCases { - - @Test - @JsonTestCase("integration_test_files/retry_test_cases/01_REST_with_retry_test.json") - public void restRetry() { - - } - - @Test - @JsonTestCase("integration_test_files/retry_test_cases/02_REST_with_retry_within_loop_test.json") - public void restRetryWithinLoop() { - - } - - @Test - @JsonTestCase("integration_test_files/retry_test_cases/03_failing_REST_with_retry_within_loop_test.json") - public void failingRestRetryWithinLoop() { - - } -} diff --git a/core/src/test/java/org/jsmart/zerocode/core/runner/retry/RetryWithStateTest.java b/core/src/test/java/org/jsmart/zerocode/core/runner/retry/RetryWithStateTest.java deleted file mode 100644 index f42bf30f5..000000000 --- a/core/src/test/java/org/jsmart/zerocode/core/runner/retry/RetryWithStateTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.jsmart.zerocode.core.runner.retry; - -import com.github.tomakehurst.wiremock.WireMockServer; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.jsmart.zerocode.core.domain.JsonTestCase; -import org.jsmart.zerocode.core.domain.TargetEnv; -import org.jsmart.zerocode.core.runner.ZeroCodeUnitRunner; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED; -import static java.lang.Thread.sleep; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -@TargetEnv("dev_test.properties") -@RunWith(ZeroCodeUnitRunner.class) -public class RetryWithStateTest { - private static final Logger LOGGER = LoggerFactory.getLogger(RetryWithStateTest.class); - - static String basePath; - static String fullPath; - static int port = 8484; - - static WireMockServer mockServer; - - @BeforeClass - public static void setUpWireMock() throws Exception { - mockServer = new WireMockServer(port); - basePath = "http://localhost:" + port; - String path = "/retry/ids/1"; - fullPath = basePath + path; - - mockServer.start(); - - mockServer.stubFor(get(urlEqualTo(path)) - .inScenario("Retry Scenario") - .whenScenarioStateIs(STARTED) - .willReturn(aResponse() - .withStatus(500)) - .willSetStateTo("retry") - ); - - mockServer.stubFor(get(urlEqualTo(path)) - .inScenario("Retry Scenario") - .whenScenarioStateIs("retry") - .willReturn(aResponse() - .withStatus(200)) - ); - } - - @AfterClass - public static void tearDown() { - LOGGER.debug("##Stopping the mock server and then shutting down"); - mockServer.stop(); - mockServer.shutdown(); - LOGGER.debug("##Successfully stopped the mock server and then SHUTDOWN."); - } - - @Test - @JsonTestCase("integration_test_files/retry_test_cases/04_REST_retry_with_state_test.json") - public void testRetryScenario() { - } - - @Ignore("Only for sanity") - @Test - public void testRetry() throws Exception { - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet(fullPath); - - HttpResponse response = httpClient.execute(request); - assertThat(response.getStatusLine().getStatusCode(), is(500)); - - sleep(1000); - - response = httpClient.execute(request); - assertThat(response.getStatusLine().getStatusCode(), is(200)); - } -} diff --git a/core/src/test/java/org/jsmart/zerocode/core/runner/retry/ZeroCodeMultiStepsScenarioRunnerImplRetryTest.java b/core/src/test/java/org/jsmart/zerocode/core/runner/retry/ZeroCodeMultiStepsScenarioRunnerImplRetryTest.java deleted file mode 100644 index 99d1e7a37..000000000 --- a/core/src/test/java/org/jsmart/zerocode/core/runner/retry/ZeroCodeMultiStepsScenarioRunnerImplRetryTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.jsmart.zerocode.core.runner.retry; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.jsmart.zerocode.core.di.provider.ObjectMapperProvider; -import org.jsmart.zerocode.core.domain.reports.ZeroCodeReport; -import org.jsmart.zerocode.core.constants.ZeroCodeReportConstants; -import org.jsmart.zerocode.core.domain.reports.ZeroCodeReportStep; -import org.junit.Test; -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.jsmart.zerocode.core.constants.ZeroCodeReportConstants.TARGET_REPORT_DIR; - -public class ZeroCodeMultiStepsScenarioRunnerImplRetryTest { - - private static final ObjectMapper mapper = new ObjectMapperProvider().get(); - - @Test - public void testRetryScenarios() { - - final String SCENARIO_RETRY = "Rest with Retry Test"; - final String SCENARIO_RETRY_LOOP = "Rest with Retry within loop Test"; - final String SCENARIO_FAILED_RETRY_LOOP = "Failing Rest with Retry within loop Test"; - - // mvn test without clean, or launching the test repeatedly from within the ide, - // leaves the reports from the previous run in the target-directory. - // Because we use the reports of *this* run to assert, we clean out the old ones. - deleteScenarioReport(SCENARIO_RETRY); - deleteScenarioReport(SCENARIO_RETRY_LOOP); - deleteScenarioReport(SCENARIO_FAILED_RETRY_LOOP); - - Result result = JUnitCore.runClasses(RetryTestCases.class); - assertThat(result.getRunCount(), is(3)); - - ZeroCodeReport restWithRetryReport = getScenarioReport(SCENARIO_RETRY); - // loop: 0, retry-max: 12 - // the first attempts fails, the second one succeeds, which ends the retry mechanism - // note that the first step in all scenarios is the call to wiremock, hence the index starts at 1 - assertStepFailed(restWithRetryReport, 1); - assertStepSucceeded(restWithRetryReport, 2); - - ZeroCodeReport restWithRetryWithinLoopReport = getScenarioReport(SCENARIO_RETRY_LOOP); - // loop: 0, retry-max: 3 - // in the first loop-iteration, the first attempt fails. The second one succeeds, ending this loop-iteration - assertStepFailed(restWithRetryReport, 1); - assertStepSucceeded(restWithRetryWithinLoopReport, 2); - assertStepCount(restWithRetryWithinLoopReport, 3); - - ZeroCodeReport failingRestWithRetryWithinLoopReport = getScenarioReport(SCENARIO_FAILED_RETRY_LOOP); - // loop: 0, retry-max: 3 - // all requests fail: it retries 3 times in the first loop-iteration - // This makes the first loop-iteration fail, so the second is not executed - // so we expect to see only 3 failed attempts - assertStepFailed(failingRestWithRetryWithinLoopReport, 1); - assertStepFailed(failingRestWithRetryWithinLoopReport, 2); - assertStepFailed(failingRestWithRetryWithinLoopReport, 3); - - assertStepCount(failingRestWithRetryWithinLoopReport, 4); - - } - - private void deleteScenarioReport(String scenarioName) { - List scenarioReportFiles = findScenarioReportFiles(scenarioName); - for (File file : scenarioReportFiles) { - file.delete(); - } - } - - private ZeroCodeReport getScenarioReport(String scenarioName) { - List scenarioReportFiles = findScenarioReportFiles(scenarioName); - assertThat(scenarioReportFiles.size(), is(1)); - return fileToZeroCodeReport(scenarioReportFiles.get(0)); - } - - private void assertStepSucceeded(ZeroCodeReport report, int stepIndex) { - ZeroCodeReportStep step = getStep(report, stepIndex); - assertThat(step.getResult(), is(ZeroCodeReportConstants.RESULT_PASS)); - } - - private void assertStepFailed(ZeroCodeReport report, int stepIndex) { - ZeroCodeReportStep step = getStep(report, stepIndex); - assertThat(step.getResult(), is(ZeroCodeReportConstants.RESULT_FAIL)); - } - - private void assertStepCount(ZeroCodeReport report, int stepCount) { - assertThat(report.getResults().get(0).getSteps().size(), is(stepCount)); - } - - private ZeroCodeReportStep getStep(ZeroCodeReport report, int stepIndex) { - return report.getResults().get(0).getSteps().get(stepIndex); - } - - - private List findScenarioReportFiles(String scenarioName) { - File[] files = new File(TARGET_REPORT_DIR).listFiles((dir, fileName) -> fileName.matches(scenarioName + "([a-f0-9-]*)\\.json$")); - if ( files == null ) { - return new ArrayList<>(); - } - return Arrays.asList(files); - } - - private ZeroCodeReport fileToZeroCodeReport(File thisFile) { - try { - return mapper.readValue(new File(thisFile.getAbsolutePath()), ZeroCodeReport.class); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/core/src/test/java/org/jsmart/zerocode/core/tests/SmartJUnitRunnerTestCases.java b/core/src/test/java/org/jsmart/zerocode/core/tests/SmartJUnitRunnerTestCases.java index c9a76d6e8..2c0e764cc 100644 --- a/core/src/test/java/org/jsmart/zerocode/core/tests/SmartJUnitRunnerTestCases.java +++ b/core/src/test/java/org/jsmart/zerocode/core/tests/SmartJUnitRunnerTestCases.java @@ -43,12 +43,6 @@ public void testASmartTestCase_request_response__and_assertion_path() throws Exc } - @Test - @JsonTestCase("integration_test_files/json_paths_jayway/06_will_mock_using_wiremock_and_run_other_steps.json") - public void willMockAndRunNextStep() throws Exception { - - } - @Test @JsonTestCase("integration_test_files/json_paths_jayway/07_REST_with_loop_test.json") public void restViaLoop() throws Exception { diff --git a/core/src/test/java/org/jsmart/zerocode/wiremock/WireMockIntegrationTest.java b/core/src/test/java/org/jsmart/zerocode/wiremock/WireMockIntegrationTest.java deleted file mode 100644 index c91cf1a2b..000000000 --- a/core/src/test/java/org/jsmart/zerocode/wiremock/WireMockIntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.jsmart.zerocode.wiremock; - -import org.jsmart.zerocode.core.domain.JsonTestCase; -import org.jsmart.zerocode.core.domain.TargetEnv; -import org.jsmart.zerocode.core.runner.ZeroCodeUnitRunner; -import org.junit.Test; -import org.junit.runner.RunWith; - -@TargetEnv("web_app.properties") -@RunWith(ZeroCodeUnitRunner.class) -public class WireMockIntegrationTest { - - @Test - @JsonTestCase("integration_test_files/wiremock_integration/mock_via_wiremock_then_test_the_end_point.json") - public void testWireMock() throws Exception { - - } - - @Test - @JsonTestCase("integration_test_files/wiremock_integration/wiremock_with_template.json") - public void testWireMockWithTemplate() { - - } -} - diff --git a/core/src/test/resources/integration_test_files/json_paths_jayway/06_will_mock_using_wiremock_and_run_other_steps.json b/core/src/test/resources/integration_test_files/json_paths_jayway/06_will_mock_using_wiremock_and_run_other_steps.json deleted file mode 100755 index 97612dab9..000000000 --- a/core/src/test/resources/integration_test_files/json_paths_jayway/06_will_mock_using_wiremock_and_run_other_steps.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "scenarioName": "06_will_mock_using_wiremock_and_run_other_steps", - "loop": 5, //comments -- Allowed - "steps": [ - { - "name": "GetBathRoomDetails", - "url": "/$MOCK", - "operation": "$USE.WIREMOCK", //<--- can be $USE.VIRTUOSO - "request": { - "mocks": [ - { - "name": "Mock the Get Person", - "operation": "GET", - "url": "/google-guys/persons/p001", - "response": { - "status": 200, - "body": { - "id": "p001", - "source": { - "code": "GOOGLE.UK" - } - } - } - }, - { - "name": "Mock the POST Person", - "operation": "POST", - "url": "/google-guys/persons/p002", - "response": { - "status": 201, - "body": { - "id": "p002", - "source": { - "code": "GOOGLE.IN" - } - } - } - } - ] - }, - "assertions": { - "status": 200 //<--- when all mocks have been successfully created. - } - }, - { - "name": "get_person", - "url": "http://localhost:8888/google-guys/persons/p001", - "operation": "GET", - "request": { - "headers": { - "Content-Type": "application/json;charset=UTF-8" - }, - "body": { - } - }, - "assertions": { - "status": 200 - } - }, - { - "name": "POST_Create_Person", - "url": "http://localhost:8888/google-guys/persons/p002", - "operation": "POST", - "request": { - "headers": { - "Content-Type": "application/json;charset=UTF-8" - }, - "body": { - } - }, - "assertions": { - "status": 201 - } - } - - ] -} diff --git a/core/src/test/resources/integration_test_files/retry_test_cases/01_REST_with_retry_test.json b/core/src/test/resources/integration_test_files/retry_test_cases/01_REST_with_retry_test.json deleted file mode 100755 index 9dbd38d21..000000000 --- a/core/src/test/resources/integration_test_files/retry_test_cases/01_REST_with_retry_test.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "scenarioName": "Rest with Retry Test", - "steps": [ - { - "name": "RetryUntilSuccessMock", - "url": "/$MOCK", - "operation": "$USE.WIREMOCK", - "request": { - "mocks": [ - { - "name": "SlidingDateMock", - "operation": "GET", - "url": "/retry/001", - "response": { - "status": 200, - "body": { - "fixed_date_time": "${LOCAL.DATETIME.NOW:uuuu-MM-dd'T'HH:mm:ss.SSS}", - "dynamic_oneMinuteAgo": "{{localdatetime offset='-1 seconds'}}" - } - } - } - ] - }, - "assertions": { - "status": 200 - } - }, - { - "retry": {"max": 12, "delay": 1000}, - "name": "GetDatesRequest", - "url": "http://localhost:8888/retry/001", - "operation": "GET", - "request": { - "headers": { - "Content-Type": "application/json;charset=UTF-8" - }, - "body": { - } - }, - "assertions": { - "status": 200, - "body": { - "dynamic_oneMinuteAgo": "$LOCAL.DATETIME.AFTER:${$.GetDatesRequest.response.body.fixed_date_time}" - // NOTE that the inverse does not work, because - // the right-hand value stays fixed to the result of the first iteration - // the left-hand value does schange for each iteration - // "fixed_date_time": "$DATE.BEFORE:${$.GetDatesRequest.response.body.dynamic_oneMinuteAgo}" - } - } - } - - ] -} diff --git a/core/src/test/resources/integration_test_files/retry_test_cases/02_REST_with_retry_within_loop_test.json b/core/src/test/resources/integration_test_files/retry_test_cases/02_REST_with_retry_within_loop_test.json deleted file mode 100755 index 513fc5165..000000000 --- a/core/src/test/resources/integration_test_files/retry_test_cases/02_REST_with_retry_within_loop_test.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "scenarioName": "Rest with Retry within loop Test", - "steps": [ - { - "name": "RetryUntilSuccessMock", - "url": "/$MOCK", - "operation": "$USE.WIREMOCK", - "request": { - "mocks": [ - { - "name": "SlidingDateMock", - "operation": "GET", - "url": "/retry/002", - "response": { - "status": 200, - "body": { - "fixed_date_time": "${LOCAL.DATETIME.NOW:uuuu-MM-dd'T'HH:mm:ss.SSS}", - "dynamic_oneMinuteAgo": "{{localdatetime offset='-1 seconds'}}" - } - } - } - ] - }, - "assertions": { - "status": 200 - } - }, - { - "retry": {"max": 3, "delay": 1000}, - "name": "GetDatesRequest", - "url": "http://localhost:8888/retry/002", - "operation": "GET", - "request": { - "headers": { - "Content-Type": "application/json;charset=UTF-8" - }, - "body": { - } - }, - "assertions": { - "status": 200, - "body": { - "dynamic_oneMinuteAgo": "$LOCAL.DATETIME.AFTER:${$.GetDatesRequest.response.body.fixed_date_time}" - // NOTE that the inverse does not work, because - // the right-hand value stays fixed to the result of the first iteration - // the left-hand value does schange for each iteration - // "fixed_date_time": "$DATE.BEFORE:${$.GetDatesRequest.response.body.dynamic_oneMinuteAgo}" - } - } - } - - ] -} diff --git a/core/src/test/resources/integration_test_files/retry_test_cases/03_failing_REST_with_retry_within_loop_test.json b/core/src/test/resources/integration_test_files/retry_test_cases/03_failing_REST_with_retry_within_loop_test.json deleted file mode 100755 index 2ab79382b..000000000 --- a/core/src/test/resources/integration_test_files/retry_test_cases/03_failing_REST_with_retry_within_loop_test.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "scenarioName": "Failing Rest with Retry within loop Test", - "steps": [ - { - "name": "FailingRetryUntilSuccessMock", - "url": "/$MOCK", - "operation": "$USE.WIREMOCK", - "request": { - "mocks": [ - { - "name": "SlidingDateMock", - "operation": "GET", - "url": "/retry/003", - "response": { - "status": 400, - "body": { - } - } - } - ] - }, - "assertions": { - "status": 200 - } - }, - { - "retry": {"max": 3, "delay": 0}, - "name": "GetFailingRequest", - "url": "http://localhost:8888/retry/003", - "operation": "GET", - "request": { - "headers": { - "Content-Type": "application/json;charset=UTF-8" - }, - "body": { - } - }, - "assertions": { - "status": 200 - } - } - - ] -} diff --git a/core/src/test/resources/integration_test_files/retry_test_cases/04_REST_retry_with_state_test.json b/core/src/test/resources/integration_test_files/retry_test_cases/04_REST_retry_with_state_test.json deleted file mode 100755 index a31eea532..000000000 --- a/core/src/test/resources/integration_test_files/retry_test_cases/04_REST_retry_with_state_test.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "scenarioName": "WireMock State Saved For Retry", - "steps": [ - { - "retry": { - "max": 5, - "delay": 500 - }, - "name": "GetDatesRequest", - "url": "http://localhost:8484/retry/ids/1", - "operation": "GET", - "request": { - "headers": { - "Content-Type": "application/json;charset=UTF-8" - } - }, - "assertions": { - "status": 200 - } - } - ] -} diff --git a/core/src/test/resources/integration_test_files/wiremock_integration/mock_via_wiremock_then_test_the_end_point.json b/core/src/test/resources/integration_test_files/wiremock_integration/mock_via_wiremock_then_test_the_end_point.json deleted file mode 100644 index 63a2ed08c..000000000 --- a/core/src/test/resources/integration_test_files/wiremock_integration/mock_via_wiremock_then_test_the_end_point.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "scenarioName": "Will Mock some End Points via WireMock and Test the end points using Zerocode", - "steps": [ - { - "name": "setup_mocks", - "url": "/$MOCK", - "operation": "$USE.WIREMOCK", - "request": { - "mocks": [ - { - "name": "mocking_a_GET_endpoint_with_headers", - "operation": "GET", - "url": "/api/v1/amazon/customers/cust-007", - "request": { - "headers": { - "api_key": "key-01-01", - "api_secret": "secret-01-01" - } - }, - "response": { - "status": 200, - "body": { - "id": "cust-007", - "type": "Premium" - }, - "headers": { - "Content-Type": "application/json" - } - } - } - ] - }, - "assertions": { - "status": 200 - } - }, - //------------- Mocking done at this point via WireMock --------------- - - //------------- Let's verify the end points by writing the following small tests ------------ - { - "name": "verify_get_customer_with_headers", - "url": "/api/v1/amazon/customers/cust-007", - "operation": "GET", - "request": { - "headers": { - "api_key": "key-01-01", //<--- Please try with a wrong key. The test should fail. - "api_secret": "secret-01-01" - } - }, - "assertions": { - "status": 200, - "body": { - "id": "cust-007", - "type": "Premium" - }, - "headers": { - "Content-Type": ["application/json"] - } - } - }, - { - "name": "verify_get_customer_without_headers", - "url": "/api/v1/amazon/customers/cust-007", - "operation": "GET", - "request": { - "headers": { - //"api_key": "key-01-01", //<--- Please try with a wrong key. The test should fail. - "api_secret": "secret-01-01" - } - }, - "assertions": { - "status" : 404, - "rawBody" : "$CONTAINS.STRING:Request was not matched" - } - } - - ] -} diff --git a/core/src/test/resources/integration_test_files/wiremock_integration/wiremock_end_point_json_body.json b/core/src/test/resources/integration_test_files/wiremock_integration/wiremock_end_point_json_body.json deleted file mode 100644 index b87ec2cd8..000000000 --- a/core/src/test/resources/integration_test_files/wiremock_integration/wiremock_end_point_json_body.json +++ /dev/null @@ -1,94 +0,0 @@ -{ - "scenarioName": "create_mocks", - "steps": [ - { - "name": "GetBathRoomDetails", - "url": "/$MOCK", - "operation": "$USE.WIREMOCK", - "request": { - "mocks": [ - { - "name": "Mock the Get Person", - "operation": "GET", - "url": "/google-guys/persons/p001", - "request": { - "headers": { - "key": "key-007", - "secret": "secret-007" - } - }, - "response": { - "status": 200, - "headers": { - "Content-Type": "application/json" - }, - "body": { - "id": "p001", - "source": { - "code": "GOOGLE.UK" - } - } - } - }, - { - "name": "Mock the POST Person", - "operation": "POST", - "url": "/google-guys/persons/p002", - "request": { - "body": { - "id": "p002" - } - }, - "response": { - "status": 201, - "body": { - "id": "p002", - "source": { - "code": "GOOGLE.IN" - } - } - } - }, - { - "name": "Mock the PATCH Person", - "operation": "PATCH", - "url": "/customers/cust345", - "request": { - "body": { - "email": "new_email_to_update@gmail.com" - } - }, - "response": { - "status": 200, - "body": { - "id": "cust345", - "message": "email updated" - } - } - }, - { - "name": "Mock the DELETE Person", - "operation": "DELETE", - "url": "/customers/cust302", - "request": { - "headers": { - "Content-Type": "application/json" - }, - "body": {} - }, - "response": { - "status": 204, - "headers": { - "Content-Type": "application/json" - }, - "body": {} - } - } - ] - }, - "assertions": { - "status": 200 - } - } - ] -} diff --git a/core/src/test/resources/integration_test_files/wiremock_integration/wiremock_end_point_soap_xml_body.json b/core/src/test/resources/integration_test_files/wiremock_integration/wiremock_end_point_soap_xml_body.json deleted file mode 100644 index 9031d95bd..000000000 --- a/core/src/test/resources/integration_test_files/wiremock_integration/wiremock_end_point_soap_xml_body.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "scenarioName": "soap xmlBody mocking", - "steps": [ - { - "name": "mock_soap_xml_response", - "url": "/$MOCK", - "operation": "$USE.WIREMOCK", - "request": { - "mocks": [ - { - "name": "mocking_SOAP_to_get_device_details", - "operation": "POST", - "url": "/ws", - "request": { - }, - "response": { - "status": 200, - "xmlBody": "1iPadIt is a tablet computers designed, developed and marketed by Apple." - } - } - ] - }, - "assertions": { - "status": 200 - } - } - ] -} diff --git a/core/src/test/resources/integration_test_files/wiremock_integration/wiremock_with_template.json b/core/src/test/resources/integration_test_files/wiremock_integration/wiremock_with_template.json deleted file mode 100644 index 7e5612b8c..000000000 --- a/core/src/test/resources/integration_test_files/wiremock_integration/wiremock_with_template.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "scenarioName": "templated wiremock", - "steps": [ - { - "name": "templated_response", - "url": "/$MOCK", - "operation": "$USE.WIREMOCK", - "request": { - "mocks": [ - { - "name": "Template 001", - "operation": "GET", - "url": "/template/001", - "request": { - }, - "response": { - "status": 200, - "headers" : { - "Content-Type" : "application/json" - }, - "body": { - // Showcases the use of WireMock's Response Templates - // http://wiremock.org/docs/response-templating/ - // "fixed_date_time" is set by ZeroCode at mock-creation time, so it will remain the same accross subsequent calls - // "dynamic_oneMinuteAgo", "dynamic_oneMinuteAhead" and "ucparam" are resolved at mock-response time, so they can be different per call - // The templates are Handlebars Templates, where {{...}} delimits the templates, and inside you can put 'helpers' - // localdatetime is one of those helpers that returns the current date (LocalDateTime, for compatibility with LOCAL.DATETIME.NOW) - // and provides 'offset' to manipulate it. See the section 'Date and time helpers' on the WireMock-link for more info about offset. - // upper is another helper, that uppercases it's argument (i.c. the first value of the request-parameter named 'param' - "fixed_date_time": "${LOCAL.DATETIME.NOW:uuuu-MM-dd'T'HH:mm:ss.SSS}", - "dynamic_oneMinuteAgo": "{{localdatetime offset='-1 minutes'}}", - "dynamic_oneMinuteAhead": "{{localdatetime offset='+1 minutes'}}", - "ucparam": "{{upper request.query.param[0]}}" - } - } - } - ] - }, - "assertions": { - "status": 200 - } - }, - { - "name": "GetTemplate", - "url": "/template/001", - "operation": "GET", - "loop": 3, - "request": { - "headers": { - "Content-Type": "application/json;charset=UTF-8" - }, - "queryParams": { - "param": "lowerToUpper" - }, - "body": { - } - }, - "assertions": { - "status": 200, - "body": { - "ucparam": "LOWERTOUPPER", - "fixed_date_time": "$LOCAL.DATETIME.AFTER:${$.GetTemplate.response.body.dynamic_oneMinuteAgo}", - "fixed_date_time": "$LOCAL.DATETIME.BEFORE:${$.GetTemplate.response.body.dynamic_oneMinuteAhead}" - } - } - } - ] -} diff --git a/core/src/test/resources/unit_test_files/wiremock/test_mock_step.json b/core/src/test/resources/unit_test_files/wiremock/test_mock_step.json deleted file mode 100644 index 83462fd52..000000000 --- a/core/src/test/resources/unit_test_files/wiremock/test_mock_step.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "Mock the Get Person", - "operation": "GET", - "url": "/google-guys/persons/p001", - "response": { - "status": 200, - "body": { - "id": "p001", - "source": { - "code": "GOOGLE.UK" - } - } - } -} \ No newline at end of file diff --git a/core/src/test/resources/unit_test_files/wiremock/test_mock_step_request_body.json b/core/src/test/resources/unit_test_files/wiremock/test_mock_step_request_body.json deleted file mode 100644 index 24ff05d6f..000000000 --- a/core/src/test/resources/unit_test_files/wiremock/test_mock_step_request_body.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "Mock the Get Person With Request Body", - "operation": "GET", - "url": "/google-guys/persons/p001", - "request": { - "body": { - "name": "Emma", - "age": 33, - "address": { - "line1": "address line 1", - "line2": "address line 2" - } - } - }, - "response": { - "status": 200, - "body": { - "id": "p001", - "source": { - "code": "GOOGLE.UK" - } - } - } -} \ No newline at end of file diff --git a/core/src/test/resources/unit_test_files/wiremock/test_mock_step_request_headers.json b/core/src/test/resources/unit_test_files/wiremock/test_mock_step_request_headers.json deleted file mode 100644 index 06f6d1752..000000000 --- a/core/src/test/resources/unit_test_files/wiremock/test_mock_step_request_headers.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "Mock the Get Person With Request Headers", - "operation": "GET", - "url": "/google-guys/persons/p001", - "request" : { - "headers":{ - "key": "key-001", - "secret": "secret-001" - } - }, - "response": { - "status": 200, - "body": { - "id": "p001", - "source": { - "code": "GOOGLE.UK" - } - } - } -} \ No newline at end of file diff --git a/core/src/test/resources/web_app.properties b/core/src/test/resources/web_app.properties index c0c2f35ad..3ae2f43b6 100644 --- a/core/src/test/resources/web_app.properties +++ b/core/src/test/resources/web_app.properties @@ -4,7 +4,3 @@ web.application.endpoint.port=8889 # Web Service context; Leave it blank in case you do not have a common context web.application.endpoint.context= - -# WireMock will use this port for mocking dependent end points -mock.api.port=8889 -#mock.api.port=8888 # Tensor Flow - Jupyter runs at 8888 during Python linear regression. \ No newline at end of file diff --git a/http-testing-examples/src/main/java/org/jsmart/zerocode/zerocodejavaexec/wiremock/ZeroCodeWireMockRunner.java b/http-testing-examples/src/main/java/org/jsmart/zerocode/zerocodejavaexec/wiremock/ZeroCodeWireMockRunner.java deleted file mode 100644 index a3fbc929e..000000000 --- a/http-testing-examples/src/main/java/org/jsmart/zerocode/zerocodejavaexec/wiremock/ZeroCodeWireMockRunner.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.jsmart.zerocode.zerocodejavaexec.wiremock; - -import com.github.tomakehurst.wiremock.WireMockServer; -import org.jsmart.zerocode.core.runner.ZeroCodeUnitRunner; -import org.junit.runners.model.InitializationError; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; - -public class ZeroCodeWireMockRunner extends ZeroCodeUnitRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(ZeroCodeWireMockRunner.class); - static String basePath; - static String fullPath; - static int port = 8383; - - static WireMockServer mockServer = new WireMockServer(port); - public ZeroCodeWireMockRunner(Class klass) throws InitializationError { - super(klass); - simulateServerDelay(); - } - - - public static void simulateServerDelay() { - LOGGER.debug("Setting up WireMock with server delay..."); - - basePath = "http://localhost:" + port; - String path = "/delay/ids/2"; - fullPath = basePath + path; - - mockServer.start(); - - mockServer.stubFor( - get(urlEqualTo(path)) - .willReturn(aResponse() - .withStatus(200) - .withFixedDelay(2000) - )); - } -} diff --git a/http-testing-examples/src/test/java/org/jsmart/zerocode/testhelp/tests/helloworldimplicitdelay/JustHelloImplicitDelayTimeOutTest.java b/http-testing-examples/src/test/java/org/jsmart/zerocode/testhelp/tests/helloworldimplicitdelay/JustHelloImplicitDelayTimeOutTest.java deleted file mode 100644 index bd79b7d1b..000000000 --- a/http-testing-examples/src/test/java/org/jsmart/zerocode/testhelp/tests/helloworldimplicitdelay/JustHelloImplicitDelayTimeOutTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.jsmart.zerocode.testhelp.tests.helloworldimplicitdelay; - -import org.jsmart.zerocode.core.domain.Scenario; -import org.jsmart.zerocode.core.domain.TargetEnv; -import org.jsmart.zerocode.zerocodejavaexec.wiremock.ZeroCodeWireMockRunner; -import org.junit.Test; -import org.junit.runner.RunWith; - -@TargetEnv("localhost_app.properties") -@RunWith(ZeroCodeWireMockRunner.class) -public class JustHelloImplicitDelayTimeOutTest { - - /** - * Server response delay = 2000 milli sec (2sec) - See the WireMock delay - * Max timeout = 1000 milli sec (1 sec) - See the localhost_app.properties - * - The below test fails due to Max-timeout config - * - You can tweak this to different value and make it/Pass/Fail - */ - @Test - @Scenario("helloworld_implicit_delay/http_implicit_delay_max_timeout_scenario.json") - public void testImplicitDelay_max1Sec() { - } - -} diff --git a/http-testing-examples/src/test/java/org/jsmart/zerocode/testhelp/tests/wiremock/WireMockCustomerEndPointTest.java b/http-testing-examples/src/test/java/org/jsmart/zerocode/testhelp/tests/wiremock/WireMockCustomerEndPointTest.java deleted file mode 100644 index 589c8e4bc..000000000 --- a/http-testing-examples/src/test/java/org/jsmart/zerocode/testhelp/tests/wiremock/WireMockCustomerEndPointTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.jsmart.zerocode.testhelp.tests.wiremock; - -import org.jsmart.zerocode.core.domain.JsonTestCase; -import org.jsmart.zerocode.core.domain.TargetEnv; -import org.jsmart.zerocode.core.runner.ZeroCodeUnitRunner; -import org.junit.Test; -import org.junit.runner.RunWith; - -@TargetEnv("customer_web_app.properties") -@RunWith(ZeroCodeUnitRunner.class) -public class WireMockCustomerEndPointTest { - - @Test - @JsonTestCase("wiremock_tests/mock_via_wiremock_then_test_the_end_point.json") - public void testHelloWorld_localhostApi() throws Exception { - - } - - @Test - @JsonTestCase("wiremock_tests/soap_mocking_via_wiremock_test.json") - public void testHelloWorld_soap() throws Exception { - - } - - String s = "\n" + - "\n" + - " \n" + - " \n" + - " string\n" + - " dateTime\n" + - " \n" + - " \n" + - ""; -} diff --git a/http-testing-examples/src/test/resources/customer_web_app.properties b/http-testing-examples/src/test/resources/customer_web_app.properties index 0230e83de..12746d5c5 100644 --- a/http-testing-examples/src/test/resources/customer_web_app.properties +++ b/http-testing-examples/src/test/resources/customer_web_app.properties @@ -4,6 +4,3 @@ restful.application.endpoint.port=8888 # Web Service context; Leave it blank in case you do not have a common context restful.application.endpoint.context= - -# WireMock will use this port for mocking dependent end points -mock.api.port=8888 \ No newline at end of file diff --git a/http-testing-examples/src/test/resources/localhost_app.properties b/http-testing-examples/src/test/resources/localhost_app.properties index 6bc2722c8..1fc512d71 100644 --- a/http-testing-examples/src/test/resources/localhost_app.properties +++ b/http-testing-examples/src/test/resources/localhost_app.properties @@ -2,7 +2,4 @@ web.application.endpoint.host=http://localhost web.application.endpoint.port=8383 web.application.endpoint.context= -# To make the test PASS, update this value to 3000(3 sec) or anything higher than 2000. -# Where 2000 milli-sec(2sec) is the delay from the Web(WireMock) server in responding -# to the http request. http.max.timeout.milliseconds=2500 \ No newline at end of file diff --git a/http-testing-examples/src/test/resources/wiremock_tests/mock_via_wiremock_then_test_the_end_point.json b/http-testing-examples/src/test/resources/wiremock_tests/mock_via_wiremock_then_test_the_end_point.json deleted file mode 100644 index ba92e91e6..000000000 --- a/http-testing-examples/src/test/resources/wiremock_tests/mock_via_wiremock_then_test_the_end_point.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "scenarioName": "Will Mock some End Points via WireMock and Test the end points using Zerocode", - "steps": [ - { - "name": "setup_mocks", - "url": "/$MOCK", - "method": "$USE.WIREMOCK", - "request": { - "mocks": [ - { - "name": "mocking_a_GET_endpoint", - "method": "GET", - "url": "/api/v1/amazon/customers/UK001", - "response": { - "status": 200, - "headers": { - "Accept": "application/json" - }, - "body": { - "id": "UK001", - "name": "Adam Smith", - "Age": "33" - } - } - }, - { - "name": "mocking_a_GET_endpoint_with_headers", - "method": "GET", - "url": "/api/v1/amazon/customers/cust-007", - "request": { - "headers": { - "api_key": "key-01-01", - "api_secret": "secret-01-01" - } - }, - "response": { - "status": 200, - "body": { - "id": "cust-007", - "type": "Premium" - } - } - } - ] - }, - "assertions": { - "status": 200 - } - }, - //------------- All mocking done at this point via WireMock --------------- - - //------------- Let's verify the end points by writing the following small tests ------------ - { - "name": "actual_test_verify_get_customer", - "url": "/api/v1/amazon/customers/UK001", - "method": "GET", - "request": { - }, - "assertions": { - "status": 200 - } - }, - { - "name": "verify_get_customer_with_headers", - "url": "/api/v1/amazon/customers/cust-007", - "method": "GET", - "request": { - "headers": { - "api_key": "key-01-01", //<--- Please try with a wrong key. The test should fail. - "api_secret": "secret-01-01" - } - }, - "assertions": { - "status": 200, - "body": { - "id": "cust-007", - "type": "Premium" - } - } - }, - { - "name": "verify_get_customer_without_headers", - "url": "/api/v1/amazon/customers/cust-007", - "method": "GET", - "request": { - "headers": { - //"api_key": "key-01-01", //<--- Please do not put a header, you should get 404. - "api_secret": "secret-01-01" - } - }, - "assertions": { - "status" : 404, - "rawBody" : "$CONTAINS.STRING:Request was not matched" - } - } - - ] -} diff --git a/http-testing-examples/src/test/resources/wiremock_tests/soap_mocking_via_wiremock_test.json b/http-testing-examples/src/test/resources/wiremock_tests/soap_mocking_via_wiremock_test.json deleted file mode 100644 index 49ec46194..000000000 --- a/http-testing-examples/src/test/resources/wiremock_tests/soap_mocking_via_wiremock_test.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "scenarioName": "@@Santhosh - Will Mock some End Points via WireMock and Test the end points using Zerocode", - "steps": [ - { - "name": "setup_mocks", - "url": "/$MOCK", - "method": "$USE.WIREMOCK", - "request": { - "mocks": [ - { - "name": "mocking_a_GET_endpoint", - "method": "POST", - "url": "/soap/CurrencyConvertor", - "response": { - "status": 200, - "headers": { - "Content-Type": "text/xml; charset=utf-8" - }, - "body": "\n\n \n \n string\n dateTime\n \n \n" - } - } - ] - }, - "assertions": { - "status": 200 - } - }, - //------------- All mocking done at this point via WireMock --------------- - - //------------- Let's verify the end points by writing the following step ------------ - { - "name": "invoke_currency_conversion", - "url": "/soap/CurrencyConvertor", - "method": "POST", - "request": { - "headers": { - "Content-Type": "text/xml; charset=utf-8", - //"SOAPAction": "\"http://www.webserviceX.NET/ConversionRate\"" - "SOAPAction": "http://www.webserviceX.NET/ConversionRate" - }, - "body": "\n\n \n \n AFA\n GBP\n \n \n" - }, - "assertions": { - "status": 200 - //"rawBody": "$CONTAINS.STRING:-1" - } - } - - ] -} diff --git a/junit5-testing-examples/pom.xml b/junit5-testing-examples/pom.xml index c587263ba..4a3eb4bad 100644 --- a/junit5-testing-examples/pom.xml +++ b/junit5-testing-examples/pom.xml @@ -107,10 +107,6 @@ com.jayway.jsonpath json-path - - com.github.tomakehurst - wiremock - com.h2database h2 diff --git a/pom.xml b/pom.xml index d8d18c263..c4cecdbf2 100644 --- a/pom.xml +++ b/pom.xml @@ -63,8 +63,6 @@ 1.3.14 2.0.12 - - 2.27.2 2.15.0 4.4 3.14.0 @@ -170,11 +168,6 @@ commons-io ${commons-io.version} - - com.github.tomakehurst - wiremock - ${wiremock.version} - ch.qos.logback logback-classic diff --git a/pom_OSSRH_NOTINUSE.xml b/pom_OSSRH_NOTINUSE.xml index 942251f05..29572dcd6 100644 --- a/pom_OSSRH_NOTINUSE.xml +++ b/pom_OSSRH_NOTINUSE.xml @@ -79,8 +79,6 @@ 1.3.14 2.0.12 - - 2.27.2 2.15.0 4.4 3.14.0 @@ -186,11 +184,6 @@ commons-io ${commons-io.version} - - com.github.tomakehurst - wiremock - ${wiremock.version} - ch.qos.logback logback-classic