method2testcases
stringlengths
118
3.08k
### Question: XmlSchemaBodyDTO extends BodyDTO { public XmlSchemaBody buildObject() { return (XmlSchemaBody) new XmlSchemaBody(getXml()).withOptional(getOptional()); } XmlSchemaBodyDTO(XmlSchemaBody xmlSchemaBody); XmlSchemaBodyDTO(XmlSchemaBody xmlSchemaBody, Boolean not); String getXml(); XmlSchemaBody buildObject(); }### Answer: @Test public void shouldBuildCorrectObject() { XmlSchemaBody xmlSchemaBody = new XmlSchemaBodyDTO(new XmlSchemaBody("some_body")).buildObject(); assertThat(xmlSchemaBody.getValue(), is("some_body")); assertThat(xmlSchemaBody.getType(), is(Body.Type.XML_SCHEMA)); } @Test public void shouldBuildCorrectObjectWithOptional() { XmlSchemaBody xmlSchemaBody = new XmlSchemaBodyDTO((XmlSchemaBody) new XmlSchemaBody("some_body").withOptional(true)).buildObject(); assertThat(xmlSchemaBody.getValue(), is("some_body")); assertThat(xmlSchemaBody.getType(), is(Body.Type.XML_SCHEMA)); assertThat(xmlSchemaBody.getOptional(), is(true)); }
### Question: VerificationSequenceDTO extends ObjectWithReflectiveEqualsHashCodeToString implements DTO<VerificationSequence> { public List<RequestDefinitionDTO> getHttpRequests() { return httpRequests; } VerificationSequenceDTO(VerificationSequence verification); VerificationSequenceDTO(); VerificationSequence buildObject(); List<RequestDefinitionDTO> getHttpRequests(); VerificationSequenceDTO setHttpRequests(List<RequestDefinitionDTO> httpRequests); List<ExpectationId> getExpectationIds(); VerificationSequenceDTO setExpectationIds(List<ExpectationId> expectationIds); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { VerificationSequence verification = new VerificationSequence() .withRequests( request("one"), request("two"), request("three") ); VerificationSequenceDTO verificationSequenceDTO = new VerificationSequenceDTO(verification); assertThat(verificationSequenceDTO.getHttpRequests(), is(Arrays.asList( new HttpRequestDTO(request("one")), new HttpRequestDTO(request("two")), new HttpRequestDTO(request("three")) ))); } @Test public void shouldHandleNullObjectInput() { VerificationSequenceDTO verificationSequenceDTO = new VerificationSequenceDTO(null); assertThat(verificationSequenceDTO.getHttpRequests(), is(Collections.<HttpRequestDTO>emptyList())); } @Test public void shouldHandleNullFieldInput() { VerificationSequenceDTO verificationSequenceDTO = new VerificationSequenceDTO(new VerificationSequence()); assertThat(verificationSequenceDTO.getHttpRequests(), is(Collections.<HttpRequestDTO>emptyList())); }
### Question: StringBodyDTO extends BodyWithContentTypeDTO { public StringBody buildObject() { return (StringBody) new StringBody(getString(), getRawBytes(), isSubString(), getMediaType()).withOptional(getOptional()); } StringBodyDTO(StringBody stringBody); StringBodyDTO(StringBody stringBody, Boolean not); String getString(); boolean isSubString(); byte[] getRawBytes(); StringBody buildObject(); }### Answer: @Test public void shouldHandleNull() { StringBody stringBody = new StringBodyDTO(new StringBody(null)).buildObject(); assertThat(stringBody.getValue(), is("")); assertThat(stringBody.getType(), is(Body.Type.STRING)); } @Test public void shouldHandleEmptyByteArray() { String body = ""; StringBody stringBody = new StringBodyDTO(new StringBody(body)).buildObject(); assertThat(stringBody.getValue(), is("")); assertThat(stringBody.getType(), is(Body.Type.STRING)); }
### Question: BinaryBodyDTO extends BodyWithContentTypeDTO { public byte[] getBase64Bytes() { return base64Bytes; } BinaryBodyDTO(BinaryBody binaryBody); BinaryBodyDTO(BinaryBody binaryBody, Boolean not); byte[] getBase64Bytes(); BinaryBody buildObject(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { byte[] body = DatatypeConverter.parseBase64Binary("some_body"); BinaryBodyDTO binaryBody = new BinaryBodyDTO(new BinaryBody(body)); assertThat(binaryBody.getBase64Bytes(), is(body)); assertThat(binaryBody.getType(), is(Body.Type.BINARY)); }
### Question: BinaryBodyDTO extends BodyWithContentTypeDTO { public BinaryBody buildObject() { return (BinaryBody) new BinaryBody(getBase64Bytes(), getMediaType()).withOptional(getOptional()); } BinaryBodyDTO(BinaryBody binaryBody); BinaryBodyDTO(BinaryBody binaryBody, Boolean not); byte[] getBase64Bytes(); BinaryBody buildObject(); }### Answer: @Test public void shouldBuildCorrectObject() { byte[] body = DatatypeConverter.parseBase64Binary("some_body"); BinaryBody binaryBody = new BinaryBodyDTO(new BinaryBody(body)).buildObject(); assertThat(binaryBody.getValue(), is(body)); assertThat(binaryBody.getType(), is(Body.Type.BINARY)); } @Test public void shouldBuildCorrectObjectWithOptional() { byte[] body = DatatypeConverter.parseBase64Binary("some_body"); BinaryBody binaryBody = new BinaryBodyDTO((BinaryBody) new BinaryBody(body).withOptional(true)).buildObject(); assertThat(binaryBody.getValue(), is(body)); assertThat(binaryBody.getType(), is(Body.Type.BINARY)); assertThat(binaryBody.getOptional(), is(true)); } @Test public void shouldHandleNull() { byte[] body = null; BinaryBody binaryBody = new BinaryBodyDTO(new BinaryBody(body)).buildObject(); assertThat(binaryBody.getValue(), is(new byte[0])); assertThat(binaryBody.getType(), is(Body.Type.BINARY)); } @Test public void shouldHandleEmptyByteArray() { byte[] body = new byte[0]; BinaryBody binaryBody = new BinaryBodyDTO(new BinaryBody(body)).buildObject(); assertThat(binaryBody.getValue(), is(new byte[0])); assertThat(binaryBody.getType(), is(Body.Type.BINARY)); }
### Question: JsonPathBodyDTO extends BodyDTO { public String getJsonPath() { return jsonPath; } JsonPathBodyDTO(JsonPathBody jsonPathBody); JsonPathBodyDTO(JsonPathBody jsonPathBody, Boolean not); String getJsonPath(); JsonPathBody buildObject(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { JsonPathBodyDTO xpathBody = new JsonPathBodyDTO(new JsonPathBody("some_body")); assertThat(xpathBody.getJsonPath(), is("some_body")); assertThat(xpathBody.getType(), is(Body.Type.JSON_PATH)); }
### Question: JsonPathBodyDTO extends BodyDTO { public JsonPathBody buildObject() { return (JsonPathBody) new JsonPathBody(getJsonPath()).withOptional(getOptional()); } JsonPathBodyDTO(JsonPathBody jsonPathBody); JsonPathBodyDTO(JsonPathBody jsonPathBody, Boolean not); String getJsonPath(); JsonPathBody buildObject(); }### Answer: @Test public void shouldBuildCorrectObject() { JsonPathBody jsonPathBody = new JsonPathBodyDTO(new JsonPathBody("some_body")).buildObject(); assertThat(jsonPathBody.getValue(), is("some_body")); assertThat(jsonPathBody.getType(), is(Body.Type.JSON_PATH)); } @Test public void shouldBuildCorrectObjectWithOptional() { JsonPathBody jsonPathBody = new JsonPathBodyDTO((JsonPathBody) new JsonPathBody("some_body").withOptional(true)).buildObject(); assertThat(jsonPathBody.getValue(), is("some_body")); assertThat(jsonPathBody.getType(), is(Body.Type.JSON_PATH)); assertThat(jsonPathBody.getOptional(), is(true)); }
### Question: XmlBodyDTO extends BodyWithContentTypeDTO { public String getXml() { return xml; } XmlBodyDTO(XmlBody xmlBody); XmlBodyDTO(XmlBody xmlBody, Boolean not); String getXml(); byte[] getRawBytes(); XmlBody buildObject(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { XmlBodyDTO xmlBody = new XmlBodyDTO(new XmlBody("some_body")); assertThat(xmlBody.getXml(), is("some_body")); assertThat(xmlBody.getType(), is(Body.Type.XML)); assertThat(xmlBody.getMediaType(), is(MediaType.create("application", "xml").withCharset("utf-8"))); }
### Question: XmlBodyDTO extends BodyWithContentTypeDTO { public XmlBody buildObject() { return (XmlBody) new XmlBody(getXml(), getRawBytes(), getMediaType()).withOptional(getOptional()); } XmlBodyDTO(XmlBody xmlBody); XmlBodyDTO(XmlBody xmlBody, Boolean not); String getXml(); byte[] getRawBytes(); XmlBody buildObject(); }### Answer: @Test public void shouldHandleNull() { String body = null; XmlBody xmlBody = new XmlBodyDTO(new XmlBody(body)).buildObject(); assertThat(xmlBody.getValue(), nullValue()); assertThat(xmlBody.getType(), is(Body.Type.XML)); } @Test public void shouldHandleEmptyByteArray() { String body = ""; XmlBody xmlBody = new XmlBodyDTO(new XmlBody(body)).buildObject(); assertThat(xmlBody.getValue(), is("")); assertThat(xmlBody.getType(), is(Body.Type.XML)); }
### Question: ParameterDTO extends KeyToMultiValueDTO implements DTO<Parameter> { public Parameter buildObject() { return new Parameter(getName(), getValues()); } ParameterDTO(Parameter parameter); protected ParameterDTO(); Parameter buildObject(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { ParameterDTO parameter = new ParameterDTO(new Parameter("first", "first_one", "first_two")); assertThat(parameter.getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); assertThat(parameter.buildObject().getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); }
### Question: ParameterBodyDTO extends BodyDTO { public Parameters getParameters() { return parameters; } ParameterBodyDTO(ParameterBody parameterBody); ParameterBodyDTO(ParameterBody parameterBody, Boolean not); Parameters getParameters(); ParameterBody buildObject(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { ParameterBodyDTO parameterBody = new ParameterBodyDTO(new ParameterBody( new Parameter("some", "value") )); assertThat(parameterBody.getParameters().getEntries(), containsInAnyOrder(new Parameter("some", "value"))); assertThat(parameterBody.getType(), is(Body.Type.PARAMETERS)); }
### Question: ParameterBodyDTO extends BodyDTO { public ParameterBody buildObject() { return (ParameterBody) new ParameterBody(parameters).withOptional(getOptional()); } ParameterBodyDTO(ParameterBody parameterBody); ParameterBodyDTO(ParameterBody parameterBody, Boolean not); Parameters getParameters(); ParameterBody buildObject(); }### Answer: @Test public void shouldBuildCorrectObject() { ParameterBody parameterBody = new ParameterBodyDTO(new ParameterBody( new Parameter("some", "value") )).buildObject(); assertThat(parameterBody.getValue().getEntries(), containsInAnyOrder(new Parameter("some", "value"))); assertThat(parameterBody.getType(), is(Body.Type.PARAMETERS)); } @Test public void shouldBuildCorrectObjectWithOptional() { ParameterBody parameterBody = new ParameterBodyDTO((ParameterBody) new ParameterBody( new Parameter("some", "value") ).withOptional(true)).buildObject(); assertThat(parameterBody.getValue().getEntries(), containsInAnyOrder(new Parameter("some", "value"))); assertThat(parameterBody.getType(), is(Body.Type.PARAMETERS)); assertThat(parameterBody.getOptional(), is(true)); }
### Question: HttpObjectCallbackDTO extends ObjectWithReflectiveEqualsHashCodeToString implements DTO<HttpObjectCallback> { public String getClientId() { return clientId; } HttpObjectCallbackDTO(HttpObjectCallback httpObjectCallback); HttpObjectCallbackDTO(); HttpObjectCallback buildObject(); String getClientId(); HttpObjectCallbackDTO setClientId(String clientId); Boolean getResponseCallback(); HttpObjectCallbackDTO setResponseCallback(Boolean responseCallback); DelayDTO getDelay(); void setDelay(DelayDTO delay); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { String clientId = UUIDService.getUUID(); HttpObjectCallback httpObjectCallback = new HttpObjectCallback() .withClientId(clientId); HttpObjectCallbackDTO httpObjectCallbackDTO = new HttpObjectCallbackDTO(httpObjectCallback); assertThat(httpObjectCallbackDTO.getClientId(), is(clientId)); } @Test public void shouldHandleNullObjectInput() { HttpObjectCallbackDTO httpObjectCallbackDTO = new HttpObjectCallbackDTO(null); assertThat(httpObjectCallbackDTO.getClientId(), is(nullValue())); } @Test public void shouldHandleNullFieldInput() { HttpObjectCallbackDTO httpObjectCallbackDTO = new HttpObjectCallbackDTO(new HttpObjectCallback()); assertThat(httpObjectCallbackDTO.getClientId(), is(nullValue())); }
### Question: RegexBodyDTO extends BodyDTO { public String getRegex() { return regex; } RegexBodyDTO(RegexBody regexBody); RegexBodyDTO(RegexBody regexBody, Boolean not); String getRegex(); RegexBody buildObject(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { RegexBodyDTO regexBody = new RegexBodyDTO(new RegexBody("some_body")); assertThat(regexBody.getRegex(), is("some_body")); assertThat(regexBody.getType(), is(Body.Type.REGEX)); }
### Question: RegexBodyDTO extends BodyDTO { public RegexBody buildObject() { return (RegexBody) new RegexBody(getRegex()).withOptional(getOptional()); } RegexBodyDTO(RegexBody regexBody); RegexBodyDTO(RegexBody regexBody, Boolean not); String getRegex(); RegexBody buildObject(); }### Answer: @Test public void shouldBuildCorrectObject() { RegexBody regexBody = new RegexBodyDTO(new RegexBody("some_body")).buildObject(); assertThat(regexBody.getValue(), is("some_body")); assertThat(regexBody.getType(), is(Body.Type.REGEX)); } @Test public void shouldBuildCorrectObjectWithOptional() { RegexBody regexBody = new RegexBodyDTO((RegexBody) new RegexBody("some_body").withOptional(true)).buildObject(); assertThat(regexBody.getValue(), is("some_body")); assertThat(regexBody.getType(), is(Body.Type.REGEX)); assertThat(regexBody.getOptional(), is(true)); } @Test public void shouldHandleNull() { String body = null; RegexBody regexBody = new RegexBodyDTO(new RegexBody(body)).buildObject(); assertThat(regexBody.getValue(), nullValue()); assertThat(regexBody.getType(), is(Body.Type.REGEX)); } @Test public void shouldHandleEmptyByteArray() { String body = ""; RegexBody regexBody = new RegexBodyDTO(new RegexBody(body)).buildObject(); assertThat(regexBody.getValue(), is("")); assertThat(regexBody.getType(), is(Body.Type.REGEX)); }
### Question: JsonBodyDTO extends BodyWithContentTypeDTO { public JsonBody buildObject() { return (JsonBody) new JsonBody(getJson(), getRawBytes(), getMediaType(), getMatchType()).withOptional(getOptional()); } JsonBodyDTO(JsonBody jsonBody); JsonBodyDTO(JsonBody jsonBody, Boolean not); String getJson(); MatchType getMatchType(); byte[] getRawBytes(); JsonBody buildObject(); }### Answer: @Test public void shouldHandleNull() { String body = null; JsonBody jsonBody = new JsonBodyDTO(new JsonBody(body)).buildObject(); assertThat(jsonBody.getValue(), CoreMatchers.nullValue()); assertThat(jsonBody.getType(), is(Body.Type.JSON)); } @Test public void shouldHandleEmptyByteArray() { String body = ""; JsonBody jsonBody = new JsonBodyDTO(new JsonBody(body)).buildObject(); assertThat(jsonBody.getValue(), is("")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); }
### Question: HttpTemplateDTO extends ObjectWithReflectiveEqualsHashCodeToString implements DTO<HttpTemplate> { public HttpTemplate.TemplateType getTemplateType() { return templateType; } HttpTemplateDTO(HttpTemplate httpTemplate); HttpTemplateDTO(); HttpTemplate buildObject(); HttpTemplate.TemplateType getTemplateType(); HttpTemplateDTO setTemplateType(HttpTemplate.TemplateType templateType); String getTemplate(); HttpTemplateDTO setTemplate(String template); DelayDTO getDelay(); HttpTemplateDTO setDelay(DelayDTO delay); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { HttpTemplate.TemplateType type = HttpTemplate.TemplateType.VELOCITY; HttpTemplate httpTemplate = new HttpTemplate(type); HttpTemplateDTO httpTemplateDTO = new HttpTemplateDTO(httpTemplate); assertThat(httpTemplateDTO.getTemplateType(), is(type)); }
### Question: HttpTemplateDTO extends ObjectWithReflectiveEqualsHashCodeToString implements DTO<HttpTemplate> { public String getTemplate() { return template; } HttpTemplateDTO(HttpTemplate httpTemplate); HttpTemplateDTO(); HttpTemplate buildObject(); HttpTemplate.TemplateType getTemplateType(); HttpTemplateDTO setTemplateType(HttpTemplate.TemplateType templateType); String getTemplate(); HttpTemplateDTO setTemplate(String template); DelayDTO getDelay(); HttpTemplateDTO setDelay(DelayDTO delay); }### Answer: @Test public void shouldHandleNullObjectInput() { HttpTemplateDTO httpTemplateDTO = new HttpTemplateDTO(null); assertThat(httpTemplateDTO.getTemplate(), is(nullValue())); }
### Question: CookieDTO extends KeyAndValueDTO implements DTO<Cookie> { public Cookie buildObject() { return new Cookie(getName(), getValue()); } CookieDTO(Cookie cookie); protected CookieDTO(); Cookie buildObject(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { CookieDTO cookie = new CookieDTO(new Cookie("name", "value")); assertThat(cookie.getValue(), is(string("value"))); assertThat(cookie.getName(), is(string("name"))); assertThat(cookie.buildObject().getName(), is(string("name"))); assertThat(cookie.buildObject().getValue(), is(string("value"))); }
### Question: JsonSchemaBodyDTO extends BodyDTO { public JsonSchemaBody buildObject() { return (JsonSchemaBody) new JsonSchemaBody(getJson()).withParameterStyles(parameterStyles).withOptional(getOptional()); } JsonSchemaBodyDTO(JsonSchemaBody jsonSchemaBody); JsonSchemaBodyDTO(JsonSchemaBody jsonSchemaBody, Boolean not); String getJson(); Map<String, ParameterStyle> getParameterStyles(); JsonSchemaBody buildObject(); }### Answer: @Test public void shouldBuildCorrectObject() { JsonSchemaBody jsonSchemaBody = new JsonSchemaBodyDTO(new JsonSchemaBody("some_body")).buildObject(); assertThat(jsonSchemaBody.getValue(), is("some_body")); assertThat(jsonSchemaBody.getType(), is(Body.Type.JSON_SCHEMA)); } @Test public void shouldBuildCorrectObjectWithOptional() { JsonSchemaBody jsonSchemaBody = new JsonSchemaBodyDTO((JsonSchemaBody) new JsonSchemaBody("some_body").withOptional(true)).buildObject(); assertThat(jsonSchemaBody.getValue(), is("some_body")); assertThat(jsonSchemaBody.getType(), is(Body.Type.JSON_SCHEMA)); assertThat(jsonSchemaBody.getOptional(), is(true)); } @Test public void shouldHandleNull() { String body = null; JsonSchemaBody jsonSchemaBody = new JsonSchemaBodyDTO(new JsonSchemaBody(body)).buildObject(); assertThat(jsonSchemaBody.getValue(), nullValue()); assertThat(jsonSchemaBody.getType(), is(Body.Type.JSON_SCHEMA)); } @Test public void shouldHandleEmptyByteArray() { String body = ""; JsonSchemaBody jsonSchemaBody = new JsonSchemaBodyDTO(new JsonSchemaBody(body)).buildObject(); assertThat(jsonSchemaBody.getValue(), is("")); assertThat(jsonSchemaBody.getType(), is(Body.Type.JSON_SCHEMA)); }
### Question: HttpClassCallbackDTO extends ObjectWithReflectiveEqualsHashCodeToString implements DTO<HttpClassCallback> { public String getCallbackClass() { return callbackClass; } HttpClassCallbackDTO(HttpClassCallback httpClassCallback); HttpClassCallbackDTO(); HttpClassCallback buildObject(); String getCallbackClass(); HttpClassCallbackDTO setCallbackClass(String callbackClass); DelayDTO getDelay(); void setDelay(DelayDTO delay); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { String callbackClass = HttpClassCallbackDTOTest.class.getName(); HttpClassCallback httpClassCallback = callback(callbackClass); HttpClassCallbackDTO httpClassCallbackDTO = new HttpClassCallbackDTO(httpClassCallback); assertThat(httpClassCallbackDTO.getCallbackClass(), is(callbackClass)); } @Test public void shouldHandleNullObjectInput() { HttpClassCallbackDTO httpClassCallbackDTO = new HttpClassCallbackDTO(null); assertThat(httpClassCallbackDTO.getCallbackClass(), is(nullValue())); } @Test public void shouldHandleNullFieldInput() { HttpClassCallbackDTO httpClassCallbackDTO = new HttpClassCallbackDTO(new HttpClassCallback()); assertThat(httpClassCallbackDTO.getCallbackClass(), is(nullValue())); }
### Question: XPathBodyDTO extends BodyDTO { public String getXPath() { return xpath; } XPathBodyDTO(XPathBody xPathBody); XPathBodyDTO(XPathBody xPathBody, Boolean not); String getXPath(); XPathBody buildObject(); }### Answer: @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)); }
### Question: 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(); }### Answer: @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)); }
### Question: HeaderDTO extends KeyToMultiValueDTO implements DTO<Header> { public Header buildObject() { return new Header(getName(), getValues()); } HeaderDTO(Header header); protected HeaderDTO(); Header buildObject(); }### Answer: @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"))); }
### Question: 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); }### Answer: @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}); }
### Question: 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(); }### Answer: @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"); }
### Question: 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(); }### Answer: @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()); }
### Question: 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(); }### Answer: @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); }
### Question: 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(); }### Answer: @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()); }
### Question: 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); }### Answer: @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}); }
### Question: 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(); }### Answer: @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); }
### Question: 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(); }### Answer: @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()); }
### Question: 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); }### Answer: @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}); }
### Question: Base64Converter extends ObjectWithReflectiveEqualsHashCodeToString { public String bytesToBase64String(byte[] data) { return new String(ENCODER.encode(data), UTF_8); } byte[] base64StringToBytes(String data); String bytesToBase64String(byte[] data); }### Answer: @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==")); }
### Question: 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); }### Answer: @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")); }
### Question: 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); }### Answer: @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}); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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(); }
### Question: HttpResponseActionHandler { public HttpResponse handle(HttpResponse httpResponse) { return httpResponse.clone(); } HttpResponse handle(HttpResponse httpResponse); }### Answer: @Test public void shouldHandleHttpRequests() { HttpResponse httpResponse = mock(HttpResponse.class); HttpResponseActionHandler httpResponseActionHandler = new HttpResponseActionHandler(); httpResponseActionHandler.handle(httpResponse); verify(httpResponse).clone(); }
### Question: 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); }### Answer: @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); }
### Question: HttpResponseClassCallbackActionHandler { public HttpResponse handle(HttpClassCallback httpClassCallback, HttpRequest request) { return invokeCallbackMethod(httpClassCallback, request); } HttpResponseClassCallbackActionHandler(MockServerLogger mockServerLogger); HttpResponse handle(HttpClassCallback httpClassCallback, HttpRequest request); }### Answer: @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"))); }
### Question: 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(); }### Answer: @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)); }
### Question: URLParser { public static boolean isFullUrl(String uri) { return uri != null && uri.matches(schemeRegex); } static boolean isFullUrl(String uri); static String returnPath(String path); }### Answer: @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")); }
### Question: 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); }### Answer: @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")); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @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)); }
### Question: ExpectationInitializerLoader { public Expectation[] loadExpectations() { final Expectation[] expectationsFromInitializerClass = retrieveExpectationsFromInitializerClass(); final Expectation[] expectationsFromJson = retrieveExpectationsFromJson(); return ArrayUtils.addAll(expectationsFromInitializerClass, expectationsFromJson); } ExpectationInitializerLoader(MockServerLogger mockServerLogger, RequestMatchers requestMatchers); Expectation[] loadExpectations(); }### Answer: @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); } }
### Question: 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); }### Answer: @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)); }
### Question: BooksPageController { @RequestMapping(value = "/book/{id}", method = RequestMethod.GET) public String getBook(@PathVariable String id, Model model) { model.addAttribute("book", bookService.getBook(id)); return "book"; } @RequestMapping(value = "/books", method = RequestMethod.GET) String getBookList(Model model); @RequestMapping(value = "/book/{id}", method = RequestMethod.GET) String getBook(@PathVariable String id, Model model); }### Answer: @Test public void shouldLoadSingleBook() { Model mockModel = mock(Model.class); Book book = new Book(1, "title", "author", "isbn", "publicationDate"); when(bookService.getBook("1")).thenReturn(book); String viewName = booksPageController.getBook("1", mockModel); assertEquals("book", viewName); verify(mockModel).addAttribute(eq("book"), same(book)); }
### Question: InventoryStockTakeResource extends BaseRestObjectResource<InventoryStockTake> { @Override public InventoryStockTake save(InventoryStockTake delegate) { if (!userCanProcessAdjustment()) { throw new RestClientException("The current user not authorized to process this operation."); } StockOperation operation = createOperation(delegate); operationService.submitOperation(operation); return newDelegate(); } InventoryStockTakeResource(); @Override DelegatingResourceDescription getRepresentationDescription(Representation rep); @Override InventoryStockTake newDelegate(); Boolean userCanProcessAdjustment(); @Override InventoryStockTake save(InventoryStockTake delegate); StockOperation createOperation(InventoryStockTake delegate); @Override Class<? extends IObjectDataService<InventoryStockTake>> getServiceClass(); }### Answer: @Test(expected = RestClientException.class) public void save_shouldThrowExceptionIfUserNotAuthorised() throws Exception { when(StockOperationTypeResource.userCanProcess(WellKnownOperationTypes.getAdjustment())).thenReturn(false); resource.save(delegate); }
### Question: AdjustmentOperationType extends StockOperationTypeBase { @Override public void onCancelled(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); if (!negateAppliedQuantity()) { tx.setQuantity(tx.getQuantity() * -1); } } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); }### Answer: @Test public void onCancelled_shouldSetStockroomAndNegateQuantity() throws Exception { AdjustmentOperationType adjustmentOperationType = (AdjustmentOperationType)stockOperationTypeDataService.getById(0); StockOperation stockOperation = stockOperationDataService.getById(7); adjustmentOperationType.onCancelled(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 3); assertTrue(transaction.getQuantity() == -5); } }
### Question: AdjustmentOperationType extends StockOperationTypeBase { @Override public void onCompleted(StockOperation operation) { operation.getReserved().clear(); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); }### Answer: @Test public void onCompleted_shouldClearReservedTransactions() throws Exception { AdjustmentOperationType adjustmentOperationType = (AdjustmentOperationType)stockOperationTypeDataService.getById(0); StockOperation stockOperation = stockOperationDataService.getById(7); assertTrue(stockOperation.getReserved().size() == 1); adjustmentOperationType.onCompleted(stockOperation); assertTrue(stockOperation.getReserved().size() == 0); }
### Question: ReceiptOperationType extends StockOperationTypeBase { @Override public void onCancelled(StockOperation operation) { operation.getReserved().clear(); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(StockOperation operation); @Override void onCancelled(StockOperation operation); @Override void onCompleted(final StockOperation operation); }### Answer: @Test public void onCancelled_shouldClearReservedTransactions() throws Exception { ReceiptOperationType receiptOperationType = (ReceiptOperationType)stockOperationTypeDataService.getById(7); StockOperation stockOperation = stockOperationDataService.getById(4); assertTrue(stockOperation.getReserved().size() == 1); receiptOperationType.onCancelled(stockOperation); assertTrue(stockOperation.getReserved().size() == 0); }
### Question: ReceiptOperationType extends StockOperationTypeBase { @Override public void onCompleted(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getDestination()); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(StockOperation operation); @Override void onCancelled(StockOperation operation); @Override void onCompleted(final StockOperation operation); }### Answer: @Test public void onCompleted_shouldSetDestinationStockroom() throws Exception { ReceiptOperationType receiptOperationType = (ReceiptOperationType)stockOperationTypeDataService.getById(7); StockOperation stockOperation = stockOperationDataService.getById(4); receiptOperationType.onCompleted(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 4); } }
### Question: TransferOperationType extends StockOperationTypeBase { @Override public void onPending(final StockOperation operation) { executeCopyReserved(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); tx.setQuantity(tx.getQuantity() * -1); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(final StockOperation operation); }### Answer: @Test public void onPending_shouldNegateQuantityAndSetStockroom() throws Exception { TransferOperationType transferOperationType = (TransferOperationType)stockOperationTypeDataService.getById(5); StockOperation stockOperation = stockOperationDataService.getById(8); transferOperationType.onPending(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 3); assertTrue(transaction.getQuantity() == -5); } }
### Question: TransferOperationType extends StockOperationTypeBase { @Override public void onCancelled(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(final StockOperation operation); }### Answer: @Test public void onCancelled_shouldSetStockroom() throws Exception { TransferOperationType transferOperationType = (TransferOperationType)stockOperationTypeDataService.getById(5); StockOperation stockOperation = stockOperationDataService.getById(8); transferOperationType.onCancelled(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 3); assertTrue(transaction.getQuantity() == 5); } }
### Question: TransferOperationType extends StockOperationTypeBase { @Override public void onCompleted(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getDestination()); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(final StockOperation operation); }### Answer: @Test public void onCompleted_shouldSetDestinationStockroom() throws Exception { TransferOperationType transferOperationType = (TransferOperationType)stockOperationTypeDataService.getById(5); StockOperation stockOperation = stockOperationDataService.getById(8); transferOperationType.onCompleted(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 4); assertTrue(transaction.getQuantity() == 5); } }
### Question: DistributionOperationType extends StockOperationTypeBase { @Override public void onPending(final StockOperation operation) { executeCopyReserved(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); tx.setPatient(operation.getPatient()); tx.setInstitution(operation.getInstitution()); tx.setQuantity(tx.getQuantity() * -1); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); }### Answer: @Test public void onPending_shouldNegateQuantityAndSetStockroomAndPatient() throws Exception { DistributionOperationType distributionOperationType = (DistributionOperationType)stockOperationTypeDataService.getById(2); StockOperation stockOperation = stockOperationDataService.getById(5); stockOperation.setPatient(patient); distributionOperationType.onPending(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertEquals(3, (int)transaction.getStockroom().getId()); assertEquals(-5, (int)transaction.getQuantity()); assertEquals(patient.getId(), transaction.getPatient().getPatientId()); } }
### Question: DistributionOperationType extends StockOperationTypeBase { @Override public void onCancelled(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); }### Answer: @Test public void onCancelled_shouldSetStockroom() throws Exception { DistributionOperationType distributionOperationType = (DistributionOperationType)stockOperationTypeDataService.getById(2); StockOperation stockOperation = stockOperationDataService.getById(5); distributionOperationType.onCancelled(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertNotNull(transactions); assertEquals(1, transactions.size()); for (StockOperationTransaction transaction : transactions) { assertEquals(3, (int)transaction.getStockroom().getId()); } }
### Question: DistributionOperationType extends StockOperationTypeBase { @Override public void onCompleted(StockOperation operation) { operation.getReserved().clear(); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); }### Answer: @Test public void onCompleted_shouldClearReservedTransactions() throws Exception { DistributionOperationType distributionOperationType = (DistributionOperationType)stockOperationTypeDataService.getById(2); StockOperation stockOperation = stockOperationDataService.getById(5); assertEquals(1, stockOperation.getReserved().size()); distributionOperationType.onCompleted(stockOperation); assertEquals(0, stockOperation.getReserved().size()); }
### Question: AdjustmentOperationType extends StockOperationTypeBase { @Override public void onPending(final StockOperation operation) { executeCopyReserved(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); if (negateAppliedQuantity()) { tx.setQuantity(tx.getQuantity() * -1); } } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); }### Answer: @Test public void onPending_shouldNegateQuantityAndSetStockroomAndPatient() throws Exception { AdjustmentOperationType adjustmentOperationType = (AdjustmentOperationType)stockOperationTypeDataService.getById(0); StockOperation stockOperation = stockOperationDataService.getById(7); adjustmentOperationType.onPending(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 3); } }
### Question: ProjectionDescriptor extends TransformationDescriptor<Input, Output> { public static ProjectionDescriptor<Record, Record> createForRecords(RecordType inputType, String... fieldNames) { final SerializableFunction<Record, Record> javaImplementation = createRecordJavaImplementation(fieldNames, inputType); return new ProjectionDescriptor<>( javaImplementation, Arrays.asList(fieldNames), inputType, new RecordType(fieldNames) ); } ProjectionDescriptor(Class<Input> inputTypeClass, Class<Output> outputTypeClass, String... fieldNames); ProjectionDescriptor(BasicDataUnitType<Input> inputType, BasicDataUnitType<Output> outputType, String... fieldNames); private ProjectionDescriptor(SerializableFunction<Input, Output> javaImplementation, List<String> fieldNames, BasicDataUnitType<Input> inputType, BasicDataUnitType<Output> outputType); static ProjectionDescriptor<Record, Record> createForRecords(RecordType inputType, String... fieldNames); List<String> getFieldNames(); }### Answer: @Test public void testRecordImplementation() { RecordType inputType = new RecordType("a", "b", "c"); final ProjectionDescriptor<Record, Record> descriptor = ProjectionDescriptor.createForRecords(inputType, "c", "a"); Assert.assertEquals(new RecordType("c", "a"), descriptor.getOutputType()); final Function<Record, Record> javaImplementation = descriptor.getJavaImplementation(); Assert.assertEquals( new Record("world", 10), javaImplementation.apply(new Record(10, "hello", "world")) ); }
### Question: Bitmask implements Cloneable, Iterable<Integer> { public Bitmask flip(int fromIndex, int toIndex) { if (fromIndex < toIndex) { this.ensureCapacity(toIndex - 1); int fromLongPos = getLongPos(fromIndex); int untilLongPos = getLongPos(toIndex - 1); for (int longPos = fromLongPos; longPos <= untilLongPos; longPos++) { int fromOffset = (longPos == fromLongPos) ? getOffset(fromIndex) : 0; int untilOffset = (longPos == untilLongPos) ? getOffset(toIndex - 1) + 1 : BITS_PER_WORD; long flipMask = createAllSetBits(untilOffset) ^ createAllSetBits(fromOffset); this.bits[longPos] ^= flipMask; } this.cardinalityCache = -1; } return this; } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; }### Answer: @Test public void testFlip() { testFlip(0, 256); testFlip(32, 256); testFlip(32, 224); testFlip(65, 67); }
### Question: Bitmask implements Cloneable, Iterable<Integer> { public int cardinality() { if (this.cardinalityCache == -1) { this.cardinalityCache = 0; for (long bits : this.bits) { this.cardinalityCache += Long.bitCount(bits); } } return this.cardinalityCache; } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; }### Answer: @Test public void testCardinality() { Assert.assertEquals(0, createBitmask(0).orInPlace(createBitmask(0)).cardinality()); Assert.assertEquals(1, createBitmask(0, 65).orInPlace(createBitmask(0)).cardinality()); Assert.assertEquals(2, createBitmask(0, 65, 66).orInPlace(createBitmask(0)).cardinality()); Assert.assertEquals(3, createBitmask(0, 65, 66, 128).orInPlace(createBitmask(0)).cardinality()); }
### Question: Bitmask implements Cloneable, Iterable<Integer> { public Bitmask or(Bitmask that) { Bitmask copy = new Bitmask(this, that.bits.length << WORD_ADDRESS_BITS); return copy.orInPlace(that); } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; }### Answer: @Test public void testOr() { Assert.assertEquals(createBitmask(0, 0), createBitmask(0).or(createBitmask(0, 0))); Assert.assertEquals(createBitmask(0, 0, 1), createBitmask(0, 1).or(createBitmask(0, 0))); Assert.assertEquals(createBitmask(0, 0, 1, 65, 128), createBitmask(0, 1, 128).or(createBitmask(0, 0, 65))); Assert.assertEquals(createBitmask(0, 0, 1, 65, 128), createBitmask(0, 0, 65).or(createBitmask(0, 1, 128))); }
### Question: Bitmask implements Cloneable, Iterable<Integer> { public Bitmask andNot(Bitmask that) { Bitmask copy = new Bitmask(this, that.bits.length << WORD_ADDRESS_BITS); return copy.andNotInPlace(that); } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; }### Answer: @Test public void testAndNot() { Assert.assertEquals(createBitmask(0), createBitmask(0).andNot(createBitmask(0, 0))); Assert.assertEquals(createBitmask(0, 1), createBitmask(0, 0, 1).andNot(createBitmask(0, 0))); Assert.assertEquals(createBitmask(0, 1, 128), createBitmask(0, 1, 128).andNot(createBitmask(0, 0, 65))); Assert.assertEquals(createBitmask(0, 65), createBitmask(0, 1, 65, 128).andNot(createBitmask(0, 1, 128))); }
### Question: Bitmask implements Cloneable, Iterable<Integer> { public int nextSetBit(int from) { int longPos = getLongPos(from); int offset = getOffset(from); while (longPos < this.bits.length) { long bits = this.bits[longPos]; int nextOffset = Long.numberOfTrailingZeros(bits & ~createAllSetBits(offset)); if (nextOffset < BITS_PER_WORD) { return longPos << WORD_ADDRESS_BITS | nextOffset; } longPos++; offset = 0; } return -1; } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; }### Answer: @Test public void testNextSetBit() { testSetBits(); testSetBits(0); testSetBits(1); testSetBits(0, 1); testSetBits(420); testSetBits(1, 420); testSetBits(1, 420, 421, 500); testSetBits(1, 2, 3, 65); }
### Question: AggregatingCardinalityEstimator implements CardinalityEstimator { @Override public CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates) { return this.alternativeEstimators.stream() .map(alternativeEstimator -> alternativeEstimator.estimate(optimizationContext, inputEstimates)) .sorted((estimate1, estimate2) -> Double.compare(estimate2.getCorrectnessProbability(), estimate1.getCorrectnessProbability())) .findFirst() .orElseThrow(IllegalStateException::new); } AggregatingCardinalityEstimator(List<CardinalityEstimator> alternativeEstimators); @Override CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates); }### Answer: @Test public void testEstimate() { OptimizationContext optimizationContext = mock(OptimizationContext.class); when(optimizationContext.getConfiguration()).thenReturn(new Configuration()); CardinalityEstimator partialEstimator1 = new DefaultCardinalityEstimator(0.9, 1, false, cards -> cards[0] * 2); CardinalityEstimator partialEstimator2 = new DefaultCardinalityEstimator(0.8, 1, false, cards -> cards[0] * 3); CardinalityEstimator estimator = new AggregatingCardinalityEstimator( Arrays.asList(partialEstimator1, partialEstimator2) ); CardinalityEstimate inputEstimate = new CardinalityEstimate(10, 100, 0.3); CardinalityEstimate outputEstimate = estimator.estimate(optimizationContext, inputEstimate); CardinalityEstimate expectedEstimate = new CardinalityEstimate(2 * 10, 2 * 100, 0.3 * 0.9); Assert.assertEquals(expectedEstimate, outputEstimate); }
### Question: RecordType extends BasicDataUnitType<Record> { @Override public boolean isSupertypeOf(BasicDataUnitType<?> that) { return this.equals(that); } RecordType(String... fieldNames); String[] getFieldNames(); @Override boolean isSupertypeOf(BasicDataUnitType<?> that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); int getIndex(String fieldName); }### Answer: @Test public void testSupertype() { DataSetType<Record> t1 = DataSetType.createDefault(Record.class); DataSetType<Record> t2 = DataSetType.createDefault(new RecordType("a", "b")); DataSetType<Record> t3 = DataSetType.createDefault(new RecordType("a", "b", "c")); Assert.assertTrue(t1.isSupertypeOf(t2)); Assert.assertFalse(t2.isSupertypeOf(t1)); Assert.assertTrue(t1.isSupertypeOf(t3)); Assert.assertFalse(t3.isSupertypeOf(t1)); Assert.assertTrue(t2.isSupertypeOf(t2)); Assert.assertFalse(t2.isSupertypeOf(t3)); Assert.assertTrue(t3.isSupertypeOf(t3)); Assert.assertFalse(t3.isSupertypeOf(t2)); }
### Question: CliArguments { public static CliArguments fromArgs(String... args) { final CliArguments arguments = new CliArguments(); JCommander.newBuilder() .addObject(arguments) .build().parse(args); arguments.validate(); return arguments; } CliArguments(); CliArguments(PasswordReader passwordReader); Algorithm algorithm(); String username(); String password(); int cost(); int iterations(); int keyLength(); String salt(); void validate(); static CliArguments fromArgs(String... args); boolean help(); }### Answer: @Test public void shouldErrorOutEncryptionAlgorithmIsNotSpecified() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Expected encryption algorithm: [-B, -P, -S]"); String[] args = {"-u", "admin", "-p", "badger"}; CliArguments.fromArgs(args); } @Test public void shouldErrorOutOnInvalidBCryptArguments() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Argument to -C must be an integer value: 4 to 31"); String[] args = {"-B", "-u", "admin", "-p", "badger", "-C", "1"}; CliArguments.fromArgs(args); } @Test public void shouldErrorOutIfRequiredOptionsMissingInCliArguments() throws Exception { thrown.expect(ParameterException.class); thrown.expectMessage("The following option is required: [-u]"); String[] args = {"-p", "badger"}; CliArguments.fromArgs(args); }
### Question: GetPluginIconExecutor implements RequestExecutor { @Override public GoPluginApiResponse execute() throws Exception { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("content_type", getContentType()); jsonObject.addProperty("data", Base64.getEncoder().encodeToString(Util.readResourceBytes(getIcon()))); DefaultGoPluginApiResponse defaultGoPluginApiResponse = new DefaultGoPluginApiResponse(200, GSON.toJson(jsonObject)); return defaultGoPluginApiResponse; } @Override GoPluginApiResponse execute(); }### Answer: @Test public void rendersIconInBase64() throws Exception { GoPluginApiResponse response = new GetPluginIconExecutor().execute(); HashMap<String, String> hashMap = new Gson().fromJson(response.responseBody(), HashMap.class); assertThat(hashMap.size(), is(2)); assertThat(hashMap.get("content_type"), is("image/png")); assertThat(Util.readResourceBytes("/gocd_72_72_icon.png"), is(Base64.getDecoder().decode(hashMap.get("data")))); }
### Question: GetCapabilitiesExecutor { public GoPluginApiResponse execute() { Capabilities capabilities = getCapabilities(); return new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, capabilities.toJSON()); } GoPluginApiResponse execute(); }### Answer: @Test public void shouldExposeItsCapabilities() throws Exception { GoPluginApiResponse response = new GetCapabilitiesExecutor().execute(); assertThat(response.responseCode(), CoreMatchers.is(200)); String expectedJSON = "{\n" + " \"supported_auth_type\":\"password\",\n" + " \"can_search\":true,\n" + " \"can_authorize\":false,\n" + " \"can_get_user_roles\":false\n" + "}"; JSONAssert.assertEquals(expectedJSON, response.responseBody(), true); }
### Question: GetAuthConfigViewExecutor implements RequestExecutor { @Override public GoPluginApiResponse execute() throws Exception { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("template", Util.readResource("/auth-config.template.html")); DefaultGoPluginApiResponse defaultGoPluginApiResponse = new DefaultGoPluginApiResponse(200, GSON.toJson(jsonObject)); return defaultGoPluginApiResponse; } @Override GoPluginApiResponse execute(); }### Answer: @Test public void shouldRenderTheTemplateInJSON() throws Exception { GoPluginApiResponse response = new GetAuthConfigViewExecutor().execute(); assertThat(response.responseCode(), is(200)); Map<String, String> hashSet = new Gson().fromJson(response.responseBody(), HashMap.class); assertThat(hashSet, Matchers.hasEntry("template", Util.readResource("/auth-config.template.html"))); }
### Question: GetAuthConfigMetadataExecutor implements RequestExecutor { public GoPluginApiResponse execute() throws Exception { final List<ProfileMetadata> authConfigMetadata = MetadataHelper.getMetadata(Configuration.class); return new DefaultGoPluginApiResponse(200, GSON.toJson(authConfigMetadata)); } GoPluginApiResponse execute(); }### Answer: @Test public void shouldSerializeAllFields() throws Exception { GoPluginApiResponse response = new GetAuthConfigMetadataExecutor().execute(); List list = new Gson().fromJson(response.responseBody(), List.class); assertEquals(list.size(), MetadataHelper.getMetadata(Configuration.class).size()); } @Test public void assertJsonStructure() throws Exception { GoPluginApiResponse response = new GetAuthConfigMetadataExecutor().execute(); assertThat(response.responseCode(), is(200)); String expectedJSON = "[\n" + " {\n" + " \"key\": \"PasswordFilePath\",\n" + " \"metadata\": {\n" + " \"required\": true,\n" + " \"secure\": false\n" + " }\n" + " }\n" + "]"; JSONAssert.assertEquals(expectedJSON, response.responseBody(), true); }
### Question: AuthConfigValidateRequestExecutor implements RequestExecutor { public GoPluginApiResponse execute() throws Exception { Map<String, String> configuration = GSON.fromJson(request.requestBody(), Map.class); final List<Map<String, String>> validationResult = Configuration.validate(configuration); return DefaultGoPluginApiResponse.success(GSON.toJson(validationResult)); } AuthConfigValidateRequestExecutor(GoPluginApiRequest request); GoPluginApiResponse execute(); }### Answer: @Test public void shouldBarfWhenUnknownKeysArePassed() throws Exception { when(request.requestBody()).thenReturn(new Gson().toJson(Collections.singletonMap("foo", "bar"))); GoPluginApiResponse response = new AuthConfigValidateRequestExecutor(request).execute(); String json = response.responseBody(); String expectedJSON = "[\n" + " {\n" + " \"message\": \"PasswordFilePath must not be blank.\",\n" + " \"key\": \"PasswordFilePath\"\n" + " },\n" + " {\n" + " \"key\": \"foo\",\n" + " \"message\": \"Is an unknown property\"\n" + " }\n" + "]"; JSONAssert.assertEquals(expectedJSON, json, JSONCompareMode.NON_EXTENSIBLE); } @Test public void shouldValidateMandatoryKeys() throws Exception { when(request.requestBody()).thenReturn(new Gson().toJson(Collections.emptyMap())); GoPluginApiResponse response = new AuthConfigValidateRequestExecutor(request).execute(); String json = response.responseBody(); String expectedJSON = "[\n" + " {\n" + " \"message\": \"PasswordFilePath must not be blank.\",\n" + " \"key\": \"PasswordFilePath\"\n" + " }\n" + "]"; JSONAssert.assertEquals(expectedJSON, json, JSONCompareMode.NON_EXTENSIBLE); }
### Question: CliArguments { public String password() { if (isBlank(password)) { password = passwordReader.readPassword(); } return password; } CliArguments(); CliArguments(PasswordReader passwordReader); Algorithm algorithm(); String username(); String password(); int cost(); int iterations(); int keyLength(); String salt(); void validate(); static CliArguments fromArgs(String... args); boolean help(); }### Answer: @Test public void shouldPromptForPasswordIfNotProvidedAsArgument() throws Exception { final PasswordReader passwordReader = mock(PasswordReader.class); when(passwordReader.readPassword()).thenReturn("password-from-cli"); final CliArguments arguments = new CliArguments(passwordReader); final String password = arguments.password(); assertThat(password, is("password-from-cli")); }
### Question: PasswordFileReader { public Properties read(String passwordFilePath) throws IOException { final Properties properties = new Properties(); try (Reader inputStream = new InputStreamReader(new FileInputStream(passwordFilePath), UTF_8)) { properties.load(inputStream); } return properties; } Properties read(String passwordFilePath); }### Answer: @Test public void shouldReadPasswordFile() throws Exception { PasswordFileReader reader = new PasswordFileReader(); Properties properties = reader.read(PasswordFileReaderTest.class.getResource("/password.properties").getFile()); assertThat(properties.getProperty("username"), is("{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g=")); }
### Question: SHA1Matcher implements HashMatcher { @Override public boolean matches(String plainText, String hashed) { final String digest = sha1Digest(plainText.getBytes()); return hashed.equals(digest) || hashed.equals("{SHA}" + digest); } @Override boolean matches(String plainText, String hashed); }### Answer: @Test public void shouldReturnTrueForValidPassword() throws Exception { HashMatcher sha1 = new SHA1Matcher(); final boolean matching = sha1.matches("badger", "ThmbShxAtJepX80c2JY1FzOEmUk="); assertTrue(matching); } @Test public void shouldReturnFalseForInvalidPassword() throws Exception { HashMatcher sha1 = new SHA1Matcher(); final boolean matching = sha1.matches("random", "ThmbShxAtJepX80c2JY1FzOEmUk="); assertFalse(matching); } @Test public void shouldValidateHashWithSHAPrefix() throws Exception { HashMatcher sha1 = new SHA1Matcher(); final boolean matching = sha1.matches("badger", "{SHA}ThmbShxAtJepX80c2JY1FzOEmUk="); assertTrue(matching); }
### Question: BCryptMatcher implements HashMatcher { @Override public boolean matches(String plainText, String hashed) { final String processedHash = hashed.replaceFirst("^\\$2y\\$", "\\$2a\\$").replaceFirst("^\\$2b\\$", "\\$2a\\$"); return BCrypt.checkpw(plainText, processedHash); } @Override boolean matches(String plainText, String hashed); }### Answer: @Test public void shouldReturnTrueForValidPassword() throws Exception { final boolean matches = bcryptMatcher.matches("bob", "$2y$05$6x2HXaQcqi7osijESYtUTeJBx5rYpIYQJlP51rFZCRpuE3hBH/LAq"); assertTrue(matches); } @Test public void shouldReturnFalseForInvalidPassword() throws Exception { final boolean matches = bcryptMatcher.matches("bob", "$2y$05$6x2HXaQcqi7osijESYtUTeJBx5rYpIYQJlP51rFZCRpuE3hBH/dad"); assertFalse(matches); }
### Question: BCryptProvider implements HashProvider { @Override public String hash(CliArguments arguments) { final String salt = BCrypt.gensalt(arguments.cost()); final String hashedPasswd = BCrypt.hashpw(arguments.password(), salt); return format("{0}={1}", arguments.username(), hashedPasswd); } @Override String hash(CliArguments arguments); }### Answer: @Test public void shouldGeneratePasswordFileEntryUsingBCrypt() throws Exception { when(cliArguments.algorithm()).thenReturn(Algorithm.BCRYPT); when(cliArguments.cost()).thenReturn(6); final String hash = provider.hash(cliArguments); assertThat(hash,startsWith("admin=$2a$06$")); }
### Question: GraphicsBounds { public static Rectangle createBounds() { return new BufferedImage(800, 600, BufferedImage.TYPE_3BYTE_BGR) .createGraphics() .getDeviceConfiguration() .getBounds(); } static void main(String[] args); static Rectangle createBounds(); }### Answer: @Test void createBounds() throws Exception { assertThat(GraphicsBounds.createBounds()) .isEqualTo(new Rectangle(0, 0, 800, 600)); }
### Question: HeaderExtractor implements IExtractor { @Override public String extractValue(IHttpRequest request) { return StringUtils.defaultIfEmpty(request.getHeaderField(key), null); } HeaderExtractor(String key); @Override String extractValue(IHttpRequest request); }### Answer: @Test public void testHeaderExtraction() { IHttpRequest request = mock(IHttpRequest.class); when(request.getHeaderField(eq("testField"))).thenReturn("test"); HeaderExtractor extractor = new HeaderExtractor("testField"); assertEquals("test", extractor.extractValue(request)); when(request.getHeaderField(eq("testField"))).thenReturn(null); assertEquals(null, extractor.extractValue(request)); when(request.getHeaderField(eq("testField"))).thenReturn(""); assertEquals(null, extractor.extractValue(request)); }
### Question: FormExtractor implements IExtractor { @Override public String extractValue(IHttpRequest request) { return StringUtils.defaultIfEmpty(request.getFormParameterValue(key), null); } FormExtractor(String key); @Override String extractValue(IHttpRequest request); }### Answer: @Test public void testFormExtraction() { IHttpRequest request = mock(IHttpRequest.class); when(request.getFormParameterValue(eq("testField"))).thenReturn("test"); FormExtractor extractor = new FormExtractor("testField"); assertEquals("test", extractor.extractValue(request)); when(request.getFormParameterValue(eq("testField"))).thenReturn(null); assertEquals(null, extractor.extractValue(request)); when(request.getFormParameterValue(eq("testField"))).thenReturn(""); assertEquals(null, extractor.extractValue(request)); }
### Question: ScopeParser { public Set<String> parseScope(String scope) { if (scope == null) { return null; } Scanner scanner = new Scanner(StringUtils.trim(scope)); try { scanner.useDelimiter(" "); Set<String> result = new HashSet<>(); while (scanner.hasNext(SCOPE_PATTERN)) { String scopeToken = scanner.next(SCOPE_PATTERN); result.add(scopeToken); } return result; } finally { scanner.close(); } } String render(Set<String> scopes); Set<String> parseScope(String scope); }### Answer: @Test public void testParsing() { assertEquals(null, parser.parseScope(null)); assertTrue(parser.parseScope("").isEmpty()); assertTrue(parser.parseScope("scope").contains("scope")); assertTrue(parser.parseScope("sco/pe").contains("sco/pe")); assertTrue(parser.parseScope("scope scope1").contains("scope1")); assertTrue(parser.parseScope("scope scope1 ").contains("scope1")); assertTrue(parser.parseScope(" scope scope1").contains("scope1")); assertTrue(parser.parseScope(" scope Scope1").contains("Scope1")); assertTrue(parser.parseScope(" scope Scope1!").contains("Scope1!")); parser.parseScope(" scope sc/ope1"); }
### Question: ScopeParser { public String render(Set<String> scopes) { if (scopes == null) { return null; } StringBuffer buffer = new StringBuffer(); for (String scope : scopes) { if (buffer.length()>0) { buffer.append(" "); } buffer.append(scope); } return buffer.toString(); } String render(Set<String> scopes); Set<String> parseScope(String scope); }### Answer: @Test public void testRender() { Set<String> scopes = new HashSet<>(Arrays.asList("aa","bb","cc")); assertNull(parser.render(null)); assertEquals("aa bb cc", parser.render(scopes)); assertEquals(scopes, parser.parseScope(parser.render(scopes))); scopes = new HashSet<>(Arrays.asList("aa")); assertEquals("aa", parser.render(scopes)); scopes = new HashSet<>(); assertEquals("", parser.render(scopes)); }
### Question: UrlBuilder { protected Map<String, String> parseQueryParameters(String query) { if (query == null) { return null; } Scanner scanner = new Scanner(query); try { scanner.useDelimiter("[&=]"); Map<String, String> result = new LinkedHashMap<>(); while (scanner.hasNext(".+")) { String key = scanner.next("[^=]+"); String value = null; if (scanner.hasNext("[^&]+")) { value = scanner.next("[^&]+"); } result.put(key, value); } return result; } finally { scanner.close(); } } URI addQueryParameters(Map<String, Object> parameters, URI baseUrl); String addQueryParameters(String queryParams, Map<String, Object> newParameters); URI setFragment(URI baseUri, String newFragment); }### Answer: @Test public void testParsing() { Map<String, String> params; params = urlBuilder.parseQueryParameters("a=b&c=d"); assertEquals("b", params.get("a")); assertEquals("d", params.get("c")); params = urlBuilder.parseQueryParameters("a=b&c="); assertEquals("b", params.get("a")); assertEquals(null, params.get("c")); }
### Question: UrlBuilder { protected String render(Map<String, String> params) throws UnsupportedEncodingException { StringBuffer buffer = new StringBuffer(); for (Map.Entry<String, String> entry : params.entrySet()) { if (buffer.length()>0) { buffer.append("&"); } buffer.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.name())); buffer.append("="); if (entry.getValue()!=null) { buffer.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name())); } } return buffer.toString(); } URI addQueryParameters(Map<String, Object> parameters, URI baseUrl); String addQueryParameters(String queryParams, Map<String, Object> newParameters); URI setFragment(URI baseUri, String newFragment); }### Answer: @Test public void testRender() throws UrlBuilderException, URISyntaxException { URI baseUri = new URI("http: Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put("cd","gh"); parameters.put("numtest",1); URI result = urlBuilder.addQueryParameters(parameters, baseUri); assertEquals("http: parameters.put("abc","g"); result = urlBuilder.addQueryParameters(parameters, baseUri); assertEquals("http: }
### Question: FormParser { public Form parseForm(InputStream inputStream) throws FormParserException { Form result = new Form(); Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name()); scanner.useDelimiter(Pattern.compile("[&=]")); try { while (scanner.hasNext(FIELD_PATTERN)) { String name = urlDecode(scanner.next(FIELD_PATTERN)); String value = urlDecode(scanner.next(FIELD_PATTERN)); result.param(name, value); } } catch (NoSuchElementException | UnsupportedEncodingException e) { throw new FormParserException(e); } finally { scanner.close(); } return result; } Form parseForm(InputStream inputStream); }### Answer: @Test public void testParse() throws FormParserException { Form f = parser.parseForm(toInputStream("a=b&c=d")); assertTrue(f.asMap().containsKey("a")); assertTrue(f.asMap().containsKey("c")); assertEquals("b", f.asMap().getFirst("a")); assertEquals("d", f.asMap().getFirst("c")); f = parser.parseForm(toInputStream("a=b")); try { f = parser.parseForm(toInputStream("a=")); fail(); } catch (Exception e) { } try { f = parser.parseForm(toInputStream("a=b&c")); fail(); } catch (Exception e) { } }
### Question: SequenceProgram implements Program { @SuppressWarnings("Guava") public static Function<Holder<Program>, Void> prepend(Program program) { return (holder) -> { if (holder == null) { throw new IllegalStateException("No program holder"); } Program chain = holder.get(); if (chain == null) { chain = Programs.standard(); } holder.set(new SequenceProgram(program, chain)); return null; }; } SequenceProgram(Program... programs); @SuppressWarnings("Guava") // Must conform to Calcite's API static Function<Holder<Program>, Void> prepend(Program program); ImmutableList<Program> getPrograms(); @Override RelNode run(RelOptPlanner relOptPlanner, RelNode relNode, RelTraitSet relTraitSet, List<RelOptMaterialization> relOptMaterializationList, List<RelOptLattice> relOptLatticeList); }### Answer: @Test(expected = RuntimeException.class) public void testPrepend_throwsIfNoHolderIsGiven() { SequenceProgram.prepend(subProgram).apply(null); }
### Question: JournalledJdbcTable extends JdbcTable { @Override public RelNode toRel(RelOptTable.ToRelContext context, RelOptTable relOptTable) { JdbcRelBuilder relBuilder = relBuilderFactory.create( context.getCluster(), relOptTable.getRelOptSchema() ); relBuilder.scanJdbc( getJournalTable(), JdbcTableUtils.getQualifiedName(relOptTable, getJournalTable()) ); RexInputRef versionField = relBuilder.field(getVersionField()); RexInputRef subsequentVersionField = relBuilder.field(getSubsequentVersionField()); RexInputRef maxVersionField = relBuilder.appendField(relBuilder.makeOver( SqlStdOperatorTable.MAX, ImmutableList.of(versionField), relBuilder.fields(getKeyColumnNames()) )); relBuilder.filter( relBuilder.equals(versionField, maxVersionField), relBuilder.isNull(subsequentVersionField) ); return relBuilder.build(); } JournalledJdbcTable( String tableName, JournalledJdbcSchema journalledJdbcSchema, JdbcTable journalTable, String[] keyColumnNames ); @Override RelNode toRel(RelOptTable.ToRelContext context, RelOptTable relOptTable); }### Answer: @Test public void testToRel_changesTableToJournal() { table.toRel(context, relOptTable); Mockito.verify(relBuilder).scanJdbc(Mockito.same(journalTable), Mockito.any()); }
### Question: JournalledJdbcSchema extends JdbcSchema { public static JournalledJdbcSchema create( SchemaPlus parentSchema, String name, Map<String, Object> operand ) { DataSource dataSource; try { dataSource = parseDataSource(operand); } catch (Exception e) { throw new IllegalArgumentException("Error while reading dataSource", e); } String catalog = (String) operand.get("jdbcCatalog"); String schema = (String) operand.get("jdbcSchema"); Expression expression = null; if (parentSchema != null) { expression = Schemas.subSchemaExpression(parentSchema, name, JdbcSchema.class); } final SqlDialect dialect = createDialect(dataSource); final JdbcConvention convention = JdbcConvention.of(dialect, expression, name); return new JournalledJdbcSchema(dataSource, dialect, convention, catalog, schema, operand); } private JournalledJdbcSchema( DataSource dataSource, SqlDialect dialect, JdbcConvention convention, String catalog, String schema, Map<String, Object> operand ); static JournalledJdbcSchema create( SchemaPlus parentSchema, String name, Map<String, Object> operand ); @Override Table getTable(String name); @Override Set<String> getTableNames(); }### Answer: @Test public void testFactoryWillAutomaticallyAddRules() { JournalledJdbcSchema.Factory.INSTANCE.setAutomaticallyAddRules(true); JournalledJdbcSchema.Factory.INSTANCE.create(null, "my-parent", options); try { Program def = Mockito.mock(Program.class); Holder<Program> holder = Holder.of(def); Hook.PROGRAM.run(holder); Assert.assertTrue(holder.get() instanceof SequenceProgram); Assert.assertTrue(((SequenceProgram) holder.get()).getPrograms().get(0) instanceof ForcedRulesProgram); } finally { JournalledJdbcSchema.Factory.INSTANCE.setAutomaticallyAddRules(false); JournalledJdbcRuleManager.removeHook(); } }
### Question: JournalledJdbcSchema extends JdbcSchema { String getVersionField() { return versionField; } private JournalledJdbcSchema( DataSource dataSource, SqlDialect dialect, JdbcConvention convention, String catalog, String schema, Map<String, Object> operand ); static JournalledJdbcSchema create( SchemaPlus parentSchema, String name, Map<String, Object> operand ); @Override Table getTable(String name); @Override Set<String> getTableNames(); }### Answer: @Test public void testDefaultVersionField() { options.remove("journalVersionField"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getVersionField(), "version_number"); }
### Question: JournalledJdbcSchema extends JdbcSchema { String getSubsequentVersionField() { return subsequentVersionField; } private JournalledJdbcSchema( DataSource dataSource, SqlDialect dialect, JdbcConvention convention, String catalog, String schema, Map<String, Object> operand ); static JournalledJdbcSchema create( SchemaPlus parentSchema, String name, Map<String, Object> operand ); @Override Table getTable(String name); @Override Set<String> getTableNames(); }### Answer: @Test public void testDefaultSubsequentVersionField() { options.remove("journalSubsequentVersionField"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getSubsequentVersionField(), "subsequent_version_number"); }
### Question: JournalledJdbcSchema extends JdbcSchema { String journalNameFor(String virtualName) { return virtualName + journalSuffix; } private JournalledJdbcSchema( DataSource dataSource, SqlDialect dialect, JdbcConvention convention, String catalog, String schema, Map<String, Object> operand ); static JournalledJdbcSchema create( SchemaPlus parentSchema, String name, Map<String, Object> operand ); @Override Table getTable(String name); @Override Set<String> getTableNames(); }### Answer: @Test public void testDefaultJournalSuffix() { options.remove("journalSuffix"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.journalNameFor("foo"), "foo_journal"); }
### Question: JournalledJdbcSchema extends JdbcSchema { private static JournalVersionType getVersionType(String name) { for (JournalVersionType v : JournalVersionType.values()) { if (v.name().equalsIgnoreCase(name)) { return v; } } throw new IllegalArgumentException("Unknown version type: " + name); } private JournalledJdbcSchema( DataSource dataSource, SqlDialect dialect, JdbcConvention convention, String catalog, String schema, Map<String, Object> operand ); static JournalledJdbcSchema create( SchemaPlus parentSchema, String name, Map<String, Object> operand ); @Override Table getTable(String name); @Override Set<String> getTableNames(); }### Answer: @Test public void testDefaultsToTimestampVersioning() { JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getVersionType(), JournalVersionType.TIMESTAMP); } @Test public void testVersionTypeCanBeChanged() { options.put("journalVersionType", "BIGINT"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getVersionType(), JournalVersionType.BIGINT); } @Test public void testVersionTypeIsCaseInsensitive() { options.put("journalVersionType", "bigint"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getVersionType(), JournalVersionType.BIGINT); }
### Question: JournalledJdbcSchema extends JdbcSchema { @Override public Set<String> getTableNames() { return getTableMap(true).keySet(); } private JournalledJdbcSchema( DataSource dataSource, SqlDialect dialect, JdbcConvention convention, String catalog, String schema, Map<String, Object> operand ); static JournalledJdbcSchema create( SchemaPlus parentSchema, String name, Map<String, Object> operand ); @Override Table getTable(String name); @Override Set<String> getTableNames(); }### Answer: @Test public void testGetTableNamesReturnsVirtualTables() { JournalledJdbcSchema schema = makeSchema(); Set<String> names = schema.getTableNames(); Assert.assertTrue(names.contains("MY_TABLE")); Assert.assertTrue(names.contains("OTHER_TABLE")); }
### Question: BankAccountService { public static TransferResult transfer(BankAccount to, BankAccount from, Money money) { BankAccount updatedFrom = from.withdrawTo(to, money); BankAccount updatedTo = to.depositFrom(from, money); return TransferResult.of(updatedTo, updatedFrom); } static TransferResult transfer(BankAccount to, BankAccount from, Money money); }### Answer: @Test public void transfer1() throws Exception { Money initialMoney = Money.of(10000); BankAccount bankAccount1 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney); BankAccount bankAccount2 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney); System.out.println("bankAccount1 = " + bankAccount1.getBalance()); System.out.println("bankAccount2 = " + bankAccount2.getBalance()); BankAccountService.TransferResult transferResult = BankAccountService.transfer( bankAccount1, bankAccount2, Money.of(10000) ); System.out.println("to = " + transferResult.getTo().getBalance()); System.out.println("from = " + transferResult.getFrom().getBalance()); } @Test public void transfer2() throws Exception { Money initialMoney = Money.of(10000); BankAccount bankAccount1 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney); BankAccount bankAccount2 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney); System.out.println("bankAccount1 = " + bankAccount1.getBalance()); System.out.println("bankAccount2 = " + bankAccount2.getBalance()); try { BankAccountService.transfer(bankAccount1, bankAccount2, Money.of(20000)); fail("No error occurred!!!"); } catch (IllegalArgumentException ignored) { ; } }
### Question: Encoding { public abstract Integer oid(); Encoding(final Charset charset); void encodeBinary(final V value, final BufferWriter writer); V decode(final Format format, final BufferReader reader); abstract Integer oid(); Set<Integer> additionalOids(); abstract Class<V> valueClass(); }### Answer: @Test public void oi() { assertEquals(expectedOid, enc.oid()); }