Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 0 additions & 4 deletions core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,6 @@
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
Expand Down
4 changes: 0 additions & 4 deletions core/pom_OSSRH_NOTINUSE.xml
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,6 @@
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand All @@ -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 {

Expand Down Expand Up @@ -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 <env host config .properties> 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.
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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<String> urls) {
Set<String> 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<String> 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<String, Helper> getWiremockHelpers() {
Map<String, Helper> 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<String, Object> 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.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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());
Expand Down
Loading
Loading