src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
XPathBodyDTO extends BodyDTO { public String getXPath() { return xpath; } XPathBodyDTO(XPathBody xPathBody); XPathBodyDTO(XPathBody xPathBody, Boolean not); String getXPath(); XPathBody buildObject(); }
@Test public void shouldReturnValuesSetInConstructor() { XPathBodyDTO xpathBody = new XPathBodyDTO(new XPathBody("some_body")); assertThat(xpathBody.getXPath(), is("some_body")); assertThat(xpathBody.getType(), is(Body.Type.XPATH)); }
XPathBodyDTO extends BodyDTO { public XPathBody buildObject() { return (XPathBody) new XPathBody(getXPath()).withOptional(getOptional()); } XPathBodyDTO(XPathBody xPathBody); XPathBodyDTO(XPathBody xPathBody, Boolean not); String getXPath(); XPathBody buildObject(); }
@Test public void shouldBuildCorrectObject() { XPathBody xPathBody = new XPathBodyDTO(new XPathBody("some_body")).buildObject(); assertThat(xPathBody.getValue(), is("some_body")); assertThat(xPathBody.getType(), is(Body.Type.XPATH)); } @Test public void shouldBuildCorrectObjectWithOptional() { XPathBody xPathBody = new XPathBodyDTO((XPathBody) new XPathBody("some_body").withOptional(true)).buildObject(); assertThat(xPathBody.getValue(), is("some_body")); assertThat(xPathBody.getType(), is(Body.Type.XPATH)); assertThat(xPathBody.getOptional(), is(true)); }
HeaderDTO extends KeyToMultiValueDTO implements DTO<Header> { public Header buildObject() { return new Header(getName(), getValues()); } HeaderDTO(Header header); protected HeaderDTO(); Header buildObject(); }
@Test public void shouldReturnValuesSetInConstructor() { HeaderDTO header = new HeaderDTO(new Header("first", "first_one", "first_two")); assertThat(header.getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); assertThat(header.buildObject().getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); }
HttpRequestSerializer implements Serializer<HttpRequest> { public HttpRequest deserialize(String jsonHttpRequest) { if (isBlank(jsonHttpRequest)) { throw new IllegalArgumentException( "1 error:" + NEW_LINE + " - a request is required but value was \"" + jsonHttpRequest + "\"" + NEW_LINE + NEW_LINE + OPEN_API_SPECIFICATION_URL ); } else { if (jsonHttpRequest.contains("\"httpRequest\"")) { try { JsonNode jsonNode = objectMapper.readTree(jsonHttpRequest); if (jsonNode.has("httpRequest")) { jsonHttpRequest = jsonNode.get("httpRequest").toString(); } } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for HttpRequest " + throwable.getMessage()) .setArguments(jsonHttpRequest) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing [" + jsonHttpRequest + "] for HttpRequest", throwable); } } String validationErrors = getValidator().isValid(jsonHttpRequest); if (validationErrors.isEmpty()) { HttpRequest httpRequest = null; try { HttpRequestDTO httpRequestDTO = objectMapper.readValue(jsonHttpRequest, HttpRequestDTO.class); if (httpRequestDTO != null) { httpRequest = httpRequestDTO.buildObject(); } } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for HttpRequest" + throwable.getMessage()) .setArguments(jsonHttpRequest) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing [" + jsonHttpRequest + "] for HttpRequest", throwable); } return httpRequest; } else { throw new IllegalArgumentException(StringUtils.removeEndIgnoreCase(formatLogMessage("incorrect request json format for:{}schema validation errors:{}", jsonHttpRequest, validationErrors), "\n")); } } } HttpRequestSerializer(MockServerLogger mockServerLogger); String serialize(HttpRequest httpRequest); String serialize(boolean prettyPrint, HttpRequest httpRequest); String serialize(List<HttpRequest> httpRequests); String serialize(boolean prettyPrint, List<HttpRequest> httpRequests); String serialize(HttpRequest... httpRequests); String serialize(boolean prettyPrint, HttpRequest... httpRequests); HttpRequest deserialize(String jsonHttpRequest); @Override Class<HttpRequest> supportsType(); HttpRequest[] deserializeArray(String jsonHttpRequests); }
@Test public void deserialize() throws IOException { when(httpRequestValidator.isValid(eq("requestBytes"))).thenReturn(""); when(objectMapper.readValue(eq("requestBytes"), same(HttpRequestDTO.class))).thenReturn(fullHttpRequestDTO); HttpRequest httpRequest = httpRequestSerializer.deserialize("requestBytes"); assertEquals(fullHttpRequest, httpRequest); }
HttpRequestSerializer implements Serializer<HttpRequest> { public String serialize(HttpRequest httpRequest) { return serialize(false, httpRequest); } HttpRequestSerializer(MockServerLogger mockServerLogger); String serialize(HttpRequest httpRequest); String serialize(boolean prettyPrint, HttpRequest httpRequest); String serialize(List<HttpRequest> httpRequests); String serialize(boolean prettyPrint, List<HttpRequest> httpRequests); String serialize(HttpRequest... httpRequests); String serialize(boolean prettyPrint, HttpRequest... httpRequests); HttpRequest deserialize(String jsonHttpRequest); @Override Class<HttpRequest> supportsType(); HttpRequest[] deserializeArray(String jsonHttpRequests); }
@Test public void serialize() throws IOException { httpRequestSerializer.serialize(fullHttpRequest); verify(objectWriter).writeValueAsString(fullHttpRequestDTO); } @Test @SuppressWarnings("RedundantArrayCreation") public void shouldSerializeArray() throws IOException { httpRequestSerializer.serialize(new HttpRequest[]{fullHttpRequest, fullHttpRequest}); verify(objectWriter).writeValueAsString(new HttpRequestDTO[]{fullHttpRequestDTO, fullHttpRequestDTO}); }
ObjectMapperFactory { public static ObjectMapper createObjectMapper() { if (objectMapper == null) { objectMapper = buildObjectMapperWithDeserializerAndSerializers(Collections.emptyList(), Collections.emptyList()); } return objectMapper; } static ObjectMapper createObjectMapper(); static ObjectMapper createObjectMapper(JsonSerializer... additionJsonSerializers); static ObjectMapper createObjectMapper(JsonDeserializer... replacementJsonDeserializers); static ObjectWriter createObjectMapper(boolean pretty, JsonSerializer... additionJsonSerializers); static ObjectMapper buildObjectMapperWithoutDeserializerAndSerializers(); }
@Test public void shouldDeserializeCompleteObject() throws IOException { String json = ("{" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"method\" : \"someMethod\"," + NEW_LINE + " \"path\" : \"somePath\"," + NEW_LINE + " \"queryStringParameters\" : [ {" + NEW_LINE + " \"name\" : \"queryStringParameterNameOne\"," + NEW_LINE + " \"values\" : [ \"queryStringParameterValueOne_One\", \"queryStringParameterValueOne_Two\" ]" + NEW_LINE + " }, {" + NEW_LINE + " \"name\" : \"queryStringParameterNameTwo\"," + NEW_LINE + " \"values\" : [ \"queryStringParameterValueTwo_One\" ]" + NEW_LINE + " } ]," + NEW_LINE + " \"body\" : {" + NEW_LINE + " \"type\" : \"STRING\"," + NEW_LINE + " \"string\" : \"someBody\"" + NEW_LINE + " }," + NEW_LINE + " \"cookies\" : [ {" + NEW_LINE + " \"name\" : \"someCookieName\"," + NEW_LINE + " \"value\" : \"someCookieValue\"" + NEW_LINE + " } ]," + NEW_LINE + " \"headers\" : [ {" + NEW_LINE + " \"name\" : \"someHeaderName\"," + NEW_LINE + " \"values\" : [ \"someHeaderValue\" ]" + NEW_LINE + " } ]" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"statusCode\" : 304," + NEW_LINE + " \"body\" : \"someBody\"," + NEW_LINE + " \"cookies\" : [ {" + NEW_LINE + " \"name\" : \"someCookieName\"," + NEW_LINE + " \"value\" : \"someCookieValue\"" + NEW_LINE + " } ]," + NEW_LINE + " \"headers\" : [ {" + NEW_LINE + " \"name\" : \"someHeaderName\"," + NEW_LINE + " \"values\" : [ \"someHeaderValue\" ]" + NEW_LINE + " } ]," + NEW_LINE + " \"delay\" : {" + NEW_LINE + " \"timeUnit\" : \"MICROSECONDS\"," + NEW_LINE + " \"value\" : 1" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"remainingTimes\" : 5," + NEW_LINE + " \"unlimited\" : false" + NEW_LINE + " }" + NEW_LINE + "}"); ExpectationDTO expectationDTO = ObjectMapperFactory.createObjectMapper().readValue(json, ExpectationDTO.class); assertEquals(new ExpectationDTO() .setHttpRequest( new HttpRequestDTO() .setMethod(string("someMethod")) .setPath(string("somePath")) .setQueryStringParameters(new Parameters().withEntries( param("queryStringParameterNameOne", "queryStringParameterValueOne_One", "queryStringParameterValueOne_Two"), param("queryStringParameterNameTwo", "queryStringParameterValueTwo_One") )) .setBody(new StringBodyDTO(new StringBody("someBody"))) .setHeaders(new Headers().withEntries( header("someHeaderName", "someHeaderValue") )) .setCookies(new Cookies().withEntries( cookie("someCookieName", "someCookieValue") )) ) .setHttpResponse( new HttpResponseDTO() .setStatusCode(304) .setBody(new StringBodyDTO(new StringBody("someBody"))) .setHeaders(new Headers().withEntries( header("someHeaderName", "someHeaderValue") )) .setCookies(new Cookies().withEntries( cookie("someCookieName", "someCookieValue") )) .setDelay( new DelayDTO() .setTimeUnit(TimeUnit.MICROSECONDS) .setValue(1) ) ) .setTimes(new org.mockserver.serialization.model.TimesDTO(Times.exactly(5))), expectationDTO); }
PortBindingSerializer implements Serializer<PortBinding> { public PortBinding deserialize(String jsonPortBinding) { PortBinding portBinding = null; if (jsonPortBinding != null && !jsonPortBinding.isEmpty()) { try { portBinding = objectMapper.readValue(jsonPortBinding, PortBinding.class); } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for PortBinding " + throwable.getMessage()) .setArguments(jsonPortBinding) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing PortBinding for [" + jsonPortBinding + "]", throwable); } } return portBinding; } PortBindingSerializer(MockServerLogger mockServerLogger); String serialize(PortBinding portBinding); PortBinding deserialize(String jsonPortBinding); @Override Class<PortBinding> supportsType(); }
@Test public void deserialize() throws IOException { when(objectMapper.readValue(eq("requestBytes"), same(PortBinding.class))).thenReturn(fullPortBinding); PortBinding portBinding = portBindingSerializer.deserialize("requestBytes"); assertEquals(fullPortBinding, portBinding); } @Test public void deserializeHandleException() throws IOException { thrown.expect(RuntimeException.class); thrown.expectMessage("exception while parsing PortBinding for [requestBytes]"); when(objectMapper.readValue(eq("requestBytes"), same(PortBinding.class))).thenThrow(new RuntimeException("TEST EXCEPTION")); portBindingSerializer.deserialize("requestBytes"); }
PortBindingSerializer implements Serializer<PortBinding> { public String serialize(PortBinding portBinding) { try { return objectWriter.writeValueAsString(portBinding); } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while serializing portBinding to JSON with value " + portBinding) .setThrowable(throwable) ); throw new RuntimeException("Exception while serializing portBinding to JSON with value " + portBinding, throwable); } } PortBindingSerializer(MockServerLogger mockServerLogger); String serialize(PortBinding portBinding); PortBinding deserialize(String jsonPortBinding); @Override Class<PortBinding> supportsType(); }
@Test public void serialize() throws IOException { portBindingSerializer.serialize(fullPortBinding); verify(objectWriter).writeValueAsString(fullPortBinding); } @Test public void serializeObjectHandlesException() throws IOException { thrown.expect(RuntimeException.class); thrown.expectMessage(containsString("Exception while serializing portBinding to JSON with value")); when(objectWriter.writeValueAsString(any(PortBinding.class))).thenThrow(new RuntimeException("TEST EXCEPTION")); portBindingSerializer.serialize(portBinding()); }
VerificationSerializer implements Serializer<Verification> { public Verification deserialize(String jsonVerification) { if (isBlank(jsonVerification)) { throw new IllegalArgumentException( "1 error:" + NEW_LINE + " - a verification is required but value was \"" + jsonVerification + "\"" + NEW_LINE + NEW_LINE + OPEN_API_SPECIFICATION_URL ); } else { String validationErrors = getValidator().isValid(jsonVerification); if (validationErrors.isEmpty()) { Verification verification = null; try { VerificationDTO verificationDTO = objectMapper.readValue(jsonVerification, VerificationDTO.class); if (verificationDTO != null) { verification = verificationDTO.buildObject(); } } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for Verification " + throwable.getMessage()) .setArguments(jsonVerification) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing [" + jsonVerification + "] for Verification", throwable); } return verification; } else { throw new IllegalArgumentException(StringUtils.removeEndIgnoreCase(formatLogMessage("incorrect verification json format for:{}schema validation errors:{}", jsonVerification, validationErrors), "\n")); } } } VerificationSerializer(MockServerLogger mockServerLogger); String serialize(Verification verification); Verification deserialize(String jsonVerification); @Override Class<Verification> supportsType(); }
@Test public void deserialize() throws IOException { when(verificationValidator.isValid(eq("requestBytes"))).thenReturn(""); when(objectMapper.readValue(eq("requestBytes"), same(VerificationDTO.class))).thenReturn(fullVerificationDTO); Verification verification = verificationSerializer.deserialize("requestBytes"); assertEquals(fullVerification, verification); }
VerificationSerializer implements Serializer<Verification> { public String serialize(Verification verification) { try { return objectWriter.writeValueAsString(new VerificationDTO(verification)); } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while serializing verification to JSON with value " + verification) .setThrowable(e) ); throw new RuntimeException("Exception while serializing verification to JSON with value " + verification, e); } } VerificationSerializer(MockServerLogger mockServerLogger); String serialize(Verification verification); Verification deserialize(String jsonVerification); @Override Class<Verification> supportsType(); }
@Test public void serialize() throws IOException { verificationSerializer.serialize(fullVerification); verify(objectWriter).writeValueAsString(fullVerificationDTO); } @Test public void serializeHandlesException() throws IOException { thrown.expect(RuntimeException.class); thrown.expectMessage("Exception while serializing verification to JSON with value {" + NEW_LINE + " \"httpRequest\" : { }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"atLeast\" : 1" + NEW_LINE + " }" + NEW_LINE + "}"); when(objectWriter.writeValueAsString(any(VerificationDTO.class))).thenThrow(new RuntimeException("TEST EXCEPTION")); verificationSerializer.serialize(new Verification()); }
HttpRequestAndHttpResponseSerializer implements Serializer<HttpRequestAndHttpResponse> { public HttpRequestAndHttpResponse deserialize(String jsonHttpRequest) { if (isBlank(jsonHttpRequest)) { throw new IllegalArgumentException( "1 error:" + NEW_LINE + " - a request is required but value was \"" + jsonHttpRequest + "\"" + NEW_LINE + NEW_LINE + OPEN_API_SPECIFICATION_URL ); } else { if (jsonHttpRequest.contains("\"httpRequestAndHttpResponse\"")) { try { JsonNode jsonNode = objectMapper.readTree(jsonHttpRequest); if (jsonNode.has("httpRequestAndHttpResponse")) { jsonHttpRequest = jsonNode.get("httpRequestAndHttpResponse").toString(); } } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for HttpRequestAndHttpResponse " + throwable.getMessage()) .setArguments(jsonHttpRequest) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing [" + jsonHttpRequest + "] for HttpRequestAndHttpResponse", throwable); } } String validationErrors = getValidator().isValid(jsonHttpRequest); if (validationErrors.isEmpty()) { HttpRequestAndHttpResponse httpRequestAndHttpResponse = null; try { HttpRequestAndHttpResponseDTO httpRequestDTO = objectMapper.readValue(jsonHttpRequest, HttpRequestAndHttpResponseDTO.class); if (httpRequestDTO != null) { httpRequestAndHttpResponse = httpRequestDTO.buildObject(); } } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for HttpRequestAndHttpResponse " + throwable.getMessage()) .setArguments(jsonHttpRequest) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing [" + jsonHttpRequest + "] for HttpRequestAndHttpResponse", throwable); } return httpRequestAndHttpResponse; } else { throw new IllegalArgumentException(StringUtils.removeEndIgnoreCase(formatLogMessage("incorrect json format for:{}schema validation errors:{}", jsonHttpRequest, validationErrors), "\n")); } } } HttpRequestAndHttpResponseSerializer(MockServerLogger mockServerLogger); String serialize(HttpRequestAndHttpResponse httpRequestAndHttpResponse); String serialize(List<HttpRequestAndHttpResponse> httpRequests); String serialize(HttpRequestAndHttpResponse... httpRequests); HttpRequestAndHttpResponse deserialize(String jsonHttpRequest); @Override Class<HttpRequestAndHttpResponse> supportsType(); HttpRequestAndHttpResponse[] deserializeArray(String jsonHttpRequests); }
@Test public void deserialize() throws IOException { when(jsonSchemaHttpRequestAndHttpResponseValidator.isValid(eq("requestBytes"))).thenReturn(""); when(objectMapper.readValue(eq("requestBytes"), same(HttpRequestAndHttpResponseDTO.class))).thenReturn(fullHttpRequestAndHttpResponseDTO); HttpRequestAndHttpResponse httpRequestAndHttpResponse = httpRequestAndHttpResponseSerializer.deserialize("requestBytes"); assertEquals(fullHttpRequestAndHttpResponse, httpRequestAndHttpResponse); }
HttpRequestAndHttpResponseSerializer implements Serializer<HttpRequestAndHttpResponse> { public String serialize(HttpRequestAndHttpResponse httpRequestAndHttpResponse) { try { return objectWriter.writeValueAsString(new HttpRequestAndHttpResponseDTO(httpRequestAndHttpResponse)); } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while serializing HttpRequestAndHttpResponse to JSON with value " + httpRequestAndHttpResponse) .setThrowable(e) ); throw new RuntimeException("Exception while serializing HttpRequestAndHttpResponse to JSON with value " + httpRequestAndHttpResponse, e); } } HttpRequestAndHttpResponseSerializer(MockServerLogger mockServerLogger); String serialize(HttpRequestAndHttpResponse httpRequestAndHttpResponse); String serialize(List<HttpRequestAndHttpResponse> httpRequests); String serialize(HttpRequestAndHttpResponse... httpRequests); HttpRequestAndHttpResponse deserialize(String jsonHttpRequest); @Override Class<HttpRequestAndHttpResponse> supportsType(); HttpRequestAndHttpResponse[] deserializeArray(String jsonHttpRequests); }
@Test public void serialize() throws IOException { httpRequestAndHttpResponseSerializer.serialize(fullHttpRequestAndHttpResponse); verify(objectWriter).writeValueAsString(fullHttpRequestAndHttpResponseDTO); } @Test @SuppressWarnings("RedundantArrayCreation") public void shouldSerializeArray() throws IOException { httpRequestAndHttpResponseSerializer.serialize(new HttpRequestAndHttpResponse[]{fullHttpRequestAndHttpResponse, fullHttpRequestAndHttpResponse}); verify(objectWriter).writeValueAsString(new HttpRequestAndHttpResponseDTO[]{fullHttpRequestAndHttpResponseDTO, fullHttpRequestAndHttpResponseDTO}); }
VerificationSequenceSerializer implements Serializer<VerificationSequence> { public VerificationSequence deserialize(String jsonVerificationSequence) { if (isBlank(jsonVerificationSequence)) { throw new IllegalArgumentException( "1 error:" + NEW_LINE + " - a verification sequence is required but value was \"" + jsonVerificationSequence + "\"" + NEW_LINE + NEW_LINE + OPEN_API_SPECIFICATION_URL ); } else { String validationErrors = getValidator().isValid(jsonVerificationSequence); if (validationErrors.isEmpty()) { VerificationSequence verificationSequence = null; try { VerificationSequenceDTO verificationDTO = objectMapper.readValue(jsonVerificationSequence, VerificationSequenceDTO.class); if (verificationDTO != null) { verificationSequence = verificationDTO.buildObject(); } } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for VerificationSequence " + throwable.getMessage()) .setArguments(jsonVerificationSequence) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing [" + jsonVerificationSequence + "] for VerificationSequence", throwable); } return verificationSequence; } else { throw new IllegalArgumentException(StringUtils.removeEndIgnoreCase(formatLogMessage("incorrect verification sequence json format for:{}schema validation errors:{}", jsonVerificationSequence, validationErrors), "\n")); } } } VerificationSequenceSerializer(MockServerLogger mockServerLogger); String serialize(VerificationSequence verificationSequence); VerificationSequence deserialize(String jsonVerificationSequence); @Override Class<VerificationSequence> supportsType(); }
@Test public void deserialize() throws IOException { when(verificationSequenceValidator.isValid(eq("requestBytes"))).thenReturn(""); when(objectMapper.readValue(eq("requestBytes"), same(VerificationSequenceDTO.class))).thenReturn(fullVerificationSequenceDTO); VerificationSequence verification = verificationSequenceSerializer.deserialize("requestBytes"); assertEquals(fullVerificationSequence, verification); }
VerificationSequenceSerializer implements Serializer<VerificationSequence> { public String serialize(VerificationSequence verificationSequence) { try { return objectWriter.writeValueAsString(new VerificationSequenceDTO(verificationSequence)); } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while serializing verificationSequence to JSON with value " + verificationSequence) .setThrowable(e) ); throw new RuntimeException("Exception while serializing verificationSequence to JSON with value " + verificationSequence, e); } } VerificationSequenceSerializer(MockServerLogger mockServerLogger); String serialize(VerificationSequence verificationSequence); VerificationSequence deserialize(String jsonVerificationSequence); @Override Class<VerificationSequence> supportsType(); }
@Test public void serialize() throws IOException { verificationSequenceSerializer.serialize(fullVerificationSequence); verify(objectWriter).writeValueAsString(fullVerificationSequenceDTO); } @Test public void serializeHandlesException() throws IOException { thrown.expect(RuntimeException.class); thrown.expectMessage("Exception while serializing verificationSequence to JSON with value { }"); when(objectWriter.writeValueAsString(any(VerificationSequenceDTO.class))).thenThrow(new RuntimeException("TEST EXCEPTION")); verificationSequenceSerializer.serialize(new VerificationSequence()); }
OpenAPIExpectationSerializer implements Serializer<OpenAPIExpectation> { public OpenAPIExpectation deserialize(String jsonOpenAPIExpectation) { if (isBlank(jsonOpenAPIExpectation)) { throw new IllegalArgumentException( "1 error:" + NEW_LINE + " - an expectation is required but value was \"" + jsonOpenAPIExpectation + "\"" + NEW_LINE + NEW_LINE + OPEN_API_SPECIFICATION_URL ); } else { String validationErrors = getValidator().isValid(jsonOpenAPIExpectation); if (validationErrors.isEmpty()) { OpenAPIExpectation expectation = null; try { OpenAPIExpectationDTO expectationDTO = objectMapper.readValue(jsonOpenAPIExpectation, OpenAPIExpectationDTO.class); if (expectationDTO != null) { expectation = expectationDTO.buildObject(); } } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for OpenAPIExpectation " + throwable.getMessage()) .setArguments(jsonOpenAPIExpectation) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing [" + jsonOpenAPIExpectation + "] for OpenAPIExpectation", throwable); } return expectation; } else { throw new IllegalArgumentException(StringUtils.removeEndIgnoreCase(formatLogMessage("incorrect openapi expectation json format for:{}schema validation errors:{}", jsonOpenAPIExpectation, validationErrors), "\n")); } } } OpenAPIExpectationSerializer(MockServerLogger mockServerLogger); String serialize(OpenAPIExpectation expectation); String serialize(List<OpenAPIExpectation> expectations); String serialize(OpenAPIExpectation... expectations); OpenAPIExpectation deserialize(String jsonOpenAPIExpectation); @Override Class<OpenAPIExpectation> supportsType(); OpenAPIExpectation[] deserializeArray(String jsonOpenAPIExpectations, boolean allowEmpty); }
@Test public void deserialize() throws IOException { when(httpRequestValidator.isValid(eq("requestBytes"))).thenReturn(""); when(objectMapper.readValue(eq("requestBytes"), same(OpenAPIExpectationDTO.class))).thenReturn(fullOpenAPIExpectationDTO); OpenAPIExpectation httpRequest = httpRequestSerializer.deserialize("requestBytes"); assertEquals(fullOpenAPIExpectation, httpRequest); }
OpenAPIExpectationSerializer implements Serializer<OpenAPIExpectation> { public String serialize(OpenAPIExpectation expectation) { if (expectation != null) { try { return objectWriter .writeValueAsString(new OpenAPIExpectationDTO(expectation)); } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while serializing expectation to JSON with value " + expectation) .setThrowable(e) ); throw new RuntimeException("Exception while serializing expectation to JSON with value " + expectation, e); } } else { return ""; } } OpenAPIExpectationSerializer(MockServerLogger mockServerLogger); String serialize(OpenAPIExpectation expectation); String serialize(List<OpenAPIExpectation> expectations); String serialize(OpenAPIExpectation... expectations); OpenAPIExpectation deserialize(String jsonOpenAPIExpectation); @Override Class<OpenAPIExpectation> supportsType(); OpenAPIExpectation[] deserializeArray(String jsonOpenAPIExpectations, boolean allowEmpty); }
@Test public void serialize() throws IOException { httpRequestSerializer.serialize(fullOpenAPIExpectation); verify(objectWriter).writeValueAsString(fullOpenAPIExpectationDTO); } @Test @SuppressWarnings("RedundantArrayCreation") public void shouldSerializeArray() throws IOException { httpRequestSerializer.serialize(new OpenAPIExpectation[]{fullOpenAPIExpectation, fullOpenAPIExpectation}); verify(objectWriter).writeValueAsString(new OpenAPIExpectationDTO[]{fullOpenAPIExpectationDTO, fullOpenAPIExpectationDTO}); }
Base64Converter extends ObjectWithReflectiveEqualsHashCodeToString { public String bytesToBase64String(byte[] data) { return new String(ENCODER.encode(data), UTF_8); } byte[] base64StringToBytes(String data); String bytesToBase64String(byte[] data); }
@Test public void shouldConvertToBase64Value() { assertThat(base64Converter.bytesToBase64String("some_value".getBytes(UTF_8)), is(DatatypeConverter.printBase64Binary("some_value".getBytes(UTF_8)))); assertThat(base64Converter.bytesToBase64String("some_value".getBytes(UTF_8)), is("c29tZV92YWx1ZQ==")); }
Base64Converter extends ObjectWithReflectiveEqualsHashCodeToString { public byte[] base64StringToBytes(String data) { if (data == null) { return new byte[0]; } if (!data.matches(BASE64_PATTERN)) { return data.getBytes(UTF_8); } return DECODER.decode(data.getBytes(UTF_8)); } byte[] base64StringToBytes(String data); String bytesToBase64String(byte[] data); }
@Test public void shouldConvertBase64ValueToString() { assertThat(new String(base64Converter.base64StringToBytes(DatatypeConverter.printBase64Binary("some_value".getBytes(UTF_8)))), is("some_value")); assertThat(base64Converter.base64StringToBytes("c29tZV92YWx1ZQ=="), is("some_value".getBytes(UTF_8))); } @Test public void shouldConvertBase64NullValueToString() { assertThat(new String(base64Converter.base64StringToBytes(null)), is("")); } @Test public void shouldNotConvertNoneBase64Value() { assertThat(new String(base64Converter.base64StringToBytes("some_value")), is("some_value")); }
HttpResponseSerializer implements Serializer<HttpResponse> { public HttpResponse deserialize(String jsonHttpResponse) { if (isBlank(jsonHttpResponse)) { throw new IllegalArgumentException( "1 error:" + NEW_LINE + " - a response is required but value was \"" + jsonHttpResponse + "\"" + NEW_LINE + NEW_LINE + OPEN_API_SPECIFICATION_URL ); } else { if (jsonHttpResponse.contains("\"httpResponse\"")) { try { JsonNode jsonNode = objectMapper.readTree(jsonHttpResponse); if (jsonNode.has("httpResponse")) { jsonHttpResponse = jsonNode.get("httpResponse").toString(); } } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for HttpResponse" + throwable.getMessage()) .setArguments(jsonHttpResponse) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing [" + jsonHttpResponse + "] for HttpResponse", throwable); } } String validationErrors = getValidator().isValid(jsonHttpResponse); if (validationErrors.isEmpty()) { HttpResponse httpResponse = null; try { HttpResponseDTO httpResponseDTO = objectMapper.readValue(jsonHttpResponse, HttpResponseDTO.class); if (httpResponseDTO != null) { httpResponse = httpResponseDTO.buildObject(); } } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while parsing{}for HttpResponse " + throwable.getMessage()) .setArguments(jsonHttpResponse) .setThrowable(throwable) ); throw new IllegalArgumentException("exception while parsing [" + jsonHttpResponse + "] for HttpResponse", throwable); } return httpResponse; } else { throw new IllegalArgumentException(StringUtils.removeEndIgnoreCase(formatLogMessage("incorrect response json format for:{}schema validation errors:{}", jsonHttpResponse, validationErrors), "\n")); } } } HttpResponseSerializer(MockServerLogger mockServerLogger); String serialize(HttpResponse httpResponse); String serialize(List<HttpResponse> httpResponses); String serialize(HttpResponse... httpResponses); HttpResponse deserialize(String jsonHttpResponse); @Override Class<HttpResponse> supportsType(); HttpResponse[] deserializeArray(String jsonHttpResponses); }
@Test public void deserialize() throws IOException { when(httpResponseValidator.isValid(eq("responseBytes"))).thenReturn(""); when(objectMapper.readValue(eq("responseBytes"), same(HttpResponseDTO.class))).thenReturn(fullHttpResponseDTO); HttpResponse httpResponse = httpResponseSerializer.deserialize("responseBytes"); assertEquals(fullHttpResponse, httpResponse); }
HttpResponseSerializer implements Serializer<HttpResponse> { public String serialize(HttpResponse httpResponse) { try { return objectWriter.writeValueAsString(new HttpResponseDTO(httpResponse)); } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while serializing httpResponse to JSON with value " + httpResponse) .setThrowable(e) ); throw new RuntimeException("Exception while serializing httpResponse to JSON with value " + httpResponse, e); } } HttpResponseSerializer(MockServerLogger mockServerLogger); String serialize(HttpResponse httpResponse); String serialize(List<HttpResponse> httpResponses); String serialize(HttpResponse... httpResponses); HttpResponse deserialize(String jsonHttpResponse); @Override Class<HttpResponse> supportsType(); HttpResponse[] deserializeArray(String jsonHttpResponses); }
@Test public void serialize() throws IOException { httpResponseSerializer.serialize(fullHttpResponse); verify(objectWriter).writeValueAsString(fullHttpResponseDTO); } @Test @SuppressWarnings("RedundantArrayCreation") public void shouldSerializeArray() throws IOException { httpResponseSerializer.serialize(new HttpResponse[]{fullHttpResponse, fullHttpResponse}); verify(objectWriter).writeValueAsString(new HttpResponseDTO[]{fullHttpResponseDTO, fullHttpResponseDTO}); }
WebSocketMessageSerializer { public Object deserialize(String messageJson) throws ClassNotFoundException, IOException { WebSocketMessageDTO webSocketMessageDTO = objectMapper.readValue(messageJson, WebSocketMessageDTO.class); if (webSocketMessageDTO.getType() != null && webSocketMessageDTO.getValue() != null) { Class format = Class.forName(webSocketMessageDTO.getType()); if (serializers.containsKey(format)) { return serializers.get(format).deserialize(webSocketMessageDTO.getValue()); } else { return objectMapper.readValue(webSocketMessageDTO.getValue(), format); } } else { return null; } } WebSocketMessageSerializer(MockServerLogger mockServerLogger); String serialize(Object message); Object deserialize(String messageJson); }
@Test public void shouldDeserializeCompleteResponse() throws IOException, ClassNotFoundException { String requestBytes = "{" + NEW_LINE + " \"type\" : \"org.mockserver.model.HttpResponse\"," + NEW_LINE + " \"value\" : \"{" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"statusCode\\\" : 123," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"headers\\\" : [ {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"name\\\" : \\\"someHeaderName\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"values\\\" : [ \\\"someHeaderValue\\\" ]" + StringEscapeUtils.escapeJava(NEW_LINE) + " } ]," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"cookies\\\" : [ {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"name\\\" : \\\"someCookieName\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"value\\\" : \\\"someCookieValue\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " } ]," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"body\\\" : \\\"somebody\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"delay\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"timeUnit\\\" : \\\"SECONDS\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"value\\\" : 5" + StringEscapeUtils.escapeJava(NEW_LINE) + " }" + StringEscapeUtils.escapeJava(NEW_LINE) + "}\"" + NEW_LINE + "}"; Object httpResponse = new WebSocketMessageSerializer(new MockServerLogger()).deserialize(requestBytes); assertEquals(new HttpResponseDTO() .setStatusCode(123) .setBody(BodyWithContentTypeDTO.createWithContentTypeDTO(exact("somebody"))) .setHeaders(new Headers().withEntries( header("someHeaderName", "someHeaderValue") )) .setCookies(new Cookies().withEntries( cookie("someCookieName", "someCookieValue") )) .setDelay(new DelayDTO(seconds(5))) .buildObject(), httpResponse); } @Test public void shouldDeserializeCompleteRequest() throws IOException, ClassNotFoundException { String requestBytes = "{" + NEW_LINE + " \"type\" : \"org.mockserver.model.HttpRequest\"," + NEW_LINE + " \"value\" : \"{" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"method\\\" : \\\"someMethod\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"path\\\" : \\\"somePath\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"queryStringParameters\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"queryParameterName\\\" : [ \\\"queryParameterValue\\\" ]" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"headers\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"someHeaderName\\\" : [ \\\"someHeaderValue\\\" ]" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"cookies\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"someCookieName\\\" : \\\"someCookieValue\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"keepAlive\\\" : false," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"secure\\\" : true," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"socketAddress\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"host\\\" : \\\"someHost\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"port\\\" : 1234," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"scheme\\\" : \\\"HTTPS\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"body\\\" : \\\"somebody\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + "}\"" + NEW_LINE + "}"; Object httpRequest = new WebSocketMessageSerializer(new MockServerLogger()).deserialize(requestBytes); assertEquals(new HttpRequestDTO() .setMethod(string("someMethod")) .setPath(string("somePath")) .setQueryStringParameters(new Parameters().withEntries( param("queryParameterName", "queryParameterValue") )) .setBody(BodyDTO.createDTO(exact("somebody"))) .setHeaders(new Headers().withEntries( header("someHeaderName", "someHeaderValue") )) .setCookies(new Cookies().withEntries( cookie("someCookieName", "someCookieValue") )) .setSecure(true) .setKeepAlive(false) .setSocketAddress(new SocketAddressDTO( new SocketAddress() .withHost("someHost") .withPort(1234) .withScheme(SocketAddress.Scheme.HTTPS) )) .buildObject(), httpRequest); }
WebSocketMessageSerializer { public String serialize(Object message) throws JsonProcessingException { if (serializers.containsKey(message.getClass())) { WebSocketMessageDTO value = new WebSocketMessageDTO().setType(message.getClass().getName()).setValue(serializers.get(message.getClass()).serialize((message))); return objectWriter.writeValueAsString(value); } else { return objectWriter.writeValueAsString(new WebSocketMessageDTO().setType(message.getClass().getName()).setValue(objectMapper.writeValueAsString(message))); } } WebSocketMessageSerializer(MockServerLogger mockServerLogger); String serialize(Object message); Object deserialize(String messageJson); }
@Test public void shouldSerializeCompleteResponse() throws IOException { String jsonHttpResponse = new WebSocketMessageSerializer(new MockServerLogger()).serialize( new HttpResponseDTO() .setStatusCode(123) .setBody(BodyWithContentTypeDTO.createWithContentTypeDTO(exact("somebody"))) .setHeaders(new Headers().withEntries( header("someHeaderName", "someHeaderValue") )) .setCookies(new Cookies().withEntries( cookie("someCookieName", "someCookieValue") )) .setDelay(new DelayDTO(minutes(1))) .buildObject() ); assertEquals("{" + NEW_LINE + " \"type\" : \"org.mockserver.model.HttpResponse\"," + NEW_LINE + " \"value\" : \"{" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"statusCode\\\" : 123," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"headers\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"someHeaderName\\\" : [ \\\"someHeaderValue\\\" ]" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"cookies\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"someCookieName\\\" : \\\"someCookieValue\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"body\\\" : \\\"somebody\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"delay\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"timeUnit\\\" : \\\"MINUTES\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"value\\\" : 1" + StringEscapeUtils.escapeJava(NEW_LINE) + " }" + StringEscapeUtils.escapeJava(NEW_LINE) + "}\"" + NEW_LINE + "}", jsonHttpResponse); } @Test public void shouldSerializeCompleteRequest() throws IOException { String jsonHttpRequest = new WebSocketMessageSerializer(new MockServerLogger()).serialize( new HttpRequestDTO() .setMethod(string("someMethod")) .setPath(string("somePath")) .setQueryStringParameters(new Parameters().withEntries( param("queryParameterName", "queryParameterValue") )) .setBody(BodyDTO.createDTO(exact("somebody"))) .setHeaders(new Headers().withEntries( header("someHeaderName", "someHeaderValue") )) .setCookies(new Cookies().withEntries( cookie("someCookieName", "someCookieValue") )) .setSecure(true) .setKeepAlive(false) .setSocketAddress(new SocketAddressDTO( new SocketAddress() .withHost("someHost") .withPort(1234) .withScheme(SocketAddress.Scheme.HTTPS) )) .buildObject() ); assertEquals("{" + NEW_LINE + " \"type\" : \"org.mockserver.model.HttpRequest\"," + NEW_LINE + " \"value\" : \"{" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"method\\\" : \\\"someMethod\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"path\\\" : \\\"somePath\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"queryStringParameters\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"queryParameterName\\\" : [ \\\"queryParameterValue\\\" ]" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"headers\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"someHeaderName\\\" : [ \\\"someHeaderValue\\\" ]" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"cookies\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"someCookieName\\\" : \\\"someCookieValue\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"keepAlive\\\" : false," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"secure\\\" : true," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"socketAddress\\\" : {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"host\\\" : \\\"someHost\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"port\\\" : 1234," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"scheme\\\" : \\\"HTTPS\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"body\\\" : \\\"somebody\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + "}\"" + NEW_LINE + "}", jsonHttpRequest); }
BinaryArrayFormatter { public static String byteArrayToString(byte[] bytes) { if (bytes != null && bytes.length > 0) { return "base64:" + NEW_LINE + " " + Joiner.on("\n ").join(Splitter .fixedLength(64) .split(Base64.getEncoder().encodeToString(bytes))) + NEW_LINE + "hex:" + NEW_LINE + " " + Joiner.on("\n ").join(Splitter .fixedLength(64) .split(String.valueOf(Hex.encodeHex(bytes)))); } else { return "base64:" + NEW_LINE + NEW_LINE + "hex:" + NEW_LINE; } } static String byteArrayToString(byte[] bytes); }
@Test public void shouldPrintByteArray() { byte[] bytes = "this is a long sentence so that I can ensure that the byte array printing does correctly wrap nicely into nice looking and pretty blocks of base64 and hex binary".getBytes(UTF_8); assertThat(BinaryArrayFormatter.byteArrayToString(bytes), is("base64:" + NEW_LINE + " dGhpcyBpcyBhIGxvbmcgc2VudGVuY2Ugc28gdGhhdCBJIGNhbiBlbnN1cmUgdGhh" + NEW_LINE + " dCB0aGUgYnl0ZSBhcnJheSBwcmludGluZyBkb2VzIGNvcnJlY3RseSB3cmFwIG5p" + NEW_LINE + " Y2VseSBpbnRvIG5pY2UgbG9va2luZyBhbmQgcHJldHR5IGJsb2NrcyBvZiBiYXNl" + NEW_LINE + " NjQgYW5kIGhleCBiaW5hcnk=" + NEW_LINE + "hex:" + NEW_LINE + " 746869732069732061206c6f6e672073656e74656e636520736f207468617420" + NEW_LINE + " 492063616e20656e737572652074686174207468652062797465206172726179" + NEW_LINE + " 207072696e74696e6720646f657320636f72726563746c792077726170206e69" + NEW_LINE + " 63656c7920696e746f206e696365206c6f6f6b696e6720616e64207072657474" + NEW_LINE + " 7920626c6f636b73206f662062617365363420616e64206865782062696e6172" + NEW_LINE + " 79")); } @Test public void shouldHandleNullArray() { byte[] bytes = null; assertThat(BinaryArrayFormatter.byteArrayToString(bytes), is("base64:" + NEW_LINE + NEW_LINE + "hex:" + NEW_LINE)); } @Test public void shouldHandleEmptyArray() { byte[] bytes = new byte[0]; assertThat(BinaryArrayFormatter.byteArrayToString(bytes), is("base64:" + NEW_LINE + NEW_LINE + "hex:" + NEW_LINE)); }
MockServerLogger { public void logEvent(LogEntry logEntry) { if (logEntry.getType() == RECEIVED_REQUEST || logEntry.getType() == FORWARDED_REQUEST || isEnabled(logEntry.getLogLevel())) { if (httpStateHandler != null) { httpStateHandler.log(logEntry); } else { writeToSystemOut(logger, logEntry); } } } @VisibleForTesting MockServerLogger(); @VisibleForTesting MockServerLogger(final Logger logger); MockServerLogger(final Class<?> loggerClass); MockServerLogger(final @Nullable HttpState httpStateHandler); static void configureLogger(); MockServerLogger setHttpStateHandler(HttpState httpStateHandler); void logEvent(LogEntry logEntry); static void writeToSystemOut(Logger logger, LogEntry logEntry); static boolean isEnabled(final Level level); }
@Test public void shouldSendEventToStateHandler() { Level originalLevel = logLevel(); try { logLevel("INFO"); HttpState mockHttpStateHandler = mock(HttpState.class); MockServerLogger logFormatter = new MockServerLogger(mockHttpStateHandler); HttpRequest request = request("some_path"); logFormatter.logEvent( new LogEntry() .setLogLevel(Level.INFO) .setHttpRequest(request) .setMessageFormat("some random message with{}and{}") .setArguments("some" + NEW_LINE + "multi-line" + NEW_LINE + "object", "another" + NEW_LINE + "multi-line" + NEW_LINE + "object") ); ArgumentCaptor<LogEntry> captor = ArgumentCaptor.forClass(LogEntry.class); verify(mockHttpStateHandler, times(1)).log(captor.capture()); LogEntry messageLogEntry = captor.getValue(); assertThat(messageLogEntry.getHttpRequests(), is(new HttpRequest[]{request})); assertThat(messageLogEntry.getMessage(), containsString("some random message with" + NEW_LINE + NEW_LINE + " some" + NEW_LINE + " multi-line" + NEW_LINE + " object" + NEW_LINE + NEW_LINE + " and" + NEW_LINE + NEW_LINE + " another" + NEW_LINE + " multi-line" + NEW_LINE + " object" + NEW_LINE)); assertThat(messageLogEntry.getMessageFormat(), containsString("some random message with{}and{}")); assertThat(messageLogEntry.getArguments(), arrayContaining(new Object[]{ "some" + NEW_LINE + "multi-line" + NEW_LINE + "object", "another" + NEW_LINE + "multi-line" + NEW_LINE + "object" })); } finally { logLevel(originalLevel.toString()); } } @Test public void shouldFormatErrorLogMessagesForRequest() { Level originalLevel = logLevel(); try { logLevel("INFO"); Logger mockLogger = mock(Logger.class); MockServerLogger logFormatter = new MockServerLogger(mockLogger); HttpRequest request = request("some_path"); logFormatter.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setHttpRequest(request) .setMessageFormat("some random message with{}and{}") .setArguments("some" + NEW_LINE + "multi-line" + NEW_LINE + "object", "another" + NEW_LINE + "multi-line" + NEW_LINE + "object") ); String message = "some random message with" + NEW_LINE + NEW_LINE + " some" + NEW_LINE + " multi-line" + NEW_LINE + " object" + NEW_LINE + NEW_LINE + " and" + NEW_LINE + NEW_LINE + " another" + NEW_LINE + " multi-line" + NEW_LINE + " object" + NEW_LINE; verify(mockLogger).error(message, (Throwable) null); } finally { logLevel(originalLevel.toString()); } } @Test public void shouldFormatLogMessagesWithException() { Level originalLevel = logLevel(); try { logLevel("INFO"); Logger mockLogger = mock(Logger.class); MockServerLogger logFormatter = new MockServerLogger(mockLogger); HttpRequest request = request("some_path"); RuntimeException exception = new RuntimeException("TEST EXCEPTION"); logFormatter.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setHttpRequest(request) .setMessageFormat("some random message with{}and{}") .setArguments( "some" + NEW_LINE + "multi-line" + NEW_LINE + "object", "another" + NEW_LINE + "multi-line" + NEW_LINE + "object" ) .setThrowable(exception) ); String message = "some random message with" + NEW_LINE + NEW_LINE + " some" + NEW_LINE + " multi-line" + NEW_LINE + " object" + NEW_LINE + NEW_LINE + " and" + NEW_LINE + NEW_LINE + " another" + NEW_LINE + " multi-line" + NEW_LINE + " object" + NEW_LINE; verify(mockLogger).error(message, exception); } finally { logLevel(originalLevel.toString()); } } @Test public void shouldFormatLogMessages() { Level originalLevel = logLevel(); try { logLevel("INFO"); Logger mockLogger = mock(Logger.class); MockServerLogger logFormatter = new MockServerLogger(mockLogger); HttpRequest request = request("some_path"); logFormatter.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setHttpRequest(request) .setMessageFormat("some random message with{}and{}") .setArguments( "some" + NEW_LINE + "multi-line" + NEW_LINE + "object", "another" + NEW_LINE + "multi-line" + NEW_LINE + "object" ) ); String message = "some random message with" + NEW_LINE + NEW_LINE + " some" + NEW_LINE + " multi-line" + NEW_LINE + " object" + NEW_LINE + NEW_LINE + " and" + NEW_LINE + NEW_LINE + " another" + NEW_LINE + " multi-line" + NEW_LINE + " object" + NEW_LINE; verify(mockLogger).error(message, (Throwable) null); } finally { logLevel(originalLevel.toString()); } }
IOStreamUtils { public static String readInputStreamToString(Socket socket) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); StringBuilder result = new StringBuilder(); String line; Integer contentLength = null; while ((line = bufferedReader.readLine()) != null) { if (line.startsWith("content-length") || line.startsWith("Content-Length")) { contentLength = Integer.parseInt(line.split(":")[1].trim()); } if (line.length() == 0) { if (contentLength != null) { result.append(NEW_LINE); for (int position = 0; position < contentLength; position++) { result.append((char) bufferedReader.read()); } } break; } result.append(line).append(NEW_LINE); } return result.toString(); } IOStreamUtils(MockServerLogger mockServerLogger); static String readInputStreamToString(Socket socket); String readInputStreamToString(ServletRequest request); void writeToOutputStream(byte[] data, ServletResponse response); }
@Test public void shouldReadSocketInputStreamWithoutNewLineToString() throws IOException { Socket socket = mock(Socket.class); when(socket.getInputStream()).thenReturn(IOUtils.toInputStream("bytes", UTF_8)); String result = IOStreamUtils.readInputStreamToString(socket); assertEquals("bytes" + NEW_LINE, result); } @Test public void shouldReadSocketInputStreamWithNewLineToString() throws IOException { Socket socket = mock(Socket.class); when(socket.getInputStream()).thenReturn(IOUtils.toInputStream("bytes" + NEW_LINE, UTF_8)); String result = IOStreamUtils.readInputStreamToString(socket); assertEquals("bytes" + NEW_LINE, result); } @Test public void shouldReadHttpRequestOnSocketInputStreamToString() throws IOException { Socket socket = mock(Socket.class); when(socket.getInputStream()).thenReturn(IOUtils.toInputStream("" + "Cache-Control:public, max-age=60" + NEW_LINE + "Content-Length:10" + NEW_LINE + "Content-Type:text/html; charset=utf-8" + NEW_LINE + "Date:Sat, 04 Jan 2014 17:18:54 GMT" + NEW_LINE + "Expires:Sat, 04 Jan 2014 17:19:54 GMT" + NEW_LINE + "Last-Modified:Sat, 04 Jan 2014 17:18:54 GMT" + NEW_LINE + "Vary:*" + NEW_LINE + NEW_LINE + "1234567890", UTF_8)); String result = IOStreamUtils.readInputStreamToString(socket); assertEquals("" + "Cache-Control:public, max-age=60" + NEW_LINE + "Content-Length:10" + NEW_LINE + "Content-Type:text/html; charset=utf-8" + NEW_LINE + "Date:Sat, 04 Jan 2014 17:18:54 GMT" + NEW_LINE + "Expires:Sat, 04 Jan 2014 17:19:54 GMT" + NEW_LINE + "Last-Modified:Sat, 04 Jan 2014 17:18:54 GMT" + NEW_LINE + "Vary:*" + NEW_LINE + NEW_LINE + "1234567890", result); } @Test public void shouldReadHttpRequestOnSocketInputStreamToStringLowerCaseHeaders() throws IOException { Socket socket = mock(Socket.class); when(socket.getInputStream()).thenReturn(IOUtils.toInputStream("" + "cache-control:public, max-age=60" + NEW_LINE + "content-length:10" + NEW_LINE + "content-type:text/html; charset=utf-8" + NEW_LINE + "date:Sat, 04 Jan 2014 17:18:54 GMT" + NEW_LINE + "expires:Sat, 04 Jan 2014 17:19:54 GMT" + NEW_LINE + "last-modified:Sat, 04 Jan 2014 17:18:54 GMT" + NEW_LINE + "vary:*" + NEW_LINE + NEW_LINE + "1234567890", UTF_8)); String result = IOStreamUtils.readInputStreamToString(socket); assertEquals("" + "cache-control:public, max-age=60" + NEW_LINE + "content-length:10" + NEW_LINE + "content-type:text/html; charset=utf-8" + NEW_LINE + "date:Sat, 04 Jan 2014 17:18:54 GMT" + NEW_LINE + "expires:Sat, 04 Jan 2014 17:19:54 GMT" + NEW_LINE + "last-modified:Sat, 04 Jan 2014 17:18:54 GMT" + NEW_LINE + "vary:*" + NEW_LINE + NEW_LINE + "1234567890", result); } @Test public void shouldReadServletRequestInputStreamToString() throws IOException { ServletRequest servletRequest = mock(ServletRequest.class); when(servletRequest.getInputStream()).thenReturn( new DelegatingServletInputStream(IOUtils.toInputStream("bytes", UTF_8)) ); String result = ioStreamUtils.readInputStreamToString(servletRequest); assertEquals("bytes", result); } @Test(expected = RuntimeException.class) public void shouldHandleExceptionWhenReadingServletRequestInputStreamToString() throws IOException { ServletRequest servletRequest = mock(ServletRequest.class); when(servletRequest.getInputStream()).thenThrow(new IOException("TEST EXCEPTION")); ioStreamUtils.readInputStreamToString(servletRequest); }
IOStreamUtils { public void writeToOutputStream(byte[] data, ServletResponse response) { try { OutputStream output = response.getOutputStream(); output.write(data); output.close(); } catch (IOException ioe) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("IOException while writing [" + new String(data) + "] to HttpServletResponse output stream") .setThrowable(ioe) ); throw new RuntimeException("IOException while writing [" + new String(data) + "] to HttpServletResponse output stream", ioe); } } IOStreamUtils(MockServerLogger mockServerLogger); static String readInputStreamToString(Socket socket); String readInputStreamToString(ServletRequest request); void writeToOutputStream(byte[] data, ServletResponse response); }
@Test public void shouldWriteToOutputStream() throws IOException { ServletResponse mockServletResponse = mock(ServletResponse.class); ServletOutputStream mockServletOutputStream = mock(ServletOutputStream.class); when(mockServletResponse.getOutputStream()).thenReturn(mockServletOutputStream); ioStreamUtils.writeToOutputStream("data".getBytes(UTF_8), mockServletResponse); verify(mockServletOutputStream).write("data".getBytes(UTF_8)); verify(mockServletOutputStream).close(); } @Test(expected = RuntimeException.class) public void shouldHandleExceptionWriteToOutputStream() throws IOException { ServletResponse mockServletResponse = mock(ServletResponse.class); when(mockServletResponse.getOutputStream()).thenThrow(new IOException("TEST EXCEPTION")); ioStreamUtils.writeToOutputStream("data".getBytes(UTF_8), mockServletResponse); }
HttpServletRequestToMockServerHttpRequestDecoder { public HttpRequest mapHttpServletRequestToMockServerRequest(HttpServletRequest httpServletRequest) { HttpRequest request = new HttpRequest(); setMethod(request, httpServletRequest); setPath(request, httpServletRequest); setQueryString(request, httpServletRequest); setBody(request, httpServletRequest); setHeaders(request, httpServletRequest); setCookies(request, httpServletRequest); setSocketAddress(request, httpServletRequest); request.withKeepAlive(isKeepAlive(httpServletRequest)); request.withSecure(httpServletRequest.isSecure()); return request; } HttpServletRequestToMockServerHttpRequestDecoder(MockServerLogger mockServerLogger); HttpRequest mapHttpServletRequestToMockServerRequest(HttpServletRequest httpServletRequest); boolean isKeepAlive(HttpServletRequest httpServletRequest); }
@Test public void shouldMapPathForRequestsWithAContextPath() { MockHttpServletRequest httpServletRequest = new MockHttpServletRequest("GET", "/requestURI"); httpServletRequest.setContextPath("contextPath"); httpServletRequest.setPathInfo("/pathInfo"); httpServletRequest.setContent("".getBytes(UTF_8)); HttpRequest httpRequest = new HttpServletRequestToMockServerHttpRequestDecoder(new MockServerLogger()).mapHttpServletRequestToMockServerRequest(httpServletRequest); assertEquals(string("/pathInfo"), httpRequest.getPath()); } @Test(expected = RuntimeException.class) public void shouldHandleExceptionWhenReadingBody() throws IOException { HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); when(httpServletRequest.getMethod()).thenReturn("GET"); when(httpServletRequest.getRequestURL()).thenReturn(new StringBuffer("requestURI")); when(httpServletRequest.getQueryString()).thenReturn("parameterName=parameterValue"); Enumeration<String> enumeration = mock(Enumeration.class); when(enumeration.hasMoreElements()).thenReturn(false); when(httpServletRequest.getHeaderNames()).thenReturn(enumeration); when(httpServletRequest.getInputStream()).thenThrow(new IOException("TEST EXCEPTION")); new HttpServletRequestToMockServerHttpRequestDecoder(new MockServerLogger()).mapHttpServletRequestToMockServerRequest(httpServletRequest); }
HttpState { public boolean handle(HttpRequest request, ResponseWriter responseWriter, boolean warDeployment) { request.withLogCorrelationId(UUIDService.getUUID()); setPort(request); if (MockServerLogger.isEnabled(Level.TRACE)) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.TRACE) .setHttpRequest(request) .setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT) .setArguments(request) ); } if (request.matches("PUT")) { CompletableFuture<Boolean> canHandle = new CompletableFuture<>(); if (request.matches("PUT", PATH_PREFIX + "/expectation", "/expectation")) { List<Expectation> upsertedExpectations = new ArrayList<>(); for (Expectation expectation : getExpectationSerializer().deserializeArray(request.getBodyAsJsonOrXmlString(), false)) { if (!warDeployment || validateSupportedFeatures(expectation, request, responseWriter)) { upsertedExpectations.addAll(add(expectation)); } } responseWriter.writeResponse(request, response() .withStatusCode(CREATED.code()) .withBody(getExpectationSerializer().serialize(upsertedExpectations), MediaType.JSON_UTF_8), true); canHandle.complete(true); } else if (request.matches("PUT", PATH_PREFIX + "/openapi", "/openapi")) { try { List<Expectation> upsertedExpectations = new ArrayList<>(); for (OpenAPIExpectation openAPIExpectation : getOpenAPIExpectationSerializer().deserializeArray(request.getBodyAsJsonOrXmlString(), false)) { upsertedExpectations.addAll(add(openAPIExpectation)); } responseWriter.writeResponse(request, response() .withStatusCode(CREATED.code()) .withBody(getExpectationSerializer().serialize(upsertedExpectations), MediaType.JSON_UTF_8), true); } catch (IllegalArgumentException iae) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception handling request for open api expectation:{}error:{}") .setArguments(request, iae.getMessage()) .setThrowable(iae) ); responseWriter.writeResponse( request, BAD_REQUEST, (!iae.getMessage().startsWith(OPEN_API_LOAD_ERROR) ? OPEN_API_LOAD_ERROR + (isNotBlank(iae.getMessage()) ? ", " : "") : "") + iae.getMessage(), MediaType.create("text", "plain").toString() ); } canHandle.complete(true); } else if (request.matches("PUT", PATH_PREFIX + "/clear", "/clear")) { clear(request); responseWriter.writeResponse(request, OK); canHandle.complete(true); } else if (request.matches("PUT", PATH_PREFIX + "/reset", "/reset")) { reset(); responseWriter.writeResponse(request, OK); canHandle.complete(true); } else if (request.matches("PUT", PATH_PREFIX + "/retrieve", "/retrieve")) { responseWriter.writeResponse(request, retrieve(request), true); canHandle.complete(true); } else if (request.matches("PUT", PATH_PREFIX + "/verify", "/verify")) { verify(getVerificationSerializer().deserialize(request.getBodyAsJsonOrXmlString()), result -> { if (isEmpty(result)) { responseWriter.writeResponse(request, ACCEPTED); } else { responseWriter.writeResponse(request, NOT_ACCEPTABLE, result, MediaType.create("text", "plain").toString()); } canHandle.complete(true); }); } else if (request.matches("PUT", PATH_PREFIX + "/verifySequence", "/verifySequence")) { verify(getVerificationSequenceSerializer().deserialize(request.getBodyAsJsonOrXmlString()), result -> { if (isEmpty(result)) { responseWriter.writeResponse(request, ACCEPTED); } else { responseWriter.writeResponse(request, NOT_ACCEPTABLE, result, MediaType.create("text", "plain").toString()); } canHandle.complete(true); }); } else { canHandle.complete(false); } try { return canHandle.get(maxFutureTimeout(), MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException ex) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception handling request:{}error:{}") .setArguments(request, ex.getMessage()) .setThrowable(ex) ); return false; } } else { return false; } } HttpState(MockServerLogger mockServerLogger, Scheduler scheduler); static void setPort(final HttpRequest request); static void setPort(final Integer port); static void setPort(final Integer... port); static void setPort(final List<Integer> port); static Integer getPort(); MockServerLogger getMockServerLogger(); void clear(HttpRequest request); void reset(); List<Expectation> add(OpenAPIExpectation openAPIExpectation); List<Expectation> add(Expectation... expectations); Expectation firstMatchingExpectation(HttpRequest request); void postProcess(Expectation expectation); void log(LogEntry logEntry); HttpResponse retrieve(HttpRequest request); Future<String> verify(Verification verification); void verify(Verification verification, Consumer<String> resultConsumer); Future<String> verify(VerificationSequence verification); void verify(VerificationSequence verification, Consumer<String> resultConsumer); boolean handle(HttpRequest request, ResponseWriter responseWriter, boolean warDeployment); WebSocketClientRegistry getWebSocketClientRegistry(); RequestMatchers getRequestMatchers(); MockServerEventLog getMockServerLog(); Scheduler getScheduler(); String getUniqueLoopPreventionHeaderName(); String getUniqueLoopPreventionHeaderValue(); void stop(); static final String LOG_SEPARATOR; static final String PATH_PREFIX; }
@Test public void shouldHandleReturnStatusRequest() { HttpRequest statusRequest = request("/mockserver/status").withMethod("PUT"); FakeResponseWriter responseWriter = new FakeResponseWriter(); boolean handle = httpState.handle(statusRequest, responseWriter, false); assertThat(handle, is(false)); assertThat(responseWriter.response, is(nullValue())); } @Test public void shouldHandleBindNewPortsRequest() { HttpRequest statusRequest = request("/mockserver/bind") .withMethod("PUT") .withBody(portBindingSerializer.serialize( portBinding(1090, 1090) )); FakeResponseWriter responseWriter = new FakeResponseWriter(); boolean handle = httpState.handle(statusRequest, responseWriter, false); assertThat(handle, is(false)); assertThat(responseWriter.response, is(nullValue())); } @Test public void shouldHandleStopRequest() { HttpRequest statusRequest = request("/mockserver/stop") .withMethod("PUT"); FakeResponseWriter responseWriter = new FakeResponseWriter(); boolean handle = httpState.handle(statusRequest, responseWriter, false); assertThat(handle, is(false)); assertThat(responseWriter.response, is(nullValue())); } @Test public void shouldHandleAddOpenAPIJsonRequest() throws JsonProcessingException { HttpRequest request = request("/mockserver/openapi").withMethod("PUT").withBody( openAPIExpectationSerializer.serialize(openAPIExpectation( FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json") )) ); FakeResponseWriter responseWriter = new FakeResponseWriter(); boolean handle = httpState.handle(request, responseWriter, false); assertThat(handle, is(true)); assertThat(responseWriter.response.getStatusCode(), is(201)); List<Expectation> actualExpectations = Arrays.asList(expectationSerializer.deserializeArray(responseWriter.response.getBodyAsString(), true)); shouldBuildPetStoreExpectations(ObjectMapperFactory.createObjectMapper().readTree(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json")).toPrettyString(), actualExpectations); } @Test public void shouldHandleAddOpenAPIJsonRequestWithSpecificResponses() throws JsonProcessingException { HttpRequest request = request("/mockserver/openapi").withMethod("PUT").withBody( openAPIExpectationSerializer.serialize(openAPIExpectation( FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json"), ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) )) ); FakeResponseWriter responseWriter = new FakeResponseWriter(); boolean handle = httpState.handle(request, responseWriter, false); assertThat(handle, is(true)); assertThat(responseWriter.response.getStatusCode(), is(201)); List<Expectation> actualExpectations = Arrays.asList(expectationSerializer.deserializeArray(responseWriter.response.getBodyAsString(), true)); shouldBuildPetStoreExpectationsWithSpecificResponses(ObjectMapperFactory.createObjectMapper().readTree(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json")).toPrettyString(), actualExpectations); } @Test public void shouldHandleInvalidOpenAPIJsonRequest() { HttpRequest request = request("/mockserver/openapi").withMethod("PUT").withBody( openAPIExpectationSerializer.serialize(openAPIExpectation("" + "\"openapi\": \"3.0.0\"," + NEW_LINE + " \"info\": {" + NEW_LINE + " \"version\": \"1.0.0\"," + NEW_LINE + " \"title\": \"Swagger Petstore\"" )) ); FakeResponseWriter responseWriter = new FakeResponseWriter(); boolean handle = httpState.handle(request, responseWriter, false); assertThat(handle, is(true)); assertThat(responseWriter.response.getStatusCode(), is(400)); assertThat(responseWriter.response.getBodyAsString(), is("Unable to load API spec, while parsing a block mapping" + NEW_LINE + " in 'reader', line 1, column 1:" + NEW_LINE + " \"openapi\": \"3.0.0\"," + NEW_LINE + " ^" + NEW_LINE + "expected <block end>, but found ','" + NEW_LINE + " in 'reader', line 1, column 19:" + NEW_LINE + " \"openapi\": \"3.0.0\"," + NEW_LINE + " ^")); } @Test public void shouldHandleAddOpenAPIYamlRequest() { HttpRequest request = request("/mockserver/openapi").withMethod("PUT").withBody( openAPIExpectationSerializer.serialize(openAPIExpectation( FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml") )) ); FakeResponseWriter responseWriter = new FakeResponseWriter(); boolean handle = httpState.handle(request, responseWriter, false); assertThat(handle, is(true)); assertThat(responseWriter.response.getStatusCode(), is(201)); List<Expectation> actualExpectations = Arrays.asList(expectationSerializer.deserializeArray(responseWriter.response.getBodyAsString(), true)); shouldBuildPetStoreExpectations(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml"), actualExpectations); } @Test public void shouldHandleAddOpenAPIYamlRequestWithSpecificResponses() { HttpRequest request = request("/mockserver/openapi").withMethod("PUT").withBody( openAPIExpectationSerializer.serialize(openAPIExpectation( FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml"), ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) )) ); FakeResponseWriter responseWriter = new FakeResponseWriter(); boolean handle = httpState.handle(request, responseWriter, false); assertThat(handle, is(true)); assertThat(responseWriter.response.getStatusCode(), is(201)); List<Expectation> actualExpectations = Arrays.asList(expectationSerializer.deserializeArray(responseWriter.response.getBodyAsString(), true)); shouldBuildPetStoreExpectationsWithSpecificResponses(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml"), actualExpectations); } @Test public void shouldHandleInvalidOpenAPIYamlRequest() { HttpRequest request = request("/mockserver/openapi").withMethod("PUT").withBody( openAPIExpectationSerializer.serialize(openAPIExpectation( FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml").substring(0, 100) )) ); FakeResponseWriter responseWriter = new FakeResponseWriter(); boolean handle = httpState.handle(request, responseWriter, false); assertThat(handle, is(true)); assertThat(responseWriter.response.getStatusCode(), is(400)); assertThat(responseWriter.response.getBodyAsString(), is("Unable to load API spec, while scanning a simple key" + NEW_LINE + " in 'reader', line 8, column 1:" + NEW_LINE + " servers" + NEW_LINE + " ^" + NEW_LINE + "could not find expected ':'" + NEW_LINE + " in 'reader', line 8, column 8:" + NEW_LINE + " servers" + NEW_LINE + " ^")); }
HttpState { public List<Expectation> add(OpenAPIExpectation openAPIExpectation) { return getOpenAPIConverter().buildExpectations(openAPIExpectation.getSpecUrlOrPayload(), openAPIExpectation.getOperationsAndResponses()).stream().map(this::add).flatMap(List::stream).collect(Collectors.toList()); } HttpState(MockServerLogger mockServerLogger, Scheduler scheduler); static void setPort(final HttpRequest request); static void setPort(final Integer port); static void setPort(final Integer... port); static void setPort(final List<Integer> port); static Integer getPort(); MockServerLogger getMockServerLogger(); void clear(HttpRequest request); void reset(); List<Expectation> add(OpenAPIExpectation openAPIExpectation); List<Expectation> add(Expectation... expectations); Expectation firstMatchingExpectation(HttpRequest request); void postProcess(Expectation expectation); void log(LogEntry logEntry); HttpResponse retrieve(HttpRequest request); Future<String> verify(Verification verification); void verify(Verification verification, Consumer<String> resultConsumer); Future<String> verify(VerificationSequence verification); void verify(VerificationSequence verification, Consumer<String> resultConsumer); boolean handle(HttpRequest request, ResponseWriter responseWriter, boolean warDeployment); WebSocketClientRegistry getWebSocketClientRegistry(); RequestMatchers getRequestMatchers(); MockServerEventLog getMockServerLog(); Scheduler getScheduler(); String getUniqueLoopPreventionHeaderName(); String getUniqueLoopPreventionHeaderValue(); void stop(); static final String LOG_SEPARATOR; static final String PATH_PREFIX; }
@Test public void shouldAddExceptionViaOpenApiClasspath() { List<Expectation> actualExpectations = httpState.add(openAPIExpectation("org/mockserver/mock/openapi_petstore_example.json")); shouldBuildPetStoreExpectations("org/mockserver/mock/openapi_petstore_example.json", actualExpectations); } @Test public void shouldAddExceptionViaOpenApiUrl() { URL schemaUrl = FileReader.getURL("org/mockserver/mock/openapi_petstore_example.json"); List<Expectation> actualExpectations = httpState.add(openAPIExpectation(String.valueOf(schemaUrl))); shouldBuildPetStoreExpectations(String.valueOf(schemaUrl), actualExpectations); } @Test public void shouldAddExceptionViaOpenApiSpec() { String schema = FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json"); List<Expectation> actualExpectations = httpState.add(openAPIExpectation(schema)); shouldBuildPetStoreExpectations(schema, actualExpectations); } @Test public void shouldAddExceptionViaOpenApiClasspathWithSpecificResponses() { List<Expectation> actualExpectations = httpState.add(openAPIExpectation("org/mockserver/mock/openapi_petstore_example.json", ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ))); shouldBuildPetStoreExpectationsWithSpecificResponses("org/mockserver/mock/openapi_petstore_example.json", actualExpectations); } @Test public void shouldAddExceptionViaOpenApiUrlWithSpecificResponses() { URL schemaUrl = FileReader.getURL("org/mockserver/mock/openapi_petstore_example.json"); List<Expectation> actualExpectations = httpState.add(openAPIExpectation(String.valueOf(schemaUrl), ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ))); shouldBuildPetStoreExpectationsWithSpecificResponses(String.valueOf(schemaUrl), actualExpectations); } @Test public void shouldAddExceptionViaOpenApiSpecWithSpecificResponses() { String schema = FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json"); List<Expectation> actualExpectations = httpState.add(openAPIExpectation(schema, ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ))); shouldBuildPetStoreExpectationsWithSpecificResponses(schema, actualExpectations); }
HttpState { public void clear(HttpRequest request) { final String logCorrelationId = UUIDService.getUUID(); RequestDefinition requestDefinition = null; if (isNotBlank(request.getBodyAsString())) { String body = request.getBodyAsJsonOrXmlString(); try { requestDefinition = resolveExpectationId(getExpectationIdSerializer().deserialize(body)); } catch (IllegalArgumentException ignore) { requestDefinition = getRequestDefinitionSerializer().deserialize(body); requestDefinition.withLogCorrelationId(logCorrelationId); } } try { ClearType type = ClearType.valueOf(defaultIfEmpty(request.getFirstQueryStringParameter("type").toUpperCase(), "ALL")); switch (type) { case LOG: mockServerLog.clear(requestDefinition); break; case EXPECTATIONS: requestMatchers.clear(requestDefinition); break; case ALL: mockServerLog.clear(requestDefinition); requestMatchers.clear(requestDefinition); break; } } catch (IllegalArgumentException iae) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setCorrelationId(logCorrelationId) .setMessageFormat("exception handling request:{}error:{}") .setArguments(request, iae.getMessage()) .setThrowable(iae) ); throw new IllegalArgumentException("\"" + request.getFirstQueryStringParameter("type") + "\" is not a valid value for \"type\" parameter, only the following values are supported " + Arrays.stream(ClearType.values()).map(input -> input.name().toLowerCase()).collect(Collectors.toList())); } System.gc(); } HttpState(MockServerLogger mockServerLogger, Scheduler scheduler); static void setPort(final HttpRequest request); static void setPort(final Integer port); static void setPort(final Integer... port); static void setPort(final List<Integer> port); static Integer getPort(); MockServerLogger getMockServerLogger(); void clear(HttpRequest request); void reset(); List<Expectation> add(OpenAPIExpectation openAPIExpectation); List<Expectation> add(Expectation... expectations); Expectation firstMatchingExpectation(HttpRequest request); void postProcess(Expectation expectation); void log(LogEntry logEntry); HttpResponse retrieve(HttpRequest request); Future<String> verify(Verification verification); void verify(Verification verification, Consumer<String> resultConsumer); Future<String> verify(VerificationSequence verification); void verify(VerificationSequence verification, Consumer<String> resultConsumer); boolean handle(HttpRequest request, ResponseWriter responseWriter, boolean warDeployment); WebSocketClientRegistry getWebSocketClientRegistry(); RequestMatchers getRequestMatchers(); MockServerEventLog getMockServerLog(); Scheduler getScheduler(); String getUniqueLoopPreventionHeaderName(); String getUniqueLoopPreventionHeaderValue(); void stop(); static final String LOG_SEPARATOR; static final String PATH_PREFIX; }
@Test public void shouldThrowExceptionForInvalidClearType() { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString("\"invalid\" is not a valid value for \"type\" parameter, only the following values are supported [log, expectations, all]")); httpState.clear(request().withQueryStringParameter("type", "invalid")); }
HttpState { public HttpResponse retrieve(HttpRequest request) { final String logCorrelationId = UUIDService.getUUID(); CompletableFuture<HttpResponse> httpResponseFuture = new CompletableFuture<>(); HttpResponse response = response().withStatusCode(OK.code()); if (request != null) { try { final RequestDefinition requestDefinition = isNotBlank(request.getBodyAsString()) ? getRequestDefinitionSerializer().deserialize(request.getBodyAsJsonOrXmlString()) : request(); requestDefinition.withLogCorrelationId(logCorrelationId); Format format = Format.valueOf(defaultIfEmpty(request.getFirstQueryStringParameter("format").toUpperCase(), "JSON")); RetrieveType type = RetrieveType.valueOf(defaultIfEmpty(request.getFirstQueryStringParameter("type").toUpperCase(), "REQUESTS")); switch (type) { case LOGS: { mockServerLog.retrieveMessageLogEntries(requestDefinition, (List<LogEntry> logEntries) -> { StringBuilder stringBuffer = new StringBuilder(); for (int i = 0; i < logEntries.size(); i++) { LogEntry messageLogEntry = logEntries.get(i); stringBuffer .append(messageLogEntry.getTimestamp()) .append(" - ") .append(messageLogEntry.getMessage()); if (i < logEntries.size() - 1) { stringBuffer.append(LOG_SEPARATOR); } } stringBuffer.append(NEW_LINE); response.withBody(stringBuffer.toString(), MediaType.PLAIN_TEXT_UTF_8); if (MockServerLogger.isEnabled(Level.INFO)) { mockServerLogger.logEvent( new LogEntry() .setType(RETRIEVED) .setLogLevel(Level.INFO) .setCorrelationId(logCorrelationId) .setHttpRequest(requestDefinition) .setMessageFormat("retrieved logs that match:{}") .setArguments(requestDefinition) ); } httpResponseFuture.complete(response); }); break; } case REQUESTS: { LogEntry logEntry = new LogEntry() .setType(RETRIEVED) .setLogLevel(Level.INFO) .setCorrelationId(logCorrelationId) .setHttpRequest(requestDefinition) .setMessageFormat("retrieved requests in " + format.name().toLowerCase() + " that match:{}") .setArguments(requestDefinition); switch (format) { case JAVA: mockServerLog .retrieveRequests( requestDefinition, requests -> { response.withBody( getRequestDefinitionSerializer().serialize(requests), MediaType.create("application", "java").withCharset(UTF_8) ); mockServerLogger.logEvent(logEntry); httpResponseFuture.complete(response); } ); break; case JSON: mockServerLog .retrieveRequests( requestDefinition, requests -> { response.withBody( getRequestDefinitionSerializer().serialize(true, requests), MediaType.JSON_UTF_8 ); mockServerLogger.logEvent(logEntry); httpResponseFuture.complete(response); } ); break; case LOG_ENTRIES: mockServerLog .retrieveRequestLogEntries( requestDefinition, logEntries -> { response.withBody( getLogEntrySerializer().serialize(logEntries), MediaType.JSON_UTF_8 ); mockServerLogger.logEvent(logEntry); httpResponseFuture.complete(response); } ); break; } break; } case REQUEST_RESPONSES: { LogEntry logEntry = new LogEntry() .setType(RETRIEVED) .setLogLevel(Level.INFO) .setCorrelationId(logCorrelationId) .setHttpRequest(requestDefinition) .setMessageFormat("retrieved requests and responses in " + format.name().toLowerCase() + " that match:{}") .setArguments(requestDefinition); switch (format) { case JAVA: response.withBody("JAVA not supported for REQUEST_RESPONSES", MediaType.create("text", "plain").withCharset(UTF_8)); mockServerLogger.logEvent(logEntry); httpResponseFuture.complete(response); break; case JSON: mockServerLog .retrieveRequestResponses( requestDefinition, httpRequestAndHttpResponses -> { response.withBody( getHttpRequestResponseSerializer().serialize(httpRequestAndHttpResponses), MediaType.JSON_UTF_8 ); mockServerLogger.logEvent(logEntry); httpResponseFuture.complete(response); } ); break; case LOG_ENTRIES: mockServerLog .retrieveRequestResponseMessageLogEntries( requestDefinition, logEntries -> { response.withBody( getLogEntrySerializer().serialize(logEntries), MediaType.JSON_UTF_8 ); mockServerLogger.logEvent(logEntry); httpResponseFuture.complete(response); } ); break; } break; } case RECORDED_EXPECTATIONS: { LogEntry logEntry = new LogEntry() .setType(RETRIEVED) .setLogLevel(Level.INFO) .setCorrelationId(logCorrelationId) .setHttpRequest(requestDefinition) .setMessageFormat("retrieved recorded expectations in " + format.name().toLowerCase() + " that match:{}") .setArguments(requestDefinition); switch (format) { case JAVA: mockServerLog .retrieveRecordedExpectations( requestDefinition, requests -> { response.withBody( getExpectationToJavaSerializer().serialize(requests), MediaType.create("application", "java").withCharset(UTF_8) ); mockServerLogger.logEvent(logEntry); httpResponseFuture.complete(response); } ); break; case JSON: mockServerLog .retrieveRecordedExpectations( requestDefinition, requests -> { response.withBody( getExpectationSerializer().serialize(requests), MediaType.JSON_UTF_8 ); mockServerLogger.logEvent(logEntry); httpResponseFuture.complete(response); } ); break; case LOG_ENTRIES: mockServerLog .retrieveRecordedExpectationLogEntries( requestDefinition, logEntries -> { response.withBody( getLogEntrySerializer().serialize(logEntries), MediaType.JSON_UTF_8 ); mockServerLogger.logEvent(logEntry); httpResponseFuture.complete(response); } ); break; } break; } case ACTIVE_EXPECTATIONS: { List<Expectation> expectations = requestMatchers.retrieveActiveExpectations(requestDefinition); switch (format) { case JAVA: response.withBody(getExpectationToJavaSerializer().serialize(expectations), MediaType.create("application", "java").withCharset(UTF_8)); break; case JSON: response.withBody(getExpectationSerializer().serialize(expectations), MediaType.JSON_UTF_8); break; case LOG_ENTRIES: response.withBody("LOG_ENTRIES not supported for ACTIVE_EXPECTATIONS", MediaType.create("text", "plain").withCharset(UTF_8)); break; } if (MockServerLogger.isEnabled(Level.INFO)) { mockServerLogger.logEvent( new LogEntry() .setType(RETRIEVED) .setLogLevel(Level.INFO) .setCorrelationId(logCorrelationId) .setHttpRequest(requestDefinition) .setMessageFormat("retrieved active expectations in " + format.name().toLowerCase() + " that match:{}") .setArguments(requestDefinition) ); } httpResponseFuture.complete(response); break; } } try { return httpResponseFuture.get(maxFutureTimeout(), MILLISECONDS); } catch (ExecutionException | InterruptedException | TimeoutException ex) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setCorrelationId(logCorrelationId) .setMessageFormat("exception handling request:{}error:{}") .setArguments(request, ex.getMessage()) .setThrowable(ex) ); throw new RuntimeException("Exception retrieving state for " + request, ex); } } catch (IllegalArgumentException iae) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setCorrelationId(logCorrelationId) .setMessageFormat("exception handling request:{}error:{}") .setArguments(request, iae.getMessage()) .setThrowable(iae) ); if (iae.getMessage().contains(RetrieveType.class.getSimpleName())) { throw new IllegalArgumentException("\"" + request.getFirstQueryStringParameter("type") + "\" is not a valid value for \"type\" parameter, only the following values are supported " + Arrays.stream(RetrieveType.values()).map(input -> input.name().toLowerCase()).collect(Collectors.toList())); } else { throw new IllegalArgumentException("\"" + request.getFirstQueryStringParameter("format") + "\" is not a valid value for \"format\" parameter, only the following values are supported " + Arrays.stream(Format.values()).map(input -> input.name().toLowerCase()).collect(Collectors.toList())); } } } else { return response().withStatusCode(200); } } HttpState(MockServerLogger mockServerLogger, Scheduler scheduler); static void setPort(final HttpRequest request); static void setPort(final Integer port); static void setPort(final Integer... port); static void setPort(final List<Integer> port); static Integer getPort(); MockServerLogger getMockServerLogger(); void clear(HttpRequest request); void reset(); List<Expectation> add(OpenAPIExpectation openAPIExpectation); List<Expectation> add(Expectation... expectations); Expectation firstMatchingExpectation(HttpRequest request); void postProcess(Expectation expectation); void log(LogEntry logEntry); HttpResponse retrieve(HttpRequest request); Future<String> verify(Verification verification); void verify(Verification verification, Consumer<String> resultConsumer); Future<String> verify(VerificationSequence verification); void verify(VerificationSequence verification, Consumer<String> resultConsumer); boolean handle(HttpRequest request, ResponseWriter responseWriter, boolean warDeployment); WebSocketClientRegistry getWebSocketClientRegistry(); RequestMatchers getRequestMatchers(); MockServerEventLog getMockServerLog(); Scheduler getScheduler(); String getUniqueLoopPreventionHeaderName(); String getUniqueLoopPreventionHeaderValue(); void stop(); static final String LOG_SEPARATOR; static final String PATH_PREFIX; }
@Test public void shouldRetrieveRecordedRequestsResponsesAsJava() { HttpResponse response = httpState .retrieve( request() .withQueryStringParameter("format", "java") .withQueryStringParameter("type", "request_responses") .withBody(httpRequestSerializer.serialize(request("request_one"))) ); assertThat(response.getBodyAsString(), is("JAVA not supported for REQUEST_RESPONSES")); } @Test public void shouldThrowExceptionForInvalidRetrieveType() { try { httpState.retrieve(request().withQueryStringParameter("type", "invalid")); fail("expected exception to be thrown"); } catch (Throwable throwable) { assertThat(throwable, instanceOf(IllegalArgumentException.class)); assertThat(throwable.getMessage(), is("\"invalid\" is not a valid value for \"type\" parameter, only the following values are supported [logs, requests, request_responses, recorded_expectations, active_expectations]")); } } @Test public void shouldThrowExceptionForInvalidRetrieveFormat() { try { httpState.retrieve(request().withQueryStringParameter("format", "invalid")); fail("expected exception to be thrown"); } catch (Throwable throwable) { assertThat(throwable, instanceOf(IllegalArgumentException.class)); assertThat(throwable.getMessage(), is("\"invalid\" is not a valid value for \"format\" parameter, only the following values are supported [java, json, log_entries]")); } }
HttpErrorActionHandler { public void handle(HttpError httpError, ChannelHandlerContext ctx) { if (httpError.getResponseBytes() != null) { ChannelHandlerContext httpCodecContext = ctx.pipeline().context(HttpServerCodec.class); if (httpCodecContext != null) { httpCodecContext.writeAndFlush(Unpooled.wrappedBuffer(httpError.getResponseBytes())).awaitUninterruptibly(); } } if (httpError.getDropConnection() != null && httpError.getDropConnection()) { ctx.disconnect(); ctx.close(); } } void handle(HttpError httpError, ChannelHandlerContext ctx); }
@Test public void shouldDropConnection() { ChannelHandlerContext mockChannelHandlerContext = mock(ChannelHandlerContext.class); HttpError httpError = error().withDropConnection(true); new HttpErrorActionHandler().handle(httpError, mockChannelHandlerContext); verify(mockChannelHandlerContext).close(); } @Test public void shouldReturnBytes() { ChannelHandlerContext mockChannelHandlerContext = mock(ChannelHandlerContext.class); ChannelPipeline mockChannelPipeline = mock(ChannelPipeline.class); ChannelFuture mockChannelFuture = mock(ChannelFuture.class); when(mockChannelHandlerContext.pipeline()).thenReturn(mockChannelPipeline); when(mockChannelPipeline.context(HttpServerCodec.class)).thenReturn(mockChannelHandlerContext); when(mockChannelHandlerContext.writeAndFlush(any(ByteBuf.class))).thenReturn(mockChannelFuture); new HttpErrorActionHandler().handle( error() .withResponseBytes("some_bytes".getBytes()), mockChannelHandlerContext ); verify(mockChannelHandlerContext).pipeline(); verify(mockChannelPipeline).context(HttpServerCodec.class); verify(mockChannelHandlerContext).writeAndFlush(Unpooled.wrappedBuffer("some_bytes".getBytes())); verify(mockChannelFuture).awaitUninterruptibly(); }
HttpForwardTemplateActionHandler extends HttpForwardAction { public HttpForwardActionResult handle(HttpTemplate httpTemplate, HttpRequest originalRequest) { TemplateEngine templateEngine; switch (httpTemplate.getTemplateType()) { case VELOCITY: templateEngine = getVelocityTemplateEngine(); break; case JAVASCRIPT: templateEngine = getJavaScriptTemplateEngine(); break; default: throw new RuntimeException("Unknown no template engine available for " + httpTemplate.getTemplateType()); } if (templateEngine != null) { HttpRequest templatedRequest = templateEngine.executeTemplate(httpTemplate.getTemplate(), originalRequest, HttpRequestDTO.class); if (templatedRequest != null) { return sendRequest(templatedRequest, null, null); } } return notFoundFuture(originalRequest); } HttpForwardTemplateActionHandler(MockServerLogger mockServerLogger, NettyHttpClient httpClient); HttpForwardActionResult handle(HttpTemplate httpTemplate, HttpRequest originalRequest); }
@Test public void shouldHandleHttpRequestsWithJavaScriptTemplateFirstExample() throws Exception { HttpTemplate template = template(HttpTemplate.TemplateType.JAVASCRIPT, "return { 'path': \"somePath\", 'body': JSON.stringify({name: 'value'}) };"); HttpRequest httpRequest = request("somePath").withBody("{\"name\":\"value\"}"); CompletableFuture<HttpResponse> httpResponse = new CompletableFuture<>(); when(mockHttpClient.sendRequest(httpRequest, null)).thenReturn(httpResponse); CompletableFuture<HttpResponse> actualHttpResponse = httpForwardTemplateActionHandler .handle(template, request() .withPath("/somePath") .withMethod("POST") .withBody("some_body") ) .getHttpResponse(); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { verify(mockHttpClient).sendRequest(httpRequest, null); assertThat(actualHttpResponse, is(sameInstance(httpResponse))); } else { assertThat(actualHttpResponse.get(), is(notFoundResponse())); } } @Test public void shouldHandleHttpRequestsWithVelocityTemplateFirstExample() { HttpTemplate template = template(HttpTemplate.TemplateType.VELOCITY, "{" + NEW_LINE + " 'path': \"$!request.path\"," + NEW_LINE + " 'method': \"$!request.method\"," + NEW_LINE + " 'body': \"$!request.body\"" + NEW_LINE + "}"); HttpRequest httpRequest = request("/somePath").withMethod("POST").withBody("some_body"); CompletableFuture<HttpResponse> httpResponse = new CompletableFuture<>(); when(mockHttpClient.sendRequest(httpRequest, null)).thenReturn(httpResponse); CompletableFuture<HttpResponse> actualHttpResponse = httpForwardTemplateActionHandler .handle(template, httpRequest) .getHttpResponse(); verify(mockHttpClient).sendRequest(httpRequest, null); assertThat(actualHttpResponse, is(sameInstance(httpResponse))); }
HttpForwardActionHandler extends HttpForwardAction { public HttpForwardActionResult handle(HttpForward httpForward, HttpRequest httpRequest) { if (httpForward.getScheme().equals(HttpForward.Scheme.HTTPS)) { httpRequest.withSecure(true); } else { httpRequest.withSecure(false); } return sendRequest(httpRequest, new InetSocketAddress(httpForward.getHost(), httpForward.getPort()), null); } HttpForwardActionHandler(MockServerLogger logFormatter, NettyHttpClient httpClient); HttpForwardActionResult handle(HttpForward httpForward, HttpRequest httpRequest); }
@Test public void shouldHandleHttpRequests() { CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>(); HttpRequest httpRequest = request(); HttpForward httpForward = forward() .withHost("some_host") .withPort(1090) .withScheme(HttpForward.Scheme.HTTP); when(mockHttpClient.sendRequest(httpRequest, new InetSocketAddress(httpForward.getHost(), httpForward.getPort()))).thenReturn(responseFuture); CompletableFuture<HttpResponse> actualHttpResponse = httpForwardActionHandler .handle(httpForward, httpRequest) .getHttpResponse(); assertThat(actualHttpResponse, is(sameInstance(responseFuture))); verify(mockHttpClient).sendRequest(httpRequest.withSecure(false), new InetSocketAddress(httpForward.getHost(), httpForward.getPort())); } @Test public void shouldHandleSecureHttpRequests() { CompletableFuture<HttpResponse> httpResponse = new CompletableFuture<>(); HttpRequest httpRequest = request(); HttpForward httpForward = forward() .withHost("some_host") .withPort(1090) .withScheme(HttpForward.Scheme.HTTPS); when(mockHttpClient.sendRequest(httpRequest, new InetSocketAddress(httpForward.getHost(), httpForward.getPort()))).thenReturn(httpResponse); CompletableFuture<HttpResponse> actualHttpResponse = httpForwardActionHandler .handle(httpForward, httpRequest) .getHttpResponse(); assertThat(actualHttpResponse, is(sameInstance(httpResponse))); verify(mockHttpClient).sendRequest(httpRequest.withSecure(true), new InetSocketAddress(httpForward.getHost(), httpForward.getPort())); }
HttpResponseActionHandler { public HttpResponse handle(HttpResponse httpResponse) { return httpResponse.clone(); } HttpResponse handle(HttpResponse httpResponse); }
@Test public void shouldHandleHttpRequests() { HttpResponse httpResponse = mock(HttpResponse.class); HttpResponseActionHandler httpResponseActionHandler = new HttpResponseActionHandler(); httpResponseActionHandler.handle(httpResponse); verify(httpResponse).clone(); }
HttpForwardObjectCallbackActionHandler extends HttpForwardAction { public void handle(final HttpActionHandler actionHandler, final HttpObjectCallback httpObjectCallback, final HttpRequest request, final ResponseWriter responseWriter, final boolean synchronous, Runnable expectationPostProcessor) { final String clientId = httpObjectCallback.getClientId(); if (LocalCallbackRegistry.forwardClientExists(clientId)) { handleLocally(actionHandler, httpObjectCallback, request, responseWriter, synchronous, clientId); } else { handleViaWebSocket(actionHandler, httpObjectCallback, request, responseWriter, synchronous, expectationPostProcessor, clientId); } } HttpForwardObjectCallbackActionHandler(HttpState httpStateHandler, NettyHttpClient httpClient); void handle(final HttpActionHandler actionHandler, final HttpObjectCallback httpObjectCallback, final HttpRequest request, final ResponseWriter responseWriter, final boolean synchronous, Runnable expectationPostProcessor); }
@Test public void shouldHandleHttpRequests() { WebSocketClientRegistry mockWebSocketClientRegistry = mock(WebSocketClientRegistry.class); HttpState mockHttpStateHandler = mock(HttpState.class); HttpObjectCallback httpObjectCallback = new HttpObjectCallback().withClientId("some_clientId"); HttpRequest request = request().withBody("some_body"); ResponseWriter mockResponseWriter = mock(ResponseWriter.class); when(mockHttpStateHandler.getWebSocketClientRegistry()).thenReturn(mockWebSocketClientRegistry); when(mockHttpStateHandler.getMockServerLogger()).thenReturn(new MockServerLogger()); new HttpForwardObjectCallbackActionHandler(mockHttpStateHandler, null).handle(mock(HttpActionHandler.class), httpObjectCallback, request, mockResponseWriter, true, null); verify(mockWebSocketClientRegistry).registerForwardCallbackHandler(any(String.class), any(WebSocketRequestCallback.class)); verify(mockWebSocketClientRegistry).sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull()); } @Test public void shouldReturnNotFound() throws ExecutionException, InterruptedException { HttpActionHandler mockActionHandler = mock(HttpActionHandler.class); HttpState mockHttpStateHandler = mock(HttpState.class); WebSocketClientRegistry mockWebSocketClientRegistry = mock(WebSocketClientRegistry.class); HttpObjectCallback httpObjectCallback = new HttpObjectCallback().withClientId("some_clientId"); HttpRequest request = request().withBody("some_body"); ResponseWriter mockResponseWriter = mock(ResponseWriter.class); when(mockHttpStateHandler.getWebSocketClientRegistry()).thenReturn(mockWebSocketClientRegistry); when(mockHttpStateHandler.getMockServerLogger()).thenReturn(new MockServerLogger()); when(mockWebSocketClientRegistry.sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull())).thenReturn(false); new HttpForwardObjectCallbackActionHandler(mockHttpStateHandler, null).handle(mockActionHandler, httpObjectCallback, request, mockResponseWriter, true, null); verify(mockWebSocketClientRegistry).registerForwardCallbackHandler(any(String.class), any(WebSocketRequestCallback.class)); verify(mockWebSocketClientRegistry).sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull()); ArgumentCaptor<HttpForwardActionResult> httpForwardActionResultArgumentCaptor = ArgumentCaptor.forClass(HttpForwardActionResult.class); verify(mockActionHandler).writeForwardActionResponse(httpForwardActionResultArgumentCaptor.capture(), same(mockResponseWriter), same(request), same(httpObjectCallback), eq(true)); assertThat(httpForwardActionResultArgumentCaptor.getValue().getHttpResponse().get(), is(notFoundResponse())); }
HttpResponseTemplateActionHandler { public HttpResponse handle(HttpTemplate httpTemplate, HttpRequest httpRequest) { HttpResponse httpResponse = notFoundResponse(); TemplateEngine templateEngine; switch (httpTemplate.getTemplateType()) { case VELOCITY: templateEngine = velocityTemplateEngine; break; case JAVASCRIPT: templateEngine = javaScriptTemplateEngine; break; default: throw new RuntimeException("Unknown no template engine available for " + httpTemplate.getTemplateType()); } if (templateEngine != null) { HttpResponse templatedResponse = templateEngine.executeTemplate(httpTemplate.getTemplate(), httpRequest, HttpResponseDTO.class); if (templatedResponse != null) { return templatedResponse; } } return httpResponse; } HttpResponseTemplateActionHandler(MockServerLogger logFormatter); HttpResponse handle(HttpTemplate httpTemplate, HttpRequest httpRequest); }
@Test public void shouldHandleHttpRequestsWithJavaScriptTemplateFirstExample() { HttpTemplate template = template(HttpTemplate.TemplateType.JAVASCRIPT, "if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': JSON.stringify({name: 'value'})" + NEW_LINE + " };" + NEW_LINE + "} else {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': request.body" + NEW_LINE + " };" + NEW_LINE + "}"); HttpResponse actualHttpResponse = httpResponseTemplateActionHandler.handle(template, request() .withPath("/somePath") .withMethod("POST") .withBody("some_body") ); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { assertThat(actualHttpResponse, is( response() .withStatusCode(200) .withBody("{\"name\":\"value\"}") )); } else { assertThat(actualHttpResponse, is( notFoundResponse() )); } } @Test public void shouldHandleHttpRequestsWithJavaScriptTemplateSecondExample() { HttpTemplate template = template(HttpTemplate.TemplateType.JAVASCRIPT, "if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': JSON.stringify({name: 'value'})" + NEW_LINE + " };" + NEW_LINE + "} else {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': request.body" + NEW_LINE + " };" + NEW_LINE + "}"); HttpResponse actualHttpResponse = httpResponseTemplateActionHandler.handle(template, request() .withPath("/someOtherPath") .withBody("some_body") ); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { assertThat(actualHttpResponse, is( response() .withStatusCode(406) .withBody("some_body") )); } else { assertThat(actualHttpResponse, is( notFoundResponse() )); } } @Test public void shouldHandleHttpRequestsWithVelocityTemplateFirstExample() { HttpTemplate template = template(HttpTemplate.TemplateType.VELOCITY, "#if ( $request.method == 'POST' && $request.path == '/somePath' )" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + " }" + NEW_LINE + "#else" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': \"$!request.body\"" + NEW_LINE + " }" + NEW_LINE + "#end"); HttpResponse actualHttpResponse = httpResponseTemplateActionHandler.handle(template, request() .withPath("/somePath") .withMethod("POST") .withBody("some_body") ); assertThat(actualHttpResponse, is( response() .withStatusCode(200) .withBody("{'name': 'value'}") )); } @Test public void shouldHandleHttpRequestsWithVelocityTemplateSecondExample() { HttpTemplate template = template(HttpTemplate.TemplateType.VELOCITY, "#if ( $request.method == 'POST' && $request.path == '/somePath' )" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + " }" + NEW_LINE + "#else" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': \"$!request.body\"" + NEW_LINE + " }" + NEW_LINE + "#end"); HttpResponse actualHttpResponse = httpResponseTemplateActionHandler.handle(template, request() .withPath("/someOtherPath") .withBody("some_body") ); assertThat(actualHttpResponse, is( response() .withStatusCode(406) .withBody("some_body") )); }
HttpForwardClassCallbackActionHandler extends HttpForwardAction { public HttpForwardActionResult handle(HttpClassCallback httpClassCallback, HttpRequest request) { return invokeCallbackMethod(httpClassCallback, request); } HttpForwardClassCallbackActionHandler(MockServerLogger mockServerLogger, NettyHttpClient httpClient); HttpForwardActionResult handle(HttpClassCallback httpClassCallback, HttpRequest request); }
@Test public void shouldHandleInvalidClass() throws Exception { CompletableFuture<HttpResponse> httpResponse = new CompletableFuture<>(); httpResponse.complete(response("some_response_body")); when(mockHttpClient.sendRequest(any(HttpRequest.class), isNull())).thenReturn(httpResponse); HttpClassCallback httpClassCallback = callback("org.mockserver.mock.action.FooBar"); CompletableFuture<HttpResponse> actualHttpResponse = httpForwardClassCallbackActionHandler .handle(httpClassCallback, request().withBody("some_body")) .getHttpResponse(); assertThat(actualHttpResponse.get(), is(httpResponse.get())); verify(mockHttpClient).sendRequest(request().withBody("some_body"), null); } @Test public void shouldHandleValidLocalClass() throws Exception { CompletableFuture<HttpResponse> httpResponse = new CompletableFuture<>(); httpResponse.complete(response("some_response_body")); when(mockHttpClient.sendRequest(any(HttpRequest.class), isNull())).thenReturn(httpResponse); HttpClassCallback httpClassCallback = HttpClassCallback.callback(HttpForwardClassCallbackActionHandlerTest.TestCallback.class); CompletableFuture<HttpResponse> actualHttpResponse = httpForwardClassCallbackActionHandler .handle(httpClassCallback, request().withBody("some_body")) .getHttpResponse(); assertThat(actualHttpResponse.get(), is(httpResponse.get())); verify(mockHttpClient).sendRequest(request("some_path"), null); }
HttpResponseObjectCallbackActionHandler { public void handle(final HttpActionHandler actionHandler, final HttpObjectCallback httpObjectCallback, final HttpRequest request, final ResponseWriter responseWriter, final boolean synchronous, Runnable expectationPostProcessor) { final String clientId = httpObjectCallback.getClientId(); if (LocalCallbackRegistry.responseClientExists(clientId)) { handleLocally(actionHandler, httpObjectCallback, request, responseWriter, synchronous, clientId); } else { handleViaWebSocket(actionHandler, httpObjectCallback, request, responseWriter, synchronous, expectationPostProcessor, clientId); } } HttpResponseObjectCallbackActionHandler(HttpState httpStateHandler); void handle(final HttpActionHandler actionHandler, final HttpObjectCallback httpObjectCallback, final HttpRequest request, final ResponseWriter responseWriter, final boolean synchronous, Runnable expectationPostProcessor); }
@Test public void shouldHandleHttpRequests() { WebSocketClientRegistry mockWebSocketClientRegistry = mock(WebSocketClientRegistry.class); HttpState mockHttpStateHandler = mock(HttpState.class); HttpObjectCallback httpObjectCallback = new HttpObjectCallback().withClientId("some_clientId"); HttpRequest request = request().withBody("some_body"); ResponseWriter mockResponseWriter = mock(ResponseWriter.class); when(mockHttpStateHandler.getWebSocketClientRegistry()).thenReturn(mockWebSocketClientRegistry); when(mockHttpStateHandler.getMockServerLogger()).thenReturn(new MockServerLogger()); new HttpResponseObjectCallbackActionHandler(mockHttpStateHandler).handle(mock(HttpActionHandler.class), httpObjectCallback, request, mockResponseWriter, true, null); verify(mockWebSocketClientRegistry).registerResponseCallbackHandler(any(String.class), any(WebSocketResponseCallback.class)); verify(mockWebSocketClientRegistry).sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull()); } @Test public void shouldReturnNotFound() { HttpActionHandler mockActionHandler = mock(HttpActionHandler.class); HttpState mockHttpStateHandler = mock(HttpState.class); WebSocketClientRegistry mockWebSocketClientRegistry = mock(WebSocketClientRegistry.class); HttpObjectCallback httpObjectCallback = new HttpObjectCallback().withClientId("some_clientId"); HttpRequest request = request().withBody("some_body"); ResponseWriter mockResponseWriter = mock(ResponseWriter.class); when(mockHttpStateHandler.getWebSocketClientRegistry()).thenReturn(mockWebSocketClientRegistry); when(mockHttpStateHandler.getMockServerLogger()).thenReturn(new MockServerLogger()); when(mockWebSocketClientRegistry.sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull())).thenReturn(false); new HttpResponseObjectCallbackActionHandler(mockHttpStateHandler).handle(mockActionHandler, httpObjectCallback, request, mockResponseWriter, true, null); verify(mockWebSocketClientRegistry).registerResponseCallbackHandler(any(String.class), any(WebSocketResponseCallback.class)); verify(mockWebSocketClientRegistry).sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull()); verify(mockActionHandler).writeResponseActionResponse(notFoundResponse().removeHeader(WEB_SOCKET_CORRELATION_ID_HEADER_NAME), mockResponseWriter, request, httpObjectCallback, true); }
HttpResponseClassCallbackActionHandler { public HttpResponse handle(HttpClassCallback httpClassCallback, HttpRequest request) { return invokeCallbackMethod(httpClassCallback, request); } HttpResponseClassCallbackActionHandler(MockServerLogger mockServerLogger); HttpResponse handle(HttpClassCallback httpClassCallback, HttpRequest request); }
@Test public void shouldHandleInvalidClass() { HttpClassCallback httpClassCallback = callback("org.mockserver.mock.action.FooBar"); HttpResponse actualHttpResponse = new HttpResponseClassCallbackActionHandler(new MockServerLogger()).handle(httpClassCallback, request().withBody("some_body")); assertThat(actualHttpResponse, is(notFoundResponse())); } @Test public void shouldHandleValidLocalClass() { HttpClassCallback httpClassCallback = callback("org.mockserver.mock.action.http.HttpResponseClassCallbackActionHandlerTest$TestCallback"); HttpResponse actualHttpResponse = new HttpResponseClassCallbackActionHandler(new MockServerLogger()).handle(httpClassCallback, request().withBody("some_body")); assertThat(actualHttpResponse, is(response("some_body"))); }
Expectation extends ObjectWithJsonToString { @JsonIgnore public boolean isActive() { return hasRemainingMatches() && isStillAlive(); } Expectation(RequestDefinition requestDefinition); Expectation(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive, int priority); static Expectation when(String specUrlOrPayload, String operationId); static Expectation when(String specUrlOrPayload, String operationId, int priority); static Expectation when(String specUrlOrPayload, String operationId, Times times, TimeToLive timeToLive); static Expectation when(String specUrlOrPayload, String operationId, Times times, TimeToLive timeToLive, int priority); static Expectation when(HttpRequest httpRequest); static Expectation when(HttpRequest httpRequest, int priority); static Expectation when(HttpRequest httpRequest, Times times, TimeToLive timeToLive); static Expectation when(HttpRequest httpRequest, Times times, TimeToLive timeToLive, int priority); Expectation withId(String key); String getId(); Expectation withPriority(int priority); int getPriority(); Expectation withCreated(long created); long getCreated(); @JsonIgnore SortableExpectationId getSortableId(); RequestDefinition getHttpRequest(); HttpResponse getHttpResponse(); HttpTemplate getHttpResponseTemplate(); HttpClassCallback getHttpResponseClassCallback(); HttpObjectCallback getHttpResponseObjectCallback(); HttpForward getHttpForward(); HttpTemplate getHttpForwardTemplate(); HttpClassCallback getHttpForwardClassCallback(); HttpObjectCallback getHttpForwardObjectCallback(); HttpOverrideForwardedRequest getHttpOverrideForwardedRequest(); HttpError getHttpError(); @JsonIgnore Action getAction(); Times getTimes(); TimeToLive getTimeToLive(); Expectation thenRespond(HttpResponse httpResponse); Expectation thenRespond(HttpTemplate httpTemplate); Expectation thenRespond(HttpClassCallback httpClassCallback); Expectation thenRespond(HttpObjectCallback httpObjectCallback); Expectation thenForward(HttpForward httpForward); Expectation thenForward(HttpTemplate httpTemplate); Expectation thenForward(HttpClassCallback httpClassCallback); Expectation thenForward(HttpObjectCallback httpObjectCallback); Expectation thenForward(HttpOverrideForwardedRequest httpOverrideForwardedRequest); Expectation thenError(HttpError httpError); @JsonIgnore boolean isActive(); boolean decrementRemainingMatches(); @SuppressWarnings("PointlessNullCheck") boolean contains(HttpRequest httpRequest); @SuppressWarnings("MethodDoesntCallSuperMethod") Expectation clone(); @Override @JsonIgnore String[] fieldsExcludedFromEqualsAndHashCode(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void shouldCalculateRemainingMatches() { assertThat(new Expectation(null, Times.once(), TimeToLive.unlimited(), 0).isActive(), is(true)); assertThat(new Expectation(null, Times.unlimited(), TimeToLive.unlimited(), 0).isActive(), is(true)); assertThat(new Expectation(null, Times.exactly(1), TimeToLive.unlimited(), 0).isActive(), is(true)); assertThat(new Expectation(null, null, TimeToLive.unlimited(), 0).isActive(), is(true)); assertThat(new Expectation(null, Times.exactly(0), TimeToLive.unlimited(), 0).isActive(), is(false)); } @Test public void shouldCalculateRemainingLife() { assertThat(new Expectation(null, Times.unlimited(), TimeToLive.unlimited(), 0).isActive(), is(true)); assertThat(new Expectation(null, Times.unlimited(), TimeToLive.exactly(TimeUnit.MINUTES, 5L), 0).isActive(), is(true)); assertThat(new Expectation(null, Times.unlimited(), null, 0).isActive(), is(true)); assertThat(new Expectation(null, Times.unlimited(), TimeToLive.exactly(TimeUnit.MICROSECONDS, 0L), 0).isActive(), is(false)); }
Expectation extends ObjectWithJsonToString { public Expectation thenRespond(HttpResponse httpResponse) { if (httpResponse != null) { validationErrors("a response", httpResponse.getType()); this.httpResponse = httpResponse; this.hashCode = 0; } return this; } Expectation(RequestDefinition requestDefinition); Expectation(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive, int priority); static Expectation when(String specUrlOrPayload, String operationId); static Expectation when(String specUrlOrPayload, String operationId, int priority); static Expectation when(String specUrlOrPayload, String operationId, Times times, TimeToLive timeToLive); static Expectation when(String specUrlOrPayload, String operationId, Times times, TimeToLive timeToLive, int priority); static Expectation when(HttpRequest httpRequest); static Expectation when(HttpRequest httpRequest, int priority); static Expectation when(HttpRequest httpRequest, Times times, TimeToLive timeToLive); static Expectation when(HttpRequest httpRequest, Times times, TimeToLive timeToLive, int priority); Expectation withId(String key); String getId(); Expectation withPriority(int priority); int getPriority(); Expectation withCreated(long created); long getCreated(); @JsonIgnore SortableExpectationId getSortableId(); RequestDefinition getHttpRequest(); HttpResponse getHttpResponse(); HttpTemplate getHttpResponseTemplate(); HttpClassCallback getHttpResponseClassCallback(); HttpObjectCallback getHttpResponseObjectCallback(); HttpForward getHttpForward(); HttpTemplate getHttpForwardTemplate(); HttpClassCallback getHttpForwardClassCallback(); HttpObjectCallback getHttpForwardObjectCallback(); HttpOverrideForwardedRequest getHttpOverrideForwardedRequest(); HttpError getHttpError(); @JsonIgnore Action getAction(); Times getTimes(); TimeToLive getTimeToLive(); Expectation thenRespond(HttpResponse httpResponse); Expectation thenRespond(HttpTemplate httpTemplate); Expectation thenRespond(HttpClassCallback httpClassCallback); Expectation thenRespond(HttpObjectCallback httpObjectCallback); Expectation thenForward(HttpForward httpForward); Expectation thenForward(HttpTemplate httpTemplate); Expectation thenForward(HttpClassCallback httpClassCallback); Expectation thenForward(HttpObjectCallback httpObjectCallback); Expectation thenForward(HttpOverrideForwardedRequest httpOverrideForwardedRequest); Expectation thenError(HttpError httpError); @JsonIgnore boolean isActive(); boolean decrementRemainingMatches(); @SuppressWarnings("PointlessNullCheck") boolean contains(HttpRequest httpRequest); @SuppressWarnings("MethodDoesntCallSuperMethod") Expectation clone(); @Override @JsonIgnore String[] fieldsExcludedFromEqualsAndHashCode(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test(expected = IllegalArgumentException.class) public void shouldPreventResponseAfterClassCallback() { HttpRequest httpRequest = new HttpRequest(); HttpClassCallback httpClassCallback = new HttpClassCallback(); HttpResponse httpResponse = new HttpResponse(); new Expectation(httpRequest, Times.once(), TimeToLive.unlimited(), 0).thenRespond(httpClassCallback).thenRespond(httpResponse); } @Test(expected = IllegalArgumentException.class) public void shouldPreventResponseAfterObjectCallback() { HttpRequest httpRequest = new HttpRequest(); HttpObjectCallback httpObjectCallback = new HttpObjectCallback(); HttpResponse httpResponse = new HttpResponse(); new Expectation(httpRequest, Times.once(), TimeToLive.unlimited(), 0).thenRespond(httpObjectCallback).thenRespond(httpResponse); } @Test(expected = IllegalArgumentException.class) public void shouldPreventClassCallbackAfterResponse() { HttpRequest httpRequest = new HttpRequest(); HttpResponse httpResponse = new HttpResponse(); HttpClassCallback httpClassCallback = new HttpClassCallback(); new Expectation(httpRequest, Times.once(), TimeToLive.unlimited(), 0).thenRespond(httpResponse).thenRespond(httpClassCallback); } @Test(expected = IllegalArgumentException.class) public void shouldPreventObjectCallbackAfterResponse() { HttpRequest httpRequest = new HttpRequest(); HttpResponse httpResponse = new HttpResponse(); HttpObjectCallback httpObjectCallback = new HttpObjectCallback(); new Expectation(httpRequest, Times.once(), TimeToLive.unlimited(), 0).thenRespond(httpResponse).thenRespond(httpObjectCallback); }
XmlStringMatcher extends BodyMatcher<String> { public boolean matches(String matched) { return matches(null, matched); } XmlStringMatcher(MockServerLogger mockServerLogger, final String matcher); XmlStringMatcher(MockServerLogger mockServerLogger, final NottableString matcher); boolean matches(String matched); boolean matches(final MatchDifference context, String matched); boolean isBlank(); }
@Test public void shouldMatchMatchingXML() { String matched = "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>"; assertTrue(new XmlStringMatcher(new MockServerLogger(), "<element><key>some_key</key><value>some_value</value></element>").matches(matched)); assertTrue(new XmlStringMatcher(new MockServerLogger(), "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>").matches(matched)); } @Test public void shouldMatchMatchingXMLWithIsNumberPlaceholder() { String matched = "" + "<message>" + NEW_LINE + " <id>67890</id>" + NEW_LINE + " <content>Hello</content>" + NEW_LINE + "</message>"; assertTrue(new XmlStringMatcher(new MockServerLogger(), "" + "<message>" + NEW_LINE + " <id>${xmlunit.isNumber}</id>" + NEW_LINE + " <content>Hello</content>" + NEW_LINE + "</message>").matches(matched)); } @Test public void shouldNotMatchMatchingXMLWithIsNumberPlaceholder() { String matched = "" + "<message>" + NEW_LINE + " <id>foo</id>" + NEW_LINE + " <content>Hello</content>" + NEW_LINE + "</message>"; assertFalse(new XmlStringMatcher(new MockServerLogger(), "" + "<message>" + NEW_LINE + " <id>${xmlunit.isNumber}</id>" + NEW_LINE + " <content>Hello</content>" + NEW_LINE + "</message>").matches(matched)); } @Test public void shouldMatchMatchingXMLWithIgnorePlaceholder() { String matched = "" + "<message>" + NEW_LINE + " <id>67890</id>" + NEW_LINE + " <content>Hello</content>" + NEW_LINE + "</message>"; assertTrue(new XmlStringMatcher(new MockServerLogger(), "" + "<message>" + NEW_LINE + " <id>${xmlunit.ignore}</id>" + NEW_LINE + " <content>Hello</content>" + NEW_LINE + "</message>").matches(matched)); } @Test public void shouldMatchMatchingXMLWithDifferentNamespaceOrders() { String matched = "" + "<?xml version=\"1.0\"?>" + NEW_LINE + NEW_LINE + "<soap:Envelope" + NEW_LINE + "xmlns:soap=\"http: "soap:encodingStyle=\"http: NEW_LINE + "<soap:Body xmlns:m=\"http: " <m:GetStockPriceResponse>" + NEW_LINE + " <m:Price>34.5</m:Price>" + NEW_LINE + " </m:GetStockPriceResponse>" + NEW_LINE + "</soap:Body>" + NEW_LINE + NEW_LINE + "</soap:Envelope>"; assertTrue(new XmlStringMatcher(new MockServerLogger(), "" + "<?xml version=\"1.0\"?>" + NEW_LINE + "<soap:Envelope" + NEW_LINE + "soap:encodingStyle=\"http: "xmlns:soap=\"http: "xmlns:m=\"http: "<soap:Body>" + NEW_LINE + " <m:GetStockPriceResponse>" + NEW_LINE + " <m:Price>34.5</m:Price>" + NEW_LINE + " </m:GetStockPriceResponse>" + NEW_LINE + "</soap:Body>" + NEW_LINE + "</soap:Envelope>").matches(matched)); } @Test public void shouldNotMatchMatchingXMLWithNot() { String matched = "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>"; assertFalse(notMatcher(new XmlStringMatcher(new MockServerLogger(), "<element><key>some_key</key><value>some_value</value></element>")).matches(matched)); assertFalse(notMatcher(new XmlStringMatcher(new MockServerLogger(), "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>")).matches(matched)); } @Test public void shouldMatchMatchingXMLWithDifferentAttributeOrder() { String matched = "" + "<element attributeOne=\"one\" attributeTwo=\"two\">" + " <key attributeOne=\"one\" attributeTwo=\"two\">some_key</key>" + " <value>some_value</value>" + "</element>"; assertTrue(new XmlStringMatcher(new MockServerLogger(), "<element attributeTwo=\"two\" attributeOne=\"one\"><key attributeTwo=\"two\" attributeOne=\"one\">some_key</key><value>some_value</value></element>").matches(matched)); assertTrue(new XmlStringMatcher(new MockServerLogger(), "<element attributeTwo=\"two\" attributeOne=\"one\">" + " <key attributeTwo=\"two\" attributeOne=\"one\">some_key</key>" + " <value>some_value</value>" + "</element>").matches(matched)); } @Test public void shouldNotMatchInvalidXml() { assertFalse(new XmlStringMatcher(new MockServerLogger(), "invalid xml").matches("<element></element>")); assertFalse(new XmlStringMatcher(new MockServerLogger(), "<element></element>").matches("invalid_xml")); } @Test public void shouldNotMatchNullExpectation() { assertFalse(new XmlStringMatcher(new MockServerLogger(), string(null)).matches("some_value")); assertFalse(new XmlStringMatcher(new MockServerLogger(), (String) null).matches("some_value")); } @Test public void shouldNotMatchEmptyExpectation() { assertFalse(new XmlStringMatcher(new MockServerLogger(), "").matches("some_value")); } @Test public void shouldNotMatchNotMatchingXML() { String matched = "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>"; assertFalse(new XmlStringMatcher(new MockServerLogger(), "" + "<another_element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</another_element>").matches(matched)); assertFalse(new XmlStringMatcher(new MockServerLogger(), "" + "<element>" + " <another_key>some_key</another_key>" + " <value>some_value</value>" + "</element>").matches(matched)); assertFalse(new XmlStringMatcher(new MockServerLogger(), "" + "<element>" + " <key>some_key</key>" + " <another_value>some_value</another_value>" + "</element>").matches(matched)); assertFalse(new XmlStringMatcher(new MockServerLogger(), "" + "<element>" + " <key>some_other_key</key>" + " <value>some_value</value>" + "</element>").matches(matched)); } @Test public void shouldMatchNotMatchingXMLWithNot() { String matched = "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>"; assertTrue(notMatcher(new XmlStringMatcher(new MockServerLogger(), "" + "<another_element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</another_element>")).matches(matched)); assertTrue(notMatcher(new XmlStringMatcher(new MockServerLogger(), "" + "<element>" + " <another_key>some_key</another_key>" + " <value>some_value</value>" + "</element>")).matches(matched)); } @Test public void shouldNotMatchXMLWithDifferentAttributes() { String matched = "" + "<element someAttribute=\"some_value\">" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>"; assertFalse(new XmlStringMatcher(new MockServerLogger(), "" + "<element someOtherAttribute=\"some_value\">" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>").matches(matched)); assertFalse(new XmlStringMatcher(new MockServerLogger(), "" + "<element someAttribute=\"some_other_value\">" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>").matches(matched)); } @Test public void shouldNotMatchNullTest() { assertFalse(new XmlStringMatcher(new MockServerLogger(), "some_value").matches(null, null)); assertFalse(new XmlStringMatcher(new MockServerLogger(), "some_value").matches(null)); } @Test public void shouldMatchNullTest() { assertTrue(notMatcher(new XmlStringMatcher(new MockServerLogger(), "some_value")).matches(null, null)); assertTrue(notMatcher(new XmlStringMatcher(new MockServerLogger(), "some_value")).matches(null)); } @Test public void shouldNotMatchEmptyTest() { assertFalse(new XmlStringMatcher(new MockServerLogger(), "some_value").matches("")); }
BooleanMatcher extends ObjectWithReflectiveEqualsHashCodeToString implements Matcher<Boolean> { @Override public boolean matches(final MatchDifference context, Boolean matched) { boolean result = false; if (matcher == null) { result = true; } else if (matched != null) { result = matched == matcher; } if (!result && context != null) { context.addDifference(mockServerLogger, "boolean match failed expected:{}found:{}", this.matcher, matched); } return result; } BooleanMatcher(MockServerLogger mockServerLogger, Boolean matcher); @Override boolean matches(final MatchDifference context, Boolean matched); boolean isBlank(); @Override @JsonIgnore String[] fieldsExcludedFromEqualsAndHashCode(); }
@Test public void shouldMatchMatchingExpectations() { assertTrue(new BooleanMatcher(new MockServerLogger(),true).matches(null, true)); assertTrue(new BooleanMatcher(new MockServerLogger(),false).matches(null, false)); } @Test public void shouldMatchNullExpectations() { assertTrue(new BooleanMatcher(new MockServerLogger(),null).matches(null, null)); assertTrue(new BooleanMatcher(new MockServerLogger(),null).matches(null, false)); } @Test public void shouldNotMatchNonMatchingExpectations() { assertFalse(new BooleanMatcher(new MockServerLogger(),true).matches(null, false)); assertFalse(new BooleanMatcher(new MockServerLogger(),false).matches(null, true)); } @Test public void shouldNotMatchNullAgainstNonMatchingExpectations() { assertFalse(new BooleanMatcher(new MockServerLogger(),true).matches(null, null)); assertFalse(new BooleanMatcher(new MockServerLogger(),false).matches(null, null)); }
SubStringMatcher extends BodyMatcher<NottableString> { public static boolean matches(String matcher, String matched, boolean ignoreCase) { if (isEmpty(matcher)) { return true; } else if (matched != null) { if (contains(matched, matcher)) { return true; } if (ignoreCase) { return containsIgnoreCase(matched, matcher); } } return false; } SubStringMatcher(MockServerLogger mockServerLogger, NottableString matcher); static boolean matches(String matcher, String matched, boolean ignoreCase); boolean matches(final MatchDifference context, String matched); boolean matches(final MatchDifference context, NottableString matched); boolean isBlank(); @Override String[] fieldsExcludedFromEqualsAndHashCode(); }
@Test public void shouldMatchMatchingString() { assertTrue(new SubStringMatcher(new MockServerLogger(), string("me_val")).matches(null, "some_value")); assertTrue(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val")).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), string("me_val"))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val"))).matches(null, "some_value")); assertFalse(new SubStringMatcher(new MockServerLogger(), string("me_val")).matches(null, NottableString.not("some_value"))); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), string("me_val"))).matches(null, "some_value")); assertFalse(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val")).matches(null, "some_value")); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val"))).matches(null, NottableString.not("some_value"))); } @Test public void shouldMatchNotMatchingString() { assertFalse(new SubStringMatcher(new MockServerLogger(), string("me_val")).matches(null, "some_other_value")); assertFalse(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val")).matches(null, NottableString.not("some_other_value"))); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), string("me_val"))).matches(null, NottableString.not("some_other_value"))); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val"))).matches(null, "some_other_value")); assertTrue(new SubStringMatcher(new MockServerLogger(), string("me_val")).matches(null, NottableString.not("some_other_value"))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), string("me_val"))).matches(null, "some_other_value")); assertTrue(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val")).matches(null, "some_other_value")); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val"))).matches(null, NottableString.not("some_other_value"))); } @Test public void shouldMatchNullMatcher() { assertTrue(new SubStringMatcher(new MockServerLogger(), string(null)).matches(null, "some_value")); assertTrue(new SubStringMatcher(new MockServerLogger(), string(null)).matches(null, "some_value")); assertTrue(new SubStringMatcher(new MockServerLogger(), NottableString.not(null)).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), string(null))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), string(null))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not(null))).matches(null, "some_value")); assertFalse(new SubStringMatcher(new MockServerLogger(), string(null)).matches(null, NottableString.not("some_value"))); assertFalse(new SubStringMatcher(new MockServerLogger(), string(null)).matches(null, NottableString.not("some_value"))); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), string(null))).matches(null, "some_value")); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), string(null))).matches(null, "some_value")); assertFalse(new SubStringMatcher(new MockServerLogger(), NottableString.not(null)).matches(null, "some_value")); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not(null))).matches(null, NottableString.not("some_value"))); } @Test public void shouldMatchNullMatched() { assertFalse(new SubStringMatcher(new MockServerLogger(), string("me_val")).matches(null, (String) null)); assertFalse(new SubStringMatcher(new MockServerLogger(), string("me_val")).matches(null, string(null))); assertFalse(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val")).matches(null, NottableString.not(null))); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), string("me_val"))).matches(null, NottableString.not(null))); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val"))).matches(null, (String) null)); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val"))).matches(null, string(null))); assertTrue(new SubStringMatcher(new MockServerLogger(), string("me_val")).matches(null, NottableString.not(null))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), string("me_val"))).matches(null, (String) null)); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), string("me_val"))).matches(null, string(null))); assertTrue(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val")).matches(null, (String) null)); assertTrue(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val")).matches(null, string(null))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val"))).matches(null, NottableString.not(null))); } @Test public void shouldMatchEmptyMatcher() { assertTrue(new SubStringMatcher(new MockServerLogger(), string("")).matches(null, "some_value")); assertTrue(new SubStringMatcher(new MockServerLogger(), string("")).matches(null, "some_value")); assertTrue(new SubStringMatcher(new MockServerLogger(), NottableString.not("")).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), string(""))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), string(""))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not(""))).matches(null, "some_value")); assertFalse(new SubStringMatcher(new MockServerLogger(), string("")).matches(null, NottableString.not("some_value"))); assertFalse(new SubStringMatcher(new MockServerLogger(), string("")).matches(null, NottableString.not("some_value"))); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), string(""))).matches(null, "some_value")); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), string(""))).matches(null, "some_value")); assertFalse(new SubStringMatcher(new MockServerLogger(), NottableString.not("")).matches(null, "some_value")); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not(""))).matches(null, NottableString.not("some_value"))); } @Test public void shouldMatchEmptyMatched() { assertFalse(new SubStringMatcher(new MockServerLogger(), string("me_val")).matches(null, "")); assertFalse(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val")).matches(null, NottableString.not(""))); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), string("me_val"))).matches(null, NottableString.not(""))); assertFalse(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val"))).matches(null, "")); assertTrue(new SubStringMatcher(new MockServerLogger(), string("me_val")).matches(null, NottableString.not(""))); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), string("me_val"))).matches(null, "")); assertTrue(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val")).matches(null, "")); assertTrue(notMatcher(new SubStringMatcher(new MockServerLogger(), NottableString.not("me_val"))).matches(null, NottableString.not(""))); }
URLParser { public static boolean isFullUrl(String uri) { return uri != null && uri.matches(schemeRegex); } static boolean isFullUrl(String uri); static String returnPath(String path); }
@Test public void shouldDetectPath() { assertTrue(URLParser.isFullUrl("http: assertTrue(URLParser.isFullUrl("https: assertTrue(URLParser.isFullUrl(" assertFalse(URLParser.isFullUrl(null)); assertFalse(URLParser.isFullUrl("/some/path")); assertFalse(URLParser.isFullUrl("some/path")); }
XmlSchemaMatcher extends BodyMatcher<String> { public boolean matches(final MatchDifference context, String matched) { boolean result = false; try { String validation = xmlSchemaValidator.isValid(matched); result = validation.isEmpty(); if (!result && context != null) { context.addDifference(mockServerLogger, "xml schema match failed expected:{}found:{}failed because:{}", this.matcher, matched, validation); } } catch (Throwable throwable) { if (context != null) { context.addDifference(mockServerLogger, throwable, "xml schema match failed expected:{}found:{}failed because:{}", this.matcher, matched, throwable.getMessage()); } } return not != result; } XmlSchemaMatcher(MockServerLogger mockServerLogger, String matcher); boolean matches(final MatchDifference context, String matched); boolean isBlank(); }
@Test public void shouldMatchXml() { String xml = "some_xml"; when(mockXmlSchemaValidator.isValid(xml)).thenReturn(""); assertTrue(xmlSchemaMatcher.matches(null, xml)); } @Test public void shouldNotMatchXml() { Level originalLevel = logLevel(); try { logLevel("TRACE"); String xml = "some_xml"; when(mockXmlSchemaValidator.isValid(xml)).thenReturn("validator_error"); assertFalse(xmlSchemaMatcher.matches(new MatchDifference(request()), xml)); verify(logger).trace("xml schema match failed expected:" + NEW_LINE + NEW_LINE + " <?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + " <xs:schema xmlns:xs=\"http: " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http: " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:schema>" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " some_xml" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " validator_error" + NEW_LINE, (Throwable) null); } finally { logLevel(originalLevel.toString()); } } @Test public void shouldHandleExpectation() { Level originalLevel = logLevel(); try { logLevel("TRACE"); String xml = "some_xml"; RuntimeException test_exception = new RuntimeException("TEST_EXCEPTION"); when(mockXmlSchemaValidator.isValid(xml)).thenThrow(test_exception); assertFalse(xmlSchemaMatcher.matches(new MatchDifference(request()), xml)); verify(logger).trace("xml schema match failed expected:" + NEW_LINE + NEW_LINE + " <?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + " <xs:schema xmlns:xs=\"http: " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http: " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:schema>" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " some_xml" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " TEST_EXCEPTION" + NEW_LINE, test_exception); } finally { logLevel(originalLevel.toString()); } }
HttpRequestsPropertiesMatcher extends AbstractHttpRequestMatcher { @Override public boolean matches(MatchDifference matchDifference, RequestDefinition requestDefinition) { boolean result = false; if (httpRequestPropertiesMatchers != null && !httpRequestPropertiesMatchers.isEmpty()) { for (HttpRequestPropertiesMatcher httpRequestPropertiesMatcher : httpRequestPropertiesMatchers) { if (matchDifference == null) { if (MockServerLogger.isEnabled(Level.TRACE) && requestDefinition instanceof HttpRequest) { matchDifference = new MatchDifference(requestDefinition); } result = httpRequestPropertiesMatcher.matches(matchDifference, requestDefinition); } else { MatchDifference singleMatchDifference = new MatchDifference(matchDifference.getHttpRequest()); result = httpRequestPropertiesMatcher.matches(singleMatchDifference, requestDefinition); matchDifference.addDifferences(singleMatchDifference.getAllDifferences()); } if (result) { break; } } } else { result = true; } return result; } protected HttpRequestsPropertiesMatcher(MockServerLogger mockServerLogger); List<HttpRequestPropertiesMatcher> getHttpRequestPropertiesMatchers(); @Override List<HttpRequest> getHttpRequests(); @Override boolean apply(RequestDefinition requestDefinition); @Override boolean matches(MatchDifference matchDifference, RequestDefinition requestDefinition); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void shouldMatchByMethod() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withMethod("GET") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withMethod("POST") )); } @Test public void shouldMatchByMethodWithOperationId() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) .withOperationId("someOperation") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withMethod("GET") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withMethod("POST") )); } @Test public void shouldMatchByPath() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/someOtherPath") )); } @Test public void shouldMatchByPathWithOperationId() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) .withOperationId("someOperation") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/someOtherPath") )); } @Test public void shouldMatchByPathWithPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{someParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithMultiplePathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{someParam}/{someOtherParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " - in: path" + NEW_LINE + " name: someOtherParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE + " minLength: 2" + NEW_LINE + " maxLength: 3" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1/ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0/ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1/a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithMultipleMissingPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " - in: path" + NEW_LINE + " name: someOtherParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE + " minLength: 2" + NEW_LINE + " maxLength: 3" + NEW_LINE) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0/ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1/a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a") )); } @Test public void shouldMatchByPathWithPathParameterAndOperationId() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{someParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") .withOperationId("someOperation") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithOptionalPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{someParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithAllowEmptyPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{someParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " allowEmptyValue: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithSimplePathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{someParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: simple" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3,4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithSimpleExplodedPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{someParam*}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: simple" + NEW_LINE + " explode: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3,4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithLabelPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{.someParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: label" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1,2,3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1,2,3,4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.0,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.a,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithLabelExplodedPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{.someParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: label" + NEW_LINE + " explode: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1.2.3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1.2.3.4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.0.1.2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.a.1.2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithMatrixPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{;someParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: matrix" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=1,2,3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=1,2,3,4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someOtherParam=1,2,3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=0,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=a,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithMatrixExplodedPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{;someParam*}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: matrix" + NEW_LINE + " explode: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=1;someParam=2;someParam=3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=1;someParam=2;someParam=3;someParam=4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someOtherParam=1;someOtherParam=2;someOtherParam=3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=0;someParam=1;someParam=2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/;someParam=a;someParam=1;someParam=2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithSimpleAndLabelExplodedPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{someSimpleParam}/{someLabelParam}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someSimpleParam" + NEW_LINE + " required: true" + NEW_LINE + " style: simple" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " - in: path" + NEW_LINE + " name: someLabelParam" + NEW_LINE + " required: true" + NEW_LINE + " style: label" + NEW_LINE + " explode: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3/.1.2.3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1/.1.2.3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3/.1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1/.1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3/.1.2.3.4") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3,4/.1.2.3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3,4/.1.2.3.4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3/.0.1.2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0,1,2/.1.2.3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/0,1,2/.0.1.2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/1,2,3/.a.1.2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a,1,2/.1.2.3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/a,1,2/.a.1.2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithLabelAndMatrixExplodedPathParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath/{.someLabelParam}/{;someMatrixParam*}\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: path" + NEW_LINE + " name: someLabelParam" + NEW_LINE + " required: true" + NEW_LINE + " style: label" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " - in: path" + NEW_LINE + " name: someMatrixParam" + NEW_LINE + " required: true" + NEW_LINE + " style: matrix" + NEW_LINE + " explode: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1,2,3/;someMatrixParam=1;someMatrixParam=2;someMatrixParam=3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1/;someMatrixParam=1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1,2,3,4/;someMatrixParam=1;someMatrixParam=2;someMatrixParam=3;someMatrixParam=4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1,2,3/;someMatrixParam=0;someMatrixParam=1;someMatrixParam=2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.0,1,2/;someMatrixParam=1;someMatrixParam=2;someMatrixParam=3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.0,1,2/;someMatrixParam=0;someMatrixParam=1;someMatrixParam=2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.1,2,3/;someMatrixParam=a;someMatrixParam=1;someMatrixParam=2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.a,1,2/;someMatrixParam=1;someMatrixParam=2;someMatrixParam=3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath/.a,1,2/;someMatrixParam=a;someMatrixParam=1;someMatrixParam=2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByQueryStringParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); } @Test public void shouldMatchByQueryStringParameterWithOperationId() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") .withOperationId("someOperation") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); } @Test public void shouldMatchByOptionalQueryString() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "0") )); } @Test public void shouldMatchByOptionalNotSpecifiedQueryString() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "0") )); } @Test public void shouldMatchQueryStringWithAllowEmpty() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " allowEmptyValue: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "0") )); } @Test public void shouldMatchByOptionalQueryStringWithAllowEmpty() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: false" + NEW_LINE + " allowEmptyValue: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "0") )); } @Test public void shouldMatchByQueryStringParameterCommonForAllPaths() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "components:" + NEW_LINE + " parameters:" + NEW_LINE + " someParam:" + NEW_LINE + " in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " someOtherParam:" + NEW_LINE + " in: query" + NEW_LINE + " name: someOtherParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE + " minLength: 2" + NEW_LINE + " maxLength: 3" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - $ref: '#/components/parameters/someParam'" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - $ref: '#/components/parameters/someOtherParam'" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "1") .withQueryStringParameter("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "0") .withQueryStringParameter("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "1") .withQueryStringParameter("someOtherParam", "a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); } @Test public void shouldMatchByQueryStringParameterCommonForPath() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); } @Test public void shouldMatchByQueryStringParameterCommonForAllPathsOverriddenAtPath() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "components:" + NEW_LINE + " parameters:" + NEW_LINE + " someParam:" + NEW_LINE + " in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " someOtherParam:" + NEW_LINE + " in: query" + NEW_LINE + " name: someOtherParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE + " minLength: 2" + NEW_LINE + " maxLength: 3" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 10" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - $ref: '#/components/parameters/someOtherParam'" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "10") .withQueryStringParameter("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "5") .withQueryStringParameter("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "10") .withQueryStringParameter("someOtherParam", "a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); } @Test public void shouldMatchByQueryStringParameterCommonForAllPathsOverriddenAtMethod() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "components:" + NEW_LINE + " parameters:" + NEW_LINE + " someParam:" + NEW_LINE + " in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " someOtherParam:" + NEW_LINE + " in: query" + NEW_LINE + " name: someOtherParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE + " minLength: 2" + NEW_LINE + " maxLength: 3" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 10" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 100" + NEW_LINE + " - $ref: '#/components/parameters/someOtherParam'" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "100") .withQueryStringParameter("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "50") .withQueryStringParameter("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someParam", "100") .withQueryStringParameter("someOtherParam", "a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("someOtherParam", "1") )); } @Test public void shouldMatchByPathWithFormQueryStringParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: form" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1,2,3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1,2,3,4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "0,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "a,1,2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithFormExplodedQueryStringParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: form" + NEW_LINE + " explode: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1", "2", "3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1", "2", "3", "4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "0", "1", "2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "a", "1", "2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithSpaceDelimitedQueryStringParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: spaceDelimited" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1%202%203") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1 2 3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1+2+3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1%202%203%204") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1 2 3 4") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1+2+3+4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "0%201%202") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "0 1 2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "0+1+2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "a%202%203") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "a 2 3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "a+2+3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithSpaceDelimitedExplodedQueryStringParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: spaceDelimited" + NEW_LINE + " explode: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1", "2", "3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1", "2", "3", "4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "0", "1", "2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "a", "1", "2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithPipeDelimitedQueryStringParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: pipeDelimited" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1|2|3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1|2|3|4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "0|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "a|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithPipeDelimitedExplodedQueryStringParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " style: pipeDelimited" + NEW_LINE + " explode: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1", "2", "3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "1", "2", "3", "4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "0", "1", "2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someParam", "a", "1", "2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithFormExplodedAndPipeDelimitedQueryStringParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someFormParam" + NEW_LINE + " required: true" + NEW_LINE + " style: form" + NEW_LINE + " explode: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " - in: query" + NEW_LINE + " name: someSpaceDelimitedParam" + NEW_LINE + " required: true" + NEW_LINE + " style: pipeDelimited" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someFormParam", "1", "2", "3") .withQueryStringParameter("someSpaceDelimitedParam", "1|2|3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someFormParam", "1") .withQueryStringParameter("someSpaceDelimitedParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someFormParam", "1", "2", "3", "4") .withQueryStringParameter("someSpaceDelimitedParam", "1|2|3|4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someFormParam", "0", "1", "2") .withQueryStringParameter("someSpaceDelimitedParam", "1|2|3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someFormParam", "1", "2", "3") .withQueryStringParameter("someSpaceDelimitedParam", "0|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someFormParam", "0", "1", "2") .withQueryStringParameter("someSpaceDelimitedParam", "0|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someFormParam", "a", "1", "2") .withQueryStringParameter("someSpaceDelimitedParam", "1|2|3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someFormParam", "1", "2", "3") .withQueryStringParameter("someSpaceDelimitedParam", "a|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someFormParam", "a", "1", "2") .withQueryStringParameter("someSpaceDelimitedParam", "a|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByPathWithSpaceDelimitedAndPipeDelimitedQueryStringParameter() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: query" + NEW_LINE + " name: someSpaceDelimitedParam" + NEW_LINE + " required: true" + NEW_LINE + " style: spaceDelimited" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " - in: query" + NEW_LINE + " name: somePipeDelimitedParam" + NEW_LINE + " required: true" + NEW_LINE + " style: pipeDelimited" + NEW_LINE + " explode: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "1%202%203") .withQueryStringParameter("somePipeDelimitedParam", "1|2|3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "1 2 3") .withQueryStringParameter("somePipeDelimitedParam", "1|2|3") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "1") .withQueryStringParameter("somePipeDelimitedParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "1+2+3+4") .withQueryStringParameter("somePipeDelimitedParam", "1|2|3|4") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "0+1+2") .withQueryStringParameter("somePipeDelimitedParam", "1|2|3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "1+2+3") .withQueryStringParameter("somePipeDelimitedParam", "0|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "0+1+2") .withQueryStringParameter("somePipeDelimitedParam", "0|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "a%201%202") .withQueryStringParameter("somePipeDelimitedParam", "1|2|3") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "1%202%203") .withQueryStringParameter("somePipeDelimitedParam", "a|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withQueryStringParameter("someSpaceDelimitedParam", "a%201%202") .withQueryStringParameter("somePipeDelimitedParam", "a|1|2") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); } @Test public void shouldMatchByHeader() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "1") )); } @Test public void shouldMatchByHeaderWithOperationId() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") .withOperationId("someOperation") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "1") )); } @Test public void shouldMatchByOptionalHeader() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " required: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "0") )); } @Test public void shouldMatchByOptionalNotSpecifiedHeader() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "0") )); } @Test public void shouldMatchHeaderWithAllowEmpty() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " allowEmptyValue: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "0") )); } @Test public void shouldMatchByHeaderCommonForAllPaths() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "components:" + NEW_LINE + " parameters:" + NEW_LINE + " someParam:" + NEW_LINE + " in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " someOtherParam:" + NEW_LINE + " in: header" + NEW_LINE + " name: someOtherParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE + " minLength: 2" + NEW_LINE + " maxLength: 3" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - $ref: '#/components/parameters/someParam'" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - $ref: '#/components/parameters/someOtherParam'" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "1") .withHeader("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "0") .withHeader("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "1") .withHeader("someOtherParam", "a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "1") )); } @Test public void shouldMatchByHeaderCommonForPath() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "1") )); } @Test public void shouldMatchByHeaderCommonForAllPathsOverriddenAtMethod() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "components:" + NEW_LINE + " parameters:" + NEW_LINE + " someParam:" + NEW_LINE + " in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " someOtherParam:" + NEW_LINE + " in: header" + NEW_LINE + " name: someOtherParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE + " minLength: 2" + NEW_LINE + " maxLength: 3" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 10" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: header" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 100" + NEW_LINE + " - $ref: '#/components/parameters/someOtherParam'" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "100") .withHeader("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "50") .withHeader("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someParam", "100") .withHeader("someOtherParam", "a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("someOtherParam", "1") )); } @Test public void shouldMatchByCookie() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "1") )); } @Test public void shouldMatchByCookieWithOperationId() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") .withOperationId("someOperation") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "1") )); } @Test public void shouldMatchByOptionalCookie() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " required: false" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "0") )); } @Test public void shouldMatchByOptionalNotSpecifiedCookie() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "0") )); } @Test public void shouldMatchCookieWithAllowEmpty() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " allowEmptyValue: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "0") )); } @Test public void shouldMatchByCookieCommonForPath() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "0") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "1") )); } @Test public void shouldMatchByCookieCommonForAllPaths() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "components:" + NEW_LINE + " parameters:" + NEW_LINE + " someParam:" + NEW_LINE + " in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " someOtherParam:" + NEW_LINE + " in: cookie" + NEW_LINE + " name: someOtherParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE + " minLength: 2" + NEW_LINE + " maxLength: 3" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - $ref: '#/components/parameters/someParam'" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - $ref: '#/components/parameters/someOtherParam'" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "1") .withCookie("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "0") .withCookie("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "1") .withCookie("someOtherParam", "a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "1") )); } @Test public void shouldMatchByCookieCommonForAllPathsOverriddenAtMethod() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "components:" + NEW_LINE + " parameters:" + NEW_LINE + " someParam:" + NEW_LINE + " in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 1" + NEW_LINE + " someOtherParam:" + NEW_LINE + " in: cookie" + NEW_LINE + " name: someOtherParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE + " minLength: 2" + NEW_LINE + " maxLength: 3" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " parameters:" + NEW_LINE + " - in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 10" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " parameters:" + NEW_LINE + " - in: cookie" + NEW_LINE + " name: someParam" + NEW_LINE + " required: true" + NEW_LINE + " schema:" + NEW_LINE + " type: integer" + NEW_LINE + " minimum: 100" + NEW_LINE + " - $ref: '#/components/parameters/someOtherParam'" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "100") .withCookie("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "50") .withCookie("someOtherParam", "ab") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someParam", "100") .withCookie("someOtherParam", "a") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withCookie("someOtherParam", "1") )); } @Test public void shouldMatchByJsonBody() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": \"abc\" }")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json; charset=utf-8") .withBody(json("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByJsonBodyWithMediaTypeRange() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/*:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByJsonBodyWithDefaultMediaType() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " \"*/*\":" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByJsonBodyWithSchemaComponent() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + "components:" + NEW_LINE + " schemas:" + NEW_LINE + " Simple:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByJsonBodyWithRequestBodyAndSchemaComponent() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " $ref: '#/components/requestBodies/SimpleBody'" + NEW_LINE + "components:" + NEW_LINE + " requestBodies:" + NEW_LINE + " SimpleBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " schemas:" + NEW_LINE + " Simple:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/json") .withBody(json("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByPlainTextBody() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " plain/text:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text; charset=utf-8") .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByPlainTextBodyWithRequiredFalse() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: false" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " plain/text:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text; charset=utf-8") .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByPlainTextBodyWithRequiredDefaulted() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " plain/text:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text; charset=utf-8") .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByPlainTextBodyWithMediaTypeRange() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " plain/*:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByPlainTextBodyWithDefaultMediaType() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " \"*/*\":" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withBody(exact("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withBody(exact("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByPlainTextBodyWithSchemaComponent() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " plain/text:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + "components:" + NEW_LINE + " schemas:" + NEW_LINE + " Simple:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByPlainTextBodyWithRequestBodyAndSchemaComponent() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " $ref: '#/components/requestBodies/SimpleBody'" + NEW_LINE + "components:" + NEW_LINE + " requestBodies:" + NEW_LINE + " SimpleBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " plain/text:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " schemas:" + NEW_LINE + " Simple:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": \"abc\" }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": 1, \"name\": 1 }")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "plain/text") .withBody(exact("{ \"id\": \"abc\", \"name\": \"abc\" }")) )); } @Test public void shouldMatchByXmlBody() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " properties:" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " email:" + NEW_LINE + " type: integer" + NEW_LINE + " format: email" + NEW_LINE + " required:" + NEW_LINE + " - name" + NEW_LINE + " - email'" + NEW_LINE + " text/plain:" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>abc</name></root>")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml; charset=utf-8") .withBody(xml("<root><id>1</id><name>abc</name></root>")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>1</name></root>")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml") .withBody(xml("<root><id>abc</id><name>1</name></root>")) )); } @Test public void shouldMatchByXmlBodyWithRequiredFalse() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: false" + NEW_LINE + " content:" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " properties:" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " email:" + NEW_LINE + " type: integer" + NEW_LINE + " format: email" + NEW_LINE + " required:" + NEW_LINE + " - name" + NEW_LINE + " - email'" + NEW_LINE + " text/plain:" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>abc</name></root>")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml; charset=utf-8") .withBody(xml("<root><id>1</id><name>abc</name></root>")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>1</name></root>")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml") .withBody(xml("<root><id>abc</id><name>1</name></root>")) )); } @Test public void shouldMatchByXmlBodyWithRequiredDefaulted() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " content:" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " properties:" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " email:" + NEW_LINE + " type: integer" + NEW_LINE + " format: email" + NEW_LINE + " required:" + NEW_LINE + " - name" + NEW_LINE + " - email'" + NEW_LINE + " text/plain:" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>abc</name></root>")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml; charset=utf-8") .withBody(xml("<root><id>1</id><name>abc</name></root>")) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>1</name></root>")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/xml") .withBody(xml("<root><id>abc</id><name>1</name></root>")) )); } @Test public void shouldMatchByXmlBodyWithSchemaComponent() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + "components:" + NEW_LINE + " schemas:" + NEW_LINE + " Simple:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>abc</name></root>")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>1</name></root>")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml") .withBody(xml("<root><id>abc</id><name>1</name></root>")) )); } @Test public void shouldMatchByXmlBodyWithRequestBodyAndSchemaComponent() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " $ref: '#/components/requestBodies/SimpleBody'" + NEW_LINE + "components:" + NEW_LINE + " requestBodies:" + NEW_LINE + " SimpleBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/json:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " schemas:" + NEW_LINE + " Simple:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>abc</name></root>")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml") .withBody(xml("<root><id>1</id><name>1</name></root>")) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/xml") .withBody(xml("<root><id>abc</id><name>1</name></root>")) )); } @Test public void shouldMatchByFormBody() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " text/plain:" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=abc") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8") .withBody("id=1&name=abc") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=abc&name=1") )); } @Test public void shouldMatchByFormBodyWithFormEncoding() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: array" + NEW_LINE + " items:" + NEW_LINE + " type: integer" + NEW_LINE + " name:" + NEW_LINE + " type: array" + NEW_LINE + " items:" + NEW_LINE + " type: string" + NEW_LINE + " encoding:" + NEW_LINE + " id:" + NEW_LINE + " style: form" + NEW_LINE + " explode: false" + NEW_LINE + " name:" + NEW_LINE + " style: form" + NEW_LINE + " explode: true" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1,2,3&name=abc&name=def") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8") .withBody("id=1,2,3&name=abc&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1,2,3&name=1&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=a,2,3&name=abc&name=def") )); } @Test public void shouldMatchByFormBodyWithSpaceDelimitedEncoding() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: array" + NEW_LINE + " items:" + NEW_LINE + " type: integer" + NEW_LINE + " name:" + NEW_LINE + " type: array" + NEW_LINE + " items:" + NEW_LINE + " type: string" + NEW_LINE + " encoding:" + NEW_LINE + " id:" + NEW_LINE + " style: spaceDelimited" + NEW_LINE + " explode: false" + NEW_LINE + " name:" + NEW_LINE + " style: spaceDelimited" + NEW_LINE + " explode: true" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1%202%203&name=abc&name=def") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1+2+3&name=abc&name=def") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1 2 3&name=abc&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1%202%203&name=1&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1+2+3&name=1&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1 2 3&name=1&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=a%202%203&name=abc&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=a+2+3&name=abc&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=a 2 3&name=abc&name=def") )); } @Test public void shouldMatchByFormBodyWithPipeDelimitedEncoding() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: array" + NEW_LINE + " items:" + NEW_LINE + " type: integer" + NEW_LINE + " name:" + NEW_LINE + " type: array" + NEW_LINE + " items:" + NEW_LINE + " type: string" + NEW_LINE + " encoding:" + NEW_LINE + " id:" + NEW_LINE + " style: pipeDelimited" + NEW_LINE + " explode: false" + NEW_LINE + " name:" + NEW_LINE + " style: pipeDelimited" + NEW_LINE + " explode: true" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1|2|3&name=abc&name=def") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8") .withBody("id=1|2|3&name=abc&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1|2|3&name=1&name=def") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=a|2|3&name=abc&name=def") )); } @Test public void shouldMatchByFormBodyWithRequiredFalse() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: false" + NEW_LINE + " content:" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " text/plain:" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=abc") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8") .withBody("id=1&name=abc") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=abc&name=1") )); } @Test public void shouldMatchByFormBodyWithRequiredDefaulted() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " content:" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE + " text/plain:" + NEW_LINE + " schema:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=abc") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8") .withBody("id=1&name=abc") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withPath("/somePath") .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=abc&name=1") )); } @Test public void shouldMatchByFormBodyWithSchemaComponent() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + "components:" + NEW_LINE + " schemas:" + NEW_LINE + " Simple:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=abc") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=abc&name=1") )); } @Test public void shouldMatchByFormBodyWithRequestBodyAndSchemaComponent() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " post:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " requestBody:" + NEW_LINE + " $ref: '#/components/requestBodies/SimpleBody'" + NEW_LINE + "components:" + NEW_LINE + " requestBodies:" + NEW_LINE + " SimpleBody:" + NEW_LINE + " required: true" + NEW_LINE + " content:" + NEW_LINE + " application/x-www-form-urlencoded:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " application/xml:" + NEW_LINE + " schema:" + NEW_LINE + " $ref: '#/components/schemas/Simple'" + NEW_LINE + " schemas:" + NEW_LINE + " Simple:" + NEW_LINE + " type: object" + NEW_LINE + " required:" + NEW_LINE + " - id" + NEW_LINE + " - name" + NEW_LINE + " properties:" + NEW_LINE + " id:" + NEW_LINE + " type: integer" + NEW_LINE + " format: int64" + NEW_LINE + " name:" + NEW_LINE + " type: string" + NEW_LINE) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=abc") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=1&name=1") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("content-type", "application/x-www-form-urlencoded") .withBody("id=abc&name=1") )); } @Test public void shouldHandleBlankStrings() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("") .withOperationId("") )); HttpRequest httpRequest = request(); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); thenMatchesEmptyFieldDifferences(matchDifference, matches, true); } @Test public void shouldMatchBySecuritySchemeInHeaderWithBasic() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - BasicAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BasicAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: basic" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "basic " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "basic") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInHeaderWithBearer() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - BearerAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BearerAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: bearer" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInHeaderWithApiKey() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - ApiKeyAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " ApiKeyAuth:" + NEW_LINE + " type: apiKey" + NEW_LINE + " in: header" + NEW_LINE + " name: X-API-Key" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("X-API-Key", UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("X-API-Key", "") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInHeaderWithOpenIdConnect() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - OpenID:" + NEW_LINE + " - read" + NEW_LINE + " - write" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " OpenID:" + NEW_LINE + " type: openIdConnect" + NEW_LINE + " openIdConnectUrl: https: ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInHeaderWithOAuth2() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - OAuth2:" + NEW_LINE + " - read" + NEW_LINE + " - write" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " OAuth2:" + NEW_LINE + " type: oauth2" + NEW_LINE + " flows:" + NEW_LINE + " authorizationCode:" + NEW_LINE + " authorizationUrl: https: " tokenUrl: https: " scopes:" + NEW_LINE + " read: Grants read access" + NEW_LINE + " write: Grants write access" + NEW_LINE + " admin: Grants access to admin operations" ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInHeaderWithMultiAuthorizationHeaderSchemes() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - BasicAuth: []" + NEW_LINE + " - BearerAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BasicAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: basic" + NEW_LINE + " BearerAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: bearer" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "basic " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInHeaderWithMultiSchemesIncludingAPIKey() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - BasicAuth: []" + NEW_LINE + " - BearerAuth: []" + NEW_LINE + " - ApiKeyAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BasicAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: basic" + NEW_LINE + " BearerAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: bearer" + NEW_LINE + " ApiKeyAuth:" + NEW_LINE + " type: apiKey" + NEW_LINE + " in: header" + NEW_LINE + " name: X-API-Key" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "basic " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("X-API-Key", UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("X-API-Key", "") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchByDefaultSecuritySchemeInHeaderWithMultiSchemesIncludingAPIKey() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "security:" + NEW_LINE + " - BasicAuth: []" + NEW_LINE + " - BearerAuth: []" + NEW_LINE + " - ApiKeyAuth: []" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BasicAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: basic" + NEW_LINE + " BearerAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: bearer" + NEW_LINE + " ApiKeyAuth:" + NEW_LINE + " type: apiKey" + NEW_LINE + " in: header" + NEW_LINE + " name: X-API-Key" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "basic " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("X-API-Key", UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("X-API-Key", "") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchByDefaultSecuritySchemeInHeaderWithMultiSchemesIncludingAPIKeyWithOperationOverride() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "security:" + NEW_LINE + " - BasicAuth: []" + NEW_LINE + " - BearerAuth: []" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - ApiKeyAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BasicAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: basic" + NEW_LINE + " BearerAuth:" + NEW_LINE + " type: http" + NEW_LINE + " scheme: bearer" + NEW_LINE + " ApiKeyAuth:" + NEW_LINE + " type: apiKey" + NEW_LINE + " in: header" + NEW_LINE + " name: X-API-Key" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "basic " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withHeader("X-API-Key", UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "bearer") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withHeader("X-API-Key", "") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInQueryStringParameterWithBasic() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - BasicAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BasicAuth:" + NEW_LINE + " type: http" + NEW_LINE + " in: query" + NEW_LINE + " scheme: basic" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "basic " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "basic") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInQueryStringParameterWithBearer() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - BearerAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BearerAuth:" + NEW_LINE + " type: http" + NEW_LINE + " in: query" + NEW_LINE + " scheme: bearer" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "bearer " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "bearer") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInQueryStringParameterWithApiKey() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - ApiKeyAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " ApiKeyAuth:" + NEW_LINE + " type: apiKey" + NEW_LINE + " in: query" + NEW_LINE + " name: X-API-Key" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("X-API-Key", UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("X-API-Key", "") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInQueryStringParameterWithOpenIdConnect() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - OpenID:" + NEW_LINE + " - read" + NEW_LINE + " - write" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " OpenID:" + NEW_LINE + " type: openIdConnect" + NEW_LINE + " in: query" + NEW_LINE + " openIdConnectUrl: https: ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "bearer " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInQueryStringParameterWithOAuth2() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - OAuth2:" + NEW_LINE + " - read" + NEW_LINE + " - write" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " OAuth2:" + NEW_LINE + " type: oauth2" + NEW_LINE + " in: query" + NEW_LINE + " flows:" + NEW_LINE + " authorizationCode:" + NEW_LINE + " authorizationUrl: https: " tokenUrl: https: " scopes:" + NEW_LINE + " read: Grants read access" + NEW_LINE + " write: Grants write access" + NEW_LINE + " admin: Grants access to admin operations" ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "bearer " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInQueryStringParameterWithMultiAuthorizationQueryStringParameterSchemes() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - BasicAuth: []" + NEW_LINE + " - BearerAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BasicAuth:" + NEW_LINE + " type: http" + NEW_LINE + " in: query" + NEW_LINE + " scheme: basic" + NEW_LINE + " BearerAuth:" + NEW_LINE + " type: http" + NEW_LINE + " in: query" + NEW_LINE + " scheme: bearer" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "basic " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "bearer " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "bearer") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldMatchBySecuritySchemeInQueryStringParameterWithMultiSchemesIncludingAPIKey() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE + " security:" + NEW_LINE + " - BasicAuth: []" + NEW_LINE + " - BearerAuth: []" + NEW_LINE + " - ApiKeyAuth: []" + NEW_LINE + "components:" + NEW_LINE + " securitySchemes:" + NEW_LINE + " BasicAuth:" + NEW_LINE + " type: http" + NEW_LINE + " in: query" + NEW_LINE + " scheme: basic" + NEW_LINE + " BearerAuth:" + NEW_LINE + " type: http" + NEW_LINE + " in: query" + NEW_LINE + " scheme: bearer" + NEW_LINE + " ApiKeyAuth:" + NEW_LINE + " type: apiKey" + NEW_LINE + " in: query" + NEW_LINE + " name: X-API-Key" + NEW_LINE ) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "basic " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "bearer " + UUIDService.getUUID()) )); assertTrue(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("X-API-Key", UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "bearer") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("Authorization", "wrong_scheme " + UUIDService.getUUID()) )); assertFalse(httpRequestsPropertiesMatcher.matches( request() .withQueryStringParameter("X-API-Key", "") )); assertFalse(httpRequestsPropertiesMatcher.matches( request() )); } @Test public void shouldHandleNulls() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload(null) .withOperationId(null) )); HttpRequest httpRequest = request(); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); thenMatchesEmptyFieldDifferences(matchDifference, matches, true); } @Test public void shouldMatchSingleOperationInOpenAPIJsonUrl() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("listPets") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); thenMatchesEmptyFieldDifferences(matchDifference, matches, true); } @Test public void shouldMatchSingleOperationInOpenAPIJsonSpec() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json")) .withOperationId("listPets") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); thenMatchesEmptyFieldDifferences(matchDifference, matches, true); } @Test public void shouldMatchSingleOperationInOpenAPIYamlUrl() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.yaml") .withOperationId("listPets") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); thenMatchesEmptyFieldDifferences(matchDifference, matches, true); } @Test public void shouldMatchSingleOperationInOpenAPIYamlSpec() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml")) .withOperationId("listPets") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); thenMatchesEmptyFieldDifferences(matchDifference, matches, true); } @Test public void shouldMatchAnyOperationInOpenAPI() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); thenMatchesEmptyFieldDifferences(matchDifference, matches, true); } @Test public void shouldNotMatchRequestWithWrongOperationIdInOpenAPI() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("showPetById") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); assertThat(matches, is(false)); assertThat(matchDifference.getDifferences(METHOD), nullValue()); assertThat(matchDifference.getDifferences(PATH), containsInAnyOrder( " string or regex match failed expected:" + NEW_LINE + NEW_LINE + " /pets/.*" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " /pets" + NEW_LINE, " expected path /pets/{petId} has 2 parts but path /pets has 1 part " )); assertThat(matchDifference.getDifferences(QUERY_PARAMETERS), nullValue()); assertThat(matchDifference.getDifferences(COOKIES), nullValue()); assertThat(matchDifference.getDifferences(HEADERS), nullValue()); assertThat(matchDifference.getDifferences(BODY), nullValue()); assertThat(matchDifference.getDifferences(SSL_MATCHES), nullValue()); assertThat(matchDifference.getDifferences(KEEP_ALIVE), nullValue()); assertThat(matchDifference.getDifferences(OPERATION), nullValue()); assertThat(matchDifference.getDifferences(OPENAPI), nullValue()); } @Test public void shouldNotMatchRequestWithWrongOperationIdWithNullContextInOpenAPI() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("showPetById") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(httpRequest); thenMatchesEmptyFieldDifferences(matchDifference, matches, false); } @Test public void shouldNotMatchRequestWithMethodMismatchInOpenAPI() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("showPetById") )); HttpRequest httpRequest = request() .withMethod("PUT") .withPath("/pets") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); assertThat(matches, is(false)); assertThat(matchDifference.getDifferences(METHOD), containsInAnyOrder(" string or regex match failed expected:" + NEW_LINE + NEW_LINE + " GET" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " PUT" + NEW_LINE)); assertThat(matchDifference.getDifferences(PATH), nullValue()); assertThat(matchDifference.getDifferences(QUERY_PARAMETERS), nullValue()); assertThat(matchDifference.getDifferences(COOKIES), nullValue()); assertThat(matchDifference.getDifferences(HEADERS), nullValue()); assertThat(matchDifference.getDifferences(BODY), nullValue()); assertThat(matchDifference.getDifferences(SSL_MATCHES), nullValue()); assertThat(matchDifference.getDifferences(KEEP_ALIVE), nullValue()); assertThat(matchDifference.getDifferences(OPERATION), nullValue()); assertThat(matchDifference.getDifferences(OPENAPI), nullValue()); } @Test public void shouldNotMatchRequestWithPathMismatchInOpenAPI() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("showPetById") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/wrong") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); assertThat(matches, is(false)); assertThat(matchDifference.getDifferences(METHOD), nullValue()); assertThat(matchDifference.getDifferences(PATH), containsInAnyOrder( " string or regex match failed expected:" + NEW_LINE + NEW_LINE + " /pets/.*" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " /wrong" + NEW_LINE, " expected path /pets/{petId} has 2 parts but path /wrong has 1 part " )); assertThat(matchDifference.getDifferences(QUERY_PARAMETERS), nullValue()); assertThat(matchDifference.getDifferences(COOKIES), nullValue()); assertThat(matchDifference.getDifferences(HEADERS), nullValue()); assertThat(matchDifference.getDifferences(BODY), nullValue()); assertThat(matchDifference.getDifferences(SSL_MATCHES), nullValue()); assertThat(matchDifference.getDifferences(KEEP_ALIVE), nullValue()); assertThat(matchDifference.getDifferences(OPERATION), nullValue()); assertThat(matchDifference.getDifferences(OPENAPI), nullValue()); } @Test public void shouldNotMatchRequestWithHeaderMismatchInOpenAPI() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("somePath") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/some/path") .withQueryStringParameter("limit", "10"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); assertThat(matches, is(false)); assertThat(matchDifference.getDifferences(METHOD), nullValue()); assertThat(matchDifference.getDifferences(PATH), nullValue()); assertThat(matchDifference.getDifferences(QUERY_PARAMETERS), nullValue()); assertThat(matchDifference.getDifferences(COOKIES), nullValue()); assertThat(matchDifference.getDifferences(HEADERS), containsInAnyOrder(" multimap subset match failed expected:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"keyMatchStyle\" : \"MATCHING_KEY\"," + NEW_LINE + " \"X-Request-ID\" : {" + NEW_LINE + " \"parameterStyle\" : \"SIMPLE\"," + NEW_LINE + " \"values\" : [ {" + NEW_LINE + " \"schema\" : {" + NEW_LINE + " \"type\" : \"string\"," + NEW_LINE + " \"format\" : \"uuid\"" + NEW_LINE + " }" + NEW_LINE + " } ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " none" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " none is not a subset" + NEW_LINE)); assertThat(matchDifference.getDifferences(BODY), nullValue()); assertThat(matchDifference.getDifferences(SSL_MATCHES), nullValue()); assertThat(matchDifference.getDifferences(KEEP_ALIVE), nullValue()); assertThat(matchDifference.getDifferences(OPERATION), nullValue()); assertThat(matchDifference.getDifferences(OPENAPI), nullValue()); } @Test public void shouldNotMatchRequestWithHeaderAndQueryParameterMismatchInOpenAPI() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("somePath") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/some/path") .withQueryStringParameter("limit", "not_a_number"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); assertThat(matches, is(false)); assertThat(matchDifference.getDifferences(METHOD), nullValue()); assertThat(matchDifference.getDifferences(PATH), nullValue()); assertThat(matchDifference.getDifferences(QUERY_PARAMETERS), nullValue()); assertThat(matchDifference.getDifferences(COOKIES), nullValue()); assertThat(matchDifference.getDifferences(HEADERS), containsInAnyOrder(" multimap subset match failed expected:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"keyMatchStyle\" : \"MATCHING_KEY\"," + NEW_LINE + " \"X-Request-ID\" : {" + NEW_LINE + " \"parameterStyle\" : \"SIMPLE\"," + NEW_LINE + " \"values\" : [ {" + NEW_LINE + " \"schema\" : {" + NEW_LINE + " \"type\" : \"string\"," + NEW_LINE + " \"format\" : \"uuid\"" + NEW_LINE + " }" + NEW_LINE + " } ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " none" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " none is not a subset" + NEW_LINE)); assertThat(matchDifference.getDifferences(BODY), nullValue()); assertThat(matchDifference.getDifferences(SSL_MATCHES), nullValue()); assertThat(matchDifference.getDifferences(KEEP_ALIVE), nullValue()); assertThat(matchDifference.getDifferences(OPERATION), nullValue()); assertThat(matchDifference.getDifferences(OPENAPI), nullValue()); } @Test public void shouldNotMatchRequestWithHeaderAndQueryParameterMismatchInOpenAPIWithoutOperationId() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") )); HttpRequest httpRequest = request() .withMethod("GET") .withPath("/some/path") .withQueryStringParameter("limit", "not_a_number"); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); assertThat(matches, is(false)); assertThat(matchDifference.getDifferences(PATH), containsInAnyOrder(" string or regex match failed expected:" + NEW_LINE + NEW_LINE + " /pets" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " /some/path" + NEW_LINE, " string or regex match failed expected:" + NEW_LINE + NEW_LINE + " /pets/.*" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " /some/path" + NEW_LINE)); assertThat(matchDifference.getDifferences(METHOD), containsInAnyOrder(" string or regex match failed expected:" + NEW_LINE + NEW_LINE + " POST" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " GET" + NEW_LINE, " string or regex match failed expected:" + NEW_LINE + NEW_LINE + " POST" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " GET" + NEW_LINE)); assertThat(matchDifference.getDifferences(QUERY_PARAMETERS), nullValue()); assertThat(matchDifference.getDifferences(COOKIES), nullValue()); assertThat(matchDifference.getDifferences(HEADERS), containsInAnyOrder(" multimap subset match failed expected:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"keyMatchStyle\" : \"MATCHING_KEY\"," + NEW_LINE + " \"X-Request-ID\" : {" + NEW_LINE + " \"parameterStyle\" : \"SIMPLE\"," + NEW_LINE + " \"values\" : [ {" + NEW_LINE + " \"schema\" : {" + NEW_LINE + " \"type\" : \"string\"," + NEW_LINE + " \"format\" : \"uuid\"" + NEW_LINE + " }" + NEW_LINE + " } ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " none" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " none is not a subset" + NEW_LINE)); assertThat(matchDifference.getDifferences(BODY), nullValue()); assertThat(matchDifference.getDifferences(SSL_MATCHES), nullValue()); assertThat(matchDifference.getDifferences(KEEP_ALIVE), nullValue()); assertThat(matchDifference.getDifferences(OPERATION), nullValue()); assertThat(matchDifference.getDifferences(OPENAPI), nullValue()); } @Test public void shouldNotMatchRequestWithBodyMismatchWithContentTypeInOpenAPI() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("createPets") )); HttpRequest httpRequest = request() .withMethod("POST") .withPath("/pets") .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"id\": \"invalid_id_format\", " + NEW_LINE + " \"name\": \"scruffles\", " + NEW_LINE + " \"tag\": \"dog\"" + NEW_LINE + "}")); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); assertThat(matches, is(false)); assertThat(matchDifference.getDifferences(METHOD), nullValue()); assertThat(matchDifference.getDifferences(PATH), nullValue()); assertThat(matchDifference.getDifferences(QUERY_PARAMETERS), nullValue()); assertThat(matchDifference.getDifferences(COOKIES), nullValue()); assertThat(matchDifference.getDifferences(HEADERS), nullValue()); String bodyError = " json schema match failed expected:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"required\" : [ \"id\", \"name\" ]," + NEW_LINE + " \"type\" : \"object\"," + NEW_LINE + " \"properties\" : {" + NEW_LINE + " \"id\" : {" + NEW_LINE + " \"type\" : \"integer\"," + NEW_LINE + " \"format\" : \"int64\"" + NEW_LINE + " }," + NEW_LINE + " \"name\" : {" + NEW_LINE + " \"type\" : \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"tag\" : {" + NEW_LINE + " \"type\" : \"string\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"id\": \"invalid_id_format\", " + NEW_LINE + " \"name\": \"scruffles\", " + NEW_LINE + " \"tag\": \"dog\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " 2 errors:" + NEW_LINE + " - field: \"/id\" for schema: \"/properties/id\" has error: \"instance type (string) does not match any allowed primitive type (allowed: [\"integer\"])\"" + NEW_LINE + " - schema: \"/properties/id\" has error: \"format attribute \"int64\" not supported\"" + NEW_LINE; assertThat(matchDifference.getDifferences(BODY), containsInAnyOrder(bodyError, bodyError)); assertThat(matchDifference.getDifferences(SSL_MATCHES), nullValue()); assertThat(matchDifference.getDifferences(KEEP_ALIVE), nullValue()); assertThat(matchDifference.getDifferences(OPERATION), nullValue()); assertThat(matchDifference.getDifferences(OPENAPI), nullValue()); } @Test public void shouldNotMatchRequestWithBodyMismatchWithContentTypeInOpenAPIWithoutOperationID() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") )); HttpRequest httpRequest = request() .withMethod("POST") .withPath("/pets") .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"id\": \"invalid_id_format\", " + NEW_LINE + " \"name\": \"scruffles\", " + NEW_LINE + " \"tag\": \"dog\"" + NEW_LINE + "}")); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); assertThat(matches, is(false)); String methodError = " string or regex match failed expected:" + NEW_LINE + NEW_LINE + " GET" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " POST" + NEW_LINE; assertThat(matchDifference.getDifferences(METHOD), containsInAnyOrder(methodError, methodError, methodError)); assertThat(matchDifference.getDifferences(PATH), nullValue()); assertThat(matchDifference.getDifferences(QUERY_PARAMETERS), nullValue()); assertThat(matchDifference.getDifferences(COOKIES), nullValue()); assertThat(matchDifference.getDifferences(HEADERS), nullValue()); String bodyError = " json schema match failed expected:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"required\" : [ \"id\", \"name\" ]," + NEW_LINE + " \"type\" : \"object\"," + NEW_LINE + " \"properties\" : {" + NEW_LINE + " \"id\" : {" + NEW_LINE + " \"type\" : \"integer\"," + NEW_LINE + " \"format\" : \"int64\"" + NEW_LINE + " }," + NEW_LINE + " \"name\" : {" + NEW_LINE + " \"type\" : \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"tag\" : {" + NEW_LINE + " \"type\" : \"string\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"id\": \"invalid_id_format\", " + NEW_LINE + " \"name\": \"scruffles\", " + NEW_LINE + " \"tag\": \"dog\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " 2 errors:" + NEW_LINE + " - field: \"/id\" for schema: \"/properties/id\" has error: \"instance type (string) does not match any allowed primitive type (allowed: [\"integer\"])\"" + NEW_LINE + " - schema: \"/properties/id\" has error: \"format attribute \"int64\" not supported\"" + NEW_LINE; assertThat(matchDifference.getDifferences(BODY), containsInAnyOrder(bodyError, bodyError)); assertThat(matchDifference.getDifferences(SSL_MATCHES), nullValue()); assertThat(matchDifference.getDifferences(KEEP_ALIVE), nullValue()); assertThat(matchDifference.getDifferences(OPERATION), nullValue()); assertThat(matchDifference.getDifferences(OPENAPI), nullValue()); } @Test public void shouldNotMatchRequestInOpenAPIWithBodyMismatch() { HttpRequestsPropertiesMatcher httpRequestsPropertiesMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); httpRequestsPropertiesMatcher.update(new Expectation( new OpenAPIDefinition() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("createPets") )); HttpRequest httpRequest = request() .withMethod("POST") .withPath("/pets") .withBody(json("{" + NEW_LINE + " \"id\": \"invalid_id_format\", " + NEW_LINE + " \"name\": \"scruffles\", " + NEW_LINE + " \"tag\": \"dog\"" + NEW_LINE + "}")); MatchDifference matchDifference = new MatchDifference(httpRequest); boolean matches = httpRequestsPropertiesMatcher.matches(matchDifference, httpRequest); assertThat(matches, is(false)); assertThat(matchDifference.getDifferences(METHOD), nullValue()); assertThat(matchDifference.getDifferences(PATH), nullValue()); assertThat(matchDifference.getDifferences(QUERY_PARAMETERS), nullValue()); assertThat(matchDifference.getDifferences(COOKIES), nullValue()); assertThat(matchDifference.getDifferences(HEADERS), nullValue()); String schemaValidationError = " json schema match failed expected:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"required\" : [ \"id\", \"name\" ]," + NEW_LINE + " \"type\" : \"object\"," + NEW_LINE + " \"properties\" : {" + NEW_LINE + " \"id\" : {" + NEW_LINE + " \"type\" : \"integer\"," + NEW_LINE + " \"format\" : \"int64\"" + NEW_LINE + " }," + NEW_LINE + " \"name\" : {" + NEW_LINE + " \"type\" : \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"tag\" : {" + NEW_LINE + " \"type\" : \"string\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"id\": \"invalid_id_format\", " + NEW_LINE + " \"name\": \"scruffles\", " + NEW_LINE + " \"tag\": \"dog\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " 2 errors:" + NEW_LINE + " - field: \"/id\" for schema: \"/properties/id\" has error: \"instance type (string) does not match any allowed primitive type (allowed: [\"integer\"])\"" + NEW_LINE + " - schema: \"/properties/id\" has error: \"format attribute \"int64\" not supported\"" + NEW_LINE; assertThat(matchDifference.getDifferences(BODY), containsInAnyOrder(schemaValidationError, schemaValidationError)); assertThat(matchDifference.getDifferences(SSL_MATCHES), nullValue()); assertThat(matchDifference.getDifferences(KEEP_ALIVE), nullValue()); assertThat(matchDifference.getDifferences(OPERATION), nullValue()); assertThat(matchDifference.getDifferences(OPENAPI), nullValue()); }
URLParser { public static String returnPath(String path) { String result; if (URLParser.isFullUrl(path)) { result = path.replaceAll(schemeHostAndPortRegex, ""); } else { result = path; } return substringBefore(result, "?"); } static boolean isFullUrl(String uri); static String returnPath(String path); }
@Test public void shouldReturnPath() { assertThat(URLParser.returnPath("http: assertThat(URLParser.returnPath("https: assertThat(URLParser.returnPath("https: assertThat(URLParser.returnPath("https: assertThat(URLParser.returnPath("http: assertThat(URLParser.returnPath("https: assertThat(URLParser.returnPath(" assertThat(URLParser.returnPath(" assertThat(URLParser.returnPath("/some/path"), is("/some/path")); assertThat(URLParser.returnPath("/123/456"), is("/123/456")); } @Test public void shouldStripQueryString() { assertThat(URLParser.returnPath("http: assertThat(URLParser.returnPath("https: assertThat(URLParser.returnPath("https: assertThat(URLParser.returnPath("https: assertThat(URLParser.returnPath("http: assertThat(URLParser.returnPath("https: assertThat(URLParser.returnPath(" assertThat(URLParser.returnPath(" assertThat(URLParser.returnPath("/some/path?foo=foo%3Dbar%26bar%3Dfoo%26bar%3Dfoo&foo=foo%3Dbar%26bar%3Dfoo%26bar%3Dfoo"), is("/some/path")); assertThat(URLParser.returnPath("/123/456%3Ffoo%3Dbar%26bar%3Dfoo%26bar%3Dfoo"), is("/123/456%3Ffoo%3Dbar%26bar%3Dfoo%26bar%3Dfoo")); }
ExceptionHandling { public static void swallowThrowable(Runnable runnable) { try { runnable.run(); } catch (Throwable throwable) { if (MockServerLogger.isEnabled(WARN)) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(WARN) .setMessageFormat(throwable.getMessage()) .setThrowable(throwable) ); } } } static void swallowThrowable(Runnable runnable); static void closeOnFlush(Channel ch); static boolean connectionClosedException(Throwable throwable); static boolean sslHandshakeException(Throwable throwable); static boolean connectionException(Throwable throwable); }
@Test public void shouldSwallowException() { String originalLogLevel = ConfigurationProperties.logLevel().name(); try { ConfigurationProperties.logLevel("INFO"); ExceptionHandling.mockServerLogger = mock(MockServerLogger.class); swallowThrowable(() -> { throw new RuntimeException(); }); verify(ExceptionHandling.mockServerLogger).logEvent(any(LogEntry.class)); } finally { ConfigurationProperties.logLevel(originalLogLevel); } } @Test public void shouldOnlyLogExceptions() { ExceptionHandling.mockServerLogger = mock(MockServerLogger.class); swallowThrowable(() -> { System.out.println("ignore me"); }); verify(ExceptionHandling.mockServerLogger, never()).logEvent(any(LogEntry.class)); }
ConfigurationProperties { public static int nioEventLoopThreadCount() { return readIntegerProperty(MOCKSERVER_NIO_EVENT_LOOP_THREAD_COUNT, "MOCKSERVER_NIO_EVENT_LOOP_THREAD_COUNT", DEFAULT_NIO_EVENT_LOOP_THREAD_COUNT); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadNIOEventLoopThreadCount() { System.clearProperty("mockserver.nioEventLoopThreadCount"); assertEquals(5, nioEventLoopThreadCount()); nioEventLoopThreadCount(2); assertEquals("2", System.getProperty("mockserver.nioEventLoopThreadCount")); assertEquals(2, nioEventLoopThreadCount()); } @Test public void shouldHandleInvalidNIOEventLoopThreadCount() { System.setProperty("mockserver.nioEventLoopThreadCount", "invalid"); assertEquals(5, nioEventLoopThreadCount()); }
ConfigurationProperties { public static int actionHandlerThreadCount() { return readIntegerProperty(MOCKSERVER_ACTION_HANDLER_THREAD_COUNT, "MOCKSERVER_ACTION_HANDLER_THREAD_COUNT", DEFAULT_ACTION_HANDLER_THREAD_COUNT); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadActionHandlerThreadCount() { System.clearProperty("mockserver.actionHandlerThreadCount"); int actionHandlerThreadCount = Math.max(5, Runtime.getRuntime().availableProcessors()); assertEquals(actionHandlerThreadCount, actionHandlerThreadCount()); actionHandlerThreadCount(2); assertEquals("2", System.getProperty("mockserver.actionHandlerThreadCount")); assertEquals(2, actionHandlerThreadCount()); }
ConfigurationProperties { public static int webSocketClientEventLoopThreadCount() { return readIntegerProperty(MOCKSERVER_WEB_SOCKET_CLIENT_EVENT_LOOP_THREAD_COUNT, "MOCKSERVER_WEB_SOCKET_CLIENT_EVENT_LOOP_THREAD_COUNT", DEFAULT_WEB_SOCKET_CLIENT_EVENT_LOOP_THREAD_COUNT); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadWebSocketClientEventLoopThreadCount() { System.clearProperty("mockserver.webSocketClientEventLoopThreadCount"); assertEquals(5, webSocketClientEventLoopThreadCount()); webSocketClientEventLoopThreadCount(2); assertEquals("2", System.getProperty("mockserver.webSocketClientEventLoopThreadCount")); assertEquals(2, webSocketClientEventLoopThreadCount()); }
ConfigurationProperties { public static boolean outputMemoryUsageCsv() { return Boolean.parseBoolean(readPropertyHierarchically(MOCKSERVER_OUTPUT_MEMORY_USAGE_CSV, "MOCKSERVER_OUTPUT_MEMORY_USAGE_CSV", DEFAULT_OUTPUT_MEMORY_USAGE_CSV)); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadOutputMemoryUsageCsv() { boolean originalSetting = outputMemoryUsageCsv(); try { outputMemoryUsageCsv(true); assertTrue(outputMemoryUsageCsv()); assertEquals("true", System.getProperty("mockserver.outputMemoryUsageCsv")); outputMemoryUsageCsv(false); assertFalse(outputMemoryUsageCsv()); assertEquals("false", System.getProperty("mockserver.outputMemoryUsageCsv")); } finally { outputMemoryUsageCsv(originalSetting); } }
ConfigurationProperties { public static String memoryUsageCsvDirectory() { return readPropertyHierarchically(MOCKSERVER_MEMORY_USAGE_DIRECTORY, "MOCKSERVER_MEMORY_USAGE_DIRECTORY", "."); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadMemoryUsageCsvDirectory() throws IOException { System.clearProperty("mockserver.memoryUsageCsvDirectory"); assertEquals(".", memoryUsageCsvDirectory()); File tempFile = File.createTempFile("prefix", "suffix"); memoryUsageCsvDirectory(tempFile.getAbsolutePath()); assertEquals(tempFile.getAbsolutePath(), memoryUsageCsvDirectory()); assertEquals(tempFile.getAbsolutePath(), System.getProperty("mockserver.memoryUsageCsvDirectory")); }
RegexStringMatcher extends BodyMatcher<NottableString> { public boolean matches(String matched) { return matches(null, string(matched)); } RegexStringMatcher(MockServerLogger mockServerLogger, boolean controlPlaneMatcher); RegexStringMatcher(MockServerLogger mockServerLogger, NottableString matcher, boolean controlPlaneMatcher); boolean matches(String matched); boolean matches(final MatchDifference context, NottableString matched); boolean matches(NottableString matcher, NottableString matched, boolean ignoreCase); boolean isBlank(); }
@Test public void shouldMatchMatchingString() { assertTrue(new RegexStringMatcher(new MockServerLogger(), string("some_value"), false).matches("some_value")); } @Test public void shouldMatchUnMatchingNottedString() { assertTrue(new RegexStringMatcher(new MockServerLogger(), string("some_value"), false).matches(null, NottableString.not("not_value"))); } @Test public void shouldMatchUnMatchingNottedMatcher() { assertTrue(new RegexStringMatcher(new MockServerLogger(), NottableString.not("not_value"), false).matches("some_value")); } @Test public void shouldMatchUnMatchingNottedMatcherAndNottedString() { assertFalse(new RegexStringMatcher(new MockServerLogger(), NottableString.not("not_matcher"), false).matches(null, NottableString.not("not_value"))); } @Test public void shouldNotMatchMatchingNottedString() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("some_value"), false).matches(null, NottableString.not("some_value"))); } @Test public void shouldNotMatchMatchingNottedMatcher() { assertFalse(new RegexStringMatcher(new MockServerLogger(), NottableString.not("some_value"), false).matches("some_value")); } @Test public void shouldNotMatchMatchingNottedMatcherAndNottedString() { assertTrue(new RegexStringMatcher(new MockServerLogger(), NottableString.not("some_value"), false).matches(null, NottableString.not("some_value"))); } @Test public void shouldNotMatchMatchingString() { assertFalse(notMatcher(new RegexStringMatcher(new MockServerLogger(), string("some_value"), true)).matches("some_value")); } @Test public void shouldMatchMatchingStringWithRegexSymbols() { assertTrue(new RegexStringMatcher(new MockServerLogger(), string("text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8")); } @Test public void shouldMatchMatchingRegex() { assertTrue(new RegexStringMatcher(new MockServerLogger(), string("some_[a-z]{5}"), false).matches("some_value")); } @Test public void shouldMatchNullExpectation() { assertTrue(new RegexStringMatcher(new MockServerLogger(), string(null), false).matches("some_value")); } @Test public void shouldMatchEmptyExpectation() { assertTrue(new RegexStringMatcher(new MockServerLogger(), string(""), false).matches("some_value")); } @Test public void shouldNotMatchIncorrectString() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("some_value"), false).matches("not_matching")); } @Test public void shouldMatchIncorrectString() { assertTrue(notMatcher(new RegexStringMatcher(new MockServerLogger(), string("some_value"), true)).matches("not_matching")); } @Test public void shouldNotMatchMatchingControlPlaneRegex() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("some_value"), false).matches("some_[a-z]{5}")); } @Test public void shouldNotMatchIncorrectStringWithRegexSymbols() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"), false).matches("text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8")); } @Test public void shouldNotMatchIncorrectRegex() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("some_[a-z]{4}"), false).matches("some_value")); } @Test public void shouldNotMatchNullTest() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("some_value"), false).matches(null, string(null))); } @Test public void shouldNotMatchEmptyTest() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("some_value"), false).matches("")); } @Test public void shouldHandleIllegalRegexPatternForExpectationAndTest() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("/{}"), false).matches("/{{}")); assertFalse(new RegexStringMatcher(new MockServerLogger(), string("/{}"), false).matches("some_value")); assertFalse(new RegexStringMatcher(new MockServerLogger(), string("some_value"), false).matches("/{}")); } @Test public void shouldHandleIllegalRegexPatternForExpectation() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("/{}"), false).matches("some_value")); } @Test public void shouldHandleIllegalRegexPatternForTest() { assertFalse(new RegexStringMatcher(new MockServerLogger(), string("some_value"), false).matches("/{}")); }
ConfigurationProperties { public static int maxWebSocketExpectations() { return readIntegerProperty(MOCKSERVER_MAX_WEB_SOCKET_EXPECTATIONS, "MOCKSERVER_MAX_WEB_SOCKET_EXPECTATIONS", DEFAULT_MAX_WEB_SOCKET_EXPECTATIONS); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadMaxWebSocketExpectations() { System.clearProperty("mockserver.maxWebSocketExpectations"); assertEquals(1500, maxWebSocketExpectations()); maxWebSocketExpectations(100); assertEquals("100", System.getProperty("mockserver.maxWebSocketExpectations")); assertEquals(100, maxWebSocketExpectations()); } @Test public void shouldHandleInvalidMaxWebSocketExpectations() { System.setProperty("mockserver.maxWebSocketExpectations", "invalid"); assertEquals(1500, maxWebSocketExpectations()); }
JsonSchemaMatcher extends BodyMatcher<String> { public boolean matches(final MatchDifference context, String matched) { boolean result = false; if (matcher.equalsIgnoreCase(matched)) { result = true; } else if (!StringUtils.isBlank(matched)) { try { String validation = jsonSchemaValidator.isValid(matched, false); result = validation.isEmpty(); if (!result && context != null) { context.addDifference(mockServerLogger, "json schema match failed expected:{}found:{}failed because:{}", this.matcher, matched, validation); } } catch (Throwable throwable) { if (context != null) { context.addDifference(mockServerLogger, throwable, "json schema match failed expected:{}found:{}failed because:{}", this.matcher, matched, throwable.getMessage()); } } } return not != result; } JsonSchemaMatcher(MockServerLogger mockServerLogger, String matcher); Map<String, ParameterStyle> getParameterStyle(); JsonSchemaMatcher withParameterStyle(Map<String, ParameterStyle> parameterStyle); boolean matches(final MatchDifference context, String matched); boolean isBlank(); }
@Test public void shouldMatchJson() { String json = "some_json"; when(mockJsonSchemaValidator.isValid(json, false)).thenReturn(""); assertTrue(jsonSchemaMatcher.matches(null, json)); } @Test public void shouldNotMatchJson() { Level originalLevel = logLevel(); try { logLevel("TRACE"); String json = "some_json"; when(mockJsonSchemaValidator.isValid(json, false)).thenReturn("validator_error"); assertFalse(jsonSchemaMatcher.matches(new MatchDifference(request()), json)); verify(logger).trace("json schema match failed expected:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"enumField\": {" + NEW_LINE + " \"enum\": [ \"one\", \"two\" ]" + NEW_LINE + " }," + NEW_LINE + " \"arrayField\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }," + NEW_LINE + " \"stringField\": {" + NEW_LINE + " \"type\": \"string\"," + NEW_LINE + " \"minLength\": 5," + NEW_LINE + " \"maxLength\": 6" + NEW_LINE + " }," + NEW_LINE + " \"booleanField\": {" + NEW_LINE + " \"type\": \"boolean\"" + NEW_LINE + " }," + NEW_LINE + " \"objectField\": {" + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"stringField\": {" + NEW_LINE + " \"type\": \"string\"," + NEW_LINE + " \"minLength\": 1," + NEW_LINE + " \"maxLength\": 3" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [ \"stringField\" ]" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"additionalProperties\" : false," + NEW_LINE + " \"required\": [ \"enumField\", \"arrayField\" ]" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " some_json" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " validator_error" + NEW_LINE, (Throwable) null); } finally { logLevel(originalLevel.toString()); } } @Test public void shouldHandleExpection() { Level originalLevel = logLevel(); try { logLevel("TRACE"); String json = "some_json"; RuntimeException test_exception = new RuntimeException("TEST_EXCEPTION"); when(mockJsonSchemaValidator.isValid(json, false)).thenThrow(test_exception); assertFalse(jsonSchemaMatcher.matches(new MatchDifference(request()), json)); verify(logger).trace("json schema match failed expected:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"enumField\": {" + NEW_LINE + " \"enum\": [ \"one\", \"two\" ]" + NEW_LINE + " }," + NEW_LINE + " \"arrayField\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }," + NEW_LINE + " \"stringField\": {" + NEW_LINE + " \"type\": \"string\"," + NEW_LINE + " \"minLength\": 5," + NEW_LINE + " \"maxLength\": 6" + NEW_LINE + " }," + NEW_LINE + " \"booleanField\": {" + NEW_LINE + " \"type\": \"boolean\"" + NEW_LINE + " }," + NEW_LINE + " \"objectField\": {" + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"stringField\": {" + NEW_LINE + " \"type\": \"string\"," + NEW_LINE + " \"minLength\": 1," + NEW_LINE + " \"maxLength\": 3" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [ \"stringField\" ]" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"additionalProperties\" : false," + NEW_LINE + " \"required\": [ \"enumField\", \"arrayField\" ]" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " found:" + NEW_LINE + NEW_LINE + " some_json" + NEW_LINE + NEW_LINE + " failed because:" + NEW_LINE + NEW_LINE + " TEST_EXCEPTION" + NEW_LINE, test_exception); } finally { logLevel(originalLevel.toString()); } }
ConfigurationProperties { public static int maxInitialLineLength() { return maxInitialLineLength; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadMaxInitialLineLength() { System.clearProperty("mockserver.maxInitialLineLength"); assertEquals(Integer.MAX_VALUE, maxInitialLineLength()); maxInitialLineLength(100); assertEquals("100", System.getProperty("mockserver.maxInitialLineLength")); assertEquals(100, maxInitialLineLength()); } @Test public void shouldHandleInvalidMaxInitialLineLength() { System.setProperty("mockserver.maxInitialLineLength", "invalid"); assertEquals(Integer.MAX_VALUE, maxInitialLineLength()); }
ParameterStringMatcher extends BodyMatcher<String> { public boolean matches(final MatchDifference context, String matched) { boolean result = false; Parameters matchedParameters = formParameterParser.retrieveFormParameters(matched, matched != null && matched.contains("?")); expandedParameterDecoder.splitParameters(matcherParameters, matchedParameters); if (matcher.matches(context, matchedParameters)) { result = true; } return not != result; } ParameterStringMatcher(MockServerLogger mockServerLogger, Parameters matcherParameters, boolean controlPlaneMatcher); boolean matches(final MatchDifference context, String matched); boolean isBlank(); }
@Test public void shouldMatchMatchingString() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter("parameterTwoName", "parameterTwoValue") ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameter.*", "parameter.*") ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); } @Test public void shouldNotMatchMatchingStringWhenNotApplied() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter("parameterTwoName", "parameterTwoValue") ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertFalse(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter("parameterTwoName", "parameterTwoValue") ), true)).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter(not("parameterTwoName"), not("parameterTwoValue")) ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameterOneName"), not("parameterOneValueOne"), not("parameterOneValueTwo")), new Parameter(not("parameterTwoName"), not("parameterTwoValue")) ), true).matches(null, "" + "notParameterOneName=parameterOneValueOne" + "&notParameterOneName=parameterOneValueTwo" + "&notParameterTwoName=parameterTwoValue")); assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameterOneName"), not("parameterOneValueOne"), not("parameterOneValueTwo")), new Parameter(not("parameterTwoName"), "parameterTwoValue") ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertTrue(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter(not("parameterTwoName"), not("parameterTwoValue")) ), true)).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); } @Test public void shouldMatchMatchingStringWithNotParameterAndNormalParameter() { assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter(not("parameterTwoName"), not("parameterTwoValue")) ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter(not("parameterThree"), not("parameterThreeValueOne")) ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameterThree"), not("parameterThreeValueOne")) ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameterOne"), not("parameterOneValueOne")), new Parameter(not("parameterTwo"), not("parameterTwoValueOne")) ), true).matches(null, "" + "notParameterOne=notParameterOneValueOne" + "&notParameterTwo=notParameterTwoValueOne")); assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameter.*"), not(".*")) ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameter.*"), not("parameter.*")) ), true).matches(null, "" + "notParameterOneName=parameterOneValueOne" + "&notParameterOneName=parameterOneValueTwo" + "&notParameterTwoName=parameterTwoValue")); assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameter.*"), not("parameter.*")) ), true).matches(null, "" + "parameterOneName=notParameterOneValueOne" + "&parameterOneName=notParameterOneValueTwo" + "&parameterTwoName=notParameterTwoValue")); } @Test public void shouldMatchMatchingStringWithOnlyParameter() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameterThree"), not("parameterThreeValueOne")) ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterThree", "parameterThreeValueOne") ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameterOneName"), not("parameterOneValueOne"), not("parameterOneValueTwo")) ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo") ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); } @Test public void shouldMatchMatchingStringWithOnlyParameterForEmptyBody() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters(), true).matches(null, "parameterThree=parameterThreeValueOne")); assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterThree", "parameterThreeValueOne") ), true).matches(null, "")); assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameterThree"), not("parameterThreeValueOne")) ), true).matches(null, "")); } @Test public void shouldNotMatchMatchingStringWithNotParameterAndNormalParameter() { assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter(not("parameterTwoName"), not("parameterTwoValue"))), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); } @Test public void shouldMatchMatchingStringWithOnlyNotParameter() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameterTwoName"), not("parameterTwoValue"))), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&notParameterTwoName=parameterTwoValue")); } @Test public void shouldNotMatchMatchingStringWithOnlyNotParameterForBodyWithSingleParameter() { assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter(not("parameterTwoName"), not("parameterTwoValue"))), true).matches(null, "" + "parameterTwoName=parameterTwoValue")); } @Test public void shouldMatchNullExpectation() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), null, true).matches(null, "some_value")); } @Test public void shouldNotMatchNullExpectationWhenNotApplied() { assertFalse(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), null, true)).matches(null, "some_value")); } @Test public void shouldMatchEmptyExpectation() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters(), true).matches(null, "some_value")); } @Test public void shouldNotMatchEmptyExpectationWhenNotApplied() { assertFalse(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters(), true)).matches(null, "some_value")); } @Test public void shouldNotMatchIncorrectParameterName() { assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter("parameterTwoName", "parameterTwoValue") ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&INCORRECTParameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); } @Test public void shouldMatchIncorrectParameterNameWhenNotApplied() { assertTrue(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter("parameterTwoName", "parameterTwoValue") ), true)).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&INCORRECTParameterOneName=parameterOneValueTwo" + "&parameterTwoName=parameterTwoValue")); } @Test public void shouldNotMatchIncorrectParameterValue() { assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter("parameterTwoName", "parameterTwoValue") ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=INCORRECTParameterTwoValue")); } @Test public void shouldMatchIncorrectParameterValueWhenNotApplied() { assertTrue(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter("parameterTwoName", "parameterTwoValue") ), true)).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&parameterTwoName=INCORRECTParameterTwoValue")); } @Test public void shouldNotMatchIncorrectParameterNameAndValue() { assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter("parameterTwoName", "parameterTwoValue") ), true).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&INCORRECTParameterTwoName=INCORRECTParameterTwoValue")); } @Test public void shouldMatchIncorrectParameterNameAndValueWhenNotApplied() { assertTrue(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterOneValueOne", "parameterOneValueTwo"), new Parameter("parameterTwoName", "parameterTwoValue") ), true)).matches(null, "" + "parameterOneName=parameterOneValueOne" + "&parameterOneName=parameterOneValueTwo" + "&INCORRECTParameterTwoName=INCORRECTParameterTwoValue")); } @Test public void shouldNotMatchNullParameterValue() { assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterValueOne"), new Parameter("parameterTwoName", "parameterTwoValue") ), false).matches(null, "" + "parameterOneName=parameterValueOne" + "&parameterTwoName=")); } @Test public void shouldNotMatchNullParameterValueForControlPlane() { assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterValueOne"), new Parameter("parameterTwoName", "parameterTwoValue") ), true).matches(null, "" + "parameterOneName=parameterValueOne" + "&parameterTwoName=")); } @Test public void shouldMatchNullParameterValueWhenNotApplied() { assertTrue(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterValueOne"), new Parameter("parameterTwoName", "parameterTwoValue") ), true)).matches(null, "" + "parameterOneName=parameterValueOne" + "&parameterTwoName=")); } @Test public void shouldMatchNullParameterValueInExpectation() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterValueOne"), new Parameter("parameterTwoName", "") ), true).matches(null, "" + "parameterOneName=parameterValueOne" + "&parameterTwoName=parameterTwoValue")); } @Test public void shouldNotMatchMissingParameter() { assertFalse(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterValueOne"), new Parameter("parameterTwoName", "parameterTwoValue") ), true).matches(null, "" + "parameterOneName=parameterValueOne")); } @Test public void shouldMatchMissingParameterWhenNotApplied() { assertTrue(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters( new Parameter("parameterOneName", "parameterValueOne"), new Parameter("parameterTwoName", "parameterTwoValue") ), true)).matches(null, "" + "parameterOneName=parameterValueOne")); } @Test public void shouldMatchNullTest() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters(), true).matches(null, null)); } @Test public void shouldNotMatchNullTestWhenNotApplied() { assertFalse(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters(), true)).matches(null, null)); } @Test public void shouldMatchEmptyTest() { assertTrue(new ParameterStringMatcher(new MockServerLogger(), new Parameters(), true).matches(null, "")); } @Test public void shouldNotMatchEmptyTestWhenNotApplied() { assertFalse(NotMatcher.notMatcher(new ParameterStringMatcher(new MockServerLogger(), new Parameters(), true)).matches(null, "")); }
ConfigurationProperties { public static int maxHeaderSize() { return maxHeaderSize; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadMaxHeaderSize() { System.clearProperty("mockserver.maxHeaderSize"); assertEquals(Integer.MAX_VALUE, maxHeaderSize()); maxHeaderSize(100); assertEquals("100", System.getProperty("mockserver.maxHeaderSize")); assertEquals(100, maxHeaderSize()); } @Test public void shouldHandleInvalidMaxHeaderSize() { System.setProperty("mockserver.maxHeaderSize", "invalid"); assertEquals(Integer.MAX_VALUE, maxHeaderSize()); }
HttpRequestPropertiesMatcher extends AbstractHttpRequestMatcher { public boolean matches(final MatchDifference matchDifference, final RequestDefinition requestDefinition) { if (requestDefinition instanceof HttpRequest) { HttpRequest request = (HttpRequest) requestDefinition; StringBuilder becauseBuilder = new StringBuilder(); boolean overallMatch = matches(matchDifference, request, becauseBuilder); if (!controlPlaneMatcher) { if (overallMatch) { if (MockServerLogger.isEnabled(Level.INFO)) { mockServerLogger.logEvent( new LogEntry() .setType(EXPECTATION_MATCHED) .setLogLevel(Level.INFO) .setCorrelationId(requestDefinition.getLogCorrelationId()) .setHttpRequest(request) .setExpectation(this.expectation) .setMessageFormat(this.expectation == null ? REQUEST_DID_MATCH : EXPECTATION_DID_MATCH) .setArguments(request, (this.expectation == null ? this : this.expectation.clone())) ); } } else { becauseBuilder.replace(0, 1, ""); String because = becauseBuilder.toString(); if (MockServerLogger.isEnabled(Level.INFO)) { mockServerLogger.logEvent( new LogEntry() .setType(EXPECTATION_NOT_MATCHED) .setLogLevel(Level.INFO) .setCorrelationId(requestDefinition.getLogCorrelationId()) .setHttpRequest(request) .setExpectation(this.expectation) .setMessageFormat(this.expectation == null ? didNotMatchRequestBecause : becauseBuilder.length() > 0 ? didNotMatchExpectationBecause : didNotMatchExpectationWithoutBecause) .setArguments(request, (this.expectation == null ? this : this.expectation.clone()), because) .setBecause(because) ); } } } return overallMatch; } else if (requestDefinition instanceof OpenAPIDefinition) { if (matcherBuilder == null) { matcherBuilder = new MatcherBuilder(mockServerLogger); } boolean overallMatch = false; for (HttpRequest request : matcherBuilder.transformsToMatcher(requestDefinition).getHttpRequests()) { if (matches(request.cloneWithLogCorrelationId())) { overallMatch = true; break; } } return overallMatch; } else { return requestDefinition == null; } } HttpRequestPropertiesMatcher(MockServerLogger mockServerLogger); HttpRequest getHttpRequest(); @Override List<HttpRequest> getHttpRequests(); @Override boolean apply(RequestDefinition requestDefinition); HttpRequestPropertiesMatcher withControlPlaneMatcher(boolean controlPlaneMatcher); boolean matches(final MatchDifference matchDifference, final RequestDefinition requestDefinition); @Override String toString(); @Override @JsonIgnore String[] fieldsExcludedFromEqualsAndHashCode(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void shouldMatchSsl() { assertTrue(update(new HttpRequest().withSecure(true)).matches(null, new HttpRequest().withSecure(true))); assertTrue(update(new HttpRequest().withSecure(false)).matches(null, new HttpRequest().withSecure(false))); assertTrue(update(new HttpRequest().withSecure(null)).matches(null, new HttpRequest().withSecure(null))); assertTrue(update(new HttpRequest().withSecure(null)).matches(null, new HttpRequest().withSecure(false))); assertTrue(update(new HttpRequest().withSecure(null)).matches(null, new HttpRequest())); assertTrue(update(new HttpRequest()).matches(null, new HttpRequest().withSecure(null))); } @Test public void shouldNotMatchSsl() { assertFalse(update(new HttpRequest().withSecure(true)).matches(null, new HttpRequest().withSecure(false))); assertFalse(update(new HttpRequest().withSecure(false)).matches(null, new HttpRequest().withSecure(true))); assertFalse(update(new HttpRequest().withSecure(true)).matches(null, new HttpRequest().withSecure(null))); assertFalse(update(new HttpRequest().withSecure(false)).matches(null, new HttpRequest().withSecure(null))); } @Test public void shouldMatchSslForControlPlane() { assertTrue(updateForControlPlane(new HttpRequest().withSecure(true)).matches(null, new HttpRequest().withSecure(true))); assertTrue(updateForControlPlane(new HttpRequest().withSecure(false)).matches(null, new HttpRequest().withSecure(false))); assertTrue(updateForControlPlane(new HttpRequest().withSecure(null)).matches(null, new HttpRequest().withSecure(null))); assertTrue(updateForControlPlane(new HttpRequest().withSecure(null)).matches(null, new HttpRequest().withSecure(false))); assertTrue(updateForControlPlane(new HttpRequest().withSecure(null)).matches(null, new HttpRequest())); assertTrue(updateForControlPlane(new HttpRequest()).matches(null, new HttpRequest().withSecure(null))); } @Test public void shouldNotMatchSslForControlPlane() { assertFalse(updateForControlPlane(new HttpRequest().withSecure(true)).matches(null, new HttpRequest().withSecure(false))); assertFalse(updateForControlPlane(new HttpRequest().withSecure(false)).matches(null, new HttpRequest().withSecure(true))); assertFalse(updateForControlPlane(new HttpRequest().withSecure(true)).matches(null, new HttpRequest().withSecure(null))); assertFalse(updateForControlPlane(new HttpRequest().withSecure(false)).matches(null, new HttpRequest().withSecure(null))); }
JsonStringMatcher extends BodyMatcher<String> { public boolean matches(final MatchDifference context, String matched) { boolean result = false; try { if (StringUtils.isBlank(matcher)) { result = true; } else { Options options = Options.empty(); switch (matchType) { case STRICT: break; case ONLY_MATCHING_FIELDS: options = options.with( IGNORING_ARRAY_ORDER, IGNORING_EXTRA_ARRAY_ITEMS, IGNORING_EXTRA_FIELDS ); break; } final Difference diffListener = new Difference(); Configuration diffConfig = Configuration.empty().withDifferenceListener(diffListener).withOptions(options); try { if (matcherJsonNode == null) { matcherJsonNode = ObjectMapperFactory.createObjectMapper().readTree(matcher); } result = Diff .create( matcherJsonNode, ObjectMapperFactory.createObjectMapper().readTree(matched), "", "", diffConfig ) .similar(); } catch (Throwable throwable) { if (context != null) { context.addDifference(mockServerLogger, throwable, "exception while perform json match failed expected:{}found:{}", this.matcher, matched); } } if (!result) { if (context != null) { if (diffListener.differences.isEmpty()) { context.addDifference(mockServerLogger, "json match failed expected:{}found:{}", this.matcher, matched); } else { context.addDifference(mockServerLogger, "json match failed expected:{}found:{}failed because:{}", this.matcher, matched, Joiner.on("," + NEW_LINE).join(diffListener.differences)); } } } } } catch (Throwable throwable) { if (context != null) { context.addDifference(mockServerLogger, throwable, "json match failed expected:{}found:{}failed because:{}", this.matcher, matched, throwable.getMessage()); } } return not != result; } JsonStringMatcher(MockServerLogger mockServerLogger, String matcher, MatchType matchType); boolean matches(final MatchDifference context, String matched); boolean isBlank(); }
@Test public void shouldMatchExactMatchingJson() { String matched = "" + "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertTrue(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); } @Test public void shouldMatchExactMatchingJsonWithPlaceholder() { String matched = "" + "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"optional\": true," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertTrue(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"optional\": \"${json-unit.any-boolean}\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"${json-unit.ignore-element}\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); } @Test public void shouldNotMatchExactMatchingJson() { String matched = "" + "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertFalse(notMatcher(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)).matches(null, matched)); } @Test public void shouldMatchMatchingSubJson() { String matched = "" + "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertTrue(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); assertTrue(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); } @Test public void shouldMatchMatchingSubJsonWithSomeSubJsonFields() { String matched = "" + "{" + NEW_LINE + " \"glossary\": {" + NEW_LINE + " \"title\": \"example glossary\"," + NEW_LINE + " \"GlossDiv\": {" + NEW_LINE + " \"title\": \"S\"," + NEW_LINE + " \"GlossList\": {" + NEW_LINE + " \"GlossEntry\": {" + NEW_LINE + " \"ID\": \"SGML\"," + NEW_LINE + " \"SortAs\": \"SGML\"," + NEW_LINE + " \"GlossTerm\": \"Standard Generalized Markup Language\"," + NEW_LINE + " \"Acronym\": \"SGML\"," + NEW_LINE + " \"Abbrev\": \"ISO 8879:1986\"," + NEW_LINE + " \"GlossDef\": {" + NEW_LINE + " \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\"," + NEW_LINE + " \"GlossSeeAlso\": [" + NEW_LINE + " \"GML\"," + NEW_LINE + " \"XML\"" + NEW_LINE + " ]" + NEW_LINE + " }, " + NEW_LINE + " \"GlossSee\": \"markup\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertTrue(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"glossary\": {" + NEW_LINE + " \"GlossDiv\": {" + NEW_LINE + " \"title\": \"S\"," + NEW_LINE + " \"GlossList\": {" + NEW_LINE + " \"GlossEntry\": {" + NEW_LINE + " \"ID\": \"SGML\"," + NEW_LINE + " \"Abbrev\": \"ISO 8879:1986\"," + NEW_LINE + " \"GlossDef\": {" + NEW_LINE + " \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\"" + NEW_LINE + " }, " + NEW_LINE + " \"GlossSee\": \"markup\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); } @Test public void shouldNotMatchNotMatchingSubJsonWithSomeSubJsonFields() { String matched = "" + "{" + NEW_LINE + " \"glossary\": {" + NEW_LINE + " \"title\": \"example glossary\"," + NEW_LINE + " \"GlossDiv\": {" + NEW_LINE + " \"title\": \"S\"," + NEW_LINE + " \"GlossList\": {" + NEW_LINE + " \"GlossEntry\": {" + NEW_LINE + " \"ID\": \"SGML\"," + NEW_LINE + " \"SortAs\": \"SGML\"," + NEW_LINE + " \"GlossTerm\": \"Standard Generalized Markup Language\"," + NEW_LINE + " \"Acronym\": \"SGML\"," + NEW_LINE + " \"Abbrev\": \"ISO 8879:1986\"," + NEW_LINE + " \"GlossDef\": {" + NEW_LINE + " \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\"," + NEW_LINE + " \"GlossSeeAlso\": [" + NEW_LINE + " \"GML\"," + NEW_LINE + " \"XML\"" + NEW_LINE + " ]" + NEW_LINE + " }, " + NEW_LINE + " \"GlossSee\": \"markup\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertFalse(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"glossary\": {" + NEW_LINE + " \"GlossDiv\": {" + NEW_LINE + " \"title\": \"S\"," + NEW_LINE + " \"GlossList\": {" + NEW_LINE + " \"GlossEntry\": {" + NEW_LINE + " \"ID\": \"SGML\"," + NEW_LINE + " \"Abbrev\": \"ISO 8879:1986\"," + NEW_LINE + " \"GlossDef\": {" + NEW_LINE + " \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\"" + NEW_LINE + " }, " + NEW_LINE + " \"GlossSee\": \"markup\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.STRICT).matches(null, matched)); } @Test public void shouldMatchNotMatchingSubJsonWithSomeSubJsonFields() { String matched = "" + "{" + NEW_LINE + " \"glossary\": {" + NEW_LINE + " \"title\": \"example glossary\"," + NEW_LINE + " \"GlossDiv\": {" + NEW_LINE + " \"title\": \"S\"," + NEW_LINE + " \"GlossList\": {" + NEW_LINE + " \"GlossEntry\": {" + NEW_LINE + " \"ID\": \"SGML\"," + NEW_LINE + " \"SortAs\": \"SGML\"," + NEW_LINE + " \"GlossTerm\": \"Standard Generalized Markup Language\"," + NEW_LINE + " \"Acronym\": \"SGML\"," + NEW_LINE + " \"Abbrev\": \"ISO 8879:1986\"," + NEW_LINE + " \"GlossDef\": {" + NEW_LINE + " \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\"," + NEW_LINE + " \"GlossSeeAlso\": [" + NEW_LINE + " \"GML\"," + NEW_LINE + " \"XML\"" + NEW_LINE + " ]" + NEW_LINE + " }, " + NEW_LINE + " \"GlossSee\": \"markup\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertTrue(notMatcher(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"glossary\": {" + NEW_LINE + " \"GlossDiv\": {" + NEW_LINE + " \"title\": \"S\"," + NEW_LINE + " \"GlossList\": {" + NEW_LINE + " \"GlossEntry\": {" + NEW_LINE + " \"ID\": \"SGML\"," + NEW_LINE + " \"Abbrev\": \"ISO 8879:1986\"," + NEW_LINE + " \"GlossDef\": {" + NEW_LINE + " \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\"" + NEW_LINE + " }, " + NEW_LINE + " \"GlossSee\": \"markup\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.STRICT)).matches(null, matched)); } @Test public void shouldMatchMatchingSubJsonWithDifferentArrayOrder() { String matched = "" + "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertTrue(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); assertTrue(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); } @Test public void shouldNotMatchMatchingSubJsonWithDifferentArrayOrder() { String matched = "" + "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertFalse(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.STRICT).matches(null, matched)); assertFalse(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.STRICT).matches(null, matched)); } @Test public void shouldNotMatchIllegalJson() { assertFalse(new JsonStringMatcher(new MockServerLogger(), "illegal_json", MatchType.ONLY_MATCHING_FIELDS).matches(null, "illegal_json")); assertFalse(new JsonStringMatcher(new MockServerLogger(), "illegal_json", MatchType.ONLY_MATCHING_FIELDS).matches(null, "some_other_illegal_json")); } @Test public void shouldNotMatchNullExpectation() { assertTrue(new JsonStringMatcher(new MockServerLogger(), null, MatchType.ONLY_MATCHING_FIELDS).matches(null, "some_value")); } @Test public void shouldNotMatchEmptyExpectation() { assertTrue(new JsonStringMatcher(new MockServerLogger(), "", MatchType.ONLY_MATCHING_FIELDS).matches(null, "some_value")); } @Test public void shouldNotMatchNonMatchingJson() { String matched = "" + "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertFalse(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"wrong_value\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); } @Test public void shouldMatchJsonForIncorrectArrayOrder() { String matched = "{id:1,pets:[\"dog\",\"cat\",\"fish\"]}"; assertTrue(new JsonStringMatcher(new MockServerLogger(), "{id:1,pets:[\"cat\",\"dog\",\"fish\"]}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); } @Test public void shouldNotMatchJsonForIncorrectArrayOrder() { String matched = "{id:1,pets:[\"dog\",\"cat\",\"fish\"]}"; assertFalse(new JsonStringMatcher(new MockServerLogger(), "{id:1,pets:[\"cat\",\"dog\",\"fish\"]}", MatchType.STRICT).matches(null, matched)); } @Test public void shouldMatchJsonForExtraField() { String matched = "{id:1,pets:[\"dog\",\"cat\",\"fish\"],extraField:\"extraValue\"}"; assertTrue(new JsonStringMatcher(new MockServerLogger(), "{id:1,pets:[\"dog\",\"cat\",\"fish\"]}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); } @Test public void shouldNotMatchJsonForExtraField() { String matched = "{id:1,pets:[\"dog\",\"cat\",\"fish\"],extraField:\"extraValue\"}"; assertFalse(new JsonStringMatcher(new MockServerLogger(), "{id:1,pets:[\"dog\",\"cat\",\"fish\"]}", MatchType.STRICT).matches(null, matched)); } @Test public void shouldNotMatchNonMatchingSubJson() { String matched = "" + "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"File\"," + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"; assertFalse(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"id\": \"file\"," + NEW_LINE + " \"value\": \"other_value\"" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); assertFalse(new JsonStringMatcher(new MockServerLogger(), "{" + NEW_LINE + " \"menu\": {" + NEW_LINE + " \"popup\": {" + NEW_LINE + " \"menuitem\": [" + NEW_LINE + " {" + NEW_LINE + " \"value\": \"New\"," + NEW_LINE + " \"onclick\": \"CreateNewDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Open\"," + NEW_LINE + " \"onclick\": \"OpenDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"value\": \"Close\"," + NEW_LINE + " \"onclick\": \"CloseDoc()\"" + NEW_LINE + " }" + NEW_LINE + " ]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS).matches(null, matched)); } @Test public void shouldNotMatchNullTest() { assertFalse(new JsonStringMatcher(new MockServerLogger(), "some_value", MatchType.ONLY_MATCHING_FIELDS).matches(null, null)); } @Test public void shouldNotMatchEmptyTest() { assertFalse(new JsonStringMatcher(new MockServerLogger(), "some_value", MatchType.ONLY_MATCHING_FIELDS).matches(null, "")); } @Test public void shouldMatchBasicValues() { assertTrue(new JsonStringMatcher(new MockServerLogger(), "null", MatchType.ONLY_MATCHING_FIELDS).matches(null, "null")); assertTrue(new JsonStringMatcher(new MockServerLogger(), "1", MatchType.ONLY_MATCHING_FIELDS).matches(null, "1")); assertTrue(new JsonStringMatcher(new MockServerLogger(), "true", MatchType.ONLY_MATCHING_FIELDS).matches(null, "true")); }
ConfigurationProperties { public static int maxChunkSize() { return maxChunkSize; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadMaxChunkSize() { System.clearProperty("mockserver.maxChunkSize"); assertEquals(Integer.MAX_VALUE, maxChunkSize()); maxChunkSize(100); assertEquals("100", System.getProperty("mockserver.maxChunkSize")); assertEquals(100, maxChunkSize()); } @Test public void shouldHandleInvalidMaxChunkSize() { System.setProperty("mockserver.maxChunkSize", "invalid"); assertEquals(Integer.MAX_VALUE, maxChunkSize()); }
MatcherBuilder { public HttpRequestMatcher transformsToMatcher(RequestDefinition requestDefinition) { HttpRequestMatcher httpRequestMatcher = requestMatcherLRUCache.get(requestDefinition); if (httpRequestMatcher == null) { if (requestDefinition instanceof OpenAPIDefinition) { httpRequestMatcher = new HttpRequestsPropertiesMatcher(mockServerLogger); } else { httpRequestMatcher = new HttpRequestPropertiesMatcher(mockServerLogger); } httpRequestMatcher.update(requestDefinition); requestMatcherLRUCache.put(requestDefinition, httpRequestMatcher); } return httpRequestMatcher; } MatcherBuilder(MockServerLogger mockServerLogger); HttpRequestMatcher transformsToMatcher(RequestDefinition requestDefinition); HttpRequestMatcher transformsToMatcher(Expectation expectation); }
@Test public void shouldCreateMatcherThatMatchesAllFields() { HttpRequestMatcher httpRequestMapper = new MatcherBuilder(mockServerLogger).transformsToMatcher(new Expectation(httpRequest)); assertTrue(httpRequestMapper.matches(null, httpRequest)); } @Test public void shouldSupportSpecialCharactersWhenCharsetSpecified() { String bodyTestString = "UTF_8 characters: Bj\u00F6rk"; FullHttpRequestToMockServerHttpRequest fullHttpRequestToMockServerRequest = new FullHttpRequestToMockServerHttpRequest(mockServerLogger, false, null); FullHttpRequest fullHttpRequest = new DefaultFullHttpRequest( HTTP_1_1, GET, "/uri", wrappedBuffer(bodyTestString.getBytes(DEFAULT_HTTP_CHARACTER_SET))); fullHttpRequest.headers().add(CONTENT_TYPE, PLAIN_TEXT_UTF_8.withCharset(DEFAULT_HTTP_CHARACTER_SET).toString()); HttpRequest httpRequest = fullHttpRequestToMockServerRequest.mapFullHttpRequestToMockServerRequest(fullHttpRequest); HttpRequestMatcher httpRequestMapper = new MatcherBuilder(new MockServerLogger()).transformsToMatcher(new Expectation( new HttpRequest() .withMethod(GET.name()) .withPath("/uri") .withBody(new StringBody(bodyTestString)) )); assertThat(httpRequest.getBody().getCharset(null), is(DEFAULT_HTTP_CHARACTER_SET)); assertTrue(httpRequestMapper.matches(null, httpRequest)); } @Test public void shouldSupportSpecialCharactersWithDefaultCharset() { String bodyTestString = "UTF_8 characters: Bj\u00F6rk"; FullHttpRequestToMockServerHttpRequest fullHttpRequestToMockServerRequest = new FullHttpRequestToMockServerHttpRequest(mockServerLogger, false, null); FullHttpRequest fullHttpRequest = new DefaultFullHttpRequest( HTTP_1_1, GET, "/uri", wrappedBuffer(bodyTestString.getBytes(DEFAULT_HTTP_CHARACTER_SET)) ); HttpRequest httpRequest = fullHttpRequestToMockServerRequest.mapFullHttpRequestToMockServerRequest(fullHttpRequest); HttpRequestMatcher httpRequestMapper = new MatcherBuilder(new MockServerLogger()).transformsToMatcher(new Expectation( new HttpRequest() .withMethod(GET.name()) .withPath("/uri") .withBody(new StringBody(bodyTestString)) )); assertNull(httpRequest.getBody().getCharset(null)); assertTrue(httpRequestMapper.matches(null, httpRequest)); } @Test public void shouldCreateMatcherThatIgnoresMethod() { HttpRequestMatcher httpRequestMapper = new MatcherBuilder(mockServerLogger).transformsToMatcher(new Expectation( new HttpRequest() .withMethod("") .withPath("some_path") .withQueryStringParameter(new Parameter("queryStringParameterName", "queryStringParameterValue")) .withBody(new StringBody("some_body")) .withHeaders(new Header("name", "value")) .withCookies(new Cookie("name", "value")) )); assertTrue(httpRequestMapper.matches(null, httpRequest)); } @Test public void shouldCreateMatcherThatIgnoresPath() { HttpRequestMatcher httpRequestMapper = new MatcherBuilder(mockServerLogger).transformsToMatcher(new Expectation( new HttpRequest() .withMethod("GET") .withPath("") .withQueryStringParameter(new Parameter("queryStringParameterName", "queryStringParameterValue")) .withBody(new StringBody("some_body")) .withHeaders(new Header("name", "value")) .withCookies(new Cookie("name", "value")) )); assertTrue(httpRequestMapper.matches(null, httpRequest)); } @Test public void shouldCreateMatcherThatIgnoresQueryString() { HttpRequestMatcher httpRequestMapper = new MatcherBuilder(mockServerLogger).transformsToMatcher(new Expectation( new HttpRequest() .withMethod("GET") .withPath("some_path") .withQueryStringParameters() .withBody(new StringBody("some_body")) .withHeaders(new Header("name", "value")) .withCookies(new Cookie("name", "value")) )); assertTrue(httpRequestMapper.matches(null, httpRequest)); } @Test public void shouldCreateMatcherThatIgnoresBodyParameters() { HttpRequestMatcher httpRequestMapper = new MatcherBuilder(mockServerLogger).transformsToMatcher(new Expectation( new HttpRequest() .withMethod("GET") .withPath("some_path") .withQueryStringParameter(new Parameter("queryStringParameterName", "queryStringParameterValue")) .withBody(new ParameterBody()) .withHeaders(new Header("name", "value")) .withCookies(new Cookie("name", "value")) )); assertTrue(httpRequestMapper.matches(null, httpRequest)); } @Test public void shouldCreateMatcherThatIgnoresBody() { HttpRequestMatcher httpRequestMapper = new MatcherBuilder(mockServerLogger).transformsToMatcher(new Expectation( new HttpRequest() .withMethod("GET") .withPath("some_path") .withQueryStringParameter(new Parameter("queryStringParameterName", "queryStringParameterValue")) .withBody(new StringBody("")) .withHeaders(new Header("name", "value")) .withCookies(new Cookie("name", "value")) )); assertTrue(httpRequestMapper.matches(null, httpRequest)); } @Test public void shouldCreateMatcherThatIgnoresHeaders() { HttpRequestMatcher httpRequestMapper = new MatcherBuilder(mockServerLogger).transformsToMatcher(new Expectation( new HttpRequest() .withMethod("GET") .withPath("some_path") .withQueryStringParameter(new Parameter("queryStringParameterName", "queryStringParameterValue")) .withBody(new StringBody("some_body")) .withHeaders() .withCookies(new Cookie("name", "value")) )); assertTrue(httpRequestMapper.matches(null, httpRequest)); } @Test public void shouldCreateMatcherThatIgnoresCookies() { HttpRequestMatcher httpRequestMapper = new MatcherBuilder(mockServerLogger).transformsToMatcher(new Expectation( new HttpRequest() .withMethod("GET") .withPath("some_path") .withQueryStringParameter(new Parameter("queryStringParameterName", "queryStringParameterValue")) .withBody(new StringBody("some_body")) .withHeaders(new Header("name", "value")) .withCookies() )); assertTrue(httpRequestMapper.matches(null, httpRequest)); }
ConfigurationProperties { public static long maxSocketTimeout() { return readLongProperty(MOCKSERVER_MAX_SOCKET_TIMEOUT, "MOCKSERVER_MAX_SOCKET_TIMEOUT", TimeUnit.SECONDS.toMillis(DEFAULT_MAX_TIMEOUT)); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadMaxSocketTimeout() { System.clearProperty("mockserver.maxSocketTimeout"); assertEquals(TimeUnit.SECONDS.toMillis(20), maxSocketTimeout()); maxSocketTimeout(100); assertEquals("100", System.getProperty("mockserver.maxSocketTimeout")); assertEquals(100, maxSocketTimeout()); } @Test public void shouldHandleInvalidMaxSocketTimeout() { System.setProperty("mockserver.maxSocketTimeout", "invalid"); assertEquals(TimeUnit.SECONDS.toMillis(20), maxSocketTimeout()); }
HashMapMatcher extends NotMatcher<KeysAndValues<? extends KeyAndValue, ? extends KeysAndValues>> { public boolean matches(final MatchDifference context, KeysAndValues<? extends KeyAndValue, ? extends KeysAndValues> matched) { boolean result; if (matcher == null || matcher.isEmpty()) { result = true; } else if (matched == null || matched.isEmpty()) { if (allKeysNotted == null) { allKeysNotted = matcher.allKeysNotted(); } if (allKeysOptional == null) { allKeysOptional = matcher.allKeysOptional(); } result = allKeysNotted || allKeysOptional; } else { result = new NottableStringHashMap(mockServerLogger, controlPlaneMatcher, matched.getEntries()).containsAll(matcher); } if (!result && context != null) { context.addDifference(mockServerLogger, "map subset match failed expected:{}found:{}failed because:{}", keysAndValues, matched != null ? matched : "none", matched != null ? "map is not a subset" : "none is not a subset"); } return not != result; } HashMapMatcher(MockServerLogger mockServerLogger, KeysAndValues<? extends KeyAndValue, ? extends KeysAndValues> keysAndValues, boolean controlPlaneMatcher); boolean matches(final MatchDifference context, KeysAndValues<? extends KeyAndValue, ? extends KeysAndValues> matched); boolean isBlank(); }
@Test public void shouldMatchSingleKeyAndValueForEmptyListMatcher() { HashMapMatcher hashMapMatcher = new HashMapMatcher(new MockServerLogger(), new Cookies(), true); assertThat(hashMapMatcher.matches(null, new Cookies().withEntries( new Cookie("keyOne", "keyOneValue") )), is(true)); } @Test public void shouldMatchMultipleKeyAndValueForEmptyListMatcher() { HashMapMatcher hashMapMatcher = new HashMapMatcher(new MockServerLogger(), new Cookies(), true); assertThat(hashMapMatcher.matches(null, new Cookies().withEntries( new Cookie("keyOne", "keyOneValue"), new Cookie("keyTwo", "keyTwoValue"), new Cookie("keyThree", "keyThreeValue") )), is(true)); } @Test public void shouldMatchEmptyKeyAndValueForMatcherWithOnlySingleNottedKey() { HashMapMatcher hashMapMatcher = new HashMapMatcher(new MockServerLogger(), new Cookies().withEntries( new Cookie(not("keyOne"), string("keyOneValue")) ), true); assertThat(hashMapMatcher.matches(null, new Cookies()), is(true)); } @Test public void shouldMatchEmptyKeyAndValueForMatcherWithOnlyMultipleNottedKeys() { HashMapMatcher hashMapMatcher = new HashMapMatcher(new MockServerLogger(), new Cookies().withEntries( new Cookie(not("keyOne"), string("keyOneValue")), new Cookie(not("keyTwo"), string("keyTwoValue")), new Cookie(not("keyThree"), string("keyThreeValue")) ), true); assertThat(hashMapMatcher.matches(null, new Cookies()), is(true)); } @Test public void shouldNotMatchEmptyKeyAndValueForMatcherWithOnlyAtLeastOneNotNottedKey() { HashMapMatcher hashMapMatcher = new HashMapMatcher(new MockServerLogger(), new Cookies().withEntries( new Cookie(not("keyOne"), string("keyOneValue")), new Cookie(not("keyTwo"), string("keyTwoValue")), new Cookie(string("keyThree"), string("keyThreeValue")) ), true); assertThat(hashMapMatcher.matches(null, new Cookies()), is(false)); } @Test public void shouldMatchSingleKeyAndValueForSingleItemMatcher() { HashMapMatcher hashMapMatcher = new HashMapMatcher(new MockServerLogger(), new Cookies().withEntries( new Cookie("keyOne", "keyOneValue") ), true); assertThat(hashMapMatcher.matches(null, new Cookies().withEntries( new Cookie("keyOne", "keyOneValue") )), is(true)); } @Test public void shouldMatchMultipleKeyAndValueForSingleItemMatcher() { HashMapMatcher hashMapMatcher = new HashMapMatcher(new MockServerLogger(), new Cookies().withEntries( new Cookie("keyOne", "keyOneValue") ), true); assertThat(hashMapMatcher.matches(null, new Cookies().withEntries( new Cookie("keyOne", "keyOneValue"), new Cookie("keyTwo", "keyTwoValue"), new Cookie("keyThree", "keyThreeValue") )), is(true)); } @Test public void shouldMatchMultipleKeyAndValueForMultiItemMatcherButSubSet() { HashMapMatcher hashMapMatcher = new HashMapMatcher(new MockServerLogger(), new Cookies().withEntries( new Cookie("keyOne", "keyOneValue"), new Cookie("keyTwo", "keyTwoValue") ), true); assertThat(hashMapMatcher.matches(null, new Cookies().withEntries( new Cookie("keyOne", "keyOneValue"), new Cookie("keyTwo", "keyTwoValue"), new Cookie("keyThree", "keyThreeValue") )), is(true)); } @Test public void shouldMatchMultipleKeyAndValueForMultiItemMatcherButExactMatch() { HashMapMatcher hashMapMatcher = new HashMapMatcher(new MockServerLogger(), new Cookies().withEntries( new Cookie("keyOne", "keyOneValue"), new Cookie("keyTwo", "keyTwoValue"), new Cookie("keyThree", "keyThreeValue") ), true); assertThat(hashMapMatcher.matches(null, new Cookies().withEntries( new Cookie("keyOne", "keyOneValue"), new Cookie("keyTwo", "keyTwoValue"), new Cookie("keyThree", "keyThreeValue") )), is(true)); }
ConfigurationProperties { public static long maxFutureTimeout() { return readLongProperty(MOCKSERVER_MAX_FUTURE_TIMEOUT, "DEFAULT_MAX_FUTURE_TIMEOUT", TimeUnit.SECONDS.toMillis(DEFAULT_MAX_FUTURE_TIMEOUT)); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadMaxFutureTimeout() { System.clearProperty("mockserver.maxFutureTimeout"); assertEquals(TimeUnit.SECONDS.toMillis(60), maxFutureTimeout()); maxFutureTimeout(100); assertEquals("100", System.getProperty("mockserver.maxFutureTimeout")); assertEquals(100, maxFutureTimeout()); }
XPathMatcher extends BodyMatcher<String> { public boolean matches(final MatchDifference context, final String matched) { boolean result = false; boolean alreadyLoggedMatchFailure = false; if (xpathExpression == null) { if (context != null) { context.addDifference(mockServerLogger, "xpath match failed expected:{}found:{}failed because:{}", "null", matched, "xpath matcher was null"); alreadyLoggedMatchFailure = true; } } else if (matcher.equals(matched)) { result = true; } else if (matched != null) { try { result = (Boolean) xpathExpression.evaluate(stringToXmlDocumentParser.buildDocument(matched, (matchedInException, throwable, level) -> { if (context != null) { context.addDifference(mockServerLogger, throwable, "xpath match failed expected:{}found:{}failed because " + prettyPrint(level) + ":{}", matcher, matched, throwable.getMessage()); } }), XPathConstants.BOOLEAN); } catch (Throwable throwable) { if (context != null) { context.addDifference(mockServerLogger, throwable, "xpath match failed expected:{}found:{}failed because:{}", matcher, matched, throwable.getMessage()); alreadyLoggedMatchFailure = true; } } } if (!result && !alreadyLoggedMatchFailure && context != null) { context.addDifference(mockServerLogger, "xpath match failed expected:{}found:{}failed because:{}", matcher, matched, "xpath did not evaluate to truthy"); } return not != result; } XPathMatcher(MockServerLogger mockServerLogger, String matcher); boolean matches(final MatchDifference context, final String matched); boolean isBlank(); }
@Test public void shouldMatchMatchingXPath() { String matched = "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>"; assertTrue(new XPathMatcher(new MockServerLogger(),"/element[key = 'some_key' and value = 'some_value']").matches(null, matched)); assertTrue(new XPathMatcher(new MockServerLogger(),"/element[key = 'some_key']").matches(null, matched)); assertTrue(new XPathMatcher(new MockServerLogger(),"/element/key").matches(null, matched)); assertTrue(new XPathMatcher(new MockServerLogger(),"/element[key and value]").matches(null, matched)); } @Test public void shouldNotMatchMatchingXPathWithNot() { String matched = "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>"; assertFalse(notMatcher(new XPathMatcher(new MockServerLogger(),"/element[key = 'some_key' and value = 'some_value']")).matches(null, matched)); assertFalse(notMatcher(new XPathMatcher(new MockServerLogger(),"/element[key = 'some_key']")).matches(null, matched)); assertFalse(notMatcher(new XPathMatcher(new MockServerLogger(),"/element/key")).matches(null, matched)); assertFalse(notMatcher(new XPathMatcher(new MockServerLogger(),"/element[key and value]")).matches(null, matched)); } @Test public void shouldMatchMatchingString() { assertTrue(new XPathMatcher(new MockServerLogger(),"some_value").matches(null, "some_value")); assertFalse(new XPathMatcher(new MockServerLogger(),"some_value").matches(null, "some_other_value")); } @Test public void shouldNotMatchNullExpectation() { assertFalse(new XPathMatcher(new MockServerLogger(),null).matches(null, "some_value")); } @Test public void shouldNotMatchEmptyExpectation() { assertFalse(new XPathMatcher(new MockServerLogger(),"").matches(null, "some_value")); } @Test public void shouldNotMatchNotMatchingXPath() { String matched = "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>"; assertFalse(new XPathMatcher(new MockServerLogger(),"/element[key = 'some_key' and value = 'some_other_value']").matches(null, matched)); assertFalse(new XPathMatcher(new MockServerLogger(),"/element[key = 'some_other_key']").matches(null, matched)); assertFalse(new XPathMatcher(new MockServerLogger(),"/element/not_key").matches(null, matched)); assertFalse(new XPathMatcher(new MockServerLogger(),"/element[key and not_value]").matches(null, matched)); } @Test public void shouldMatchNotMatchingXPathWithNot() { String matched = "" + "<element>" + " <key>some_key</key>" + " <value>some_value</value>" + "</element>"; assertTrue(notMatcher(new XPathMatcher(new MockServerLogger(),"/element[key = 'some_key' and value = 'some_other_value']")).matches(null, matched)); assertTrue(notMatcher(new XPathMatcher(new MockServerLogger(),"/element[key = 'some_other_key']")).matches(null, matched)); assertTrue(notMatcher(new XPathMatcher(new MockServerLogger(),"/element/not_key")).matches(null, matched)); assertTrue(notMatcher(new XPathMatcher(new MockServerLogger(),"/element[key and not_value]")).matches(null, matched)); } @Test public void shouldNotMatchNullTest() { assertFalse(new XPathMatcher(new MockServerLogger(),"some_value").matches(null, null)); } @Test public void shouldNotMatchEmptyTest() { assertFalse(new XPathMatcher(new MockServerLogger(),"some_value").matches(null, "")); }
JsonPathMatcher extends BodyMatcher<String> { public boolean matches(final MatchDifference context, final String matched) { boolean result = false; boolean alreadyLoggedMatchFailure = false; if (jsonPath == null) { if (context != null) { context.addDifference(mockServerLogger, "json path match failed expected:{}found:{}failed because:{}", "null", matched, "json path matcher was null"); alreadyLoggedMatchFailure = true; } } else if (matcher.equals(matched)) { result = true; } else if (matched != null) { try { result = !jsonPath.<JSONArray>read(matched).isEmpty(); } catch (Throwable throwable) { if (context != null) { context.addDifference(mockServerLogger, throwable, "json path match failed expected:{}found:{}failed because:{}", matcher, matched, throwable.getMessage()); alreadyLoggedMatchFailure = true; } } } if (!result && !alreadyLoggedMatchFailure && context != null) { context.addDifference(mockServerLogger, "json path match failed expected:{}found:{}failed because:{}", matcher, matched, "json path did not evaluate to truthy"); } return not != result; } JsonPathMatcher(MockServerLogger mockServerLogger, String matcher); boolean matches(final MatchDifference context, final String matched); boolean isBlank(); }
@Test public void shouldMatchMatchingJsonPath() { String matched = "" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}"; assertTrue(new JsonPathMatcher(new MockServerLogger(),"$..book[?(@.price <= $['expensive'])]").matches(null, matched)); assertTrue(new JsonPathMatcher(new MockServerLogger(),"$..book[?(@.isbn)]").matches(null, matched)); assertTrue(new JsonPathMatcher(new MockServerLogger(),"$..bicycle[?(@.color)]").matches(null, matched)); } @Test public void shouldNotMatchMatchingJsonPathWithNot() { String matched = "" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}"; assertFalse(notMatcher(new JsonPathMatcher(new MockServerLogger(),"$..book[?(@.price <= $['expensive'])]")).matches(null, matched)); assertFalse(notMatcher(new JsonPathMatcher(new MockServerLogger(),"$..book[?(@.isbn)]")).matches(null, matched)); assertFalse(notMatcher(new JsonPathMatcher(new MockServerLogger(),"$..bicycle[?(@.color)]")).matches(null, matched)); } @Test public void shouldMatchMatchingString() { assertTrue(new JsonPathMatcher(new MockServerLogger(),"some_value").matches(null, "some_value")); assertFalse(new JsonPathMatcher(new MockServerLogger(),"some_value").matches(null, "some_other_value")); } @Test public void shouldNotMatchNullExpectation() { assertFalse(new JsonPathMatcher(new MockServerLogger(),null).matches(null, "some_value")); } @Test public void shouldNotMatchEmptyExpectation() { assertFalse(new JsonPathMatcher(new MockServerLogger(),"").matches(null, "some_value")); } @Test public void shouldNotMatchNotMatchingJsonPath() { String matched = "" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}"; assertFalse(new JsonPathMatcher(new MockServerLogger(),"$..book[?(@.price > $['expensive'])]").matches(null, matched)); assertFalse(new JsonPathMatcher(new MockServerLogger(),"$..book[?(@.color)]").matches(null, matched)); assertFalse(new JsonPathMatcher(new MockServerLogger(),"$..bicycle[?(@.isbn)]").matches(null, matched)); } @Test public void shouldMatchNotMatchingJsonPathWithNot() { String matched = "" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}"; assertTrue(notMatcher(new JsonPathMatcher(new MockServerLogger(),"$..book[?(@.price > $['expensive'])]")).matches(null, matched)); assertTrue(notMatcher(new JsonPathMatcher(new MockServerLogger(),"$..book[?(@.color)]")).matches(null, matched)); assertTrue(notMatcher(new JsonPathMatcher(new MockServerLogger(),"$..bicycle[?(@.isbn)]")).matches(null, matched)); } @Test public void shouldNotMatchNullTest() { assertFalse(new JsonPathMatcher(new MockServerLogger(),"some_value").matches(null, null)); } @Test public void shouldNotMatchEmptyTest() { assertFalse(new JsonPathMatcher(new MockServerLogger(),"some_value").matches(null, "")); }
ConfigurationProperties { public static int socketConnectionTimeout() { return readIntegerProperty(MOCKSERVER_SOCKET_CONNECTION_TIMEOUT, "MOCKSERVER_SOCKET_CONNECTION_TIMEOUT", DEFAULT_CONNECT_TIMEOUT); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadSocketConnectionTimeout() { System.clearProperty("mockserver.socketConnectionTimeout"); assertEquals(TimeUnit.SECONDS.toMillis(20), socketConnectionTimeout()); socketConnectionTimeout(100); assertEquals("100", System.getProperty("mockserver.socketConnectionTimeout")); assertEquals(100, socketConnectionTimeout()); } @Test public void shouldHandleInvalidSocketConnectionTimeout() { System.setProperty("mockserver.socketConnectionTimeout", "invalid"); assertEquals(TimeUnit.SECONDS.toMillis(20), socketConnectionTimeout()); }
BinaryMatcher extends BodyMatcher<byte[]> { public boolean matches(final MatchDifference context, byte[] matched) { boolean result = false; if (matcher == null || matcher.length == 0 || Arrays.equals(matcher, matched)) { result = true; } if (!result && context != null) { context.addDifference(mockServerLogger, "binary match failed expected:{}found:{}", BinaryArrayFormatter.byteArrayToString(this.matcher), BinaryArrayFormatter.byteArrayToString(matched)); } return not != result; } BinaryMatcher(MockServerLogger mockServerLogger, byte[] matcher); boolean matches(final MatchDifference context, byte[] matched); boolean isBlank(); @Override @JsonIgnore String[] fieldsExcludedFromEqualsAndHashCode(); }
@Test public void shouldMatchMatchingString() { assertTrue(new BinaryMatcher(new MockServerLogger(),"some_value".getBytes(UTF_8)).matches(null, "some_value".getBytes(UTF_8))); } @Test public void shouldNotMatchMatchingString() { assertFalse(notMatcher(new BinaryMatcher(new MockServerLogger(),"some_value".getBytes(UTF_8))).matches(null, "some_value".getBytes(UTF_8))); } @Test public void shouldMatchNullExpectation() { assertTrue(new BinaryMatcher(new MockServerLogger(),null).matches(null, "some_value".getBytes(UTF_8))); } @Test public void shouldNotMatchNullExpectation() { assertFalse(notMatcher(new BinaryMatcher(new MockServerLogger(),null)).matches(null, "some_value".getBytes(UTF_8))); } @Test public void shouldMatchEmptyExpectation() { assertTrue(new BinaryMatcher(new MockServerLogger(),"".getBytes(UTF_8)).matches(null, "some_value".getBytes(UTF_8))); } @Test public void shouldNotMatchEmptyExpectation() { assertFalse(notMatcher(new BinaryMatcher(new MockServerLogger(),"".getBytes(UTF_8))).matches(null, "some_value".getBytes(UTF_8))); } @Test public void shouldNotMatchIncorrectString() { assertFalse(new BinaryMatcher(new MockServerLogger(),"some_value".getBytes(UTF_8)).matches(null, "not_matching".getBytes(UTF_8))); } @Test public void shouldMatchIncorrectString() { assertTrue(notMatcher(new BinaryMatcher(new MockServerLogger(),"some_value".getBytes(UTF_8))).matches(null, "not_matching".getBytes(UTF_8))); } @Test public void shouldNotMatchNullTest() { assertFalse(new BinaryMatcher(new MockServerLogger(),"some_value".getBytes(UTF_8)).matches(null, null)); } @Test public void shouldMatchNullTest() { assertTrue(notMatcher(new BinaryMatcher(new MockServerLogger(),"some_value".getBytes(UTF_8))).matches(null, null)); } @Test public void shouldNotMatchEmptyTest() { assertFalse(new BinaryMatcher(new MockServerLogger(),"some_value".getBytes(UTF_8)).matches(null, "".getBytes(UTF_8))); } @Test public void shouldMatchEmptyTest() { assertTrue(notMatcher(new BinaryMatcher(new MockServerLogger(),"some_value".getBytes(UTF_8))).matches(null, "".getBytes(UTF_8))); }
ConfigurationProperties { public static void alwaysCloseSocketConnections(boolean alwaysClose) { System.setProperty(MOCKSERVER_ALWAYS_CLOSE_SOCKET_CONNECTIONS, "" + alwaysClose); alwaysCloseConnections = Boolean.parseBoolean(readPropertyHierarchically(MOCKSERVER_ALWAYS_CLOSE_SOCKET_CONNECTIONS, "MOCKSERVER_ALWAYS_CLOSE_SOCKET_CONNECTIONS", DEFAULT_MOCKSERVER_ALWAYS_CLOSE_SOCKET_CONNECTIONS)); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadAlwaysCloseSocketConnections() { System.clearProperty("mockserver.alwaysCloseSocketConnections"); assertFalse(alwaysCloseSocketConnections()); alwaysCloseSocketConnections(true); assertTrue(alwaysCloseSocketConnections()); assertEquals("true", System.getProperty("mockserver.alwaysCloseSocketConnections")); }
ExactStringMatcher extends BodyMatcher<NottableString> { public static boolean matches(String matcher, String matched, boolean ignoreCase) { if (StringUtils.isBlank(matcher)) { return true; } else if (matched != null) { if (matched.equals(matcher)) { return true; } if (ignoreCase) { return matched.equalsIgnoreCase(matcher); } } return false; } ExactStringMatcher(MockServerLogger mockServerLogger, NottableString matcher); static boolean matches(String matcher, String matched, boolean ignoreCase); boolean matches(final MatchDifference context, String matched); boolean matches(final MatchDifference context, NottableString matched); boolean isBlank(); @Override @JsonIgnore String[] fieldsExcludedFromEqualsAndHashCode(); }
@Test public void shouldMatchMatchingString() { assertTrue(new ExactStringMatcher(new MockServerLogger(), string("some_value")).matches(null, "some_value")); assertTrue(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value")).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), string("some_value"))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value"))).matches(null, "some_value")); assertFalse(new ExactStringMatcher(new MockServerLogger(), string("some_value")).matches(null, NottableString.not("some_value"))); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), string("some_value"))).matches(null, "some_value")); assertFalse(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value")).matches(null, "some_value")); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value"))).matches(null, NottableString.not("some_value"))); } @Test public void shouldMatchNotMatchingString() { assertFalse(new ExactStringMatcher(new MockServerLogger(), string("some_value")).matches(null, "some_other_value")); assertFalse(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value")).matches(null, NottableString.not("some_other_value"))); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), string("some_value"))).matches(null, NottableString.not("some_other_value"))); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value"))).matches(null, "some_other_value")); assertTrue(new ExactStringMatcher(new MockServerLogger(), string("some_value")).matches(null, NottableString.not("some_other_value"))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), string("some_value"))).matches(null, "some_other_value")); assertTrue(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value")).matches(null, "some_other_value")); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value"))).matches(null, NottableString.not("some_other_value"))); } @Test public void shouldMatchNullMatcher() { assertTrue(new ExactStringMatcher(new MockServerLogger(), string(null)).matches(null, "some_value")); assertTrue(new ExactStringMatcher(new MockServerLogger(), string(null)).matches(null, "some_value")); assertTrue(new ExactStringMatcher(new MockServerLogger(), NottableString.not(null)).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), string(null))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), string(null))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not(null))).matches(null, "some_value")); assertFalse(new ExactStringMatcher(new MockServerLogger(), string(null)).matches(null, NottableString.not("some_value"))); assertFalse(new ExactStringMatcher(new MockServerLogger(), string(null)).matches(null, NottableString.not("some_value"))); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), string(null))).matches(null, "some_value")); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), string(null))).matches(null, "some_value")); assertFalse(new ExactStringMatcher(new MockServerLogger(), NottableString.not(null)).matches(null, "some_value")); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not(null))).matches(null, NottableString.not("some_value"))); } @Test public void shouldMatchNullMatched() { assertFalse(new ExactStringMatcher(new MockServerLogger(), string("some_value")).matches(null, (String) null)); assertFalse(new ExactStringMatcher(new MockServerLogger(), string("some_value")).matches(null, string(null))); assertFalse(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value")).matches(null, NottableString.not(null))); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), string("some_value"))).matches(null, NottableString.not(null))); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value"))).matches(null, (String) null)); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value"))).matches(null, string(null))); assertTrue(new ExactStringMatcher(new MockServerLogger(), string("some_value")).matches(null, NottableString.not(null))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), string("some_value"))).matches(null, (String) null)); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), string("some_value"))).matches(null, string(null))); assertTrue(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value")).matches(null, (String) null)); assertTrue(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value")).matches(null, string(null))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value"))).matches(null, NottableString.not(null))); } @Test public void shouldMatchEmptyMatcher() { assertTrue(new ExactStringMatcher(new MockServerLogger(), string("")).matches(null, "some_value")); assertTrue(new ExactStringMatcher(new MockServerLogger(), string("")).matches(null, "some_value")); assertTrue(new ExactStringMatcher(new MockServerLogger(), NottableString.not("")).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), string(""))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), string(""))).matches(null, NottableString.not("some_value"))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not(""))).matches(null, "some_value")); assertFalse(new ExactStringMatcher(new MockServerLogger(), string("")).matches(null, NottableString.not("some_value"))); assertFalse(new ExactStringMatcher(new MockServerLogger(), string("")).matches(null, NottableString.not("some_value"))); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), string(""))).matches(null, "some_value")); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), string(""))).matches(null, "some_value")); assertFalse(new ExactStringMatcher(new MockServerLogger(), NottableString.not("")).matches(null, "some_value")); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not(""))).matches(null, NottableString.not("some_value"))); } @Test public void shouldMatchEmptyMatched() { assertFalse(new ExactStringMatcher(new MockServerLogger(), string("some_value")).matches(null, "")); assertFalse(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value")).matches(null, NottableString.not(""))); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), string("some_value"))).matches(null, NottableString.not(""))); assertFalse(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value"))).matches(null, "")); assertTrue(new ExactStringMatcher(new MockServerLogger(), string("some_value")).matches(null, NottableString.not(""))); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), string("some_value"))).matches(null, "")); assertTrue(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value")).matches(null, "")); assertTrue(notMatcher(new ExactStringMatcher(new MockServerLogger(), NottableString.not("some_value"))).matches(null, NottableString.not(""))); }
CORSHeaders { public static boolean isPreflightRequest(HttpRequest request) { final Headers headers = request.getHeaders(); boolean isPreflightRequest = request.getMethod().getValue().equals(OPTIONS.name()) && headers.containsEntry(HttpHeaderNames.ORIGIN.toString()) && headers.containsEntry(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD.toString()); if (isPreflightRequest) { enableCORSForAPI(true); } return isPreflightRequest; } CORSHeaders(); static boolean isPreflightRequest(HttpRequest request); void addCORSHeaders(HttpRequest request, HttpResponse response); }
@Test public void shouldDetectPreflightRequest() { assertThat(isPreflightRequest( request() .withMethod("OPTIONS") .withHeader("origin", "some_origin_header") .withHeader("access-control-request-method", "true") ), is(true)); assertThat(isPreflightRequest( request() .withMethod("GET") .withHeader("origin", "some_origin_header") .withHeader("access-control-request-method", "true") ), is(false)); assertThat(isPreflightRequest( request() .withMethod("OPTIONS") .withHeader("not_origin", "some_origin_header") .withHeader("access-control-request-method", "true") ), is(false)); assertThat(isPreflightRequest( request() .withMethod("OPTIONS") .withHeader("origin", "some_origin_header") .withHeader("not_access-control-request-method", "true") ), is(false)); }
CORSHeaders { public void addCORSHeaders(HttpRequest request, HttpResponse response) { String origin = request.getFirstHeader(HttpHeaderNames.ORIGIN.toString()); if (NULL_ORIGIN.equals(origin)) { setHeaderIfNotAlreadyExists(response, HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.toString(), NULL_ORIGIN); } else if (!origin.isEmpty() && request.getFirstHeader(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS.toString()).equals("true")) { setHeaderIfNotAlreadyExists(response, HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.toString(), origin); setHeaderIfNotAlreadyExists(response, HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS.toString(), corsAllowCredentials); } else { setHeaderIfNotAlreadyExists(response, HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.toString(), ANY_ORIGIN); } setHeaderIfNotAlreadyExists(response, HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS.toString(), corsAllowMethods); String allowHeaders = corsAllowHeaders; if (!request.getFirstHeader(HttpHeaderNames.ACCESS_CONTROL_REQUEST_HEADERS.toString()).isEmpty()) { allowHeaders += ", " + request.getFirstHeader(HttpHeaderNames.ACCESS_CONTROL_REQUEST_HEADERS.toString()); } setHeaderIfNotAlreadyExists(response, HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS.toString(), allowHeaders); setHeaderIfNotAlreadyExists(response, HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS.toString(), allowHeaders); setHeaderIfNotAlreadyExists(response, HttpHeaderNames.ACCESS_CONTROL_MAX_AGE.toString(), corsMaxAge); } CORSHeaders(); static boolean isPreflightRequest(HttpRequest request); void addCORSHeaders(HttpRequest request, HttpResponse response); }
@Test public void shouldAddCORSHeader() { HttpRequest request = request(); HttpResponse response = response(); new CORSHeaders().addCORSHeaders(request, response); assertThat(response.getFirstHeader("access-control-allow-origin"), is("*")); assertThat(response.getFirstHeader("access-control-allow-methods"), is("CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH, TRACE")); assertThat(response.getFirstHeader("access-control-allow-headers"), is("Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization")); assertThat(response.getFirstHeader("access-control-expose-headers"), is("Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization")); assertThat(response.getFirstHeader("access-control-max-age"), is("300")); } @Test public void shouldAddCORSHeaderForNullOrigin() { HttpRequest request = request() .withHeader("origin", "null"); HttpResponse response = response(); new CORSHeaders().addCORSHeaders(request, response); assertThat(response.getFirstHeader("access-control-allow-origin"), is("null")); assertThat(response.getFirstHeader("access-control-allow-methods"), is("CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH, TRACE")); assertThat(response.getFirstHeader("access-control-allow-headers"), is("Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization")); assertThat(response.getFirstHeader("access-control-expose-headers"), is("Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization")); assertThat(response.getFirstHeader("access-control-max-age"), is("300")); } @Test public void shouldAddCORSHeaderForAllowCredentials() { HttpRequest request = request() .withHeader("origin", "some_origin_value") .withHeader("access-control-allow-credentials", "true"); HttpResponse response = response(); new CORSHeaders().addCORSHeaders(request, response); assertThat(response.getFirstHeader("access-control-allow-origin"), is("some_origin_value")); assertThat(response.getFirstHeader("access-control-allow-methods"), is("CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH, TRACE")); assertThat(response.getFirstHeader("access-control-allow-headers"), is("Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization")); assertThat(response.getFirstHeader("access-control-expose-headers"), is("Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization")); assertThat(response.getFirstHeader("access-control-max-age"), is("300")); } @Test public void shouldAddCORSHeaderForAllowCredentialsWithoutOrigin() { HttpRequest request = request() .withHeader("access-control-allow-credentials", "true"); HttpResponse response = response(); new CORSHeaders().addCORSHeaders(request, response); assertThat(response.getFirstHeader("access-control-allow-origin"), is("*")); assertThat(response.getFirstHeader("access-control-allow-methods"), is("CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH, TRACE")); assertThat(response.getFirstHeader("access-control-allow-headers"), is("Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization")); assertThat(response.getFirstHeader("access-control-expose-headers"), is("Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization")); assertThat(response.getFirstHeader("access-control-max-age"), is("300")); } @Test public void shouldAddCORSHeaderForExtraRequestHeaders() { HttpRequest request = request() .withMethod("OPTIONS") .withHeader("Access-Control-Request-Headers", "X-API-Key"); HttpResponse response = response(); new CORSHeaders().addCORSHeaders(request, response); assertThat(response.getFirstHeader("access-control-allow-headers"), containsString("X-API-Key")); }
StringFormatter { public static String formatLogMessage(final String message, final Object... arguments) { return formatLogMessage(0, message, arguments); } static StringBuilder[] indentAndToString(final Object... objects); static StringBuilder[] indentAndToString(final int indent, final Object... objects); static String formatLogMessage(final String message, final Object... arguments); static String formatLogMessage(final int indent, final String message, final Object... arguments); static String formatLogMessage(final String[] messageParts, final Object... arguments); static String formatBytes(byte[] bytes); }
@Test public void shouldFormatLogMessageWithMultipleParameters() { String logMessage = StringFormatter.formatLogMessage("returning response:{}for request:{}for action:{}", response("response_body"), request("request_path"), forward()); assertThat(logMessage, is( "returning response:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"statusCode\" : 200," + NEW_LINE + " \"reasonPhrase\" : \"OK\"," + NEW_LINE + " \"body\" : \"response_body\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " for request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"path\" : \"request_path\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " for action:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"port\" : 80," + NEW_LINE + " \"scheme\" : \"HTTP\"" + NEW_LINE + " }" + NEW_LINE )); } @Test public void shouldFormatLogMessageWithMultipleParametersWithIndent() { String logMessage = StringFormatter.formatLogMessage(2, "returning response:{}for request:{}for action:{}", response("response_body"), request("request_path"), forward()); assertThat(logMessage, is(" returning response:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"statusCode\" : 200," + NEW_LINE + " \"reasonPhrase\" : \"OK\"," + NEW_LINE + " \"body\" : \"response_body\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " for request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"path\" : \"request_path\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " for action:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"port\" : 80," + NEW_LINE + " \"scheme\" : \"HTTP\"" + NEW_LINE + " }" + NEW_LINE)); } @Test public void shouldFormatLogMessageWithASingleParameter() { String logMessage = StringFormatter.formatLogMessage("returning response:{}", response("response_body")); assertThat(logMessage, is( "returning response:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"statusCode\" : 200," + NEW_LINE + " \"reasonPhrase\" : \"OK\"," + NEW_LINE + " \"body\" : \"response_body\"" + NEW_LINE + " }" + NEW_LINE )); } @Test public void shouldFormatLogMessageWithASingleParameterWithIndent() { String logMessage = StringFormatter.formatLogMessage(1, "returning response:{}", response("response_body")); assertThat(logMessage, is( " returning response:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"statusCode\" : 200," + NEW_LINE + " \"reasonPhrase\" : \"OK\"," + NEW_LINE + " \"body\" : \"response_body\"" + NEW_LINE + " }" + NEW_LINE )); } @Test public void shouldIgnoreExtraParameters() { String logMessage = StringFormatter.formatLogMessage("returning response:{}", response("response_body"), request("request_path"), forward()); assertThat(logMessage, is( "returning response:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"statusCode\" : 200," + NEW_LINE + " \"reasonPhrase\" : \"OK\"," + NEW_LINE + " \"body\" : \"response_body\"" + NEW_LINE + " }" + NEW_LINE )); } @Test public void shouldIgnoreTooFewParameters() { String logMessage = StringFormatter.formatLogMessage("returning response:{}for request:{}for action:{}", response("response_body")); assertThat(logMessage, is( "returning response:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"statusCode\" : 200," + NEW_LINE + " \"reasonPhrase\" : \"OK\"," + NEW_LINE + " \"body\" : \"response_body\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " for request:" + NEW_LINE + " for action:" )); }
ConfigurationProperties { public static Level logLevel() { return logLevel; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldThrowIllegalArgumentExceptionForInvalidLogLevel() { try { logLevel("WRONG"); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), is("log level \"WRONG\" is not legal it must be one of SL4J levels: \"TRACE\", \"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"OFF\", or the Java Logger levels: \"FINEST\", \"FINE\", \"INFO\", \"WARNING\", \"SEVERE\", \"OFF\"")); } }
StringFormatter { public static String formatBytes(byte[] bytes) { return newLineJoiner.join(fixedLengthSplitter.split(ByteBufUtil.hexDump(bytes))); } static StringBuilder[] indentAndToString(final Object... objects); static StringBuilder[] indentAndToString(final int indent, final Object... objects); static String formatLogMessage(final String message, final Object... arguments); static String formatLogMessage(final int indent, final String message, final Object... arguments); static String formatLogMessage(final String[] messageParts, final Object... arguments); static String formatBytes(byte[] bytes); }
@Test public void shouldFormatBytes() { byte[] bytes = ("" + "The trick to getting kids to eat anything is to put catchup on it." + NEW_LINE + "I like to leave work after my eight-hour tea-break." + NEW_LINE + "He barked orders at his daughters but they just stared back with amusement." + NEW_LINE + "As the years pass by, we all know owners look more and more like their dogs." + NEW_LINE + "It must be five o'clock somewhere." + NEW_LINE + "The father died during childbirth." + NEW_LINE + "He had concluded that pigs must be able to fly in Hog Heaven." + NEW_LINE + "The pet shop stocks everything you need to keep your anaconda happy." + NEW_LINE + "We should play with legos at camp." + NEW_LINE + "It doesn't sound like that will ever be on my travel list." ).getBytes(StandardCharsets.UTF_8); assertThat(formatBytes(bytes), is("" + "54686520747269636b20746f2067657474696e67206b69647320746f20656174" + NEW_LINE + "20616e797468696e6720697320746f207075742063617463687570206f6e2069" + NEW_LINE + "742e0a49206c696b6520746f206c6561766520776f726b206166746572206d79" + NEW_LINE + "2065696768742d686f7572207465612d627265616b2e0a4865206261726b6564" + NEW_LINE + "206f726465727320617420686973206461756768746572732062757420746865" + NEW_LINE + "79206a75737420737461726564206261636b207769746820616d7573656d656e" + NEW_LINE + "742e0a41732074686520796561727320706173732062792c20776520616c6c20" + NEW_LINE + "6b6e6f77206f776e657273206c6f6f6b206d6f726520616e64206d6f7265206c" + NEW_LINE + "696b6520746865697220646f67732e0a4974206d757374206265206669766520" + NEW_LINE + "6f27636c6f636b20736f6d6577686572652e0a54686520666174686572206469" + NEW_LINE + "656420647572696e67206368696c6462697274682e0a48652068616420636f6e" + NEW_LINE + "636c7564656420746861742070696773206d7573742062652061626c6520746f" + NEW_LINE + "20666c7920696e20486f672048656176656e2e0a546865207065742073686f70" + NEW_LINE + "2073746f636b732065766572797468696e6720796f75206e65656420746f206b" + NEW_LINE + "65657020796f757220616e61636f6e64612068617070792e0a57652073686f75" + NEW_LINE + "6c6420706c61792077697468206c65676f732061742063616d702e0a49742064" + NEW_LINE + "6f65736e277420736f756e64206c696b6520746861742077696c6c2065766572" + NEW_LINE + "206265206f6e206d792074726176656c206c6973742e")); }
ExpectationFileSystemPersistence implements MockServerMatcherListener { public void stop() { if (requestMatchers != null) { requestMatchers.unregisterListener(this); } } ExpectationFileSystemPersistence(MockServerLogger mockServerLogger, RequestMatchers requestMatchers); @Override void updated(RequestMatchers requestMatchers, MockServerMatcherNotifier.Cause cause); String serialize(List<Expectation> expectations); String serialize(Expectation... expectations); void stop(); }
@Test public void shouldPersistExpectationsToJsonOnAdd() throws Exception { String persistedExpectationsPath = ConfigurationProperties.persistedExpectationsPath(); ConfigurationProperties.persistExpectations(true); ExpectationFileSystemPersistence expectationFileSystemPersistence = null; try { File persistedExpectations = File.createTempFile("persistedExpectations", ".json"); ConfigurationProperties.persistedExpectationsPath(persistedExpectations.getAbsolutePath()); expectationFileSystemPersistence = new ExpectationFileSystemPersistence(mockServerLogger, requestMatchers); requestMatchers.add(new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleSecond") ) .withId("two") .thenRespond( response() .withBody("some second response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleThird") ) .withId("three") .thenRespond( response() .withBody("some third response") ), API); MILLISECONDS.sleep(1500); String expectedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecond\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"three\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleThird\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some third response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; assertThat(persistedExpectations.getAbsolutePath() + " does not match expected content", new String(Files.readAllBytes(persistedExpectations.toPath()), StandardCharsets.UTF_8), is(expectedFileContents)); } finally { ConfigurationProperties.persistedExpectationsPath(persistedExpectationsPath); ConfigurationProperties.persistExpectations(false); if (expectationFileSystemPersistence != null) { expectationFileSystemPersistence.stop(); } } } @Test public void shouldPersistExpectationsToJsonOnRemove() throws Exception { String persistedExpectationsPath = ConfigurationProperties.persistedExpectationsPath(); ConfigurationProperties.persistExpectations(true); ExpectationFileSystemPersistence expectationFileSystemPersistence = null; try { File persistedExpectations = File.createTempFile("persistedExpectations", ".json"); ConfigurationProperties.persistedExpectationsPath(persistedExpectations.getAbsolutePath()); expectationFileSystemPersistence = new ExpectationFileSystemPersistence(mockServerLogger, requestMatchers); requestMatchers.add(new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleSecond") ) .withId("two") .thenRespond( response() .withBody("some second response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleThird") ) .withId("three") .thenRespond( response() .withBody("some third response") ), API); requestMatchers.clear( request() .withPath("/simpleSecond") ); MILLISECONDS.sleep(1500); String expectedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"three\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleThird\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some third response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; assertThat(persistedExpectations.getAbsolutePath() + " does not match expected content", new String(Files.readAllBytes(persistedExpectations.toPath()), StandardCharsets.UTF_8), is(expectedFileContents)); } finally { ConfigurationProperties.persistedExpectationsPath(persistedExpectationsPath); ConfigurationProperties.persistExpectations(false); if (expectationFileSystemPersistence != null) { expectationFileSystemPersistence.stop(); } } } @Test public void shouldPersistExpectationsToJsonOnUpdate() throws Exception { String persistedExpectationsPath = ConfigurationProperties.persistedExpectationsPath(); ConfigurationProperties.persistExpectations(true); ExpectationFileSystemPersistence expectationFileSystemPersistence = null; try { File persistedExpectations = File.createTempFile("persistedExpectations", ".json"); ConfigurationProperties.persistedExpectationsPath(persistedExpectations.getAbsolutePath()); expectationFileSystemPersistence = new ExpectationFileSystemPersistence(mockServerLogger, requestMatchers); requestMatchers.add(new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleSecond") ) .withId("two") .thenRespond( response() .withBody("some second response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleThird") ) .withId("three") .thenRespond( response() .withBody("some third response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleSecondUpdated") ) .withId("two") .thenRespond( response() .withBody("some second updated response") ), API); MILLISECONDS.sleep(1500); String expectedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecondUpdated\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second updated response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"three\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleThird\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some third response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; assertThat(persistedExpectations.getAbsolutePath() + " does not match expected content", new String(Files.readAllBytes(persistedExpectations.toPath()), StandardCharsets.UTF_8), is(expectedFileContents)); } finally { ConfigurationProperties.persistedExpectationsPath(persistedExpectationsPath); ConfigurationProperties.persistExpectations(false); if (expectationFileSystemPersistence != null) { expectationFileSystemPersistence.stop(); } } } @Test public void shouldPersistExpectationsToJsonOnUpdateAll() throws Exception { String persistedExpectationsPath = ConfigurationProperties.persistedExpectationsPath(); ConfigurationProperties.persistExpectations(true); ExpectationFileSystemPersistence expectationFileSystemPersistence = null; try { File persistedExpectations = File.createTempFile("persistedExpectations", ".json"); ConfigurationProperties.persistedExpectationsPath(persistedExpectations.getAbsolutePath()); expectationFileSystemPersistence = new ExpectationFileSystemPersistence(mockServerLogger, requestMatchers); requestMatchers.add(new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleSecond") ) .withId("two") .thenRespond( response() .withBody("some second response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleThird") ) .withId("three") .thenRespond( response() .withBody("some third response") ), API); requestMatchers.update(new Expectation[]{ new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ), new Expectation( request() .withPath("/simpleSecondUpdated") ) .withId("two") .thenRespond( response() .withBody("some second updated response") ), new Expectation( request() .withPath("/simpleFourth") ) .withId("four") .thenRespond( response() .withBody("some fourth response") ) }, API); MILLISECONDS.sleep(1500); String expectedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecondUpdated\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second updated response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"four\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFourth\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some fourth response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; assertThat(persistedExpectations.getAbsolutePath() + " does not match expected content", new String(Files.readAllBytes(persistedExpectations.toPath()), StandardCharsets.UTF_8), is(expectedFileContents)); } finally { ConfigurationProperties.persistedExpectationsPath(persistedExpectationsPath); ConfigurationProperties.persistExpectations(false); if (expectationFileSystemPersistence != null) { expectationFileSystemPersistence.stop(); } } } @Test public void shouldPersistExpectationsToJsonOnUpdateAllFromFileWatcher() throws Exception { String persistedExpectationsPath = ConfigurationProperties.persistedExpectationsPath(); ConfigurationProperties.persistExpectations(true); String initializationJsonPath = ConfigurationProperties.initializationJsonPath(); ConfigurationProperties.watchInitializationJson(true); ExpectationFileSystemPersistence expectationFileSystemPersistence = null; try { File persistedExpectations = File.createTempFile("persistedExpectations", ".json"); ConfigurationProperties.persistedExpectationsPath(persistedExpectations.getAbsolutePath()); ConfigurationProperties.initializationJsonPath(persistedExpectations.getAbsolutePath()); expectationFileSystemPersistence = new ExpectationFileSystemPersistence(mockServerLogger, requestMatchers); requestMatchers.add(new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleSecond") ) .withId("two") .thenRespond( response() .withBody("some second response") ), API); requestMatchers.add(new Expectation( request() .withPath("/simpleThird") ) .withId("three") .thenRespond( response() .withBody("some third response") ), API); MILLISECONDS.sleep(1500); requestMatchers.update(new Expectation[]{ new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ), new Expectation( request() .withPath("/simpleSecondUpdated") ) .withId("two") .thenRespond( response() .withBody("some second updated response") ), new Expectation( request() .withPath("/simpleFourth") ) .withId("four") .thenRespond( response() .withBody("some fourth response") ) }, MockServerMatcherNotifier.Cause.FILE_WATCHER); MILLISECONDS.sleep(1500); String expectedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecond\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"three\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleThird\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some third response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; assertThat(persistedExpectations.getAbsolutePath() + " does not match expected content", new String(Files.readAllBytes(persistedExpectations.toPath()), StandardCharsets.UTF_8), is(expectedFileContents)); } finally { ConfigurationProperties.persistedExpectationsPath(persistedExpectationsPath); ConfigurationProperties.persistExpectations(false); ConfigurationProperties.initializationJsonPath(initializationJsonPath); ConfigurationProperties.watchInitializationJson(false); if (expectationFileSystemPersistence != null) { expectationFileSystemPersistence.stop(); } } }
ExpectationFileWatcher { public void stop() { if (fileWatcher != null) { fileWatcher.setRunning(false); } } ExpectationFileWatcher(MockServerLogger mockServerLogger, RequestMatchers requestMatchers); void stop(); }
@Test public void shouldDetectModifiedInitialiserJsonInWorkingDirectory() throws Exception { String initializationJsonPath = ConfigurationProperties.initializationJsonPath(); ConfigurationProperties.watchInitializationJson(true); ExpectationFileWatcher expectationFileWatcher = null; try { File mockserverInitialization = new File("mockserverInitialization" + UUIDService.getUUID() + ".json"); mockserverInitialization.deleteOnExit(); ConfigurationProperties.initializationJsonPath(mockserverInitialization.getPath()); CompletableFuture<String> expectationsUpdated = new CompletableFuture<>(); requestMatchers.registerListener((requestMatchers, cause) -> expectationsUpdated.complete("updated")); expectationFileWatcher = new ExpectationFileWatcher(mockServerLogger, requestMatchers); MILLISECONDS.sleep(1500); String watchedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecond\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"three\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleThird\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some third response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; Files.write(mockserverInitialization.toPath(), watchedFileContents.getBytes(StandardCharsets.UTF_8)); long updatedFileTime = System.currentTimeMillis(); expectationsUpdated.get(30, SECONDS); System.out.println("update processed in: " + (System.currentTimeMillis() - updatedFileTime) + "ms"); List<Expectation> expectations = requestMatchers.retrieveActiveExpectations(null); assertThat( expectations, contains( new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ) , new Expectation( request() .withPath("/simpleSecond") ) .withId("two") .thenRespond( response() .withBody("some second response") ), new Expectation( request() .withPath("/simpleThird") ) .withId("three") .thenRespond( response() .withBody("some third response") ) ) ); } finally { ConfigurationProperties.initializationJsonPath(initializationJsonPath); ConfigurationProperties.watchInitializationJson(false); if (expectationFileWatcher != null) { expectationFileWatcher.stop(); } } } @Test public void shouldDetectModifiedInitialiserJsonOnAdd() throws Exception { String initializationJsonPath = ConfigurationProperties.initializationJsonPath(); ConfigurationProperties.watchInitializationJson(true); ExpectationFileWatcher expectationFileWatcher = null; try { File mockserverInitialization = File.createTempFile("mockserverInitialization", ".json"); ConfigurationProperties.initializationJsonPath(mockserverInitialization.getAbsolutePath()); CompletableFuture<String> expectationsUpdated = new CompletableFuture<>(); requestMatchers.registerListener((requestMatchers, cause) -> expectationsUpdated.complete("updated")); expectationFileWatcher = new ExpectationFileWatcher(mockServerLogger, requestMatchers); MILLISECONDS.sleep(1500); String watchedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecond\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"three\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleThird\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some third response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; Files.write(mockserverInitialization.toPath(), watchedFileContents.getBytes(StandardCharsets.UTF_8)); long updatedFileTime = System.currentTimeMillis(); expectationsUpdated.get(30, SECONDS); System.out.println("update processed in: " + (System.currentTimeMillis() - updatedFileTime) + "ms"); List<Expectation> expectations = requestMatchers.retrieveActiveExpectations(null); assertThat( expectations, contains( new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ) , new Expectation( request() .withPath("/simpleSecond") ) .withId("two") .thenRespond( response() .withBody("some second response") ), new Expectation( request() .withPath("/simpleThird") ) .withId("three") .thenRespond( response() .withBody("some third response") ) ) ); } finally { ConfigurationProperties.initializationJsonPath(initializationJsonPath); ConfigurationProperties.watchInitializationJson(false); if (expectationFileWatcher != null) { expectationFileWatcher.stop(); } } } @Test public void shouldDetectModifiedInitialiserJsonOnDeletion() throws Exception { String initializationJsonPath = ConfigurationProperties.initializationJsonPath(); ConfigurationProperties.watchInitializationJson(true); ExpectationFileWatcher expectationFileWatcher = null; try { File mockserverInitialization = File.createTempFile("mockserverInitialization", ".json"); ConfigurationProperties.initializationJsonPath(mockserverInitialization.getAbsolutePath()); String watchedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecond\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"three\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleThird\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some third response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; Files.write(mockserverInitialization.toPath(), watchedFileContents.getBytes(StandardCharsets.UTF_8)); requestMatchers.update(new Expectation[]{ new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ) , new Expectation( request() .withPath("/simpleSecond") ) .withId("two") .thenRespond( response() .withBody("some second response") ), new Expectation( request() .withPath("/simpleThird") ) .withId("three") .thenRespond( response() .withBody("some third response") ) }, MockServerMatcherNotifier.Cause.FILE_WATCHER); CompletableFuture<String> expectationsUpdated = new CompletableFuture<>(); requestMatchers.registerListener((requestMatchers, cause) -> expectationsUpdated.complete("updated")); expectationFileWatcher = new ExpectationFileWatcher(mockServerLogger, requestMatchers); MILLISECONDS.sleep(1500); watchedFileContents = "[ ]"; Files.write(mockserverInitialization.toPath(), watchedFileContents.getBytes(StandardCharsets.UTF_8)); long updatedFileTime = System.currentTimeMillis(); expectationsUpdated.get(30, SECONDS); System.out.println("update processed in: " + (System.currentTimeMillis() - updatedFileTime) + "ms"); List<Expectation> expectations = requestMatchers.retrieveActiveExpectations(null); assertThat( expectations, emptyCollectionOf(Expectation.class) ); } finally { ConfigurationProperties.initializationJsonPath(initializationJsonPath); ConfigurationProperties.watchInitializationJson(false); if (expectationFileWatcher != null) { expectationFileWatcher.stop(); } } } @Test public void shouldDetectModifiedInitialiserJsonOnUpdateNoChange() throws Exception { String initializationJsonPath = ConfigurationProperties.initializationJsonPath(); ConfigurationProperties.watchInitializationJson(true); ExpectationFileWatcher expectationFileWatcher = null; try { File mockserverInitialization = File.createTempFile("mockserverInitialization", ".json"); ConfigurationProperties.initializationJsonPath(mockserverInitialization.getAbsolutePath()); String watchedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecond\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"three\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleThird\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some third response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; Files.write(mockserverInitialization.toPath(), watchedFileContents.getBytes(StandardCharsets.UTF_8)); CompletableFuture<String> expectationsUpdated = new CompletableFuture<>(); requestMatchers.registerListener((requestMatchers, cause) -> expectationsUpdated.complete("updated")); expectationFileWatcher = new ExpectationFileWatcher(mockServerLogger, requestMatchers); MILLISECONDS.sleep(1500); Files.write(mockserverInitialization.toPath(), watchedFileContents.getBytes(StandardCharsets.UTF_8)); long updatedFileTime = System.currentTimeMillis(); expectationsUpdated.get(30, SECONDS); System.out.println("update processed in: " + (System.currentTimeMillis() - updatedFileTime) + "ms"); List<Expectation> expectations = requestMatchers.retrieveActiveExpectations(null); assertThat( expectations, contains( new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ) , new Expectation( request() .withPath("/simpleSecond") ) .withId("two") .thenRespond( response() .withBody("some second response") ), new Expectation( request() .withPath("/simpleThird") ) .withId("three") .thenRespond( response() .withBody("some third response") ) ) ); } finally { ConfigurationProperties.initializationJsonPath(initializationJsonPath); ConfigurationProperties.watchInitializationJson(false); if (expectationFileWatcher != null) { expectationFileWatcher.stop(); } } } @Test public void shouldDetectModifiedInitialiserJsonOnUpdateFileChanged() throws Exception { String initializationJsonPath = ConfigurationProperties.initializationJsonPath(); ConfigurationProperties.watchInitializationJson(true); ExpectationFileWatcher expectationFileWatcher = null; try { File mockserverInitialization = File.createTempFile("mockserverInitialization", ".json"); ConfigurationProperties.initializationJsonPath(mockserverInitialization.getAbsolutePath()); String watchedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecond\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"three\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleThird\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some third response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; Files.write(mockserverInitialization.toPath(), watchedFileContents.getBytes(StandardCharsets.UTF_8)); CompletableFuture<String> expectationsUpdated = new CompletableFuture<>(); requestMatchers.registerListener((requestMatchers, cause) -> expectationsUpdated.complete("updated")); expectationFileWatcher = new ExpectationFileWatcher(mockServerLogger, requestMatchers); MILLISECONDS.sleep(1500); watchedFileContents = "[ {" + NEW_LINE + " \"id\" : \"one\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFirst\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some first response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"two\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleSecondUpdated\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some second updated response\"" + NEW_LINE + " }" + NEW_LINE + "}, {" + NEW_LINE + " \"id\" : \"four\"," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/simpleFourth\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some fourth response\"" + NEW_LINE + " }" + NEW_LINE + "} ]"; Files.write(mockserverInitialization.toPath(), watchedFileContents.getBytes(StandardCharsets.UTF_8)); long updatedFileTime = System.currentTimeMillis(); expectationsUpdated.get(30, SECONDS); System.out.println("update processed in: " + (System.currentTimeMillis() - updatedFileTime) + "ms"); List<Expectation> expectations = requestMatchers.retrieveActiveExpectations(null); assertThat( expectations, contains( new Expectation( request() .withPath("/simpleFirst") ) .withId("one") .thenRespond( response() .withBody("some first response") ), new Expectation( request() .withPath("/simpleSecondUpdated") ) .withId("two") .thenRespond( response() .withBody("some second updated response") ), new Expectation( request() .withPath("/simpleFourth") ) .withId("four") .thenRespond( response() .withBody("some fourth response") ) ) ); } finally { ConfigurationProperties.initializationJsonPath(initializationJsonPath); ConfigurationProperties.watchInitializationJson(false); if (expectationFileWatcher != null) { expectationFileWatcher.stop(); } } }
ConfigurationProperties { public static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable) { System.setProperty(MOCKSERVER_USE_BOUNCY_CASTLE_FOR_KEY_AND_CERTIFICATE_GENERATION, "" + enable); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadUseBouncyCastleForKeyAndCertificateGeneration() { System.clearProperty("mockserver.useBouncyCastleForKeyAndCertificateGeneration"); assertFalse(useBouncyCastleForKeyAndCertificateGeneration()); useBouncyCastleForKeyAndCertificateGeneration(false); assertFalse(useBouncyCastleForKeyAndCertificateGeneration()); assertEquals("false", System.getProperty("mockserver.useBouncyCastleForKeyAndCertificateGeneration")); }
HopByHopHeaderFilter { public HttpRequest onRequest(HttpRequest request) { if (request != null) { List<String> headersToRemove = Arrays.asList( "proxy-connection", "connection", "keep-alive", "transfer-encoding", "te", "trailer", "proxy-authorization", "proxy-authenticate", "upgrade" ); Headers headers = new Headers(); for (Header header : request.getHeaderList()) { if (!headersToRemove.contains(header.getName().getValue().toLowerCase(Locale.ENGLISH))) { headers.withEntry(header); } } HttpRequest clonedRequest = request.clone(); if (!headers.isEmpty()) { clonedRequest.withHeaders(headers); } return clonedRequest; } else { return null; } } HttpRequest onRequest(HttpRequest request); }
@Test public void shouldNotForwardHopByHopHeaders() { HttpRequest httpRequest = new HttpRequest(); httpRequest.withHeaders( new Header("some_other_header"), new Header("proxy-connection"), new Header("connection"), new Header("keep-alive"), new Header("transfer-encoding"), new Header("te"), new Header("trailer"), new Header("proxy-authorization"), new Header("proxy-authenticate"), new Header("upgrade") ); httpRequest = new HopByHopHeaderFilter().onRequest(httpRequest); assertEquals(httpRequest.getHeaderList().size(), 1); } @Test public void shouldNotHandleNullRequest() { assertNull(new HopByHopHeaderFilter().onRequest(null)); }
XmlSchemaValidator extends ObjectWithReflectiveEqualsHashCodeToString implements Validator<String> { @Override public String isValid(String xml) { String errorMessage = ""; try { try { schema.newValidator().validate(new StreamSource(new ByteArrayInputStream(xml.getBytes(UTF_8)))); } catch (SAXException e) { errorMessage = e.getMessage(); } } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception validating JSON") .setThrowable(e) ); return e.getClass().getSimpleName() + " - " + e.getMessage(); } return errorMessage; } XmlSchemaValidator(MockServerLogger mockServerLogger, String schema); @Override String isValid(String xml); }
@Test public void shouldSupportXmlImports() { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<ParentType>" + NEW_LINE + " <embedded>" + NEW_LINE + " <numeric>12</numeric>" + NEW_LINE + " <embedded>" + NEW_LINE + " <numeric>5</numeric>" + NEW_LINE + " </embedded>" + NEW_LINE + " </embedded>" + NEW_LINE + "</ParentType>"; XmlSchemaValidator xmlSchemaValidator = new XmlSchemaValidator(new MockServerLogger(), xmlSchemaFromResource("org/mockserver/validator/xmlschema/parent.xsd").getValue()); assertThat(xmlSchemaValidator.isValid(xml), CoreMatchers.is("")); } @Test public void shouldMatchXml() { assertThat(new XmlSchemaValidator(new MockServerLogger(), XML_SCHEMA).isValid("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), is("")); } @Test public void shouldHandleXmlMissingRequiredFields() { assertThat( new XmlSchemaValidator(new MockServerLogger(), XML_SCHEMA).isValid("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), is(MessageFormat.format(message_cvc_complex_type_2_4_a, "heading", "{from}")) ); } @Test public void shouldHandleXmlExtraField() { assertThat( new XmlSchemaValidator(new MockServerLogger(), XML_SCHEMA).isValid("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), is(MessageFormat.format(message_cvc_complex_type_2_4_a, "to", "{from}")) ); } @Test public void shouldHandleNullTest() { assertThat(new XmlSchemaValidator(new MockServerLogger(), XML_SCHEMA).isValid(null), is("NullPointerException - null")); } @Test public void shouldHandleEmptyTest() { assertThat(new XmlSchemaValidator(new MockServerLogger(), XML_SCHEMA).isValid(""), is("Premature end of file.")); }
ConfigurationProperties { public static void preventCertificateDynamicUpdate(boolean prevent) { System.setProperty(MOCKSERVER_PREVENT_CERTIFICATE_DYNAMIC_UPDATE, "" + prevent); preventCertificateDynamicUpdate = Boolean.parseBoolean(readPropertyHierarchically(MOCKSERVER_PREVENT_CERTIFICATE_DYNAMIC_UPDATE, "MOCKSERVER_PREVENT_CERTIFICATE_DYNAMIC_UPDATE", DEFAULT_PREVENT_CERTIFICATE_DYNAMIC_UPDATE)); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadPreventCertificateDynamicUpdate() { System.clearProperty("mockserver.preventCertificateDynamicUpdate"); assertFalse(preventCertificateDynamicUpdate()); preventCertificateDynamicUpdate(false); assertFalse(preventCertificateDynamicUpdate()); assertEquals("false", System.getProperty("mockserver.preventCertificateDynamicUpdate")); }
JsonSchemaValidator extends ObjectWithReflectiveEqualsHashCodeToString implements Validator<String> { @Override public String isValid(String json) { return isValid(json, true); } JsonSchemaValidator(MockServerLogger mockServerLogger, String schema); JsonSchemaValidator(MockServerLogger mockServerLogger, String routePath, String mainSchemeFile, String... referenceFiles); String getSchema(); @Override String isValid(String json); String isValid(String json, boolean addOpenAPISpecificationMessage); static Stream<T> stream(Iterator<T> iterator); Set<String> extractMessage(JsonNode reports); static final String OPEN_API_SPECIFICATION_URL; }
@Test public void shouldMatchJson() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid("{arrayField: [ \"one\" ], enumField: \"one\"}"), is("")); } @Test public void shouldHandleJsonMissingRequiredFields() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid("{}"), is("1 error:" + NEW_LINE + " - object has missing required properties ([\"arrayField\",\"enumField\"])" + NEW_LINE + NEW_LINE + OPEN_API_SPECIFICATION_URL)); } @Test public void shouldHandleJsonTooFewItems() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid("{arrayField: [ ], enumField: \\\"one\\\"}"), is("JsonParseException - Unexpected character ('\\' (code 92)): expected a valid value (JSON String, Number (or 'NaN'/'INF'/'+INF'), Array, Object or token 'null', 'true' or 'false')" + NEW_LINE + " at [Source: (String)\"{arrayField: [ ], enumField: \\\"one\\\"}\"; line: 1, column: 39]")); } @Test public void shouldHandleJsonTooLongString() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid("{arrayField: [ \\\"one\\\" ], enumField: \\\"one\\\", stringField: \\\"1234567\\\"}"), is("JsonParseException - Unexpected character ('\\' (code 92)): expected a valid value (JSON String, Number (or 'NaN'/'INF'/'+INF'), Array, Object or token 'null', 'true' or 'false')" + NEW_LINE + " at [Source: (String)\"{arrayField: [ \\\"one\\\" ], enumField: \\\"one\\\", stringField: \\\"1234567\\\"}\"; line: 1, column: 17]")); } @Test public void shouldHandleJsonIncorrectEnum() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid("{arrayField: [ \\\"one\\\" ], enumField: \\\"four\\\"}"), is("JsonParseException - Unexpected character ('\\' (code 92)): expected a valid value (JSON String, Number (or 'NaN'/'INF'/'+INF'), Array, Object or token 'null', 'true' or 'false')" + NEW_LINE + " at [Source: (String)\"{arrayField: [ \\\"one\\\" ], enumField: \\\"four\\\"}\"; line: 1, column: 17]")); } @Test public void shouldHandleJsonExtraField() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid("{arrayField: [ \\\"one\\\" ], enumField: \\\"one\\\", extra: \\\"field\\\"}"), is("JsonParseException - Unexpected character ('\\' (code 92)): expected a valid value (JSON String, Number (or 'NaN'/'INF'/'+INF'), Array, Object or token 'null', 'true' or 'false')" + NEW_LINE + " at [Source: (String)\"{arrayField: [ \\\"one\\\" ], enumField: \\\"one\\\", extra: \\\"field\\\"}\"; line: 1, column: 17]")); } @Test public void shouldHandleJsonIncorrectSubField() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid("{arrayField: [ \\\"one\\\" ], enumField: \\\"one\\\", objectField: {stringField: \\\"1234\\\"} }"), is("JsonParseException - Unexpected character ('\\' (code 92)): expected a valid value (JSON String, Number (or 'NaN'/'INF'/'+INF'), Array, Object or token 'null', 'true' or 'false')" + NEW_LINE + " at [Source: (String)\"{arrayField: [ \\\"one\\\" ], enumField: \\\"one\\\", objectField: {stringField: \\\"1234\\\"} }\"; line: 1, column: 17]")); } @Test public void shouldHandleJsonMissingSubField() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid("{arrayField: [ \\\"one\\\" ], enumField: \\\"one\\\", objectField: { } }"), is("JsonParseException - Unexpected character ('\\' (code 92)): expected a valid value (JSON String, Number (or 'NaN'/'INF'/'+INF'), Array, Object or token 'null', 'true' or 'false')" + NEW_LINE + " at [Source: (String)\"{arrayField: [ \\\"one\\\" ], enumField: \\\"one\\\", objectField: { } }\"; line: 1, column: 17]")); } @Test public void shouldHandleJsonMultipleErrors() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid("{arrayField: [ ], stringField: \\\"1234\\\"}"), is("JsonParseException - Unexpected character ('\\' (code 92)): expected a valid value (JSON String, Number (or 'NaN'/'INF'/'+INF'), Array, Object or token 'null', 'true' or 'false')" + NEW_LINE + " at [Source: (String)\"{arrayField: [ ], stringField: \\\"1234\\\"}\"; line: 1, column: 34]")); } @Test public void shouldHandleIllegalJson() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Schema must either be a path reference to a *.json file or a json string"); new JsonSchemaValidator(mockServerLogger, "illegal_json").isValid("illegal_json"); } @Test public void shouldHandleNullExpectation() { exception.expect(NullPointerException.class); new JsonSchemaValidator(mockServerLogger, null).isValid("some_value"); } @Test public void shouldHandleEmptyExpectation() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Schema must either be a path reference to a *.json file or a json string"); new JsonSchemaValidator(mockServerLogger, "").isValid("some_value"); } @Test public void shouldHandleNullTest() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid(null), is("")); } @Test public void shouldHandleEmptyTest() { assertThat(new JsonSchemaValidator(mockServerLogger, JSON_SCHEMA).isValid(""), is("")); }
ConfigurationProperties { public static String certificateAuthorityPrivateKey() { return readPropertyHierarchically(MOCKSERVER_CERTIFICATE_AUTHORITY_PRIVATE_KEY, "MOCKSERVER_CERTIFICATE_AUTHORITY_PRIVATE_KEY", DEFAULT_CERTIFICATE_AUTHORITY_PRIVATE_KEY); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadCertificateAuthorityPrivateKey() { System.clearProperty("mockserver.certificateAuthorityPrivateKey"); assertEquals("org/mockserver/socket/PKCS8CertificateAuthorityPrivateKey.pem", certificateAuthorityPrivateKey()); certificateAuthorityPrivateKey("some/private_key.pem"); assertEquals("some/private_key.pem", certificateAuthorityPrivateKey()); assertEquals("some/private_key.pem", System.getProperty("mockserver.certificateAuthorityPrivateKey")); }
ExpectationInitializerLoader { public Expectation[] loadExpectations() { final Expectation[] expectationsFromInitializerClass = retrieveExpectationsFromInitializerClass(); final Expectation[] expectationsFromJson = retrieveExpectationsFromJson(); return ArrayUtils.addAll(expectationsFromInitializerClass, expectationsFromJson); } ExpectationInitializerLoader(MockServerLogger mockServerLogger, RequestMatchers requestMatchers); Expectation[] loadExpectations(); }
@Test public void shouldLoadExpectationsFromJson() { String initializationJsonPath = ConfigurationProperties.initializationJsonPath(); try { ConfigurationProperties.initializationJsonPath("org/mockserver/server/initialize/initializerJson.json"); final Expectation[] expectations = new ExpectationInitializerLoader(new MockServerLogger(), mock(RequestMatchers.class)).loadExpectations(); assertThat(expectations, is(new Expectation[]{ new Expectation( request() .withPath("/simpleFirst") ) .thenRespond( response() .withBody("some first response") ), new Expectation( request() .withPath("/simpleSecond") ) .thenRespond( response() .withBody("some second response") ) })); } finally { ConfigurationProperties.initializationJsonPath(initializationJsonPath); } } @Test public void shouldLoadExpectationsFromInitializerClass() { String initializationClass = ConfigurationProperties.initializationClass(); try { ConfigurationProperties.initializationClass(ExpectationInitializerExample.class.getName()); final Expectation[] expectations = new ExpectationInitializerLoader(new MockServerLogger(), mock(RequestMatchers.class)).loadExpectations(); assertThat(expectations, is(new Expectation[]{ new Expectation( request("/simpleFirst") ) .thenRespond( response("some first response") ), new Expectation( request("/simpleSecond") ) .thenRespond( response("some second response") ) })); } finally { ConfigurationProperties.initializationClass(initializationClass); } }
JavaScriptTemplateEngine implements TemplateEngine { @Override public <T> T executeTemplate(String template, HttpRequest request, Class<? extends DTO<T>> dtoClass) { T result = null; String script = "function handle(request) {" + indentAndToString(template)[0] + "}"; try { if (engine != null) { Compilable compilable = (Compilable) engine; CompiledScript compiledScript = compilable.compile(script + " function serialise(request) { return JSON.stringify(handle(JSON.parse(request)), null, 2); }"); Bindings bindings = engine.createBindings(); compiledScript.eval(bindings); ScriptObjectMirror scriptObjectMirror = (ScriptObjectMirror) bindings.get("serialise"); Object stringifiedResponse = scriptObjectMirror.call(null, new HttpRequestTemplateObject(request)); JsonNode generatedObject = null; try { generatedObject = OBJECT_MAPPER.readTree(String.valueOf(stringifiedResponse)); } catch (Throwable throwable) { if (MockServerLogger.isEnabled(Level.TRACE)) { logFormatter.logEvent( new LogEntry() .setLogLevel(Level.TRACE) .setHttpRequest(request) .setMessageFormat("exception deserialising generated content:{}into json node for request:{}") .setArguments(stringifiedResponse, request) ); } } if (MockServerLogger.isEnabled(Level.INFO)) { logFormatter.logEvent( new LogEntry() .setType(TEMPLATE_GENERATED) .setLogLevel(Level.INFO) .setHttpRequest(request) .setMessageFormat(TEMPLATE_GENERATED_MESSAGE_FORMAT) .setArguments(generatedObject != null ? generatedObject : stringifiedResponse, script, request) ); } result = httpTemplateOutputDeserializer.deserializer(request, (String) stringifiedResponse, dtoClass); } else { logFormatter.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setHttpRequest(request) .setMessageFormat( "JavaScript based templating is only available in a JVM with the \"nashorn\" JavaScript engine, " + "please use a JVM with the \"nashorn\" JavaScript engine, such as Oracle Java 8+" ) .setArguments(new RuntimeException("\"nashorn\" JavaScript engine not available")) ); } } catch (Exception e) { throw new RuntimeException(formatLogMessage("Exception transforming template:{}for request:{}", script, request), e); } return result; } JavaScriptTemplateEngine(MockServerLogger logFormatter); @Override T executeTemplate(String template, HttpRequest request, Class<? extends DTO<T>> dtoClass); }
@Test public void shouldHandleHttpRequestsWithJavaScriptTemplateFirstExample() { String template = "" + "if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': JSON.stringify({name: 'value'})" + NEW_LINE + " };" + NEW_LINE + "} else {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': request.body" + NEW_LINE + " };" + NEW_LINE + "}"; HttpResponse actualHttpResponse = new JavaScriptTemplateEngine(logFormatter).executeTemplate(template, request() .withPath("/somePath") .withMethod("POST") .withBody("some_body"), HttpResponseDTO.class ); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { assertThat(actualHttpResponse, is( response() .withStatusCode(200) .withBody("{\"name\":\"value\"}") )); } else { assertThat(actualHttpResponse, nullValue()); } } @Test public void shouldHandleHttpRequestsWithSlowJavaScriptTemplate() { String template = "" + "for (var i = 0; i < 1000000000; i++) {" + NEW_LINE + " i * i;" + NEW_LINE + "}" + NEW_LINE + "if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': JSON.stringify({name: 'value'})" + NEW_LINE + " };" + NEW_LINE + "} else {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': request.body" + NEW_LINE + " };" + NEW_LINE + "}"; HttpResponse actualHttpResponse = new JavaScriptTemplateEngine(logFormatter).executeTemplate(template, request() .withPath("/somePath") .withMethod("POST") .withBody("some_body"), HttpResponseDTO.class ); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { assertThat(actualHttpResponse, is( response() .withStatusCode(200) .withBody("{\"name\":\"value\"}") )); } else { assertThat(actualHttpResponse, nullValue()); } } @Test public void shouldHandleMultipleHttpRequestsInParallel() throws InterruptedException { final String template = "" + "for (var i = 0; i < 1000000000; i++) {" + NEW_LINE + " i * i;" + NEW_LINE + "}" + NEW_LINE + "if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': JSON.stringify({name: 'value'})" + NEW_LINE + " };" + NEW_LINE + "} else {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': request.body" + NEW_LINE + " };" + NEW_LINE + "}"; final JavaScriptTemplateEngine javaScriptTemplateEngine = new JavaScriptTemplateEngine(logFormatter); final HttpRequest request = request() .withPath("/somePath") .withMethod("POST") .withBody("some_body"); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { Thread[] threads = new Thread[3]; for (int i = 0; i < threads.length; i++) { threads[i] = new Scheduler.SchedulerThreadFactory("MockServer Test " + this.getClass().getSimpleName()).newThread(() -> assertThat(javaScriptTemplateEngine.executeTemplate(template, request, HttpResponseDTO.class ), is( response() .withStatusCode(200) .withBody("{\"name\":\"value\"}") ))); threads[i].start(); } for (Thread thread : threads) { thread.join(); } } else { assertThat(javaScriptTemplateEngine.executeTemplate(template, request, HttpResponseDTO.class ), nullValue()); } } @Test public void shouldHandleHttpRequestsWithJavaScriptTemplateSecondExample() { String template = "" + "if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': JSON.stringify({name: 'value'})" + NEW_LINE + " };" + NEW_LINE + "} else {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': request.body" + NEW_LINE + " };" + NEW_LINE + "}"; HttpResponse actualHttpResponse = new JavaScriptTemplateEngine(logFormatter).executeTemplate(template, request() .withPath("/someOtherPath") .withBody("some_body"), HttpResponseDTO.class ); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { assertThat(actualHttpResponse, is( response() .withStatusCode(406) .withBody("some_body") )); } else { assertThat(actualHttpResponse, nullValue()); } } @Test public void shouldHandleHttpRequestsWithJavaScriptForwardTemplateFirstExample() { String template = "" + "return {" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'cookies' : [ {" + NEW_LINE + " 'name' : request.cookies['someCookie']," + NEW_LINE + " 'value' : \"someCookie\"" + NEW_LINE + " }, {" + NEW_LINE + " 'name' : \"someCookie\"," + NEW_LINE + " 'value' : request.cookies['someCookie']" + NEW_LINE + " } ]," + NEW_LINE + " 'keepAlive' : true," + NEW_LINE + " 'secure' : true," + NEW_LINE + " 'body' : \"some_body\"" + NEW_LINE + "};"; HttpRequest actualHttpRequest = new JavaScriptTemplateEngine(logFormatter).executeTemplate(template, request() .withPath("/somePath") .withCookie("someCookie", "someValue") .withMethod("POST") .withBody("some_body"), HttpRequestDTO.class ); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { assertThat(actualHttpRequest, is( request() .withPath("/somePath") .withCookie("someCookie", "someValue") .withCookie("someValue", "someCookie") .withKeepAlive(true) .withSecure(true) .withBody("some_body") )); } else { assertThat(actualHttpRequest, nullValue()); } } @Test public void shouldHandleHttpRequestsWithJavaScriptForwardTemplateSecondExample() { String template = "" + "return {" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'queryStringParameters' : [ {" + NEW_LINE + " 'name' : \"queryParameter\"," + NEW_LINE + " 'values' : request.queryStringParameters['queryParameter']" + NEW_LINE + " } ]," + NEW_LINE + " 'headers' : [ {" + NEW_LINE + " 'name' : \"Host\"," + NEW_LINE + " 'values' : [ \"localhost:1090\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + "};"; HttpRequest actualHttpRequest = new JavaScriptTemplateEngine(logFormatter).executeTemplate(template, request() .withPath("/someOtherPath") .withQueryStringParameter("queryParameter", "someValue") .withBody("some_body"), HttpRequestDTO.class ); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { assertThat(actualHttpRequest, is( request() .withHeader("Host", "localhost:1090") .withPath("/somePath") .withQueryStringParameter("queryParameter", "someValue") .withBody("{'name': 'value'}") )); } else { assertThat(actualHttpRequest, nullValue()); } } @Test public void shouldHandleInvalidJavaScript() { String template = "{" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'queryStringParameters' : [ {" + NEW_LINE + " 'name' : \"queryParameter\"," + NEW_LINE + " 'values' : request.queryStringParameters['queryParameter']" + NEW_LINE + " } ]," + NEW_LINE + " 'headers' : [ {" + NEW_LINE + " 'name' : \"Host\"," + NEW_LINE + " 'values' : [ \"localhost:1090\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + "};"; if (new ScriptEngineManager().getEngineByName("nashorn") != null) { exception.expect(RuntimeException.class); exception.expectCause(isA(ScriptException.class)); exception.expectMessage(containsString("Exception transforming template:" + NEW_LINE + NEW_LINE + " function handle(request) {" + NEW_LINE + " " + NEW_LINE + " {" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'queryStringParameters' : [ {" + NEW_LINE + " 'name' : \"queryParameter\"," + NEW_LINE + " 'values' : request.queryStringParameters['queryParameter']" + NEW_LINE + " } ]," + NEW_LINE + " 'headers' : [ {" + NEW_LINE + " 'name' : \"Host\"," + NEW_LINE + " 'values' : [ \"localhost:1090\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + " };" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " for request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"path\" : \"/someOtherPath\"," + NEW_LINE + " \"queryStringParameters\" : {" + NEW_LINE + " \"queryParameter\" : [ \"someValue\" ]" + NEW_LINE + " }," + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }")); } new JavaScriptTemplateEngine(logFormatter).executeTemplate(template, request() .withPath("/someOtherPath") .withQueryStringParameter("queryParameter", "someValue") .withBody("some_body"), HttpRequestDTO.class ); } @Test public void shouldRestrictGlobalContextMultipleHttpRequestsInParallel() throws InterruptedException, ExecutionException { final String template = "" + "var resbody = \"ok\"; " + NEW_LINE + "if (request.path.match(\".*1$\")) { " + NEW_LINE + " resbody = \"nok\"; " + NEW_LINE + "}; " + NEW_LINE + "resp = { " + NEW_LINE + " 'statusCode': 200, " + " 'body': resbody" + NEW_LINE + "}; " + NEW_LINE + "return resp;"; final JavaScriptTemplateEngine javaScriptTemplateEngine = new JavaScriptTemplateEngine(logFormatter); final HttpRequest ok = request() .withPath("/somePath/0") .withMethod("POST") .withBody("some_body"); final HttpRequest nok = request() .withPath("/somePath/1") .withMethod("POST") .withBody("another_body"); if (new ScriptEngineManager().getEngineByName("nashorn") != null) { ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(30); List<Future<Boolean>> futures = new ArrayList<>(); for (int i = 0; i < 100; i++) { futures.add(newFixedThreadPool.submit(() -> { assertThat(javaScriptTemplateEngine.executeTemplate(template, ok, HttpResponseDTO.class ), is( response() .withStatusCode(200) .withBody("ok") )); return true; })); futures.add(newFixedThreadPool.submit(() -> { assertThat(javaScriptTemplateEngine.executeTemplate(template, nok, HttpResponseDTO.class ), is( response() .withStatusCode(200) .withBody("nok") )); return true; })); } for (Future<Boolean> future : futures) { future.get(); } newFixedThreadPool.shutdown(); } else { assertThat(javaScriptTemplateEngine.executeTemplate(template, ok, HttpResponseDTO.class ), nullValue()); } }
ConfigurationProperties { public static String certificateAuthorityCertificate() { return readPropertyHierarchically(MOCKSERVER_CERTIFICATE_AUTHORITY_X509_CERTIFICATE, "MOCKSERVER_CERTIFICATE_AUTHORITY_X509_CERTIFICATE", DEFAULT_CERTIFICATE_AUTHORITY_X509_CERTIFICATE); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadCertificateAuthorityCertificate() throws IOException { System.clearProperty("mockserver.certificateAuthorityCertificate"); assertEquals("org/mockserver/socket/CertificateAuthorityCertificate.pem", certificateAuthorityCertificate()); File tempFile = File.createTempFile("prefix", "suffix"); certificateAuthorityCertificate(tempFile.getAbsolutePath()); assertEquals(tempFile.getAbsolutePath(), certificateAuthorityCertificate()); assertEquals(tempFile.getAbsolutePath(), System.getProperty("mockserver.certificateAuthorityCertificate")); }
VelocityTemplateEngine implements TemplateEngine { @Override public <T> T executeTemplate(String template, HttpRequest request, Class<? extends DTO<T>> dtoClass) { T result; try { Writer writer = new StringWriter(); ScriptContext context = new SimpleScriptContext(); context.setWriter(writer); context.setAttribute("request", new HttpRequestTemplateObject(request), ScriptContext.ENGINE_SCOPE); engine.eval(template, context); JsonNode generatedObject = null; try { generatedObject = OBJECT_MAPPER.readTree(writer.toString()); } catch (Throwable throwable) { if (MockServerLogger.isEnabled(Level.TRACE)) { logFormatter.logEvent( new LogEntry() .setLogLevel(Level.TRACE) .setHttpRequest(request) .setMessageFormat("exception deserialising generated content:{}into json node for request:{}") .setArguments(writer.toString(), request) ); } } if (MockServerLogger.isEnabled(Level.INFO)) { logFormatter.logEvent( new LogEntry() .setType(TEMPLATE_GENERATED) .setLogLevel(Level.INFO) .setHttpRequest(request) .setMessageFormat(TEMPLATE_GENERATED_MESSAGE_FORMAT) .setArguments(generatedObject != null ? generatedObject : writer.toString(), template, request) ); } result = httpTemplateOutputDeserializer.deserializer(request, writer.toString(), dtoClass); } catch (Exception e) { throw new RuntimeException(formatLogMessage("Exception transforming template:{}for request:{}", template, request), e); } return result; } VelocityTemplateEngine(MockServerLogger logFormatter); @Override T executeTemplate(String template, HttpRequest request, Class<? extends DTO<T>> dtoClass); }
@Test public void shouldHandleHttpRequestsWithVelocityResponseTemplateFirstExample() throws JsonProcessingException { String template = "#if ( $request.method == 'POST' && $request.path == '/somePath' )" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + " }" + NEW_LINE + "#else" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': \"$!request.body\"" + NEW_LINE + " }" + NEW_LINE + "#end"; HttpRequest request = request() .withPath("/somePath") .withMethod("POST") .withBody("some_body"); HttpResponse actualHttpResponse = new VelocityTemplateEngine(logFormatter).executeTemplate(template, request, HttpResponseDTO.class); assertThat(actualHttpResponse, is( response() .withStatusCode(200) .withBody("{'name': 'value'}") )); verify(logFormatter).logEvent( new LogEntry() .setType(TEMPLATE_GENERATED) .setLogLevel(INFO) .setHttpRequest(request) .setMessageFormat("generated output:{}from template:{}for request:{}") .setArguments(OBJECT_MAPPER.readTree("" + " {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + " }" + NEW_LINE), template, request ) ); } @Test public void shouldHandleHttpRequestsWithVelocityResponseTemplateSecondExample() throws JsonProcessingException { String template = "#if ( $request.method == 'POST' && $request.path == '/somePath' )" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + " }" + NEW_LINE + "#else" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': \"$!request.body\"" + NEW_LINE + " }" + NEW_LINE + "#end"; HttpRequest request = request() .withPath("/someOtherPath") .withBody("some_body"); HttpResponse actualHttpResponse = new VelocityTemplateEngine(logFormatter).executeTemplate(template, request, HttpResponseDTO.class); assertThat(actualHttpResponse, is( response() .withStatusCode(406) .withBody("some_body") )); verify(logFormatter).logEvent( new LogEntry() .setType(TEMPLATE_GENERATED) .setLogLevel(INFO) .setHttpRequest(request) .setMessageFormat("generated output:{}from template:{}for request:{}") .setArguments(OBJECT_MAPPER.readTree("" + " {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': \"some_body\"" + NEW_LINE + " }" + NEW_LINE), template, request ) ); } @Test public void shouldHandleHttpRequestsWithVelocityForwardTemplateFirstExample() throws JsonProcessingException { String template = "{" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'cookies' : [ {" + NEW_LINE + " 'name' : \"$!request.cookies['someCookie']\"," + NEW_LINE + " 'value' : \"someCookie\"" + NEW_LINE + " }, {" + NEW_LINE + " 'name' : \"someCookie\"," + NEW_LINE + " 'value' : \"$!request.cookies['someCookie']\"" + NEW_LINE + " } ]," + NEW_LINE + " 'keepAlive' : true," + NEW_LINE + " 'secure' : true," + NEW_LINE + " 'body' : \"some_body\"" + NEW_LINE + "}"; HttpRequest request = request() .withPath("/somePath") .withCookie("someCookie", "someValue") .withMethod("POST") .withBody("some_body"); HttpRequest actualHttpRequest = new VelocityTemplateEngine(logFormatter).executeTemplate(template, request, HttpRequestDTO.class); assertThat(actualHttpRequest, is( request() .withPath("/somePath") .withCookie("someCookie", "someValue") .withCookie("someValue", "someCookie") .withKeepAlive(true) .withSecure(true) .withBody("some_body") )); verify(logFormatter).logEvent( new LogEntry() .setType(TEMPLATE_GENERATED) .setLogLevel(INFO) .setHttpRequest(request) .setMessageFormat("generated output:{}from template:{}for request:{}") .setArguments(OBJECT_MAPPER.readTree("" + "{" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'cookies' : [ {" + NEW_LINE + " 'name' : \"someValue\"," + NEW_LINE + " 'value' : \"someCookie\"" + NEW_LINE + " }, {" + NEW_LINE + " 'name' : \"someCookie\"," + NEW_LINE + " 'value' : \"someValue\"" + NEW_LINE + " } ]," + NEW_LINE + " 'keepAlive' : true," + NEW_LINE + " 'secure' : true," + NEW_LINE + " 'body' : \"some_body\"" + NEW_LINE + "}"), template, request ) ); } @Test public void shouldHandleHttpRequestsWithVelocityForwardTemplateSecondExample() throws JsonProcessingException { String template = "{" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'queryStringParameters' : [ {" + NEW_LINE + " 'name' : \"queryParameter\"," + NEW_LINE + " 'values' : [ \"$!request.queryStringParameters['queryParameter'][0]\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'headers' : [ {" + NEW_LINE + " 'name' : \"Host\"," + NEW_LINE + " 'values' : [ \"localhost:1090\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + "}"; HttpRequest request = request() .withPath("/someOtherPath") .withQueryStringParameter("queryParameter", "someValue") .withBody("some_body"); HttpRequest actualHttpRequest = new VelocityTemplateEngine(logFormatter).executeTemplate(template, request, HttpRequestDTO.class); assertThat(actualHttpRequest, is( request() .withHeader("Host", "localhost:1090") .withPath("/somePath") .withQueryStringParameter("queryParameter", "someValue") .withBody("{'name': 'value'}") )); verify(logFormatter).logEvent( new LogEntry() .setType(TEMPLATE_GENERATED) .setLogLevel(INFO) .setHttpRequest(request) .setMessageFormat("generated output:{}from template:{}for request:{}") .setArguments(OBJECT_MAPPER.readTree("" + "{" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'queryStringParameters' : [ {" + NEW_LINE + " 'name' : \"queryParameter\"," + NEW_LINE + " 'values' : [ \"someValue\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'headers' : [ {" + NEW_LINE + " 'name' : \"Host\"," + NEW_LINE + " 'values' : [ \"localhost:1090\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + "}"), template, request ) ); } @Test public void shouldHandleInvalidVelocityTemplate() { String template = "#if {" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'queryStringParameters' : [ {" + NEW_LINE + " 'name' : \"queryParameter\"," + NEW_LINE + " 'values' : [ \"$!request.queryStringParameters['queryParameter'][0]\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'headers' : [ {" + NEW_LINE + " 'name' : \"Host\"," + NEW_LINE + " 'values' : [ \"localhost:1090\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + "}"; exception.expect(RuntimeException.class); exception.expectCause(isA(ScriptException.class)); exception.expectMessage(containsString("Exception transforming template:" + NEW_LINE + NEW_LINE + " #if {" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'queryStringParameters' : [ {" + NEW_LINE + " 'name' : \"queryParameter\"," + NEW_LINE + " 'values' : [ \"$!request.queryStringParameters['queryParameter'][0]\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'headers' : [ {" + NEW_LINE + " 'name' : \"Host\"," + NEW_LINE + " 'values' : [ \"localhost:1090\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " for request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"path\" : \"/someOtherPath\"," + NEW_LINE + " \"queryStringParameters\" : {" + NEW_LINE + " \"queryParameter\" : [ \"someValue\" ]" + NEW_LINE + " }," + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }")); new VelocityTemplateEngine(logFormatter).executeTemplate(template, request() .withPath("/someOtherPath") .withQueryStringParameter("queryParameter", "someValue") .withBody("some_body"), HttpRequestDTO.class ); } @Test public void shouldHandleMultipleHttpRequestsWithVelocityResponseTemplateInParallel() throws InterruptedException, ExecutionException { String template = "#if ( $request.method == 'POST' && $request.path == '/somePath' )" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + " }" + NEW_LINE + "#else" + NEW_LINE + " {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': \"$!request.body\"" + NEW_LINE + " }" + NEW_LINE + "#end"; HttpRequest request = request() .withPath("/somePath") .withMethod("POST") .withBody("some_body"); VelocityTemplateEngine velocityTemplateEngine = new VelocityTemplateEngine(logFormatter); ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(30); List<Future<Boolean>> futures = new ArrayList<>(); for (int i = 0; i < 100; i++) { futures.add(newFixedThreadPool.submit(() -> { assertThat(velocityTemplateEngine.executeTemplate(template, request, HttpResponseDTO.class), is( response() .withStatusCode(200) .withBody("{'name': 'value'}") )); return true; })); } for (Future<Boolean> future : futures) { future.get(); } newFixedThreadPool.shutdown(); }
ConfigurationProperties { public static boolean dynamicallyCreateCertificateAuthorityCertificate() { return Boolean.parseBoolean(readPropertyHierarchically(MOCKSERVER_DYNAMICALLY_CREATE_CERTIFICATE_AUTHORITY_CERTIFICATE, "MOCKSERVER_DYNAMICALLY_CREATE_CERTIFICATE_AUTHORITY_CERTIFICATE", DEFAULT_MOCKSERVER_DYNAMICALLY_CREATE_CERTIFICATE_AUTHORITY_CERTIFICATE)); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadDynamicallyCreateCertificateAuthorityCertificate() { System.clearProperty("mockserver.dynamicallyCreateCertificateAuthorityCertificate"); assertFalse(dynamicallyCreateCertificateAuthorityCertificate()); dynamicallyCreateCertificateAuthorityCertificate(true); assertTrue(dynamicallyCreateCertificateAuthorityCertificate()); assertEquals("true", System.getProperty("mockserver.dynamicallyCreateCertificateAuthorityCertificate")); }
SocksDetector { public static boolean isSocks4(ByteBuf msg, int actualReadableBytes) { int i = msg.readerIndex(); if (SocksVersion.valueOf(msg.getByte(i++)) != SocksVersion.SOCKS4a) { return false; } Socks4CommandType commandType = Socks4CommandType.valueOf(msg.getByte(i++)); if (!(commandType.equals(Socks4CommandType.CONNECT) || commandType.equals(Socks4CommandType.BIND))) { return false; } if (-1 == (i = consumeFields(msg, i + 2))) { return false; } return i == actualReadableBytes; } private SocksDetector(); static boolean isSocks4(ByteBuf msg, int actualReadableBytes); static boolean isSocks5(ByteBuf msg, int actualReadableBytes); }
@Test public void successfullyParseSocks4ConnectRequest() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 'f', 'o', 'o', 0x00 }); assertTrue(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void successfullyParseSocks4BindRequest() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x02, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 'f', 'o', 'o', 0x00 }); assertTrue(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void successfullyParseSocks4RequestWithEmptyUsername() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x00 }); assertTrue(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void successfullyParseSocks4RequestWithMaxLengthUsername() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', 0x00 }); assertTrue(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void failParsingSocks4RequestWithWrongProtocolVersion() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x05, 0x01, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 'f', 'o', 'o', 0x00 }); assertFalse(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void failParsingSocks4RequestWithUnsupportedCommandCode() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x03, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 'f', 'o', 'o', 0x00 }); assertFalse(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void failParsingSocks4RequestWithTooLongUsername() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', 0x00 }); assertFalse(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void failParsingSocks4RequestWithAdditionalReadableBytes() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 'f', 'o', 'o', 0x00, 0x00 }); assertFalse(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void successfullyParseSocks4aRequest() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 'f', 'o', 'o', 0x00, 'f', 'o', 'o', 0x00 }); assertTrue(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void successfullyParseSocks4aRequestWithEmptyUsername() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 'f', 'o', 'o', 0x00 }); assertTrue(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void successfullyParseSocks4aRequestWithMaxLengthHostname() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 'f', 'o', 'o', 0x00, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', 0x00 }); assertTrue(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void failParsingSocks4aRequestWithTooLongHostname() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 'f', 'o', 'o', 0x00, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', 0x00 }); assertFalse(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void failParsingSocks4aRequestWithEmptyHostname() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 'f', 'o', 'o', 0x00, 0x00 }); assertFalse(SocksDetector.isSocks4(msg, msg.readableBytes())); } @Test public void failParsingSocks4aRequestWithAdditionalReadableBytes() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 'f', 'o', 'o', 0x00, 'f', 'o', 'o', 0x00, 0x00 }); assertFalse(SocksDetector.isSocks4(msg, msg.readableBytes())); }
ConfigurationProperties { public static String directoryToSaveDynamicSSLCertificate() { return readPropertyHierarchically(MOCKSERVER_CERTIFICATE_DIRECTORY_TO_SAVE_DYNAMIC_SSL_CERTIFICATE, "MOCKSERVER_CERTIFICATE_DIRECTORY_TO_SAVE_DYNAMIC_SSL_CERTIFICATE", ""); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadDirectoryToSaveDynamicSSLCertificate() throws IOException { System.clearProperty("mockserver.directoryToSaveDynamicSSLCertificate"); assertThat(directoryToSaveDynamicSSLCertificate(), is("")); try { directoryToSaveDynamicSSLCertificate("some/random/path"); fail("expected exception to be thrown"); } catch (Throwable throwable) { assertThat(throwable, instanceOf(RuntimeException.class)); assertThat(throwable.getMessage(), is("some/random/path does not exist or is not accessible")); } File tempFile = File.createTempFile("prefix", "suffix"); directoryToSaveDynamicSSLCertificate(tempFile.getAbsolutePath()); assertThat(directoryToSaveDynamicSSLCertificate(), is(tempFile.getAbsolutePath())); assertThat(System.getProperty("mockserver.directoryToSaveDynamicSSLCertificate"), is(tempFile.getAbsolutePath())); }
SocksDetector { public static boolean isSocks5(ByteBuf msg, int actualReadableBytes) { if (SocksVersion.valueOf(msg.getByte(msg.readerIndex())) != SocksVersion.SOCKS5) { return false; } byte numberOfAuthenticationMethods = msg.getByte(msg.readerIndex() + 1); for (int i = 0; i < numberOfAuthenticationMethods; i++) { Socks5AuthMethod authMethod = Socks5AuthMethod.valueOf(msg.getByte(msg.readerIndex() + 2 + i)); if (!(NO_AUTH.equals(authMethod) || PASSWORD.equals(authMethod) || GSSAPI.equals(authMethod))) { return false; } } return actualReadableBytes == (2 + numberOfAuthenticationMethods); } private SocksDetector(); static boolean isSocks4(ByteBuf msg, int actualReadableBytes); static boolean isSocks5(ByteBuf msg, int actualReadableBytes); }
@Test public void successfullyParseSocks5Request() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x05, 0x02, 0x00, 0x02 }); assertTrue(SocksDetector.isSocks5(msg, msg.readableBytes())); } @Test public void successfullyParseSocks5RequestWithManyMethods() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x05, 0x05, 0x00, 0x01, 0x02, 0x00, 0x01 }); assertTrue(SocksDetector.isSocks5(msg, msg.readableBytes())); } @Test public void failParsingSocks5RequestWithWrongProtocolVersion() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x04, 0x05, 0x00, 0x01, 0x02, 0x00, 0x01 }); assertFalse(SocksDetector.isSocks5(msg, msg.readableBytes())); } @Test public void failParsingSocks5RequestWithUnsupportedAuthenticationMethod() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x05, 0x01, 0x05 }); assertFalse(SocksDetector.isSocks5(msg, msg.readableBytes())); } @Test public void failParsingSocks5RequestWithAdditionalReadableBytes() { ByteBuf msg = Unpooled.wrappedBuffer(new byte[]{ 0x05, 0x01, 0x00, 0x00 }); assertFalse(SocksDetector.isSocks5(msg, msg.readableBytes())); }
ConfigurationProperties { public static String privateKeyPath() { return readPropertyHierarchically(MOCKSERVER_TLS_PRIVATE_KEY_PATH, "MOCKSERVER_TLS_PRIVATE_KEY_PATH", ""); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadPrivateKeyPath() throws IOException { System.clearProperty("mockserver.privateKeyPath"); assertThat(privateKeyPath(), is("")); File tempFile = File.createTempFile("some", "temp"); privateKeyPath(tempFile.getAbsolutePath()); assertThat(privateKeyPath(), is(tempFile.getAbsolutePath())); assertEquals(tempFile.getAbsolutePath(), System.getProperty("mockserver.privateKeyPath")); }
DescriptionProcessor { public Description description(Object object) { return description(object, null); } int getMaxHttpRequestLength(); int getMaxOpenAPILength(); int getMaxOpenAPIObjectLength(); int getMaxLogEventLength(); Description description(Object object); Description description(Object object, String id); }
@Test public void shouldSerialiseMultipleLogMessageDescriptions() throws JsonProcessingException { DescriptionProcessor descriptionProcessor = new DescriptionProcessor(); List<Description> logMessageDescriptions = Arrays.asList( descriptionProcessor.description(new DashboardLogEntryDTO(new LogEntry().setEpochTime(epochTime).setType(EXPECTATION_RESPONSE))), descriptionProcessor.description(new DashboardLogEntryDTO(new LogEntry().setEpochTime(epochTime).setType(DEBUG))), descriptionProcessor.description(new DashboardLogEntryDTO(new LogEntry().setEpochTime(epochTime).setType(TEMPLATE_GENERATED))) ); String json = objectWriter.writeValueAsString(logMessageDescriptions); assertThat(json, is("[ " + "\"" + timeStamp + " EXPECTATION_RESPONSE \", " + "\"" + timeStamp + " DEBUG \", " + "\"" + timeStamp + " TEMPLATE_GENERATED \" " + "]")); } @Test public void shouldSerialiseMultipleOpenAPIDefinitions() throws JsonProcessingException { DescriptionProcessor descriptionProcessor = new DescriptionProcessor(); List<Description> logMessageDescriptions = Arrays.asList( descriptionProcessor.description( openAPI() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) .withOperationId("showPetById") ), descriptionProcessor.description( openAPI() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) ), descriptionProcessor.description( openAPI() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") ), descriptionProcessor.description( openAPI() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("someOtherOperationId") ), descriptionProcessor.description( openAPI() .withSpecUrlOrPayload("https: .withOperationId("someOtherOtherOperationId") ), descriptionProcessor.description( openAPI() .withSpecUrlOrPayload("https: ) ); String json = objectWriter.writeValueAsString(logMessageDescriptions); assertThat(json, is("[ " + "{" + NEW_LINE + " \"json\" : true," + NEW_LINE + " \"object\" : {" + NEW_LINE + " \"openapi\" : \"3.0.0\"," + NEW_LINE + " \"servers\" : [ {" + NEW_LINE + " \"url\" : \"/\"" + NEW_LINE + " } ]," + NEW_LINE + " \"paths\" : {" + NEW_LINE + " \"/somePath\" : {" + NEW_LINE + " \"get\" : {" + NEW_LINE + " \"operationId\" : \"someOperation\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"components\" : { }" + NEW_LINE + " }," + NEW_LINE + " \"first\" : \"spec \"," + NEW_LINE + " \"second\" : \" showPetById\"" + NEW_LINE + "}, " + "{" + NEW_LINE + " \"json\" : true," + NEW_LINE + " \"object\" : {" + NEW_LINE + " \"openapi\" : \"3.0.0\"," + NEW_LINE + " \"servers\" : [ {" + NEW_LINE + " \"url\" : \"/\"" + NEW_LINE + " } ]," + NEW_LINE + " \"paths\" : {" + NEW_LINE + " \"/somePath\" : {" + NEW_LINE + " \"get\" : {" + NEW_LINE + " \"operationId\" : \"someOperation\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"components\" : { }" + NEW_LINE + " }," + NEW_LINE + " \"first\" : \"spec \"," + NEW_LINE + " \"second\" : \" \"" + NEW_LINE + "}, " + "\"openapi_petstore_example.json \", " + "\"openapi_petstore_example.json someOtherOperationId\", " + "\"petstore-expanded.yaml someOtherOtherOperationId\", " + "\"petstore-expanded.yaml \" " + "]")); } @Test public void shouldSerialiseMultipleHttpRequestDefinitions() throws JsonProcessingException { DescriptionProcessor descriptionProcessor = new DescriptionProcessor(); List<Description> logMessageDescriptions = Arrays.asList( descriptionProcessor.description( request() .withPath("somePathOne") .withMethod("POST") ), descriptionProcessor.description( request() .withPath("veryLongPathThatHasASillyLength") ), descriptionProcessor.description( request() .withMethod("POST") ), descriptionProcessor.description( request() .withPath("somePathOne") ), descriptionProcessor.description( request() ) ); String json = objectWriter.writeValueAsString(logMessageDescriptions); assertThat(json, is("[ " + "\"POST somePathOne\", " + "\" veryLongPathThatHasASillyLength\", " + "\"POST \", " + "\" somePathOne\", " + "\" \" " + "]")); } @Test public void shouldSerialiseMultipleHttpRequestAndOpenAPIDefinitions() throws JsonProcessingException { DescriptionProcessor descriptionProcessor = new DescriptionProcessor(); List<Description> logMessageDescriptions = Arrays.asList( descriptionProcessor.description( request() .withPath("somePathOne") .withMethod("POST") ), descriptionProcessor.description( request() .withPath("veryLongPathThatHasASillyLength") ), descriptionProcessor.description( request() .withMethod("POST") ), descriptionProcessor.description( request() .withPath("somePathOne") ), descriptionProcessor.description( request() ), descriptionProcessor.description( openAPI() .withSpecUrlOrPayload("---" + NEW_LINE + "openapi: 3.0.0" + NEW_LINE + "paths:" + NEW_LINE + " \"/somePath\":" + NEW_LINE + " get:" + NEW_LINE + " operationId: someOperation" + NEW_LINE) ), descriptionProcessor.description( openAPI() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") ), descriptionProcessor.description( openAPI() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") .withOperationId("someOtherOperationId") ) ); String json = objectWriter.writeValueAsString(logMessageDescriptions); assertThat(json, is("[ " + "\"POST somePathOne\", " + "\" veryLongPathThatHasASillyLength\", " + "\"POST \", " + "\" somePathOne\", " + "\" \", " + "{" + NEW_LINE + " \"json\" : true," + NEW_LINE + " \"object\" : {" + NEW_LINE + " \"openapi\" : \"3.0.0\"," + NEW_LINE + " \"servers\" : [ {" + NEW_LINE + " \"url\" : \"/\"" + NEW_LINE + " } ]," + NEW_LINE + " \"paths\" : {" + NEW_LINE + " \"/somePath\" : {" + NEW_LINE + " \"get\" : {" + NEW_LINE + " \"operationId\" : \"someOperation\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"components\" : { }" + NEW_LINE + " }," + NEW_LINE + " \"first\" : \"spec \"," + NEW_LINE + " \"second\" : \" \"" + NEW_LINE + "}, " + "\"openapi_petstore_example.json \", " + "\"openapi_petstore_example.json someOtherOperationId\" " + "]")); }
Main { public static void main(String... arguments) { try { Map<String, String> parsedArguments = parseArguments(arguments); if (MockServerLogger.isEnabled(DEBUG)) { MOCK_SERVER_LOGGER.logEvent( new LogEntry() .setType(SERVER_CONFIGURATION) .setLogLevel(DEBUG) .setMessageFormat("using command line options:{}") .setArguments(Joiner.on(", ").withKeyValueSeparator("=").join(parsedArguments)) ); } if (parsedArguments.size() > 0 && parsedArguments.containsKey(serverPort.name())) { if (parsedArguments.containsKey(logLevel.name())) { ConfigurationProperties.logLevel(parsedArguments.get(logLevel.name())); } Integer[] localPorts = INTEGER_STRING_LIST_PARSER.toArray(parsedArguments.get(serverPort.name())); if (parsedArguments.containsKey(proxyRemotePort.name())) { String remoteHost = parsedArguments.get(proxyRemoteHost.name()); if (isBlank(remoteHost)) { remoteHost = "localhost"; } new MockServer(Integer.parseInt(parsedArguments.get(proxyRemotePort.name())), remoteHost, localPorts); } else { new MockServer(localPorts); } setPort(localPorts); if (ConfigurationProperties.logLevel() != null) { MOCK_SERVER_LOGGER.logEvent( new LogEntry() .setType(SERVER_CONFIGURATION) .setLogLevel(ConfigurationProperties.logLevel()) .setMessageFormat("logger level is " + ConfigurationProperties.logLevel() + ", change using:\n - 'ConfigurationProperties.logLevel(String level)' in Java code,\n - '-logLevel' command line argument,\n - 'mockserver.logLevel' JVM system property or,\n - 'mockserver.logLevel' property value in 'mockserver.properties'") ); } } else { showUsage(); } } catch (Throwable throwable) { MOCK_SERVER_LOGGER.logEvent( new LogEntry() .setType(SERVER_CONFIGURATION) .setLogLevel(ERROR) .setMessageFormat("exception while starting:{}") .setThrowable(throwable) ); if (ConfigurationProperties.disableSystemOut()) { System.out.println("exception while starting: " + throwable); } showUsage(); } } static void main(String... arguments); }
@Test public void shouldStartMockServer() { final int freePort = PortFactory.findFreePort(); MockServerClient mockServerClient = new MockServerClient("127.0.0.1", freePort); Level originalLogLevel = ConfigurationProperties.logLevel(); try { Main.main( "-serverPort", String.valueOf(freePort), "-logLevel", "DEBUG" ); assertThat(mockServerClient.hasStarted(), is(true)); assertThat(ConfigurationProperties.logLevel().toString(), is("DEBUG")); } finally { ConfigurationProperties.logLevel(originalLogLevel.toString()); stopQuietly(mockServerClient); } } @Test public void shouldStartMockServerWithRemotePortAndHost() { final int freePort = PortFactory.findFreePort(); MockServerClient mockServerClient = new MockServerClient("127.0.0.1", freePort); try { EchoServer echoServer = new EchoServer(false); echoServer.withNextResponse(response("port_forwarded_response")); Main.main( "-serverPort", String.valueOf(freePort), "-proxyRemotePort", String.valueOf(echoServer.getPort()), "-proxyRemoteHost", "127.0.0.1" ); final HttpResponse response = new NettyHttpClient(new MockServerLogger(), clientEventLoopGroup, null, false) .sendRequest( request() .withHeader(HOST.toString(), "127.0.0.1:" + freePort), 10, TimeUnit.SECONDS ); assertThat(mockServerClient.hasStarted(), is(true)); assertThat(response.getBodyAsString(), is("port_forwarded_response")); } finally { stopQuietly(mockServerClient); } } @Test public void shouldStartMockServerWithRemotePort() { final int freePort = PortFactory.findFreePort(); MockServerClient mockServerClient = new MockServerClient("127.0.0.1", freePort); try { EchoServer echoServer = new EchoServer(false); echoServer.withNextResponse(response("port_forwarded_response")); Main.main( "-serverPort", String.valueOf(freePort), "-proxyRemotePort", String.valueOf(echoServer.getPort()) ); final HttpResponse response = new NettyHttpClient(new MockServerLogger(), clientEventLoopGroup, null, false) .sendRequest( request() .withHeader(HOST.toString(), "127.0.0.1:" + freePort), 10, TimeUnit.SECONDS ); assertThat(mockServerClient.hasStarted(), is(true)); assertThat(response.getBodyAsString(), is("port_forwarded_response")); } finally { stopQuietly(mockServerClient); } } @Test public void shouldPrintOutUsageForInvalidServerPort() throws UnsupportedEncodingException { PrintStream originalPrintStream = Main.systemOut; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Main.systemOut = new PrintStream(byteArrayOutputStream, true, StandardCharsets.UTF_8.name()); Main.main("-serverPort", "A"); String actual = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8); String expected = NEW_LINE + " =====================================================================================================" + NEW_LINE + " serverPort value \"A\" is invalid, please specify a comma separated list of ports i.e. \"1080,1081,1082\"" + NEW_LINE + " =====================================================================================================" + NEW_LINE + NEW_LINE + Main.USAGE; assertThat(actual, is(expected)); } finally { Main.systemOut = originalPrintStream; } } @Test public void shouldPrintOutUsageForInvalidRemotePort() throws UnsupportedEncodingException { final int freePort = PortFactory.findFreePort(); PrintStream originalPrintStream = Main.systemOut; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Main.systemOut = new PrintStream(baos, true, StandardCharsets.UTF_8.name()); Main.main("-serverPort", String.valueOf(freePort), "-proxyRemotePort", "A"); String actual = new String(baos.toByteArray(), StandardCharsets.UTF_8); String expected = NEW_LINE + " =======================================================================" + NEW_LINE + " proxyRemotePort value \"A\" is invalid, please specify a port i.e. \"1080\"" + NEW_LINE + " =======================================================================" + NEW_LINE + NEW_LINE + Main.USAGE; assertThat(actual, is(expected)); } finally { Main.systemOut = originalPrintStream; } } @Test public void shouldPrintOutUsageForInvalidRemoteHost() throws UnsupportedEncodingException { final int freePort = PortFactory.findFreePort(); PrintStream originalPrintStream = Main.systemOut; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Main.systemOut = new PrintStream(byteArrayOutputStream, true, StandardCharsets.UTF_8.name()); Main.main("-serverPort", String.valueOf(freePort), "-proxyRemoteHost", "%^&*("); String actual = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8); String expected = NEW_LINE + " ====================================================================================================" + NEW_LINE + " proxyRemoteHost value \"%^&*(\" is invalid, please specify a host name i.e. \"localhost\" or \"127.0.0.1\"" + NEW_LINE + " ====================================================================================================" + NEW_LINE + NEW_LINE + Main.USAGE; assertThat(actual, is(expected)); } finally { Main.systemOut = originalPrintStream; } } @Test public void shouldPrintOutUsageForInvalidLogLevel() throws UnsupportedEncodingException { final int freePort = PortFactory.findFreePort(); PrintStream originalPrintStream = Main.systemOut; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Main.systemOut = new PrintStream(byteArrayOutputStream, true, StandardCharsets.UTF_8.name()); Main.main("-serverPort", String.valueOf(freePort), "-logLevel", "FOO"); String actual = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8); String expected = NEW_LINE + " ====================================================================================================================================================================================================" + NEW_LINE + " logLevel value \"FOO\" is invalid, please specify one of SL4J levels: \"TRACE\", \"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"OFF\" or the Java Logger levels: \"FINEST\", \"FINE\", \"INFO\", \"WARNING\", \"SEVERE\", \"OFF\"" + NEW_LINE + " ====================================================================================================================================================================================================" + NEW_LINE + NEW_LINE + Main.USAGE; assertThat(actual, is(expected)); } finally { Main.systemOut = originalPrintStream; } }
ConfigurationProperties { public static String x509CertificatePath() { return readPropertyHierarchically(MOCKSERVER_TLS_X509_CERTIFICATE_PATH, "MOCKSERVER_TLS_X509_CERTIFICATE_PATH", ""); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); }
@Test public void shouldSetAndReadX509CertificatePath() throws IOException { System.clearProperty("mockserver.x509CertificatePath"); assertThat(x509CertificatePath(), is("")); File tempFile = File.createTempFile("some", "temp"); x509CertificatePath(tempFile.getAbsolutePath()); assertThat(x509CertificatePath(), is(tempFile.getAbsolutePath())); assertEquals(tempFile.getAbsolutePath(), System.getProperty("mockserver.x509CertificatePath")); }
BooksPageController { @RequestMapping(value = "/books", method = RequestMethod.GET) public String getBookList(Model model) { model.addAttribute("books", bookService.getAllBooks()); return "books"; } @RequestMapping(value = "/books", method = RequestMethod.GET) String getBookList(Model model); @RequestMapping(value = "/book/{id}", method = RequestMethod.GET) String getBook(@PathVariable String id, Model model); }
@Test public void shouldLoadListOfBooks() { Model mockModel = mock(Model.class); Book[] bookList = {}; when(bookService.getAllBooks()).thenReturn(bookList); String viewName = booksPageController.getBookList(mockModel); assertEquals("books", viewName); verify(mockModel).addAttribute(eq("books"), eq(bookList)); }