src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ConfigurationProperties { public static int corsMaxAgeInSeconds() { return readIntegerProperty(MOCKSERVER_CORS_MAX_AGE_IN_SECONDS, "MOCKSERVER_CORS_MAX_AGE_IN_SECONDS", DEFAULT_CORS_MAX_AGE_IN_SECONDS); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadCORSMaxAgeInSeconds() { System.clearProperty("mockserver.corsMaxAgeInSeconds"); assertEquals(300, corsMaxAgeInSeconds()); corsMaxAgeInSeconds(100); assertEquals("100", System.getProperty("mockserver.corsMaxAgeInSeconds")); assertEquals(100, corsMaxAgeInSeconds()); } |
ConfigurationProperties { public static String livenessHttpGetPath() { return livenessHttpGetPath; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadLivenessHttpGetPath() { System.clearProperty("mockserver.livenessHttpGetPath"); assertEquals("", livenessHttpGetPath()); livenessHttpGetPath("/livenessHttpGetPath"); assertEquals("/livenessHttpGetPath", livenessHttpGetPath()); assertEquals("/livenessHttpGetPath", System.getProperty("mockserver.livenessHttpGetPath")); } |
BodyDecoderEncoder { public ByteBuf bodyToByteBuf(Body body, String contentTypeHeader) { byte[] bytes = bodyToBytes(body, contentTypeHeader); if (bytes != null) { return Unpooled.copiedBuffer(bytes); } else { return Unpooled.buffer(0, 0); } } ByteBuf bodyToByteBuf(Body body, String contentTypeHeader); ByteBuf[] bodyToByteBuf(Body body, String contentTypeHeader, int chunkSize); static byte[][] split(byte[] array, int chunkSize); BodyWithContentType byteBufToBody(ByteBuf content, String contentTypeHeader); } | @Test public void shouldSerialiseBodyToByteBufWithNoContentType() { Body body = new StringBody("şarəs"); ByteBuf result = new BodyDecoderEncoder().bodyToByteBuf(body, null); byte[] bodyBytes = new byte[result.readableBytes()]; result.readBytes(bodyBytes); assertThat(bodyBytes, is("şarəs".getBytes(DEFAULT_HTTP_CHARACTER_SET))); }
@Test public void shouldSerialiseBodyToChunkedByteBufWithNoContentType() { Body body = new StringBody("bytes"); ByteBuf[] result = new BodyDecoderEncoder().bodyToByteBuf(body, null, 2); assertThat(result.length, is(3)); byte[] bodyBytes = new byte[result[0].readableBytes()]; result[0].readBytes(bodyBytes); assertThat(bodyBytes, is("by".getBytes(DEFAULT_HTTP_CHARACTER_SET))); bodyBytes = new byte[result[1].readableBytes()]; result[1].readBytes(bodyBytes); assertThat(bodyBytes, is("te".getBytes(DEFAULT_HTTP_CHARACTER_SET))); bodyBytes = new byte[result[2].readableBytes()]; result[2].readBytes(bodyBytes); assertThat(bodyBytes, is("s".getBytes(DEFAULT_HTTP_CHARACTER_SET))); }
@Test public void shouldSerialiseBodyToByteBufWithJsonContentType() { Body body = new StringBody("şarəs"); ByteBuf result = new BodyDecoderEncoder().bodyToByteBuf(body, MediaType.APPLICATION_JSON_UTF_8.toString()); byte[] bodyBytes = new byte[result.readableBytes()]; result.readBytes(bodyBytes); assertThat(bodyBytes, is(not("şarəs".getBytes(DEFAULT_HTTP_CHARACTER_SET)))); assertThat(bodyBytes, is("şarəs".getBytes(UTF_8))); }
@Test public void shouldSerialiseBodyToChunkedByteBufWithJsonContentType() { Body body = new StringBody("şarəs"); byte[] bytes = "şarəs".getBytes(UTF_8); ByteBuf[] result = new BodyDecoderEncoder().bodyToByteBuf(body, MediaType.APPLICATION_JSON_UTF_8.toString(), 2); assertThat(result.length, is(4)); byte[] bodyBytes = new byte[result[0].readableBytes()]; result[0].readBytes(bodyBytes); assertThat(bodyBytes, is(Arrays.copyOfRange(bytes, 0, 2))); bodyBytes = new byte[result[1].readableBytes()]; result[1].readBytes(bodyBytes); assertThat(bodyBytes, is(Arrays.copyOfRange(bytes, 2, 4))); bodyBytes = new byte[result[2].readableBytes()]; result[2].readBytes(bodyBytes); assertThat(bodyBytes, is(Arrays.copyOfRange(bytes, 4, 6))); bodyBytes = new byte[result[3].readableBytes()]; result[3].readBytes(bodyBytes); assertThat(bodyBytes, is(Arrays.copyOfRange(bytes, 6, 7))); } |
BodyDecoderEncoder { public BodyWithContentType byteBufToBody(ByteBuf content, String contentTypeHeader) { if (content != null && content.readableBytes() > 0) { byte[] bodyBytes = new byte[content.readableBytes()]; content.readBytes(bodyBytes); return bytesToBody(bodyBytes, contentTypeHeader); } return null; } ByteBuf bodyToByteBuf(Body body, String contentTypeHeader); ByteBuf[] bodyToByteBuf(Body body, String contentTypeHeader, int chunkSize); static byte[][] split(byte[] array, int chunkSize); BodyWithContentType byteBufToBody(ByteBuf content, String contentTypeHeader); } | @Test public void shouldReadByteBufToStringBodyWithNoContentType() { ByteBuf byteBuf = Unpooled.copiedBuffer("bytes".getBytes(DEFAULT_HTTP_CHARACTER_SET)); BodyWithContentType result = new BodyDecoderEncoder().byteBufToBody(byteBuf, null); assertThat(result, is(exact("bytes"))); }
@Test public void shouldReadByteBufToStringBodyWithStringContentType() { ByteBuf byteBuf = Unpooled.copiedBuffer("bytes".getBytes(DEFAULT_HTTP_CHARACTER_SET)); BodyWithContentType result = new BodyDecoderEncoder().byteBufToBody(byteBuf, MediaType.TEXT_PLAIN.toString()); assertThat(result, is(exact("bytes", MediaType.TEXT_PLAIN))); }
@Test public void shouldReadByteBufToStringBodyWithStringContentTypeAndCharset() { ByteBuf byteBuf = Unpooled.copiedBuffer("bytes".getBytes(DEFAULT_HTTP_CHARACTER_SET)); BodyWithContentType result = new BodyDecoderEncoder().byteBufToBody(byteBuf, MediaType.TEXT_HTML_UTF_8.toString()); assertThat(result, is(exact("bytes", MediaType.TEXT_HTML_UTF_8))); }
@Test public void shouldReadByteBufToJsonBodyWithJsonContentType() { ByteBuf byteBuf = Unpooled.copiedBuffer("şarəs".getBytes(UTF_8)); BodyWithContentType result = new BodyDecoderEncoder().byteBufToBody(byteBuf, MediaType.APPLICATION_JSON_UTF_8.toString()); assertThat(result, is(json("şarəs", MediaType.APPLICATION_JSON_UTF_8))); }
@Test public void shouldReadByteBufToJsonBodyWithJsonContentTypeAndCharset() { ByteBuf byteBuf = Unpooled.copiedBuffer("şarəs".getBytes(DEFAULT_HTTP_CHARACTER_SET)); BodyWithContentType result = new BodyDecoderEncoder().byteBufToBody(byteBuf, MediaType.APPLICATION_JSON.toString()); assertThat(result, is(json("?ar?s", MediaType.APPLICATION_JSON))); }
@Test public void shouldReadByteBufToBinaryBodyWithBinaryContentType() { ByteBuf byteBuf = Unpooled.copiedBuffer("bytes".getBytes(DEFAULT_HTTP_CHARACTER_SET)); BodyWithContentType result = new BodyDecoderEncoder().byteBufToBody(byteBuf, MediaType.ANY_VIDEO_TYPE.toString()); assertThat(result, is(binary("bytes".getBytes(DEFAULT_HTTP_CHARACTER_SET), MediaType.ANY_VIDEO_TYPE))); }
@Test public void shouldReadByteBufToBinaryBodyWithBinaryContentTypeAndCharset() { ByteBuf byteBuf = Unpooled.copiedBuffer("bytes".getBytes(DEFAULT_HTTP_CHARACTER_SET)); BodyWithContentType result = new BodyDecoderEncoder().byteBufToBody(byteBuf, MediaType.ANY_VIDEO_TYPE.withCharset(UTF_8).toString()); assertThat(result, is(exact("bytes", MediaType.ANY_VIDEO_TYPE.withCharset(UTF_8)))); } |
NettyHttpToMockServerHttpRequestDecoder extends MessageToMessageDecoder<FullHttpRequest> { @Override protected void decode(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest, List<Object> out) { out.add(fullHttpRequestToMockServerRequest.mapFullHttpRequestToMockServerRequest(fullHttpRequest)); } NettyHttpToMockServerHttpRequestDecoder(MockServerLogger mockServerLogger, boolean isSecure, Integer port); } | @Test public void shouldDecodeMethod() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/uri"); mockServerRequestDecoder.decode(null, fullHttpRequest, output); NottableString method = ((HttpRequest) output.get(0)).getMethod(); assertThat(method, is(string("OPTIONS"))); }
@Test public void shouldDecodeQueryParameters() { String uri = "/uri?" + "queryStringParameterNameOne=queryStringParameterValueOne_One" + "&queryStringParameterNameOne=queryStringParameterValueOne_Two" + "&queryStringParameterNameTwo=queryStringParameterValueTwo_One"; fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); mockServerRequestDecoder.decode(null, fullHttpRequest, output); List<Parameter> queryStringParameters = ((HttpRequest) output.get(0)).getQueryStringParameterList(); assertThat(queryStringParameters, containsInAnyOrder( param("queryStringParameterNameOne", "queryStringParameterValueOne_One", "queryStringParameterValueOne_Two"), param("queryStringParameterNameTwo", "queryStringParameterValueTwo_One") )); }
@Test public void shouldNotSplitQueryParametersCommaDelimited() { String uri = "/uri?" + "queryStringParameterNameOne=queryStringParameterValueOne_One,queryStringParameterValueOne_Two" + "&queryStringParameterNameTwo=queryStringParameterValueTwo_One"; fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); mockServerRequestDecoder.decode(null, fullHttpRequest, output); List<Parameter> queryStringParameters = ((HttpRequest) output.get(0)).getQueryStringParameterList(); assertThat(queryStringParameters, containsInAnyOrder( param("queryStringParameterNameOne", "queryStringParameterValueOne_One,queryStringParameterValueOne_Two"), param("queryStringParameterNameTwo", "queryStringParameterValueTwo_One") )); }
@Test public void shouldNotSplitQueryParametersPipeDelimited() { String uri = "/uri?" + "queryStringParameterNameOne=queryStringParameterValueOne_One|queryStringParameterValueOne_Two" + "&queryStringParameterNameTwo=queryStringParameterValueTwo_One"; fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); mockServerRequestDecoder.decode(null, fullHttpRequest, output); List<Parameter> queryStringParameters = ((HttpRequest) output.get(0)).getQueryStringParameterList(); assertThat(queryStringParameters, containsInAnyOrder( param("queryStringParameterNameOne", "queryStringParameterValueOne_One|queryStringParameterValueOne_Two"), param("queryStringParameterNameTwo", "queryStringParameterValueTwo_One") )); }
@Test public void shouldDecodePath() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri"); mockServerRequestDecoder.decode(null, fullHttpRequest, output); HttpRequest httpRequest = ((HttpRequest) output.get(0)); assertThat(httpRequest.getPath(), is(string("/uri"))); }
@Test public void shouldDecodeHeaders() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri"); fullHttpRequest.headers().add("headerName1", "headerValue1_1"); fullHttpRequest.headers().add("headerName1", "headerValue1_2"); fullHttpRequest.headers().add("headerName2", "headerValue2"); mockServerRequestDecoder.decode(null, fullHttpRequest, output); List<Header> headers = ((HttpRequest) output.get(0)).getHeaderList(); assertThat(headers, containsInAnyOrder( header("headerName1", "headerValue1_1", "headerValue1_2"), header("headerName2", "headerValue2") )); }
@Test public void shouldDecodeIsKeepAlive() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri"); fullHttpRequest.headers().add("Connection", "keep-alive"); mockServerRequestDecoder.decode(null, fullHttpRequest, output); HttpRequest httpRequest = (HttpRequest) output.get(0); assertThat(httpRequest.isKeepAlive(), is(true)); }
@Test public void shouldDecodeIsNotKeepAlive() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri"); fullHttpRequest.headers().add("Connection", "close"); mockServerRequestDecoder.decode(null, fullHttpRequest, output); HttpRequest httpRequest = (HttpRequest) output.get(0); assertThat(httpRequest.isKeepAlive(), is(false)); }
@Test public void shouldDecodeCookies() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri"); fullHttpRequest.headers().add("Cookie", "cookieName1=cookieValue1 ; cookieName2=cookieValue2; "); fullHttpRequest.headers().add("Cookie", "cookieName3 =cookieValue3 ;"); mockServerRequestDecoder.decode(null, fullHttpRequest, output); List<Cookie> cookies = ((HttpRequest) output.get(0)).getCookieList(); assertThat(cookies, containsInAnyOrder( cookie("cookieName1", "cookieValue1 "), cookie("cookieName2", "cookieValue2"), cookie("cookieName3", "cookieValue3 ") )); }
@Test public void shouldDecodeCookiesWithEmbeddedEquals() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri"); fullHttpRequest.headers().add("Cookie", "cookieName1=cookie=Value1 ; cookieName2=cookie==Value2; "); mockServerRequestDecoder.decode(null, fullHttpRequest, output); List<Cookie> cookies = ((HttpRequest) output.get(0)).getCookieList(); assertThat(cookies, containsInAnyOrder( cookie("cookieName1", "cookie=Value1 "), cookie("cookieName2", "cookie==Value2") )); }
@Test public void shouldDecodeCookiesWithRFC2965StyleAttributes() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri"); fullHttpRequest.headers().add("Cookie", "$Version=1; Customer=WILE_E_COYOTE; $Path=/acme"); mockServerRequestDecoder.decode(null, fullHttpRequest, output); List<Cookie> cookies = ((HttpRequest) output.get(0)).getCookieList(); assertThat(cookies, containsInAnyOrder( cookie("Customer", "WILE_E_COYOTE") )); }
@Test public void shouldDecodeBodyWithContentTypeAndNoCharset() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri", Unpooled.wrappedBuffer("A normal string with ASCII characters".getBytes(DEFAULT_HTTP_CHARACTER_SET))); fullHttpRequest.headers().add(CONTENT_TYPE, MediaType.create("text", "plain").toString()); mockServerRequestDecoder.decode(null, fullHttpRequest, output); Body body = ((HttpRequest) output.get(0)).getBody(); assertThat(body, is(exact("A normal string with ASCII characters", MediaType.create("text", "plain")))); }
@Test public void shouldDecodeBodyWithNoContentType() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri", Unpooled.wrappedBuffer("A normal string with ASCII characters".getBytes(DEFAULT_HTTP_CHARACTER_SET))); mockServerRequestDecoder.decode(null, fullHttpRequest, output); Body body = ((HttpRequest) output.get(0)).getBody(); assertThat(body, is(exact("A normal string with ASCII characters"))); }
@Test public void shouldTransmitUnencodableCharacters() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri", Unpooled.wrappedBuffer("Euro sign: \u20AC".getBytes(DEFAULT_HTTP_CHARACTER_SET))); fullHttpRequest.headers().add(CONTENT_TYPE, MediaType.create("text", "plain").toString()); mockServerRequestDecoder.decode(null, fullHttpRequest, output); Body body = ((HttpRequest) output.get(0)).getBody(); assertThat(body.getRawBytes(), is("Euro sign: \u20AC".getBytes(DEFAULT_HTTP_CHARACTER_SET))); assertThat(body.getValue(), is(new String("Euro sign: \u20AC".getBytes(DEFAULT_HTTP_CHARACTER_SET), DEFAULT_HTTP_CHARACTER_SET))); }
@Test public void shouldUseDefaultCharsetIfCharsetNotSupported() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri", Unpooled.wrappedBuffer("A normal string with ASCII characters".getBytes(DEFAULT_HTTP_CHARACTER_SET))); fullHttpRequest.headers().add(CONTENT_TYPE, "plain/text; charset=invalid-charset"); mockServerRequestDecoder.decode(null, fullHttpRequest, output); Body body = ((HttpRequest) output.get(0)).getBody(); assertThat(body, is(new StringBody("A normal string with ASCII characters", "A normal string with ASCII characters".getBytes(DEFAULT_HTTP_CHARACTER_SET), false, MediaType.parse("plain/text; charset=invalid-charset")))); }
@Test public void shouldDecodeBodyWithUTF8ContentType() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri", Unpooled.wrappedBuffer("avro işarəsi: \u20AC".getBytes(StandardCharsets.UTF_8))); fullHttpRequest.headers().add(CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString()); mockServerRequestDecoder.decode(null, fullHttpRequest, output); Body body = ((HttpRequest) output.get(0)).getBody(); assertThat(body, is(exact("avro işarəsi: \u20AC", MediaType.PLAIN_TEXT_UTF_8))); }
@Test public void shouldDecodeBodyWithUTF16ContentType() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri", Unpooled.wrappedBuffer("我说中国话".getBytes(StandardCharsets.UTF_16))); fullHttpRequest.headers().add(CONTENT_TYPE, MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()); mockServerRequestDecoder.decode(null, fullHttpRequest, output); Body body = ((HttpRequest) output.get(0)).getBody(); assertThat(body, is(exact("我说中国话", MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16)))); }
@Test public void shouldDecodeBinaryBody() { fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/uri", Unpooled.wrappedBuffer("some_random_bytes".getBytes(UTF_8))); fullHttpRequest.headers().add(CONTENT_TYPE, MediaType.JPEG); mockServerRequestDecoder.decode(null, fullHttpRequest, output); Body body = ((HttpRequest) output.get(0)).getBody(); assertThat(body, is(binary("some_random_bytes".getBytes(UTF_8), MediaType.JPEG))); } |
MockServerEventBus { void publish(EventType event) { for (SubscriberHandler subscriber : subscribers.get(event)) { subscriber.handle(); } } void subscribe(SubscriberHandler subscriber, EventType... events); } | @Test public void shouldPublishStopEventWhenNoRegisterSubscriber() { bus.publish(STOP); } |
ExpandedParameterDecoder { public List<NottableString> splitOnDelimiter(ParameterStyle style, String name, List<NottableString> values) { if (isNotBlank(style.getRegex())) { List<NottableString> splitValues = new ArrayList<>(); for (NottableString value : values) { Matcher quotedValue = QUOTED_PARAMETER_VALUE.matcher(value.getValue()); if (quotedValue.matches()) { if (value.isOptional()) { splitValues.add(optional(quotedValue.group(1), value.isNot())); } else { splitValues.add(string(quotedValue.group(1), value.isNot())); } } else if (!JSON_VALUE.matcher(value.getValue()).matches()) { for (String splitValue : value.getValue().split(style.getRegex().replaceAll("<name>", name))) { if (value.isOptional()) { splitValues.add(optional(splitValue, value.isNot())); } else { splitValues.add(string(splitValue, value.isNot())); } } } } return splitValues; } else { return values; } } ExpandedParameterDecoder(MockServerLogger mockServerLogger); Parameters retrieveFormParameters(String parameterString, boolean hasPath); void splitParameters(Parameters matcher, Parameters matched); List<NottableString> splitOnDelimiter(ParameterStyle style, String name, List<NottableString> values); } | @Test public void shouldSplitMatrixParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.MATRIX_EXPLODED, "parameterName", Arrays.asList( string("2;parameterName=3"), string("3;parameterName=4;parameterName=5") )), containsInAnyOrder( string("2"), string("3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.MATRIX_EXPLODED, "parameterName", Arrays.asList( string("2;parameterName=3", true), string("3;parameterName=4;parameterName=5") )), containsInAnyOrder( string("2", true), string("3", true), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.MATRIX_EXPLODED, "parameterName", Arrays.asList( string("?2;parameterName=3"), string("3;parameterName=4;parameterName=5") )), containsInAnyOrder( string("?2"), string("?3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.MATRIX_EXPLODED, "parameterName", Arrays.asList( string("?!2;parameterName=3"), string("3;parameterName=4;parameterName=5") )), containsInAnyOrder( string("?!2"), string("?!3"), string("3"), string("4"), string("5") ) ); }
@Test public void shouldNotSplitMatrixParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.MATRIX, "parameterName", Arrays.asList( string("2;parameterName=3"), string("3;parameterName=4;parameterName=5") )), containsInAnyOrder( string("2;parameterName=3"), string("3;parameterName=4;parameterName=5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.MATRIX, "parameterName", Arrays.asList( string("2;parameterName=3", true), string("3;parameterName=4;parameterName=5") )), containsInAnyOrder( string("2;parameterName=3", true), string("3;parameterName=4;parameterName=5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.MATRIX, "parameterName", Arrays.asList( string("?2;parameterName=3"), string("3;parameterName=4;parameterName=5") )), containsInAnyOrder( string("?2;parameterName=3"), string("3;parameterName=4;parameterName=5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.MATRIX, "parameterName", Arrays.asList( string("?!2;parameterName=3"), string("3;parameterName=4;parameterName=5") )), containsInAnyOrder( string("?!2;parameterName=3"), string("3;parameterName=4;parameterName=5") ) ); }
@Test public void shouldSplitLabelParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.LABEL_EXPLODED, "parameterName", Arrays.asList( string("2.3"), string("3.4.5") )), containsInAnyOrder( string("2"), string("3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.LABEL_EXPLODED, "parameterName", Arrays.asList( string("2.3", true), string("3.4.5") )), containsInAnyOrder( string("2", true), string("3", true), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.LABEL_EXPLODED, "parameterName", Arrays.asList( string("?2.3"), string("3.4.5") )), containsInAnyOrder( string("?2"), string("?3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.LABEL_EXPLODED, "parameterName", Arrays.asList( string("?!2.3"), string("3.4.5") )), containsInAnyOrder( string("?!2"), string("?!3"), string("3"), string("4"), string("5") ) ); }
@Test public void shouldNotSplitLabelParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.LABEL, "parameterName", Arrays.asList( string("2.3"), string("3.4.5") )), containsInAnyOrder( string("2.3"), string("3.4.5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.LABEL, "parameterName", Arrays.asList( string("2.3", true), string("3.4.5") )), containsInAnyOrder( string("2.3", true), string("3.4.5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.LABEL, "parameterName", Arrays.asList( string("?2.3"), string("3.4.5") )), containsInAnyOrder( string("?2.3"), string("3.4.5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.LABEL, "parameterName", Arrays.asList( string("?!2.3"), string("3.4.5") )), containsInAnyOrder( string("?!2.3"), string("3.4.5") ) ); }
@Test public void shouldSplitFormParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.FORM, "parameterName", Arrays.asList( string("2,3"), string("3,4,5") )), containsInAnyOrder( string("2"), string("3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.FORM, "parameterName", Arrays.asList( string("2,3", true), string("3,4,5") )), containsInAnyOrder( string("2", true), string("3", true), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.FORM, "parameterName", Arrays.asList( string("?2,3"), string("3,4,5") )), containsInAnyOrder( string("?2"), string("?3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.FORM, "parameterName", Arrays.asList( string("?!2,3"), string("3,4,5") )), containsInAnyOrder( string("?!2"), string("?!3"), string("3"), string("4"), string("5") ) ); }
@Test public void shouldNotSplitFormParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.FORM_EXPLODED, "parameterName", Arrays.asList( string("2,3"), string("3,4,5") )), containsInAnyOrder( string("2,3"), string("3,4,5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.FORM_EXPLODED, "parameterName", Arrays.asList( string("2,3", true), string("3,4,5") )), containsInAnyOrder( string("2,3", true), string("3,4,5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.FORM_EXPLODED, "parameterName", Arrays.asList( string("?2,3"), string("3,4,5") )), containsInAnyOrder( string("?2,3"), string("3,4,5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.FORM_EXPLODED, "parameterName", Arrays.asList( string("?2,3", true), string("3,4,5") )), containsInAnyOrder( string("?2,3", true), string("3,4,5") ) ); }
@Test public void shouldSplitPipeDelimitedParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED, "parameterName", Arrays.asList( string("2|3"), string("3|4|5") )), containsInAnyOrder( string("2"), string("3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED, "parameterName", Arrays.asList( string("2|3", true), string("3|4|5") )), containsInAnyOrder( string("2", true), string("3", true), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED, "parameterName", Arrays.asList( string("?2|3"), string("3|4|5") )), containsInAnyOrder( string("?2"), string("?3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED, "parameterName", Arrays.asList( string("?!2|3"), string("3|4|5") )), containsInAnyOrder( string("?!2"), string("?!3"), string("3"), string("4"), string("5") ) ); }
@Test public void shouldNotSplitPipeDelimitedParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("2|3"), string("3|4|5") )), containsInAnyOrder( string("2|3"), string("3|4|5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("!2|3"), string("3|4|5") )), containsInAnyOrder( string("!2|3"), string("3|4|5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("?2,3"), string("3|4|5") )), containsInAnyOrder( string("?2,3"), string("3|4|5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("?!2|3"), string("3|4|5") )), containsInAnyOrder( string("?!2|3"), string("3|4|5") ) ); }
@Test public void shouldSplitSpaceDelimitedWithPercentCharParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("2%203"), string("3%204%205") )), containsInAnyOrder( string("2"), string("3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("2%203", true), string("3%204%205") )), containsInAnyOrder( string("2", true), string("3", true), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("?2%203"), string("3%204%205") )), containsInAnyOrder( string("?2"), string("?3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("?!2%203"), string("3%204%205") )), containsInAnyOrder( string("?!2"), string("?!3"), string("3"), string("4"), string("5") ) ); }
@Test public void shouldNotSplitSpaceDelimitedWithPercentCharParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("2%203"), string("3%204%205") )), containsInAnyOrder( string("2%203"), string("3%204%205") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("!2%203"), string("3%204%205") )), containsInAnyOrder( string("!2%203"), string("3%204%205") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("?2,3"), string("3%204%205") )), containsInAnyOrder( string("?2,3"), string("3%204%205") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("?!2%203"), string("3%204%205") )), containsInAnyOrder( string("?!2%203"), string("3%204%205") ) ); }
@Test public void shouldSplitSpaceDelimitedWithSpaceCharParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("2 3"), string("3 4 5") )), containsInAnyOrder( string("2"), string("3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("2 3", true), string("3 4 5") )), containsInAnyOrder( string("2", true), string("3", true), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("?2 3"), string("3 4 5") )), containsInAnyOrder( string("?2"), string("?3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("?!2 3"), string("3 4 5") )), containsInAnyOrder( string("?!2"), string("?!3"), string("3"), string("4"), string("5") ) ); }
@Test public void shouldNotSplitSpaceDelimitedWithSpaceCharParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("2 3"), string("3 4 5") )), containsInAnyOrder( string("2 3"), string("3 4 5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("!2 3"), string("3 4 5") )), containsInAnyOrder( string("!2 3"), string("3 4 5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("?2,3"), string("3 4 5") )), containsInAnyOrder( string("?2,3"), string("3 4 5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("?!2 3"), string("3 4 5") )), containsInAnyOrder( string("?!2 3"), string("3 4 5") ) ); }
@Test public void shouldSplitSpaceDelimitedWithPlusCharParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("2+3"), string("3+4+5") )), containsInAnyOrder( string("2"), string("3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("2+3", true), string("3+4+5") )), containsInAnyOrder( string("2", true), string("3", true), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("?2+3"), string("3+4+5") )), containsInAnyOrder( string("?2"), string("?3"), string("3"), string("4"), string("5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.SPACE_DELIMITED, "parameterName", Arrays.asList( string("?!2+3"), string("3+4+5") )), containsInAnyOrder( string("?!2"), string("?!3"), string("3"), string("4"), string("5") ) ); }
@Test public void shouldNotSplitSpaceDelimitedWithPlusCharParameters() { assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("2+3"), string("3+4+5") )), containsInAnyOrder( string("2+3"), string("3+4+5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("!2+3"), string("3+4+5") )), containsInAnyOrder( string("!2+3"), string("3+4+5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("?2,3"), string("3+4+5") )), containsInAnyOrder( string("?2,3"), string("3+4+5") ) ); assertThat(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter( ParameterStyle.PIPE_DELIMITED_EXPLODED, "parameterName", Arrays.asList( string("?!2+3"), string("3+4+5") )), containsInAnyOrder( string("?!2+3"), string("3+4+5") ) ); } |
ForwardChainExpectation { public Expectation[] respond(final HttpResponse httpResponse) { expectation.thenRespond(httpResponse); return mockServerClient.upsert(expectation); } ForwardChainExpectation(MockServerLogger mockServerLogger, MockServerEventBus mockServerEventBus, MockServerClient mockServerClient, Expectation expectation); Expectation[] respond(final HttpResponse httpResponse); Expectation[] respond(final HttpTemplate httpTemplate); Expectation[] respond(final HttpClassCallback httpClassCallback); Expectation[] respond(final ExpectationResponseCallback expectationResponseCallback); Expectation[] respond(final ExpectationResponseCallback expectationResponseCallback, Delay delay); Expectation[] forward(final HttpForward httpForward); Expectation[] forward(final HttpTemplate httpTemplate); Expectation[] forward(final HttpClassCallback httpClassCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final ExpectationForwardAndResponseCallback expectationForwardResponseCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final Delay delay); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final ExpectationForwardAndResponseCallback expectationForwardResponseCallback, final Delay delay); Expectation[] forward(final HttpOverrideForwardedRequest httpOverrideForwardedRequest); Expectation[] error(final HttpError httpError); } | @Test public void shouldSetResponse() { HttpResponse response = response(); Expectation[] upsertedExpectations = forwardChainExpectation.respond(response); assertThat(upsertedExpectations, is(new Expectation[]{mockExpectation})); verify(mockExpectation).thenRespond(same(response)); verify(mockAbstractClient).upsert(mockExpectation); }
@Test public void shouldSetResponseTemplate() { HttpTemplate template = template(HttpTemplate.TemplateType.VELOCITY, "some_template"); Expectation[] upsertedExpectations = forwardChainExpectation.respond(template); assertThat(upsertedExpectations, is(new Expectation[]{mockExpectation})); verify(mockExpectation).thenRespond(same(template)); verify(mockAbstractClient).upsert(mockExpectation); }
@Test public void shouldSetResponseClassCallback() { HttpClassCallback callback = callback(); Expectation[] upsertedExpectations = forwardChainExpectation.respond(callback); assertThat(upsertedExpectations, is(new Expectation[]{mockExpectation})); verify(mockExpectation).thenRespond(same(callback)); verify(mockAbstractClient).upsert(mockExpectation); } |
ExpandedParameterDecoder { public void splitParameters(Parameters matcher, Parameters matched) { if (matcher != null && matched != null) { for (Parameter matcherEntry : matcher.getEntries()) { if (matcherEntry.getName().getParameterStyle() != null && matcherEntry.getName().getParameterStyle().isExploded()) { for (Parameter matchedEntry : matched.getEntries()) { if (matcherEntry.getName().getValue().equals(matchedEntry.getName().getValue()) || matchedEntry.getName().getValue().matches(matcherEntry.getName().getValue())) { matchedEntry.replaceValues(new ExpandedParameterDecoder(mockServerLogger).splitOnDelimiter(matcherEntry.getName().getParameterStyle(), matcherEntry.getName().getValue(), matchedEntry.getValues())); matched.replaceEntry(matchedEntry); } } } } } } ExpandedParameterDecoder(MockServerLogger mockServerLogger); Parameters retrieveFormParameters(String parameterString, boolean hasPath); void splitParameters(Parameters matcher, Parameters matched); List<NottableString> splitOnDelimiter(ParameterStyle style, String name, List<NottableString> values); } | @Test public void shouldSplitByMatchParameters() { Parameters matcher = new Parameters( param(string("some_name"), string("1")).withStyle(ParameterStyle.SPACE_DELIMITED), param(string("some_other_name"), string("a")).withStyle(ParameterStyle.MATRIX_EXPLODED), param(string("some_other_name_two"), string("value")).withStyle(ParameterStyle.PIPE_DELIMITED) ); Parameters matched = new Parameters( param(string("some_name"), string("1%202 3+4")), param(string("some_other_name"), string("a;some_other_name=b;some_other_name=c")), param(string("some_other_name_two"), string("one|two|three")) ); new ExpandedParameterDecoder(mockServerLogger).splitParameters(matcher, matched); assertThat(matched, is(new Parameters( param("some_name", "1", "2", "3", "4"), param("some_other_name", "a", "b", "c"), param("some_other_name_two", "one", "two", "three") ))); }
@Test public void shouldSplitByMatchParametersAndMatchByRegex() { Parameters matcher = new Parameters( param(string("some_name"), string("1")).withStyle(ParameterStyle.SPACE_DELIMITED), param(string("some_other_[a-z]{2}me"), string("a")).withStyle(ParameterStyle.FORM), param(string("some_other_name_.*"), string("value")).withStyle(ParameterStyle.PIPE_DELIMITED) ); Parameters matched = new Parameters( param(string("some_name"), string("1%202 3+4")), param(string("some_other_name"), string("a,b,c")), param(string("some_other_name_two"), string("one|two|three")) ); new ExpandedParameterDecoder(mockServerLogger).splitParameters(matcher, matched); assertThat(matched, is(new Parameters( param("some_name", "1", "2", "3", "4"), param("some_other_name", "a", "b", "c"), param("some_other_name_two", "one", "two", "three") ))); } |
BodyServletDecoderEncoder { public void bodyToServletResponse(HttpServletResponse httpServletResponse, Body body, String contentTypeHeader) { byte[] bytes = bodyDecoderEncoder.bodyToBytes(body, contentTypeHeader); if (bytes != null) { ioStreamUtils.writeToOutputStream(bytes, httpServletResponse); } } BodyServletDecoderEncoder(MockServerLogger mockServerLogger); void bodyToServletResponse(HttpServletResponse httpServletResponse, Body body, String contentTypeHeader); BodyWithContentType servletRequestToBody(HttpServletRequest servletRequest); } | @Test public void shouldSerialiseBodyToServletResponseWithNoContentType() throws IOException { Body body = new StringBody("bytes"); HttpServletResponse servletResponse = mock(HttpServletResponse.class); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(servletResponse.getOutputStream()).thenReturn( new DelegatingServletOutputStream(outputStream) ); new BodyServletDecoderEncoder(mockServerLogger).bodyToServletResponse(servletResponse, body, null); assertThat(outputStream.toByteArray(), is("bytes".getBytes(DEFAULT_HTTP_CHARACTER_SET))); }
@Test public void shouldSerialiseBodyToServletResponseWithJsonContentType() throws IOException { Body body = new StringBody("şarəs"); HttpServletResponse servletResponse = mock(HttpServletResponse.class); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(servletResponse.getOutputStream()).thenReturn( new DelegatingServletOutputStream(outputStream) ); new BodyServletDecoderEncoder(mockServerLogger).bodyToServletResponse(servletResponse, body, MediaType.APPLICATION_JSON_UTF_8.toString()); assertThat(outputStream.toByteArray(), is("şarəs".getBytes(UTF_8))); } |
BodyServletDecoderEncoder { public BodyWithContentType servletRequestToBody(HttpServletRequest servletRequest) { if (servletRequest != null) { String contentTypeHeader = servletRequest.getHeader(CONTENT_TYPE.toString()); try { byte[] bodyBytes = ByteStreams.toByteArray(servletRequest.getInputStream()); return bodyDecoderEncoder.bytesToBody(bodyBytes, contentTypeHeader); } catch (Throwable throwable) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setMessageFormat("exception while reading HttpServletRequest input stream") .setThrowable(throwable) ); throw new RuntimeException("IOException while reading HttpServletRequest input stream", throwable); } } return null; } BodyServletDecoderEncoder(MockServerLogger mockServerLogger); void bodyToServletResponse(HttpServletResponse httpServletResponse, Body body, String contentTypeHeader); BodyWithContentType servletRequestToBody(HttpServletRequest servletRequest); } | @Test public void shouldReadServletRequestToStringBodyWithNoContentType() throws IOException { HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getInputStream()).thenReturn( new DelegatingServletInputStream(IOUtils.toInputStream("bytes", DEFAULT_HTTP_CHARACTER_SET)) ); BodyWithContentType result = new BodyServletDecoderEncoder(mockServerLogger).servletRequestToBody(servletRequest); assertThat(result, is(exact("bytes"))); }
@Test public void shouldReadServletRequestToStringBodyWithStringContentType() throws IOException { HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getHeader(CONTENT_TYPE.toString())).thenReturn(MediaType.TEXT_PLAIN.toString()); when(servletRequest.getInputStream()).thenReturn( new DelegatingServletInputStream(IOUtils.toInputStream("bytes", DEFAULT_HTTP_CHARACTER_SET)) ); BodyWithContentType result = new BodyServletDecoderEncoder(mockServerLogger).servletRequestToBody(servletRequest); assertThat(result, is(exact("bytes", MediaType.TEXT_PLAIN))); }
@Test public void shouldReadServletRequestToStringBodyWithStringContentTypeAndCharset() throws IOException { HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getHeader(CONTENT_TYPE.toString())).thenReturn(MediaType.TEXT_HTML_UTF_8.toString()); when(servletRequest.getInputStream()).thenReturn( new DelegatingServletInputStream(IOUtils.toInputStream("bytes", UTF_8)) ); BodyWithContentType result = new BodyServletDecoderEncoder(mockServerLogger).servletRequestToBody(servletRequest); assertThat(result, is(exact("bytes", MediaType.TEXT_HTML_UTF_8))); }
@Test public void shouldReadServletRequestToJsonBodyWithJsonContentType() throws IOException { HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getHeader(CONTENT_TYPE.toString())).thenReturn(MediaType.APPLICATION_JSON_UTF_8.toString()); when(servletRequest.getInputStream()).thenReturn( new DelegatingServletInputStream(IOUtils.toInputStream("şarəs", UTF_8)) ); BodyWithContentType result = new BodyServletDecoderEncoder(mockServerLogger).servletRequestToBody(servletRequest); assertThat(result, is(json("şarəs", MediaType.APPLICATION_JSON_UTF_8))); }
@Test public void shouldReadServletRequestToJsonBodyWithJsonContentTypeAndCharset() throws IOException { HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getHeader(CONTENT_TYPE.toString())).thenReturn(MediaType.APPLICATION_JSON.toString()); when(servletRequest.getInputStream()).thenReturn( new DelegatingServletInputStream(IOUtils.toInputStream("şarəs", DEFAULT_HTTP_CHARACTER_SET)) ); BodyWithContentType result = new BodyServletDecoderEncoder(mockServerLogger).servletRequestToBody(servletRequest); assertThat(result, is(json("?ar?s", MediaType.APPLICATION_JSON))); }
@Test public void shouldReadServletRequestToBinaryBodyWithBinaryContentType() throws IOException { HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getHeader(CONTENT_TYPE.toString())).thenReturn(MediaType.ANY_VIDEO_TYPE.toString()); when(servletRequest.getInputStream()).thenReturn( new DelegatingServletInputStream(IOUtils.toInputStream("bytes", DEFAULT_HTTP_CHARACTER_SET)) ); BodyWithContentType result = new BodyServletDecoderEncoder(mockServerLogger).servletRequestToBody(servletRequest); assertThat(result, is(binary("bytes".getBytes(DEFAULT_HTTP_CHARACTER_SET), MediaType.ANY_VIDEO_TYPE))); }
@Test public void shouldReadServletRequestToBinaryBodyWithBinaryContentTypeAndCharset() throws IOException { HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getHeader(CONTENT_TYPE.toString())).thenReturn(MediaType.ANY_VIDEO_TYPE.withCharset(UTF_8).toString()); when(servletRequest.getInputStream()).thenReturn( new DelegatingServletInputStream(IOUtils.toInputStream("bytes", UTF_8)) ); BodyWithContentType result = new BodyServletDecoderEncoder(mockServerLogger).servletRequestToBody(servletRequest); assertThat(result, is(exact("bytes", MediaType.ANY_VIDEO_TYPE.withCharset(UTF_8)))); }
@Test(expected = RuntimeException.class) public void shouldHandleExceptionWhenReadInputStreamToByteArray() throws IOException { HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getHeader(CONTENT_TYPE.toString())).thenReturn(""); when(servletRequest.getInputStream()).thenThrow(new IOException("TEST EXCEPTION")); new BodyServletDecoderEncoder(mockServerLogger).servletRequestToBody(servletRequest); } |
NettyHttpToMockServerHttpResponseDecoder extends MessageToMessageDecoder<FullHttpResponse> { @Override protected void decode(ChannelHandlerContext ctx, FullHttpResponse fullHttpResponse, List<Object> out) { out.add(fullHttpResponseToMockServerResponse.mapFullHttpResponseToMockServerResponse(fullHttpResponse)); } NettyHttpToMockServerHttpResponseDecoder(MockServerLogger mockServerLogger); } | @Test public void shouldDecodeStatusCode() { fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.METHOD_NOT_ALLOWED); mockServerResponseDecoder.decode(null, fullHttpResponse, output); HttpResponse httpResponse = (HttpResponse) output.get(0); assertThat(httpResponse.getStatusCode(), is(HttpResponseStatus.METHOD_NOT_ALLOWED.code())); }
@Test public void shouldDecodeHeaders() { fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); fullHttpResponse.headers().add("headerName1", "headerValue1_1"); fullHttpResponse.headers().add("headerName1", "headerValue1_2"); fullHttpResponse.headers().add("headerName2", "headerValue2"); mockServerResponseDecoder.decode(null, fullHttpResponse, output); List<Header> headers = ((HttpResponse) output.get(0)).getHeaderList(); assertThat(headers, containsInAnyOrder( header("headerName1", "headerValue1_1", "headerValue1_2"), header("headerName2", "headerValue2") )); }
@Test public void shouldDecodeCookies() { fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); fullHttpResponse.headers().add("Cookie", "cookieName1=cookieValue1 ; cookieName2=cookieValue2; "); fullHttpResponse.headers().add("Cookie", "cookieName3 =cookieValue3_1; cookieName4=cookieValue3_2"); mockServerResponseDecoder.decode(null, fullHttpResponse, output); List<Cookie> cookies = ((HttpResponse) output.get(0)).getCookieList(); assertThat(cookies, containsInAnyOrder( cookie("cookieName1", "cookieValue1"), cookie("cookieName2", "cookieValue2"), cookie("cookieName3", "cookieValue3_1"), cookie("cookieName4", "cookieValue3_2") )); }
@Test public void shouldDecodeCookiesWithEmbeddedEquals() { fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); fullHttpResponse.headers().add("Cookie", "cookieName1=cookie=Value1 ; cookieName2=cookie==Value2; "); mockServerResponseDecoder.decode(null, fullHttpResponse, output); List<Cookie> cookies = ((HttpResponse) output.get(0)).getCookieList(); assertThat(cookies, containsInAnyOrder( cookie("cookieName1", "cookie=Value1"), cookie("cookieName2", "cookie==Value2") )); }
@Test public void shouldDecodeUTF8Body() { fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer("some_random_string".getBytes(UTF_8))); fullHttpResponse.headers().add(CONTENT_TYPE, MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()); mockServerResponseDecoder.decode(null, fullHttpResponse, output); Body body = ((HttpResponse) output.get(0)).getBody(); assertThat(body, is(exact("some_random_string", MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8)))); }
@Test public void shouldDecodeUTF16Body() { fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer("我说中国话".getBytes(StandardCharsets.UTF_16))); fullHttpResponse.headers().add(CONTENT_TYPE, MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()); mockServerResponseDecoder.decode(null, fullHttpResponse, output); Body body = ((HttpResponse) output.get(0)).getBody(); assertThat(body, is(exact("我说中国话", MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16)))); }
@Test public void shouldDecodeBinaryBody() { fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer("some_random_bytes".getBytes(UTF_8))); fullHttpResponse.headers().add(CONTENT_TYPE, "image/jpeg"); mockServerResponseDecoder.decode(null, fullHttpResponse, output); Body body = ((HttpResponse) output.get(0)).getBody(); assertThat(body, is(binary("some_random_bytes".getBytes(UTF_8), MediaType.parse("image/jpeg")))); } |
OpenAPIConverter { public List<Expectation> buildExpectations(String specUrlOrPayload, Map<String, String> operationsAndResponses) { OpenAPI openAPI = buildOpenAPI(specUrlOrPayload); return openAPI .getPaths() .values() .stream() .flatMap(pathItem -> pathItem .readOperations() .stream() ) .filter(operation -> operationsAndResponses == null || operationsAndResponses.containsKey(operation.getOperationId())) .map(operation -> new Expectation(openAPI(specUrlOrPayload, operation.getOperationId())) .thenRespond(buildHttpResponse( openAPI, operation.getResponses(), operationsAndResponses != null ? operationsAndResponses.get(operation.getOperationId()) : null )) ) .collect(Collectors.toList()); } OpenAPIConverter(MockServerLogger mockServerLogger); List<Expectation> buildExpectations(String specUrlOrPayload, Map<String, String> operationsAndResponses); static boolean isJsonContentType(String contentType); } | @Test public void shouldHandleAddOpenAPIJson() { String specUrlOrPayload = FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json"); List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, null ); shouldBuildPetStoreExpectations(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIJsonWithSpecificResponses() { String specUrlOrPayload = FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json"); List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) ); shouldBuildPetStoreExpectationsWithSpecificResponses(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIYaml() { String specUrlOrPayload = FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml"); List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, null ); shouldBuildPetStoreExpectations(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIYamlWithSpecificResponses() { String specUrlOrPayload = FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml"); List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) ); shouldBuildPetStoreExpectationsWithSpecificResponses(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIJsonClasspath() { String specUrlOrPayload = "org/mockserver/mock/openapi_petstore_example.json"; List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, null ); shouldBuildPetStoreExpectations(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIJsonClasspathWithSpecificResponses() { String specUrlOrPayload = "org/mockserver/mock/openapi_petstore_example.json"; List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) ); shouldBuildPetStoreExpectationsWithSpecificResponses(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIYamlClasspath() { String specUrlOrPayload = "org/mockserver/mock/openapi_petstore_example.yaml"; List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, null ); shouldBuildPetStoreExpectations(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIYamlClasspathWithSpecificResponses() { String specUrlOrPayload = "org/mockserver/mock/openapi_petstore_example.yaml"; List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) ); shouldBuildPetStoreExpectationsWithSpecificResponses(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIJsonUrl() { String specUrlOrPayload = FileReader.getURL("org/mockserver/mock/openapi_petstore_example.json").toString(); List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, null ); shouldBuildPetStoreExpectations(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIJsonUrlWithSpecificResponses() { String specUrlOrPayload = FileReader.getURL("org/mockserver/mock/openapi_petstore_example.json").toString(); List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) ); shouldBuildPetStoreExpectationsWithSpecificResponses(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIYamlUrl() { String specUrlOrPayload = FileReader.getURL("org/mockserver/mock/openapi_petstore_example.yaml").toString(); List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, null ); shouldBuildPetStoreExpectations(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIYamlUrlWithSpecificResponses() { String specUrlOrPayload = FileReader.getURL("org/mockserver/mock/openapi_petstore_example.yaml").toString(); List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) ); shouldBuildPetStoreExpectationsWithSpecificResponses(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIJsonWithSpecificationExamples() { String specUrlOrPayload = "org/mockserver/mock/openapi_petstore_example_with_examples.json"; List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, null ); shouldBuildPetStoreExpectationsWithExamples(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIJsonWithSpecificResponsesWithSpecificationExamples() { String specUrlOrPayload = "org/mockserver/mock/openapi_petstore_example_with_examples.json"; List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) ); shouldBuildPetStoreExpectationsWithExamplesAndSpecificResponses(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIYamlWithSpecificationExamples() { String specUrlOrPayload = "org/mockserver/mock/openapi_petstore_example_with_examples.yaml"; List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, null ); shouldBuildPetStoreExpectationsWithExamples(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleAddOpenAPIYamlWithSpecificResponsesWithSpecificationExamples() { String specUrlOrPayload = "org/mockserver/mock/openapi_petstore_example_with_examples.yaml"; List<Expectation> actualExpectations = new OpenAPIConverter(mockServerLogger).buildExpectations( specUrlOrPayload, ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) ); shouldBuildPetStoreExpectationsWithExamplesAndSpecificResponses(specUrlOrPayload, actualExpectations); }
@Test public void shouldHandleInvalidOpenAPIJson() { try { new OpenAPIConverter(mockServerLogger).buildExpectations( "" + "\"openapi\": \"3.0.0\"," + NEW_LINE + " \"info\": {" + NEW_LINE + " \"version\": \"1.0.0\"," + NEW_LINE + " \"title\": \"Swagger Petstore\"", null ); fail("exception expected"); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), is("Unable to load API spec, while parsing a block mapping" + NEW_LINE + " in 'reader', line 1, column 1:" + NEW_LINE + " \"openapi\": \"3.0.0\"," + NEW_LINE + " ^" + NEW_LINE + "expected <block end>, but found ','" + NEW_LINE + " in 'reader', line 1, column 19:" + NEW_LINE + " \"openapi\": \"3.0.0\"," + NEW_LINE + " ^")); } }
@Test public void shouldHandleInvalidOpenAPIYaml() { try { new OpenAPIConverter(mockServerLogger).buildExpectations( FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml").substring(0, 100), null ); fail("exception expected"); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), is("Unable to load API spec, while scanning a simple key" + NEW_LINE + " in 'reader', line 8, column 1:" + NEW_LINE + " servers" + NEW_LINE + " ^" + NEW_LINE + "could not find expected ':'" + NEW_LINE + " in 'reader', line 8, column 8:" + NEW_LINE + " servers" + NEW_LINE + " ^")); } }
@Test public void shouldHandleInvalidOpenAPIJsonUrl() { try { new OpenAPIConverter(mockServerLogger).buildExpectations( "" + "\"openapi\": \"3.0.0\"," + NEW_LINE + " \"info\": {" + NEW_LINE + " \"version\": \"1.0.0\"," + NEW_LINE + " \"title\": \"Swagger Petstore\"", null ); fail("exception expected"); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), is("Unable to load API spec, while parsing a block mapping" + NEW_LINE + " in 'reader', line 1, column 1:" + NEW_LINE + " \"openapi\": \"3.0.0\"," + NEW_LINE + " ^" + NEW_LINE + "expected <block end>, but found ','" + NEW_LINE + " in 'reader', line 1, column 19:" + NEW_LINE + " \"openapi\": \"3.0.0\"," + NEW_LINE + " ^")); } }
@Test public void shouldHandleInvalidOpenAPIYamlUrl() { try { new OpenAPIConverter(mockServerLogger).buildExpectations( FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.yaml").substring(0, 100), null ); fail("exception expected"); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), is("Unable to load API spec, while scanning a simple key" + NEW_LINE + " in 'reader', line 8, column 1:" + NEW_LINE + " servers" + NEW_LINE + " ^" + NEW_LINE + "could not find expected ':'" + NEW_LINE + " in 'reader', line 8, column 8:" + NEW_LINE + " servers" + NEW_LINE + " ^")); } } |
ForwardChainExpectation { public Expectation[] forward(final HttpForward httpForward) { expectation.thenForward(httpForward); return mockServerClient.upsert(expectation); } ForwardChainExpectation(MockServerLogger mockServerLogger, MockServerEventBus mockServerEventBus, MockServerClient mockServerClient, Expectation expectation); Expectation[] respond(final HttpResponse httpResponse); Expectation[] respond(final HttpTemplate httpTemplate); Expectation[] respond(final HttpClassCallback httpClassCallback); Expectation[] respond(final ExpectationResponseCallback expectationResponseCallback); Expectation[] respond(final ExpectationResponseCallback expectationResponseCallback, Delay delay); Expectation[] forward(final HttpForward httpForward); Expectation[] forward(final HttpTemplate httpTemplate); Expectation[] forward(final HttpClassCallback httpClassCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final ExpectationForwardAndResponseCallback expectationForwardResponseCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final Delay delay); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final ExpectationForwardAndResponseCallback expectationForwardResponseCallback, final Delay delay); Expectation[] forward(final HttpOverrideForwardedRequest httpOverrideForwardedRequest); Expectation[] error(final HttpError httpError); } | @Test public void shouldSetForward() { HttpForward forward = forward(); Expectation[] upsertedExpectations = forwardChainExpectation.forward(forward); assertThat(upsertedExpectations, is(new Expectation[]{mockExpectation})); verify(mockExpectation).thenForward(same(forward)); verify(mockAbstractClient).upsert(mockExpectation); }
@Test public void shouldSetForwardTemplate() { HttpTemplate template = template(HttpTemplate.TemplateType.VELOCITY, "some_template"); Expectation[] upsertedExpectations = forwardChainExpectation.forward(template); assertThat(upsertedExpectations, is(new Expectation[]{mockExpectation})); verify(mockExpectation).thenForward(same(template)); verify(mockAbstractClient).upsert(mockExpectation); }
@Test public void shouldSetForwardClassCallback() { HttpClassCallback callback = callback(); Expectation[] upsertedExpectations = forwardChainExpectation.forward(callback); assertThat(upsertedExpectations, is(new Expectation[]{mockExpectation})); verify(mockExpectation).thenForward(same(callback)); verify(mockAbstractClient).upsert(mockExpectation); }
@Test public void shouldSetOverrideForwardedRequest() { Expectation[] upsertedExpectations = forwardChainExpectation.forward(forwardOverriddenRequest(request().withBody("some_replaced_body"))); assertThat(upsertedExpectations, is(new Expectation[]{mockExpectation})); verify(mockExpectation).thenForward(forwardOverriddenRequest(request().withBody("some_replaced_body"))); verify(mockAbstractClient).upsert(mockExpectation); } |
MockServerClient implements Stoppable { public MockServerClient setRequestOverride(HttpRequest requestOverride) { if (requestOverride == null) { throw new IllegalArgumentException("Request with default properties can not be null"); } else { this.requestOverride = requestOverride; } return this; } MockServerClient(CompletableFuture<Integer> portFuture); MockServerClient(String host, int port); MockServerClient(String host, int port, String contextPath); MockServerClient setRequestOverride(HttpRequest requestOverride); boolean isSecure(); MockServerClient withSecure(boolean secure); InetSocketAddress remoteAddress(); String contextPath(); Integer getPort(); MockServerClient openUI(); MockServerClient openUI(TimeUnit timeUnit, long pause); @Deprecated @SuppressWarnings({"DeprecatedIsStillUsed", "RedundantSuppression"}) boolean isRunning(); @Deprecated boolean isRunning(int attempts, long timeout, TimeUnit timeUnit); boolean hasStopped(); boolean hasStopped(int attempts, long timeout, TimeUnit timeUnit); boolean hasStarted(); boolean hasStarted(int attempts, long timeout, TimeUnit timeUnit); List<Integer> bind(Integer... ports); Future<MockServerClient> stopAsync(); void stop(); Future<MockServerClient> stop(boolean ignoreFailure); @Override void close(); MockServerClient reset(); MockServerClient clear(RequestDefinition requestDefinition); MockServerClient clear(ExpectationId expectationId); MockServerClient clear(RequestDefinition requestDefinition, ClearType type); MockServerClient clear(ExpectationId expectationId, ClearType type); MockServerClient verify(RequestDefinition... requestDefinitions); MockServerClient verify(ExpectationId... expectationIds); @SuppressWarnings("DuplicatedCode") MockServerClient verify(RequestDefinition requestDefinition, VerificationTimes times); @SuppressWarnings("DuplicatedCode") MockServerClient verify(ExpectationId expectationId, VerificationTimes times); @SuppressWarnings({"DuplicatedCode", "UnusedReturnValue"}) MockServerClient verifyZeroInteractions(); RequestDefinition[] retrieveRecordedRequests(RequestDefinition requestDefinition); String retrieveRecordedRequests(RequestDefinition requestDefinition, Format format); LogEventRequestAndResponse[] retrieveRecordedRequestsAndResponses(RequestDefinition requestDefinition); String retrieveRecordedRequestsAndResponses(RequestDefinition requestDefinition, Format format); Expectation[] retrieveRecordedExpectations(RequestDefinition requestDefinition); String retrieveRecordedExpectations(RequestDefinition requestDefinition, Format format); String retrieveLogMessages(RequestDefinition requestDefinition); String[] retrieveLogMessagesArray(RequestDefinition requestDefinition); ForwardChainExpectation when(RequestDefinition requestDefinition); ForwardChainExpectation when(RequestDefinition requestDefinition, Times times); ForwardChainExpectation when(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive); ForwardChainExpectation when(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive, Integer priority); Expectation[] upsert(OpenAPIExpectation... openAPIExpectations); Expectation[] upsert(Expectation... expectations); @Deprecated Expectation[] sendExpectation(Expectation... expectations); Expectation[] retrieveActiveExpectations(RequestDefinition requestDefinition); String retrieveActiveExpectations(RequestDefinition requestDefinition, Format format); } | @Test public void shouldHandleNullHttpRequestEnhancerException() { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString("Request with default properties can not be null")); mockServerClient.setRequestOverride(null); } |
Parameter extends KeyToMultiValue { public static Parameter param(String name, String... value) { return new Parameter(name, value); } Parameter(String name, String... value); Parameter(NottableString name, NottableString... value); Parameter(NottableString name, String... value); Parameter(String name, Collection<String> value); Parameter(NottableString name, Collection<NottableString> value); static Parameter param(String name, String... value); static Parameter param(NottableString name, NottableString... value); static Parameter param(NottableString name, String... value); static Parameter param(String name, Collection<String> value); static Parameter param(NottableString name, Collection<NottableString> value); static Parameter schemaParam(String name, String... values); static Parameter schemaParam(NottableString name, String... values); static Parameter optionalParam(String name, String... values); Parameter withStyle(ParameterStyle style); } | @Test public void shouldReturnValueSetInStaticConstructors() { Parameter firstParameter = param("first", "first_one", "first_two"); Parameter secondParameter = param("second", Arrays.asList("second_one", "second_two")); assertThat(firstParameter.getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); assertThat(secondParameter.getValues(), containsInAnyOrder(string("second_one"), string("second_two"))); } |
BinaryBody extends BodyWithContentType<byte[]> { public static BinaryBody binary(byte[] body) { return new BinaryBody(body); } BinaryBody(byte[] bytes); BinaryBody(byte[] bytes, MediaType contentType); static BinaryBody binary(byte[] body); static BinaryBody binary(byte[] body, MediaType contentType); byte[] getValue(); @JsonIgnore byte[] getRawBytes(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldAlwaysCreateNewObject() { byte[] body = DatatypeConverter.parseBase64Binary("some_body"); assertEquals(binary(body), binary(body)); assertNotSame(binary(body), binary(body)); } |
BinaryBody extends BodyWithContentType<byte[]> { public byte[] getValue() { return bytes; } BinaryBody(byte[] bytes); BinaryBody(byte[] bytes, MediaType contentType); static BinaryBody binary(byte[] body); static BinaryBody binary(byte[] body, MediaType contentType); byte[] getValue(); @JsonIgnore byte[] getRawBytes(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldReturnValuesSetInConstructor() { byte[] body = DatatypeConverter.parseBase64Binary("some_body"); BinaryBody binaryBody = new BinaryBody(body); assertThat(binaryBody.getValue(), is(body)); assertThat(binaryBody.getType(), is(Body.Type.BINARY)); assertThat(binaryBody.getCharset(null), nullValue()); assertThat(binaryBody.getCharset(StandardCharsets.UTF_8), is(StandardCharsets.UTF_8)); assertThat(binaryBody.getContentType(), nullValue()); } |
PortBinding extends ObjectWithJsonToString { public List<Integer> getPorts() { return ports; } static PortBinding portBinding(Integer... ports); static PortBinding portBinding(List<Integer> ports); List<Integer> getPorts(); PortBinding setPorts(List<Integer> ports); String getVersion(); String getArtifactId(); String getGroupId(); } | @Test public void shouldReturnValuesSetInConstructor() { PortBinding portBinding = new PortBinding(); assertThat(portBinding.getPorts(), empty()); } |
HttpObjectCallback extends Action<HttpObjectCallback> { public HttpObjectCallback withClientId(String clientId) { this.clientId = clientId; this.hashCode = 0; return this; } String getClientId(); HttpObjectCallback withClientId(String clientId); Boolean getResponseCallback(); HttpObjectCallback withResponseCallback(Boolean responseCallback); @SuppressWarnings("UnusedReturnValue") HttpObjectCallback withActionType(Type actionType); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldReturnFormattedRequestInToString() { TestCase.assertEquals("{" + NEW_LINE + " \"clientId\" : \"some_client_id\"" + NEW_LINE + "}", new HttpObjectCallback() .withClientId("some_client_id") .toString() ); } |
HttpForward extends Action<HttpForward> { public static HttpForward forward() { return new HttpForward(); } static HttpForward forward(); @Override @JsonIgnore Type getType(); String getHost(); HttpForward withHost(String host); Integer getPort(); HttpForward withPort(Integer port); Scheme getScheme(); HttpForward withScheme(Scheme scheme); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldAlwaysCreateNewObject() { assertEquals(forward(), forward()); assertNotSame(forward(), forward()); } |
Cookie extends KeyAndValue { public Cookie(String name, String value) { super(name, value); } Cookie(String name, String value); Cookie(NottableString name, NottableString value); Cookie(NottableString name, String value); static Cookie cookie(String name, String value); static Cookie cookie(NottableString name, NottableString value); static Cookie cookie(NottableString name, String value); static Cookie schemaCookie(String name, String value); static Cookie optionalCookie(String name, String value); static Cookie optionalCookie(String name, NottableString value); } | @Test public void shouldReturnValueSetInStaticConstructors() { Cookie firstCookie = cookie("name", "value"); assertThat(firstCookie.getName(), is(string("name"))); assertThat(firstCookie.getValue(), is(string("value"))); } |
HttpError extends Action<HttpError> { public static HttpError error() { return new HttpError(); } static HttpError error(); HttpError withDropConnection(Boolean dropConnection); Boolean getDropConnection(); HttpError withResponseBytes(byte[] responseBytes); byte[] getResponseBytes(); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test @SuppressWarnings("AccessStaticViaInstance") public void shouldAlwaysCreateNewObject() { assertEquals(error(), error()); assertNotSame(error(), error()); } |
XmlBody extends BodyWithContentType<String> { public static XmlBody xml(String xml) { return new XmlBody(xml); } XmlBody(String xml); XmlBody(String xml, Charset charset); XmlBody(String xml, MediaType contentType); XmlBody(String xml, byte[] rawBytes, MediaType contentType); static XmlBody xml(String xml); static XmlBody xml(String xml, Charset charset); static XmlBody xml(String xml, MediaType contentType); String getValue(); @JsonIgnore byte[] getRawBytes(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static final MediaType DEFAULT_XML_CONTENT_TYPE; } | @Test public void shouldAlwaysCreateNewObject() { assertEquals(xml("some_body"), xml("some_body")); assertNotSame(xml("some_body"), xml("some_body")); } |
Cookies extends KeysAndValues<Cookie, Cookies> { @Override public Cookie build(NottableString name, NottableString value) { return new Cookie(name, value); } Cookies(List<Cookie> cookies); Cookies(Cookie... cookies); Cookies(Map<NottableString, NottableString> cookies); @Override Cookie build(NottableString name, NottableString value); @SuppressWarnings("MethodDoesntCallSuperMethod") Cookies clone(); } | @Test public void shouldBuildCookie() { Cookies cookies = new Cookies(); Cookie cookie = cookies.build(string("name"), string("value")); assertThat(cookie, is(new Cookie(string("name"), string("value")))); } |
HttpTemplate extends Action<HttpTemplate> { public static HttpTemplate template(TemplateType type) { return new HttpTemplate(type); } HttpTemplate(TemplateType type); static HttpTemplate template(TemplateType type); static HttpTemplate template(TemplateType type, String template); TemplateType getTemplateType(); HttpTemplate withTemplate(String template); String getTemplate(); void withActionType(Type actionType); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test @SuppressWarnings("AccessStaticViaInstance") public void shouldAlwaysCreateNewObject() { assertEquals(template(JAVASCRIPT), template(JAVASCRIPT)); assertEquals(template(VELOCITY), template(VELOCITY)); assertNotSame(template(JAVASCRIPT), template(JAVASCRIPT)); assertNotSame(template(VELOCITY), template(VELOCITY)); } |
HttpTemplate extends Action<HttpTemplate> { public TemplateType getTemplateType() { return templateType; } HttpTemplate(TemplateType type); static HttpTemplate template(TemplateType type); static HttpTemplate template(TemplateType type, String template); TemplateType getTemplateType(); HttpTemplate withTemplate(String template); String getTemplate(); void withActionType(Type actionType); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void returnsTemplateType() { assertEquals(JAVASCRIPT, new HttpTemplate(JAVASCRIPT).getTemplateType()); } |
HttpRequest extends RequestDefinition implements HttpMessage<HttpRequest, Body> { public static HttpRequest request() { return new HttpRequest(); } static HttpRequest request(); static HttpRequest request(String path); Boolean isKeepAlive(); HttpRequest withKeepAlive(Boolean isKeepAlive); Boolean isSecure(); HttpRequest withSecure(Boolean isSecure); SocketAddress getSocketAddress(); HttpRequest withSocketAddress(SocketAddress socketAddress); HttpRequest withSocketAddress(String host, Integer port, SocketAddress.Scheme scheme); HttpRequest withSocketAddress(String host, Integer port); HttpRequest withSocketAddressFromHostHeader(); HttpRequest withSocketAddress(Boolean isSecure, String host, Integer port); HttpRequest withMethod(String method); HttpRequest withMethodSchema(String method); HttpRequest withMethod(NottableString method); NottableString getMethod(); String getMethod(String defaultValue); HttpRequest withPath(String path); HttpRequest withPath(NottableString path); HttpRequest withPathSchema(String path); NottableString getPath(); boolean matches(final String method); boolean matches(final String method, final String... paths); Parameters getPathParameters(); HttpRequest withPathParameters(Parameters parameters); HttpRequest withPathParameters(List<Parameter> parameters); HttpRequest withPathParameters(Parameter... parameters); HttpRequest withPathParameters(Map<String, List<String>> parameters); HttpRequest withPathParameter(Parameter parameter); HttpRequest withPathParameter(String name, String... values); HttpRequest withSchemaPathParameter(String name, String... values); HttpRequest withPathParameter(NottableString name, NottableString... values); List<Parameter> getPathParameterList(); @SuppressWarnings("unused") boolean hasPathParameter(String name, String value); @SuppressWarnings("unused") boolean hasPathParameter(NottableString name, NottableString value); String getFirstPathParameter(String name); Parameters getQueryStringParameters(); HttpRequest withQueryStringParameters(Parameters parameters); HttpRequest withQueryStringParameters(List<Parameter> parameters); HttpRequest withQueryStringParameters(Parameter... parameters); HttpRequest withQueryStringParameters(Map<String, List<String>> parameters); HttpRequest withQueryStringParameter(Parameter parameter); HttpRequest withQueryStringParameter(String name, String... values); HttpRequest withSchemaQueryStringParameter(String name, String... values); HttpRequest withQueryStringParameter(NottableString name, NottableString... values); List<Parameter> getQueryStringParameterList(); @SuppressWarnings("unused") boolean hasQueryStringParameter(String name, String value); @SuppressWarnings("unused") boolean hasQueryStringParameter(NottableString name, NottableString value); String getFirstQueryStringParameter(String name); HttpRequest withBody(String body); HttpRequest withBody(String body, Charset charset); HttpRequest withBody(byte[] body); HttpRequest withBody(Body body); Body getBody(); @JsonIgnore byte[] getBodyAsRawBytes(); @JsonIgnore String getBodyAsString(); @JsonIgnore String getBodyAsJsonOrXmlString(); Headers getHeaders(); HttpRequest withHeaders(Headers headers); HttpRequest withHeaders(List<Header> headers); HttpRequest withHeaders(Header... headers); HttpRequest withHeader(Header header); HttpRequest withHeader(String name, String... values); HttpRequest withSchemaHeader(String name, String... values); HttpRequest withHeader(NottableString name, NottableString... values); HttpRequest withContentType(MediaType mediaType); HttpRequest replaceHeader(Header header); List<Header> getHeaderList(); List<String> getHeader(String name); String getFirstHeader(String name); boolean containsHeader(String name); boolean containsHeader(String name, String value); HttpRequest removeHeader(String name); HttpRequest removeHeader(NottableString name); Cookies getCookies(); HttpRequest withCookies(Cookies cookies); HttpRequest withCookies(List<Cookie> cookies); HttpRequest withCookies(Cookie... cookies); HttpRequest withCookie(Cookie cookie); HttpRequest withCookie(String name, String value); HttpRequest withSchemaCookie(String name, String value); HttpRequest withCookie(NottableString name, NottableString value); List<Cookie> getCookieList(); InetSocketAddress socketAddressFromHostHeader(); HttpRequest shallowClone(); @SuppressWarnings("MethodDoesntCallSuperMethod") HttpRequest clone(); HttpRequest update(HttpRequest replaceRequest); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldAlwaysCreateNewObject() { assertEquals(request(), HttpRequest.request()); assertNotSame(HttpRequest.request(), HttpRequest.request()); } |
HttpResponse extends Action<HttpResponse> implements HttpMessage<HttpResponse, BodyWithContentType> { public static HttpResponse response() { return new HttpResponse(); } static HttpResponse response(); static HttpResponse response(String body); static HttpResponse notFoundResponse(); HttpResponse withStatusCode(Integer statusCode); Integer getStatusCode(); HttpResponse withReasonPhrase(String reasonPhrase); String getReasonPhrase(); HttpResponse withBody(String body); HttpResponse withBody(String body, Charset charset); HttpResponse withBody(String body, MediaType contentType); HttpResponse withBody(byte[] body); HttpResponse withBody(BodyWithContentType body); BodyWithContentType getBody(); @JsonIgnore byte[] getBodyAsRawBytes(); @JsonIgnore String getBodyAsString(); Headers getHeaders(); HttpResponse withHeaders(Headers headers); HttpResponse withHeaders(List<Header> headers); HttpResponse withHeaders(Header... headers); HttpResponse withHeader(Header header); HttpResponse withHeader(String name, String... values); HttpResponse withHeader(NottableString name, NottableString... values); HttpResponse withContentType(MediaType mediaType); HttpResponse replaceHeader(Header header); HttpResponse replaceHeader(String name, String... values); List<Header> getHeaderList(); Multimap<NottableString, NottableString> getHeaderMultimap(); List<String> getHeader(String name); String getFirstHeader(String name); boolean containsHeader(String name); HttpResponse removeHeader(String name); HttpResponse removeHeader(NottableString name); boolean containsHeader(String name, String value); Cookies getCookies(); HttpResponse withCookies(Cookies cookies); HttpResponse withCookies(List<Cookie> cookies); HttpResponse withCookies(Cookie... cookies); HttpResponse withCookie(Cookie cookie); HttpResponse withCookie(String name, String value); HttpResponse withCookie(NottableString name, NottableString value); List<Cookie> getCookieList(); Map<NottableString, NottableString> getCookieMap(); boolean cookieHeadeDoesNotAlreadyExists(Cookie cookieValue); boolean cookieHeadeDoesNotAlreadyExists(String name, String value); HttpResponse withConnectionOptions(ConnectionOptions connectionOptions); ConnectionOptions getConnectionOptions(); @Override @JsonIgnore Type getType(); HttpResponse shallowClone(); @SuppressWarnings("MethodDoesntCallSuperMethod") HttpResponse clone(); HttpResponse update(HttpResponse replaceResponse); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldAlwaysCreateNewObject() { assertEquals(response(), response()); assertNotSame(response(), response()); } |
StringBody extends BodyWithContentType<String> { public static StringBody exact(String body) { return new StringBody(body); } StringBody(String value); StringBody(String value, Charset charset); StringBody(String value, MediaType contentType); StringBody(String value, byte[] rawBytes, boolean subString, MediaType contentType); static StringBody exact(String body); static StringBody exact(String body, Charset charset); static StringBody exact(String body, MediaType contentType); static StringBody subString(String body); static StringBody subString(String body, Charset charset); static StringBody subString(String body, MediaType contentType); String getValue(); @JsonIgnore byte[] getRawBytes(); boolean isSubString(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static final MediaType DEFAULT_CONTENT_TYPE; } | @Test public void shouldAlwaysCreateNewObject() { assertEquals(exact("some_body"), exact("some_body")); assertNotSame(exact("some_body"), exact("some_body")); } |
StringBody extends BodyWithContentType<String> { public String getValue() { return value; } StringBody(String value); StringBody(String value, Charset charset); StringBody(String value, MediaType contentType); StringBody(String value, byte[] rawBytes, boolean subString, MediaType contentType); static StringBody exact(String body); static StringBody exact(String body, Charset charset); static StringBody exact(String body, MediaType contentType); static StringBody subString(String body); static StringBody subString(String body, Charset charset); static StringBody subString(String body, MediaType contentType); String getValue(); @JsonIgnore byte[] getRawBytes(); boolean isSubString(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static final MediaType DEFAULT_CONTENT_TYPE; } | @Test public void shouldReturnValuesSetInConstructor() { StringBody stringBody = new StringBody("some_body"); assertThat(stringBody.getValue(), is("some_body")); assertThat(stringBody.getType(), is(Body.Type.STRING)); assertThat(stringBody.getCharset(null), nullValue()); assertThat(stringBody.getCharset(StandardCharsets.UTF_8), is(StandardCharsets.UTF_8)); assertThat(stringBody.getContentType(), nullValue()); } |
MediaType extends ObjectWithJsonToString { @SuppressWarnings("UnstableApiUsage") public static MediaType parse(String mediaTypeHeader) { if (isNotBlank(mediaTypeHeader)) { int typeSeparator = mediaTypeHeader.indexOf(TYPE_SEPARATOR); int typeEndIndex = 0; String type = null; String subType = null; if (typeSeparator != -1) { typeEndIndex = mediaTypeHeader.indexOf(PARAMETER_START); if (typeEndIndex == -1) { typeEndIndex = mediaTypeHeader.length(); } String typeString = mediaTypeHeader.substring(0, typeEndIndex).trim(); type = substringBefore(typeString, "/").trim().toLowerCase(); subType = substringAfter(typeString, "/").trim().toLowerCase(); if (typeEndIndex < mediaTypeHeader.length()) { typeEndIndex++; } } String parameters = mediaTypeHeader.substring(typeEndIndex).trim().toLowerCase().replaceAll("\"", ""); Map<String, String> parameterMap = null; if (isNotBlank(parameters)) { try { parameterMap = Splitter.on(';').trimResults().omitEmptyStrings().withKeyValueSeparator('=').split(parameters); if (parameterMap.size() > 1) { parameterMap = parameterMap.entrySet() .stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new )); } } catch (Throwable throwable) { MOCK_SERVER_LOGGER.logEvent( new LogEntry() .setLogLevel(WARN) .setMessageFormat("invalid parameters format \"" + parameters + "\", expected{}see:{}") .setArguments("Content-Type := type \"/\" subtype *[\";\" parameter]\nparameter := attribute \"=\" value", "https: .setThrowable(throwable) ); } } return new MediaType(type, subType, parameterMap); } else { return new MediaType(null, null); } } MediaType(String type, String subtype); MediaType(String type, String subtype, Map<String, String> parameters); private MediaType(String type, String subtype, String charset, Map<String, String> parameterMap); @SuppressWarnings("UnstableApiUsage") static MediaType parse(String mediaTypeHeader); static MediaType create(String type, String subType); String getType(); String getSubtype(); Map<String, String> getParameters(); MediaType withCharset(Charset charset); MediaType withCharset(String charset); Charset getCharset(); Charset getCharsetOrDefault(); boolean isCompatible(MediaType other); boolean isJson(); boolean isXml(); boolean isString(); @Override String toString(); static final Charset DEFAULT_HTTP_CHARACTER_SET; final static MediaType WILDCARD; final static MediaType APPLICATION_ATOM_XML; final static MediaType APPLICATION_XHTML_XML; final static MediaType APPLICATION_SVG_XML; final static MediaType APPLICATION_XML; final static MediaType APPLICATION_XML_UTF_8; final static MediaType APPLICATION_JSON; final static MediaType APPLICATION_JSON_UTF_8; final static MediaType JSON_UTF_8; final static MediaType APPLICATION_FORM_URLENCODED; final static MediaType FORM_DATA; final static MediaType MULTIPART_FORM_DATA; final static MediaType APPLICATION_OCTET_STREAM; static final MediaType APPLICATION_BINARY; static final MediaType PDF; static final MediaType ATOM_UTF_8; final static MediaType TEXT_PLAIN; final static MediaType PLAIN_TEXT_UTF_8; final static MediaType TEXT_XML; final static MediaType TEXT_XML_UTF_8; final static MediaType XML_UTF_8; final static MediaType TEXT_HTML; final static MediaType TEXT_HTML_UTF_8; final static MediaType HTML_UTF_8; static final MediaType SERVER_SENT_EVENTS; static final MediaType APPLICATION_JSON_PATCH_JSON; static final MediaType ANY_VIDEO_TYPE; static final MediaType ANY_AUDIO_TYPE; static final MediaType ANY_IMAGE_TYPE; static final MediaType QUICKTIME; static final MediaType JPEG; static final MediaType PNG; } | @Test public void shouldParseWithoutCharset() { String[] rfcContentTypeExamples = new String[]{ "text/html", "text/html;", "Text/HTML", "Text/HTML;", }; for (String rfcContentTypeExample : rfcContentTypeExamples) { assertThat(rfcContentTypeExample, MediaType.parse(rfcContentTypeExample), is(new MediaType("text", "html"))); } } |
MediaType extends ObjectWithJsonToString { @Override public String toString() { return toString; } MediaType(String type, String subtype); MediaType(String type, String subtype, Map<String, String> parameters); private MediaType(String type, String subtype, String charset, Map<String, String> parameterMap); @SuppressWarnings("UnstableApiUsage") static MediaType parse(String mediaTypeHeader); static MediaType create(String type, String subType); String getType(); String getSubtype(); Map<String, String> getParameters(); MediaType withCharset(Charset charset); MediaType withCharset(String charset); Charset getCharset(); Charset getCharsetOrDefault(); boolean isCompatible(MediaType other); boolean isJson(); boolean isXml(); boolean isString(); @Override String toString(); static final Charset DEFAULT_HTTP_CHARACTER_SET; final static MediaType WILDCARD; final static MediaType APPLICATION_ATOM_XML; final static MediaType APPLICATION_XHTML_XML; final static MediaType APPLICATION_SVG_XML; final static MediaType APPLICATION_XML; final static MediaType APPLICATION_XML_UTF_8; final static MediaType APPLICATION_JSON; final static MediaType APPLICATION_JSON_UTF_8; final static MediaType JSON_UTF_8; final static MediaType APPLICATION_FORM_URLENCODED; final static MediaType FORM_DATA; final static MediaType MULTIPART_FORM_DATA; final static MediaType APPLICATION_OCTET_STREAM; static final MediaType APPLICATION_BINARY; static final MediaType PDF; static final MediaType ATOM_UTF_8; final static MediaType TEXT_PLAIN; final static MediaType PLAIN_TEXT_UTF_8; final static MediaType TEXT_XML; final static MediaType TEXT_XML_UTF_8; final static MediaType XML_UTF_8; final static MediaType TEXT_HTML; final static MediaType TEXT_HTML_UTF_8; final static MediaType HTML_UTF_8; static final MediaType SERVER_SENT_EVENTS; static final MediaType APPLICATION_JSON_PATCH_JSON; static final MediaType ANY_VIDEO_TYPE; static final MediaType ANY_AUDIO_TYPE; static final MediaType ANY_IMAGE_TYPE; static final MediaType QUICKTIME; static final MediaType JPEG; static final MediaType PNG; } | @Test public void shouldSerialiseToStringWithAdditionParametersAndNoCharset() { assertThat(new MediaType("application", "soap+xml", ImmutableMap.of( "action", "somerandomstuff" )).toString(), is("application/soap+xml; action=somerandomstuff")); } |
RegexBody extends Body<String> { public String getValue() { return regex; } RegexBody(String regex); String getValue(); static RegexBody regex(String regex); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldReturnValuesSetInConstructor() { RegexBody regexBody = new RegexBody("some_body"); assertThat(regexBody.getValue(), is("some_body")); assertThat(regexBody.getType(), is(Body.Type.REGEX)); assertThat(regexBody.getContentType(), nullValue()); assertThat(regexBody.getCharset(StandardCharsets.UTF_8), is(StandardCharsets.UTF_8)); } |
XmlSchemaBody extends Body<String> { public String getValue() { return xmlSchema; } XmlSchemaBody(String xmlSchema); static XmlSchemaBody xmlSchema(String xmlSchema); static XmlSchemaBody xmlSchemaFromResource(String xmlSchemaPath); String getValue(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldReturnValuesSetInConstructor() { XmlSchemaBody xmlSchemaBody = new XmlSchemaBody("some_body"); assertThat(xmlSchemaBody.getValue(), is("some_body")); assertThat(xmlSchemaBody.getType(), is(Body.Type.XML_SCHEMA)); } |
ObjectWithJsonToString extends ObjectWithReflectiveEqualsHashCodeToString { @Override public String toString() { try { String valueAsString = ObjectMapperFactory .createObjectMapper(true) .writeValueAsString(this); if (valueAsString.startsWith(ESCAPED_QUOTE) && valueAsString.endsWith(ESCAPED_QUOTE)) { valueAsString = valueAsString.substring(1, valueAsString.length() - 1); } return valueAsString; } catch (Exception e) { return super.toString(); } } @Override String toString(); } | @Test public void shouldConvertObjectToJSON() { assertThat(new TestObject().toString(), is("{" + NEW_LINE + " \"stringField\" : \"stringField\"," + NEW_LINE + " \"intField\" : 100" + NEW_LINE + "}")); } |
ParameterBody extends Body<Parameters> { public Parameters getValue() { return this.parameters; } ParameterBody(Parameter... parameters); ParameterBody(List<Parameter> parameters); ParameterBody(Parameters parameters); static ParameterBody params(Parameters parameters); static ParameterBody params(Parameter... parameters); static ParameterBody params(List<Parameter> parameters); Parameters getValue(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldReturnValuesSetInConstructor() { ParameterBody parameterBody = new ParameterBody( new Parameter("some", "value") ); assertThat(parameterBody.getValue().getEntries(), containsInAnyOrder(new Parameter("some", "value"))); assertThat(parameterBody.getType(), is(Body.Type.PARAMETERS)); }
@Test public void shouldReturnValuesSetInConstructorWithList() { ParameterBody parameterBody = new ParameterBody(Collections.singletonList( new Parameter("some", "value") )); assertThat(parameterBody.getValue().getEntries(), containsInAnyOrder(new Parameter("some", "value"))); assertThat(parameterBody.getType(), is(Body.Type.PARAMETERS)); } |
ForwardChainExpectation { public Expectation[] error(final HttpError httpError) { expectation.thenError(httpError); return mockServerClient.upsert(expectation); } ForwardChainExpectation(MockServerLogger mockServerLogger, MockServerEventBus mockServerEventBus, MockServerClient mockServerClient, Expectation expectation); Expectation[] respond(final HttpResponse httpResponse); Expectation[] respond(final HttpTemplate httpTemplate); Expectation[] respond(final HttpClassCallback httpClassCallback); Expectation[] respond(final ExpectationResponseCallback expectationResponseCallback); Expectation[] respond(final ExpectationResponseCallback expectationResponseCallback, Delay delay); Expectation[] forward(final HttpForward httpForward); Expectation[] forward(final HttpTemplate httpTemplate); Expectation[] forward(final HttpClassCallback httpClassCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final ExpectationForwardAndResponseCallback expectationForwardResponseCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final Delay delay); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final ExpectationForwardAndResponseCallback expectationForwardResponseCallback, final Delay delay); Expectation[] forward(final HttpOverrideForwardedRequest httpOverrideForwardedRequest); Expectation[] error(final HttpError httpError); } | @Test public void shouldSetError() { HttpError error = error(); Expectation[] upsertedExpectations = forwardChainExpectation.error(error); assertThat(upsertedExpectations, is(new Expectation[]{mockExpectation})); verify(mockExpectation).thenError(same(error)); verify(mockAbstractClient).upsert(mockExpectation); } |
XPathBody extends Body<String> { public String getValue() { return xpath; } XPathBody(String xpath); String getValue(); static XPathBody xpath(String xpath); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldReturnValuesSetInConstructor() { XPathBody xPathBody = new XPathBody("some_body"); assertThat(xPathBody.getValue(), is("some_body")); assertThat(xPathBody.getType(), is(Body.Type.XPATH)); assertThat(xPathBody.getContentType(), nullValue()); assertThat(xPathBody.getCharset(StandardCharsets.UTF_8), is(StandardCharsets.UTF_8)); } |
NottableSchemaString extends NottableString { public static NottableSchemaString notSchema(String value) { return new NottableSchemaString(value, Boolean.TRUE); } private NottableSchemaString(String schema, Boolean not); private NottableSchemaString(String schema); static NottableSchemaString schemaString(String value, Boolean not); static NottableSchemaString schemaString(String value); static NottableSchemaString notSchema(String value); boolean matches(String json); boolean matchesIgnoreCase(String json); @Override String toString(); } | @Test public void shouldReturnValuesSetInConstructors() { NottableSchemaString nottableString = notSchema("{ \"type\": \"string\" }"); assertThat(nottableString.isNot(), is(true)); assertThat(nottableString.getValue(), is("{ \"type\": \"string\" }")); } |
NottableSchemaString extends NottableString { public static NottableSchemaString schemaString(String value, Boolean not) { return new NottableSchemaString(value, not); } private NottableSchemaString(String schema, Boolean not); private NottableSchemaString(String schema); static NottableSchemaString schemaString(String value, Boolean not); static NottableSchemaString schemaString(String value); static NottableSchemaString notSchema(String value); boolean matches(String json); boolean matchesIgnoreCase(String json); @Override String toString(); } | @Test public void shouldReturnValuesSetInConstructorsWithDefaultNotSetting() { NottableSchemaString nottableString = schemaString("{ \"type\": \"string\" }"); assertThat(nottableString.isNot(), is(false)); assertThat(nottableString.getValue(), is("{ \"type\": \"string\" }")); }
@Test public void shouldReturnValuesSetInConstructorsWithDefaultNottedString() { NottableSchemaString nottableString = schemaString("!{ \"type\": \"string\" }"); assertThat(nottableString.isNot(), is(true)); assertThat(nottableString.getValue(), is("{ \"type\": \"string\" }")); }
@Test public void shouldReturnValuesSetInConstructorsWithNullNotParameter() { NottableSchemaString nottableString = schemaString("{ \"type\": \"string\" }", null); assertThat(nottableString.isNot(), is(false)); assertThat(nottableString.getValue(), is("{ \"type\": \"string\" }")); } |
Header extends KeyToMultiValue { public Header(String name, String... value) { super(name, value); } Header(String name, String... value); Header(NottableString name, NottableString... value); Header(NottableString name, String... value); Header(String name, Collection<String> value); Header(NottableString name, Collection<NottableString> value); static Header header(String name, int value); static Header header(String name, String... value); static Header header(NottableString name, NottableString... value); static Header header(String name, Collection<String> value); static Header header(NottableString name, Collection<NottableString> value); static Header schemaHeader(String name, String... values); static Header optionalHeader(String name, String... values); } | @Test public void shouldReturnValueSetInStaticConstructors() { Header firstHeader = header("first", "first_one", "first_two"); Header secondHeader = header("second", Arrays.asList("second_one", "second_two")); assertThat(firstHeader.getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); assertThat(secondHeader.getValues(), containsInAnyOrder(string("second_one"), string("second_two"))); } |
HttpClassCallback extends Action<HttpClassCallback> { public static HttpClassCallback callback() { return new HttpClassCallback(); } static HttpClassCallback callback(); static HttpClassCallback callback(String callbackClass); static HttpClassCallback callback(Class<? extends ExpectationCallback<HttpRequest>> callbackClass); String getCallbackClass(); HttpClassCallback withCallbackClass(String callbackClass); @SuppressWarnings("rawtypes") HttpClassCallback withCallbackClass(Class<? extends ExpectationCallback<? extends HttpMessage>> callbackClass); HttpClassCallback withActionType(Type actionType); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test @SuppressWarnings("AccessStaticViaInstance") public void shouldAlwaysCreateNewObject() { assertEquals(callback(), callback()); assertNotSame(callback(), callback()); } |
ObjectWithReflectiveEqualsHashCodeToString { @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this, fieldsExcludedFromEqualsAndHashCode()); } @Override String toString(); @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") boolean equals(Object other); @Override int hashCode(); } | @Test public void hashCodeIdentical() { assertEquals(new Header("name", "value").hashCode(), new Header("name", "value").hashCode()); }
@Test public void hashCodeDifferent() { assertNotEquals(new Header("name", "value").hashCode(), new Header("foo", "bar").hashCode()); } |
ProxyServlet extends HttpServlet implements ServletContextListener { @Override public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { ResponseWriter responseWriter = new ServletResponseWriter(new MockServerLogger(), httpServletResponse); HttpRequest request = null; try { request = httpServletRequestToMockServerRequestDecoder.mapHttpServletRequestToMockServerRequest(httpServletRequest); final String hostHeader = request.getFirstHeader(HOST.toString()); if (isNotBlank(hostHeader)) { scheduler.submit(() -> addSubjectAlternativeName(hostHeader)); } if (!httpStateHandler.handle(request, responseWriter, true)) { if (request.getPath().getValue().equals("/_mockserver_callback_websocket")) { responseWriter.writeResponse(request, NOT_IMPLEMENTED, "ExpectationResponseCallback, ExpectationForwardCallback or ExpectationForwardAndResponseCallback is not supported by MockServer deployed as a WAR", "text/plain"); } else if (request.matches("PUT", PATH_PREFIX + "/status", "/status") || isNotBlank(ConfigurationProperties.livenessHttpGetPath()) && request.matches("GET", ConfigurationProperties.livenessHttpGetPath())) { responseWriter.writeResponse(request, OK, portBindingSerializer.serialize(portBinding(httpServletRequest.getLocalPort())), "application/json"); } else if (request.matches("PUT", PATH_PREFIX + "/bind", "/bind")) { responseWriter.writeResponse(request, NOT_IMPLEMENTED); } else if (request.matches("PUT", PATH_PREFIX + "/stop", "/stop")) { responseWriter.writeResponse(request, NOT_IMPLEMENTED); } else { String portExtension = ""; if (!(httpServletRequest.getLocalPort() == 443 && httpServletRequest.isSecure() || httpServletRequest.getLocalPort() == 80)) { portExtension = ":" + httpServletRequest.getLocalPort(); } actionHandler.processAction(request, responseWriter, null, ImmutableSet.of( httpServletRequest.getLocalAddr() + portExtension, "localhost" + portExtension, "127.0.0.1" + portExtension ), true, true); } } } catch (IllegalArgumentException iae) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setHttpRequest(request) .setMessageFormat("exception processing request:{}error:{}") .setArguments(request, iae.getMessage()) ); responseWriter.writeResponse(request, BAD_REQUEST, iae.getMessage(), MediaType.create("text", "plain").toString()); } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setHttpRequest(request) .setMessageFormat("exception processing " + request) .setThrowable(e) ); responseWriter.writeResponse(request, response().withStatusCode(BAD_REQUEST.code()).withBody(e.getMessage()), true); } } @SuppressWarnings("WeakerAccess") ProxyServlet(); @Override void destroy(); @Override void contextInitialized(ServletContextEvent sce); @Override void contextDestroyed(ServletContextEvent sce); @Override void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); } | @Test public void shouldRetrieveRequests() { httpStateHandler.log( new LogEntry() .setHttpRequest(request("request_one")) .setType(RECEIVED_REQUEST) ); proxyServlet .service( buildHttpServletRequest( "PUT", "/mockserver/retrieve", httpRequestSerializer.serialize(request("request_one")) ), response ); assertResponse(response, 200, httpRequestSerializer.serialize(Collections.singletonList( request("request_one") ))); }
@Test public void shouldClear() { httpStateHandler.add(new Expectation(request("request_one")).thenRespond(response("response_one"))); httpStateHandler.log( new LogEntry() .setHttpRequest(request("request_one")) .setType(EXPECTATION_MATCHED) ); MockHttpServletRequest clearRequest = buildHttpServletRequest( "PUT", "/mockserver/clear", httpRequestSerializer.serialize(request("request_one")) ); proxyServlet.service(clearRequest, response); assertResponse(response, 200, ""); assertThat(httpStateHandler.firstMatchingExpectation(request("request_one")), is(nullValue())); assertThat(httpStateHandler.retrieve(request("/retrieve") .withMethod("PUT") .withBody( httpRequestSerializer.serialize(request("request_one")) )), is(response().withBody("[]", MediaType.JSON_UTF_8).withStatusCode(200))); }
@Test public void shouldReturnStatus() { MockHttpServletRequest statusRequest = buildHttpServletRequest( "PUT", "/status", "" ); proxyServlet.service(statusRequest, response); assertResponse(response, 200, portBindingSerializer.serialize( portBinding(80) )); }
@Test public void shouldReturnStatusOnCustomPath() { String originalStatusPath = ConfigurationProperties.livenessHttpGetPath(); try { ConfigurationProperties.livenessHttpGetPath("/livenessProbe"); MockHttpServletRequest statusRequest = buildHttpServletRequest( "GET", "/livenessProbe", "" ); proxyServlet.service(statusRequest, response); assertResponse(response, 200, portBindingSerializer.serialize( portBinding(80) )); } finally { ConfigurationProperties.livenessHttpGetPath(originalStatusPath); } }
@Test public void shouldBindNewPorts() { MockHttpServletRequest statusRequest = buildHttpServletRequest( "PUT", "/bind", portBindingSerializer.serialize( portBinding(1090, 1090) )); proxyServlet.service(statusRequest, response); assertResponse(response, 501, ""); }
@Test public void shouldStop() { MockHttpServletRequest statusRequest = buildHttpServletRequest( "PUT", "/stop", "" ); proxyServlet.service(statusRequest, response); assertResponse(response, 501, ""); }
@Test public void shouldRetrieveRecordedExpectations() { httpStateHandler.log( new LogEntry() .setType(FORWARDED_REQUEST) .setHttpRequest(request("request_one")) .setHttpResponse(response("response_one")) .setExpectation(new Expectation(request("request_one"), Times.once(), TimeToLive.unlimited(), 0).withId("key_one").thenRespond(response("response_one"))) ); MockHttpServletRequest expectationRetrieveExpectationsRequest = buildHttpServletRequest( "PUT", "/mockserver/retrieve", httpRequestSerializer.serialize(request("request_one")) ); expectationRetrieveExpectationsRequest.setQueryString("type=" + RetrieveType.RECORDED_EXPECTATIONS.name()); proxyServlet.service(expectationRetrieveExpectationsRequest, response); assertResponse(response, 200, expectationSerializer.serialize(Collections.singletonList( new Expectation(request("request_one"), Times.once(), TimeToLive.unlimited(), 0).withId("key_one").thenRespond(response("response_one")) ))); }
@Test public void shouldRetrieveLogMessages() { Level originalLevel = ConfigurationProperties.logLevel(); try { ConfigurationProperties.logLevel("INFO"); httpStateHandler.log( new LogEntry() .setType(RECEIVED_REQUEST) .setLogLevel(Level.INFO) .setHttpRequest(request("request_one")) .setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT) .setArguments(request("request_one")) ); MockHttpServletRequest retrieveLogRequest = buildHttpServletRequest( "PUT", "/mockserver/retrieve", httpRequestSerializer.serialize(request("request_one")) ); retrieveLogRequest.setQueryString("type=" + RetrieveType.LOGS.name()); proxyServlet.service(retrieveLogRequest, response); assertThat(response.getStatus(), is(200)); assertThat( new String(response.getContentAsByteArray(), UTF_8), is(endsWith(LOG_DATE_FORMAT.format(new Date(TimeService.currentTimeMillis())) + " - received request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"path\" : \"request_one\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE)) ); } finally { ConfigurationProperties.logLevel(originalLevel.name()); } }
@Test public void shouldProxyRequestsOnDefaultPort() { HttpRequest request = request("request_one").withHeader("Host", "localhost").withMethod("GET"); MockHttpServletRequest httpServletRequest = buildHttpServletRequest("GET", "request_one", ""); httpServletRequest.addHeader("Host", "localhost"); httpServletRequest.setLocalAddr("local_address"); httpServletRequest.setLocalPort(80); proxyServlet.service(httpServletRequest, response); verify(mockActionHandler).processAction( eq( request .withSecure(false) .withKeepAlive(true) ), any(ServletResponseWriter.class), isNull(), eq(ImmutableSet.of( "local_address", "localhost", "127.0.0.1" )), eq(true), eq(true)); }
@Test public void shouldProxyRequestsOnNonDefaultPort() { HttpRequest request = request("request_one").withHeader("Host", "localhost").withMethod("GET"); MockHttpServletRequest httpServletRequest = buildHttpServletRequest("GET", "request_one", ""); httpServletRequest.addHeader("Host", "localhost"); httpServletRequest.setLocalAddr("local_address"); httpServletRequest.setLocalPort(666); proxyServlet.service(httpServletRequest, response); verify(mockActionHandler).processAction( eq( request .withSecure(false) .withKeepAlive(true) ), any(ServletResponseWriter.class), isNull(), eq(ImmutableSet.of( "local_address:666", "localhost:666", "127.0.0.1:666" )), eq(true), eq(true)); }
@Test public void shouldProxySecureRequestsOnDefaultPort() { HttpRequest request = request("request_one").withHeader("Host", "localhost").withMethod("GET"); MockHttpServletRequest httpServletRequest = buildHttpServletRequest("GET", "request_one", ""); httpServletRequest.addHeader("Host", "localhost"); httpServletRequest.setSecure(true); httpServletRequest.setLocalAddr("local_address"); httpServletRequest.setLocalPort(443); proxyServlet.service(httpServletRequest, response); verify(mockActionHandler).processAction( eq( request .withSecure(true) .withKeepAlive(true) ), any(ServletResponseWriter.class), isNull(), eq(ImmutableSet.of( "local_address", "localhost", "127.0.0.1" )), eq(true), eq(true)); }
@Test public void shouldProxySecureRequestsOnNonDefaultPort() { HttpRequest request = request("request_one").withHeader("Host", "localhost").withMethod("GET"); MockHttpServletRequest httpServletRequest = buildHttpServletRequest("GET", "request_one", ""); httpServletRequest.addHeader("Host", "localhost"); httpServletRequest.setSecure(true); httpServletRequest.setLocalAddr("local_address"); httpServletRequest.setLocalPort(666); proxyServlet.service(httpServletRequest, response); verify(mockActionHandler).processAction( eq( request .withSecure(true) .withKeepAlive(true) ), any(ServletResponseWriter.class), isNull(), eq(ImmutableSet.of( "local_address:666", "localhost:666", "127.0.0.1:666" )), eq(true), eq(true)); } |
ObjectWithReflectiveEqualsHashCodeToString { @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } return new EqualsBuilder() .setExcludeFields(fieldsExcludedFromEqualsAndHashCode()) .setReflectUpToClass(ObjectWithReflectiveEqualsHashCodeToString.class) .setTestTransients(false) .setTestRecursive(false) .reflectionAppend(this, other) .isEquals(); } @Override String toString(); @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") boolean equals(Object other); @Override int hashCode(); } | @Test public void equalsIdentical() { assertTrue(new Header("name", "value").equals(new Header("name", "value"))); }
@Test public void notEqualsDifferent() { assertFalse(new Header("name", "value").equals(new Header("foo", "bar"))); } |
ObjectWithReflectiveEqualsHashCodeToString { @Override public String toString() { return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE, null, ObjectWithReflectiveEqualsHashCodeToString.class, false, false).setExcludeFieldNames(fieldsExcludedFromEqualsAndHashCode()).toString(); } @Override String toString(); @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") boolean equals(Object other); @Override int hashCode(); } | @Test public void toStringReturnStrings() { assertThat(new Header("name", "value").toString(), instanceOf(String.class)); } |
JsonSchemaBody extends Body<String> { public String getValue() { return jsonSchema; } JsonSchemaBody(String jsonSchema); static JsonSchemaBody jsonSchema(String jsonSchema); static JsonSchemaBody jsonSchemaFromResource(String jsonSchemaPath); Map<String, ParameterStyle> getParameterStyles(); JsonSchemaBody withParameterStyles(Map<String, ParameterStyle> parameterStyles); String getValue(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void shouldReturnValuesSetInConstructor() { JsonSchemaBody jsonSchemaBody = new JsonSchemaBody("some_body"); assertThat(jsonSchemaBody.getValue(), is("some_body")); assertThat(jsonSchemaBody.getType(), is(Body.Type.JSON_SCHEMA)); } |
Headers extends KeysToMultiValues<Header, Headers> { @Override public Header build(NottableString name, Collection<NottableString> values) { return new Header(name, values); } Headers(List<Header> headers); Headers(Header... headers); Headers(Multimap<NottableString, NottableString> headers); @Override Header build(NottableString name, Collection<NottableString> values); Headers withKeyMatchStyle(KeyMatchStyle keyMatchStyle); @SuppressWarnings("MethodDoesntCallSuperMethod") Headers clone(); } | @Test public void shouldBuildHeader() { Headers headers = new Headers(); Header header = headers.build(string("name"), Arrays.asList( string("value_one"), string("value_two") )); assertThat(header, is(new Header(string("name"), string("value_one"), string("value_two")))); } |
CircularConcurrentLinkedDeque extends ConcurrentLinkedDeque<E> { @Override public boolean add(E element) { if (maxSize > 0) { evictExcessElements(); return super.add(element); } else { return false; } } CircularConcurrentLinkedDeque(int maxSize, Consumer<E> onEvictCallback); void setMaxSize(int maxSize); @Override boolean add(E element); @Override boolean addAll(Collection<? extends E> collection); @Override boolean offer(E element); void clear(); @Deprecated boolean remove(Object o); boolean removeItem(E e); } | @Test public void shouldNotAllowAddingMoreThenMaximumNumberOfEntriesWhenUsingAdd() { CircularConcurrentLinkedDeque<String> concurrentLinkedQueue = new CircularConcurrentLinkedDeque<String>(3, null); concurrentLinkedQueue.add("1"); concurrentLinkedQueue.add("2"); concurrentLinkedQueue.add("3"); concurrentLinkedQueue.add("4"); assertEquals(3, concurrentLinkedQueue.size()); assertThat(concurrentLinkedQueue, not(contains("1"))); assertThat(concurrentLinkedQueue, contains("2", "3", "4")); } |
CircularConcurrentLinkedDeque extends ConcurrentLinkedDeque<E> { @Override public boolean addAll(Collection<? extends E> collection) { if (maxSize > 0) { boolean result = false; for (E element : collection) { if (add(element)) { result = true; } } return result; } else { return false; } } CircularConcurrentLinkedDeque(int maxSize, Consumer<E> onEvictCallback); void setMaxSize(int maxSize); @Override boolean add(E element); @Override boolean addAll(Collection<? extends E> collection); @Override boolean offer(E element); void clear(); @Deprecated boolean remove(Object o); boolean removeItem(E e); } | @Test public void shouldNotAllowAddingMoreThenMaximumNumberOfEntriesWhenUsingAddAll() { CircularConcurrentLinkedDeque<String> concurrentLinkedQueue = new CircularConcurrentLinkedDeque<String>(3, null); concurrentLinkedQueue.addAll(Arrays.asList("1", "2", "3", "4")); assertEquals(3, concurrentLinkedQueue.size()); assertThat(concurrentLinkedQueue, not(contains("1"))); assertThat(concurrentLinkedQueue, contains("2", "3", "4")); } |
SubSetMatcher { static boolean containsSubset(RegexStringMatcher regexStringMatcher, List<ImmutableEntry> subset, List<ImmutableEntry> superset) { boolean result = true; Set<Integer> matchingIndexes = new HashSet<>(); for (ImmutableEntry subsetItem : subset) { Set<Integer> subsetItemMatchingIndexes = matchesIndexes(regexStringMatcher, subsetItem, superset); boolean optionalAndNotPresent = subsetItem.isOptional() && !containsKey(regexStringMatcher, subsetItem, superset); boolean nottedAndPresent = nottedAndPresent(regexStringMatcher, subsetItem, superset); if ((!optionalAndNotPresent && subsetItemMatchingIndexes.isEmpty()) || nottedAndPresent) { result = false; break; } matchingIndexes.addAll(subsetItemMatchingIndexes); } if (result) { long subsetNonOptionalSize = subset.stream().filter(ImmutableEntry::isNotOptional).count(); result = matchingIndexes.size() >= subsetNonOptionalSize; } return result; } } | @Test public void shouldContainSubsetForEmpty() { assertTrue(containsSubset(regexStringMatcher, Collections.emptyList(), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForMultiValuesAllMatching() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, "one", "one_two"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, "one", "one_two"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForMultiValuesSubset() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, "one", "one_two"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForNottedKey() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "!two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "notTwo", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForNottedValue() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "!two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "notTwo"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForNottedMultiValue() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, "one", "!one_two"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, "one", "notOne_two"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForSubsetWithPresentOptional() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three"), new ImmutableEntry(regexStringMatcher, "four", "four") ))) ); }
@Test public void shouldContainSubsetForSubsetWithNotPresentOptional() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForOptionalWrongValue() { assertFalse(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three"), new ImmutableEntry(regexStringMatcher, "four", "wrong") ))) ); }
@Test public void shouldContainSubsetForOptionalWrongValueInReverse() { assertFalse(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three"), new ImmutableEntry(regexStringMatcher, "?four", "wrong") ))) ); }
@Test public void shouldContainSubsetForExtraValue() { assertFalse(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four"), new ImmutableEntry(regexStringMatcher, "five", "five") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three"), new ImmutableEntry(regexStringMatcher, "four", "four") ))) ); }
@Test public void shouldContainSubsetForWrongValue() { assertFalse(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "wrong"), new ImmutableEntry(regexStringMatcher, "three", "three"), new ImmutableEntry(regexStringMatcher, "four", "four") ))) ); }
@Test public void shouldContainSubsetForWrongKey() { assertFalse(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "wrong", "two"), new ImmutableEntry(regexStringMatcher, "three", "three"), new ImmutableEntry(regexStringMatcher, "four", "four") ))) ); }
@Test public void shouldContainSubsetForSchemaKey() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, schemaString("{\"type\": \"string\", \"pattern\": \"tw.{1}\"}"), string("two")) ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForSchemaValue() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, string("two"), schemaString("{\"type\": \"string\", \"pattern\": \"tw.{1}\"}")) ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForSchemaMultiValue() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, string("one"), schemaString("{\"type\": \"string\", \"pattern\": \"one_t.*\"}")), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, "one", "one_two"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); }
@Test public void shouldContainSubsetForSchemaKeyAndMultiValue() { assertTrue(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, schemaString("{\"type\": \"string\", \"pattern\": \"o.*\"}"), string("one_one")), new ImmutableEntry(regexStringMatcher, schemaString("{\"type\": \"string\", \"pattern\": \"o.*\"}"), string("one_two")), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, "one", "one_two"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); assertFalse(containsSubset(regexStringMatcher, Arrays.asList( new ImmutableEntry(regexStringMatcher, schemaString("{\"type\": \"string\", \"pattern\": \"o.*\"}"), string("one_one")), new ImmutableEntry(regexStringMatcher, schemaString("{\"type\": \"string\", \"pattern\": \"o.*\"}"), string("one_two")), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "?four", "four") ), new ArrayList<>(Arrays.asList( new ImmutableEntry(regexStringMatcher, "one", "one_one"), new ImmutableEntry(regexStringMatcher, "two", "two"), new ImmutableEntry(regexStringMatcher, "three", "three") ))) ); } |
CircularHashMap extends LinkedHashMap<K, V> { public K findKey(V value) { for (Map.Entry<K, V> entry : entrySet()) { V entryValue = entry.getValue(); if (entryValue == value || (value != null && value.equals(entryValue))) { return entry.getKey(); } } return null; } CircularHashMap(int maxSize); K findKey(V value); } | @Test public void shouldFindKeyByObject() { CircularHashMap<String, String> circularHashMap = new CircularHashMap<>(5); circularHashMap.put("0", "a"); circularHashMap.put("1", "b"); circularHashMap.put("2", "c"); circularHashMap.put("3", "d"); circularHashMap.put("4", "d"); circularHashMap.put("5", "e"); assertThat(circularHashMap.findKey("b"), is("1")); assertThat(circularHashMap.findKey("c"), is("2")); assertThat(circularHashMap.findKey("x"), nullValue()); assertThat(circularHashMap.findKey("a"), nullValue()); assertThat(circularHashMap.findKey("d"), is("3")); } |
PortFactory { public static int findFreePort() { int[] freePorts = findFreePorts(1); return freePorts[random.nextInt(freePorts.length)]; } static int findFreePort(); } | @Test public void shouldFindFreePort() throws IOException { int freePort = PortFactory.findFreePort(); assertTrue(new ServerSocket(freePort).isBound()); } |
X509Generator { public X509AndPrivateKey generateRootX509AndPrivateKey(final CertificateSigningRequest csr) throws IOException, NoSuchAlgorithmException, CertificateException, InvalidKeyException, NoSuchProviderException, SignatureException { final KeyPair keyPair = generateKeyPair(csr.getKeyPairAlgorithm(), csr.getKeyPairSize()); final X500Name subjectAndIssuer = new X500Name(buildDistinguishedName(csr.getCommonName())); X509CertInfo x509CertInfo = buildX509CertInfo(subjectAndIssuer, subjectAndIssuer, keyPair.getPublic(), csr); updateWithRootCertificateExtensions(x509CertInfo, keyPair.getPublic()); return signX509KeyPair(keyPair.getPrivate(), keyPair, x509CertInfo, csr.getSigningAlgorithm()); } X509Generator(MockServerLogger mockServerLogger); X509AndPrivateKey generateRootX509AndPrivateKey(final CertificateSigningRequest csr); X509AndPrivateKey generateLeafX509AndPrivateKey(final CertificateSigningRequest csr, String issuerDistinguishingName, final String caPrivateKey, final X509Certificate caCertificate); } | @Test public void shouldCreateRootCertificateWithCorrectAlgorithmAndKeySize() throws Exception { X509Generator x509Generator = new X509Generator(new MockServerLogger()); int keySize = KEY_SIZE; X509AndPrivateKey keyPair = x509Generator.generateRootX509AndPrivateKey(csr); X509Certificate x509Certificate = x509FromPEM(keyPair.getCert()); assertEquals("RSA", x509Certificate.getPublicKey().getAlgorithm()); assertEquals(keySize, ((RSAPublicKey) x509Certificate.getPublicKey()).getModulus().bitLength()); }
@Test public void shouldCreateRootCertificateWithValidExpiry() throws Exception { X509Generator x509Generator = new X509Generator(new MockServerLogger()); X509AndPrivateKey keyPair = x509Generator.generateRootX509AndPrivateKey(csr); X509Certificate x509Certificate = x509FromPEM(keyPair.getCert()); LocalDateTime instantWithinValidityRange = LocalDateTime.now().plusDays(30); x509Certificate.checkValidity(Date.from(instantWithinValidityRange.atZone(ZoneId.systemDefault()).toInstant())); }
@Test public void shouldCreateRootCertificateThatIsNotYetValid() throws Exception { X509Generator x509Generator = new X509Generator(new MockServerLogger()); X509AndPrivateKey keyPair = x509Generator.generateRootX509AndPrivateKey(csr); X509Certificate x509Certificate = x509FromPEM(keyPair.getCert()); Instant instantBeforeIssueTime = NOT_BEFORE.toInstant().minus(1, ChronoUnit.DAYS); try { x509Certificate.checkValidity(Date.from(instantBeforeIssueTime.atZone(ZoneId.systemDefault()).toInstant())); fail("expected exception to be thrown"); } catch (CertificateNotYetValidException cynyve) { assertThat(cynyve.getMessage(), containsString("NotBefore")); } }
@Test public void shouldCreateRootCertificateThatExpires() throws Exception { X509Generator x509Generator = new X509Generator(new MockServerLogger()); X509AndPrivateKey keyPair = x509Generator.generateRootX509AndPrivateKey(csr); X509Certificate x509Certificate = x509FromPEM(keyPair.getCert()); Instant instantAfterIssueTime = NOT_AFTER.toInstant().plus(1, ChronoUnit.DAYS); try { x509Certificate.checkValidity(Date.from(instantAfterIssueTime.atZone(ZoneId.systemDefault()).toInstant())); fail("expected exception to be thrown"); } catch (CertificateExpiredException cynyve) { assertThat(cynyve.getMessage(), containsString("NotAfter")); } }
@Test public void shouldCreateRootCertificateThatCanBePEMEncodedAndDecoded() throws Exception { X509Generator x509Generator = new X509Generator(new MockServerLogger()); X509AndPrivateKey keyPair = x509Generator.generateRootX509AndPrivateKey(csr); assertEquals(keyPair.getPrivateKey(), privateKeyToPEM(privateKeyBytesFromPEM(keyPair.getPrivateKey()))); assertEquals(keyPair.getCert(), certToPEM(certFromPem(keyPair.getCert()))); }
@Test public void shouldCreateRootCertificateWithCorrectCertExtensions() throws Exception { X509Generator x509Generator = new X509Generator(new MockServerLogger()); CertificateSigningRequest csr = new CertificateSigningRequest() .setCommonName(ROOT_COMMON_NAME) .setKeyPairSize(KEY_SIZE); X509AndPrivateKey pemRootKeyPair = x509Generator.generateRootX509AndPrivateKey(csr); X509Certificate x509Certificate = x509FromPEM(pemRootKeyPair.getCert()); boolean[] keyUsage = x509Certificate.getKeyUsage(); assertArrayEquals(new boolean[]{false, false, false, false, false, true, false, false, false}, keyUsage); if (x509Certificate instanceof X509CertImpl) { ((X509CertImpl) x509Certificate).getBasicConstraintsExtension().get(IS_CA); } }
@Test public void shouldCreateRootCertificateWithPositiveSerialNumber() throws Exception { X509Generator x509Generator = new X509Generator(new MockServerLogger()); X509AndPrivateKey keyPair = x509Generator.generateRootX509AndPrivateKey(csr); X509Certificate x509Certificate = x509FromPEM(keyPair.getCert()); assertTrue("The ca cert serial number is non-negative", x509Certificate.getSerialNumber().compareTo(BigInteger.ZERO) > 0); } |
HttpTemplateToJavaSerializer implements ToJavaSerializer<HttpTemplate> { @Override public String serialize(int numberOfSpacesToIndent, HttpTemplate httpTemplate) { StringBuffer output = new StringBuffer(); if (httpTemplate != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("template(HttpTemplate.TemplateType.").append(httpTemplate.getTemplateType().name()).append(")"); if (isNotBlank(httpTemplate.getTemplate())) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withTemplate(\"").append(StringEscapeUtils.escapeJava(httpTemplate.getTemplate())).append("\")"); } if (httpTemplate.getDelay() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withDelay(").append(new DelayToJavaSerializer().serialize(0, httpTemplate.getDelay())).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, HttpTemplate httpTemplate); } | @Test public void shouldSerializeFullObjectWithCallbackAsJava() { assertEquals(NEW_LINE + " template(HttpTemplate.TemplateType.JAVASCRIPT)" + NEW_LINE + " .withTemplate(\"" + StringEscapeUtils.escapeJava("if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': JSON.stringify({name: 'value'})" + NEW_LINE + " };" + NEW_LINE + "} else {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': request.body" + NEW_LINE + " };" + NEW_LINE + "}" ) + "\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.SECONDS, 5))", new HttpTemplateToJavaSerializer().serialize(1, new HttpTemplate(HttpTemplate.TemplateType.JAVASCRIPT) .withTemplate("if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': JSON.stringify({name: 'value'})" + NEW_LINE + " };" + NEW_LINE + "} else {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': request.body" + NEW_LINE + " };" + NEW_LINE + "}" ) .withDelay(new Delay(SECONDS, 5)) ) ); } |
HttpOverrideForwardedRequestToJavaSerializer implements ToJavaSerializer<HttpOverrideForwardedRequest> { @Override public String serialize(int numberOfSpacesToIndent, HttpOverrideForwardedRequest httpForward) { StringBuffer output = new StringBuffer(); if (httpForward != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("forwardOverriddenRequest()"); if (httpForward.getHttpRequest() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withRequest("); output.append(new HttpRequestToJavaSerializer().serialize(numberOfSpacesToIndent + 2, httpForward.getHttpRequest())); appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(")"); } if (httpForward.getHttpResponse() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withResponse("); output.append(new HttpResponseToJavaSerializer().serialize(numberOfSpacesToIndent + 2, httpForward.getHttpResponse())); appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(")"); } if (httpForward.getDelay() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withDelay("); output.append(new DelayToJavaSerializer().serialize(0, httpForward.getDelay())); output.append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, HttpOverrideForwardedRequest httpForward); } | @Test public void shouldSerializeFullObjectWithForwardAsJava() { assertEquals(NEW_LINE + " forwardOverriddenRequest()" + NEW_LINE + " .withRequest(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePathOne\")" + NEW_LINE + " .withBody(new StringBody(\"responseBodyOne\"))" + NEW_LINE + " )" + NEW_LINE + " .withResponse(" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(304)" + NEW_LINE + " .withReasonPhrase(\"someReason\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"responseHeaderNameOne\", \"responseHeaderValueOneOne\", \"responseHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"responseHeaderNameTwo\", \"responseHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"responseCookieNameOne\", \"responseCookieValueOne\")," + NEW_LINE + " new Cookie(\"responseCookieNameTwo\", \"responseCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(\"responseBody\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))" + NEW_LINE + " )" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))", new HttpOverrideForwardedRequestToJavaSerializer().serialize(1, new HttpOverrideForwardedRequest() .withHttpRequest(new HttpRequest() .withMethod("GET") .withPath("somePathOne") .withBody(new StringBody("responseBodyOne")) ) .withHttpResponse(new HttpResponse() .withStatusCode(304) .withReasonPhrase("someReason") .withHeaders( new Header("responseHeaderNameOne", "responseHeaderValueOneOne", "responseHeaderValueOneTwo"), new Header("responseHeaderNameTwo", "responseHeaderValueTwo") ) .withCookies( new Cookie("responseCookieNameOne", "responseCookieValueOne"), new Cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withBody("responseBody") .withDelay(TimeUnit.MILLISECONDS, 100) ) .withDelay(TimeUnit.MILLISECONDS, 100) ) ); } |
ConnectionOptionsToJavaSerializer implements ToJavaSerializer<ConnectionOptions> { @Override public String serialize(int numberOfSpacesToIndent, ConnectionOptions connectionOptions) { StringBuffer output = new StringBuffer(); if (connectionOptions != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("connectionOptions()"); if (connectionOptions.getSuppressContentLengthHeader() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withSuppressContentLengthHeader(").append(connectionOptions.getSuppressContentLengthHeader()).append(")"); } if (connectionOptions.getContentLengthHeaderOverride() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withContentLengthHeaderOverride(").append(connectionOptions.getContentLengthHeaderOverride()).append(")"); } if (connectionOptions.getSuppressConnectionHeader() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withSuppressConnectionHeader(").append(connectionOptions.getSuppressConnectionHeader()).append(")"); } if (connectionOptions.getChunkSize() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withChunkSize(").append(connectionOptions.getChunkSize()).append(")"); } if (connectionOptions.getKeepAliveOverride() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withKeepAliveOverride(").append(connectionOptions.getKeepAliveOverride()).append(")"); } if (connectionOptions.getCloseSocket() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withCloseSocket(").append(connectionOptions.getCloseSocket()).append(")"); } if (connectionOptions.getCloseSocketDelay() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withCloseSocketDelay(").append(new DelayToJavaSerializer().serialize(0, connectionOptions.getCloseSocketDelay())).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, ConnectionOptions connectionOptions); } | @Test public void shouldSerializeFullObjectWithForwardAsJava() { assertEquals(NEW_LINE + " connectionOptions()" + NEW_LINE + " .withSuppressContentLengthHeader(false)" + NEW_LINE + " .withContentLengthHeaderOverride(10)" + NEW_LINE + " .withSuppressConnectionHeader(true)" + NEW_LINE + " .withChunkSize(100)" + NEW_LINE + " .withKeepAliveOverride(false)" + NEW_LINE + " .withCloseSocket(true)" + NEW_LINE + " .withCloseSocketDelay(new Delay(TimeUnit.MILLISECONDS, 50))", new ConnectionOptionsToJavaSerializer().serialize(1, new ConnectionOptions() .withSuppressContentLengthHeader(false) .withContentLengthHeaderOverride(10) .withSuppressConnectionHeader(true) .withChunkSize(100) .withKeepAliveOverride(false) .withCloseSocket(true) .withCloseSocketDelay(new Delay(MILLISECONDS, 50)) ) ); } |
NottableStringToJavaSerializer { public static String serialize(NottableString nottableString, boolean alwaysNottableString) { if (nottableString.isOptional()) { return "optional(\"" + StringEscapeUtils.escapeJava(nottableString.getValue()) + "\")"; } else if (nottableString.isNot()) { return "not(\"" + StringEscapeUtils.escapeJava(nottableString.getValue()) + "\")"; } else if (alwaysNottableString) { return "string(\"" + StringEscapeUtils.escapeJava(nottableString.getValue()) + "\")"; } else { return "\"" + StringEscapeUtils.escapeJava(nottableString.getValue()) + "\""; } } static String serialize(NottableString nottableString, boolean alwaysNottableString); } | @Test public void shouldSerializeNottedString() { assertEquals("not(\"some_value\")", NottableStringToJavaSerializer.serialize(string("some_value", true), false) ); }
@Test public void shouldSerializeString() { assertEquals("\"some_value\"", NottableStringToJavaSerializer.serialize(string("some_value", false), false) ); } |
TimeToLiveToJavaSerializer implements ToJavaSerializer<TimeToLive> { @Override public String serialize(int numberOfSpacesToIndent, TimeToLive timeToLive) { StringBuffer output = new StringBuffer(); if (timeToLive != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output); if (timeToLive.isUnlimited()) { output.append("TimeToLive.unlimited()"); } else { output.append("TimeToLive.exactly(TimeUnit.").append(timeToLive.getTimeUnit().name()).append(", ").append(timeToLive.getTimeToLive()).append("L)"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, TimeToLive timeToLive); } | @Test public void shouldSerializeUnlimitedTimeToLiveAsJava() { assertEquals(NEW_LINE + " TimeToLive.unlimited()", new TimeToLiveToJavaSerializer().serialize(1, TimeToLive.unlimited() ) ); }
@Test public void shouldSerializeExactlyTimeToLiveAsJava() { assertEquals(NEW_LINE + " TimeToLive.exactly(TimeUnit.SECONDS, 100L)", new TimeToLiveToJavaSerializer().serialize(1, TimeToLive.exactly(TimeUnit.SECONDS, 100L) ) ); } |
TimesToJavaSerializer implements ToJavaSerializer<Times> { @Override public String serialize(int numberOfSpacesToIndent, Times times) { StringBuffer output = new StringBuffer(); if (times != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output); if (times.isUnlimited()) { output.append("Times.unlimited()"); } else if (times.getRemainingTimes() == 1) { output.append("Times.once()"); } else { output.append("Times.exactly(").append(times.getRemainingTimes()).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Times times); } | @Test public void shouldSerializeUnlimitedTimesAsJava() { assertEquals(NEW_LINE + " Times.unlimited()", new TimesToJavaSerializer().serialize(1, Times.unlimited() ) ); }
@Test public void shouldSerializeOnceTimesAsJava() { assertEquals(NEW_LINE + " Times.once()", new TimesToJavaSerializer().serialize(1, Times.once() ) ); }
@Test public void shouldSerializeExactlyTimesAsJava() { assertEquals(NEW_LINE + " Times.exactly(2)", new TimesToJavaSerializer().serialize(1, Times.exactly(2) ) ); } |
ParameterToJavaSerializer implements MultiValueToJavaSerializer<Parameter> { @Override public String serialize(int numberOfSpacesToIndent, Parameter parameter) { StringBuilder output = new StringBuilder(); output.append(NEW_LINE).append(Strings.padStart("", numberOfSpacesToIndent * INDENT_SIZE, ' ')); String serializedKey = NottableStringToJavaSerializer.serialize(parameter.getName(), false); output.append("new Parameter(").append(serializedKey); for (NottableString value : parameter.getValues()) { output.append(", ").append(NottableStringToJavaSerializer.serialize(value, serializedKey.endsWith(")"))); } output.append(")"); return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Parameter parameter); @Override String serializeAsJava(int numberOfSpacesToIndent, List<Parameter> parameters); @Override String serializeAsJava(int numberOfSpacesToIndent, Parameter... object); } | @Test public void shouldSerializeParameter() { assertEquals(NEW_LINE + " new Parameter(\"requestParameterNameOne\", \"requestParameterValueOneOne\", \"requestParameterValueOneTwo\")", new ParameterToJavaSerializer().serialize(1, new Parameter("requestParameterNameOne", "requestParameterValueOneOne", "requestParameterValueOneTwo")) ); } |
ParameterToJavaSerializer implements MultiValueToJavaSerializer<Parameter> { @Override public String serializeAsJava(int numberOfSpacesToIndent, List<Parameter> parameters) { StringBuilder output = new StringBuilder(); for (int i = 0; i < parameters.size(); i++) { output.append(serialize(numberOfSpacesToIndent, parameters.get(i))); if (i < (parameters.size() - 1)) { output.append(","); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Parameter parameter); @Override String serializeAsJava(int numberOfSpacesToIndent, List<Parameter> parameters); @Override String serializeAsJava(int numberOfSpacesToIndent, Parameter... object); } | @Test public void shouldSerializeMultipleParameters() { assertEquals(NEW_LINE + " new Parameter(\"requestParameterNameOne\", \"requestParameterValueOneOne\", \"requestParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestParameterNameTwo\", \"requestParameterValueTwo\")", new ParameterToJavaSerializer().serializeAsJava(1, new Parameter("requestParameterNameOne", "requestParameterValueOneOne", "requestParameterValueOneTwo"), new Parameter("requestParameterNameTwo", "requestParameterValueTwo")) ); }
@Test public void shouldSerializeListOfParameters() { assertEquals(NEW_LINE + " new Parameter(\"requestParameterNameOne\", \"requestParameterValueOneOne\", \"requestParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestParameterNameTwo\", \"requestParameterValueTwo\")", new ParameterToJavaSerializer().serializeAsJava(1, Arrays.asList( new Parameter("requestParameterNameOne", "requestParameterValueOneOne", "requestParameterValueOneTwo"), new Parameter("requestParameterNameTwo", "requestParameterValueTwo") )) ); }
@Test public void shouldSerializeListOfNottedAndOptionalParameters() { assertEquals(NEW_LINE + " new Parameter(not(\"requestParameterNameOne\"), not(\"requestParameterValueOneOne\"), string(\"requestParameterValueOneTwo\"))," + NEW_LINE + " new Parameter(optional(\"requestParameterNameTwo\"), not(\"requestParameterValueTwo\"))", new ParameterToJavaSerializer().serializeAsJava(1, Arrays.asList( new Parameter(not("requestParameterNameOne"), not("requestParameterValueOneOne"), string("requestParameterValueOneTwo")), new Parameter(optional("requestParameterNameTwo"), not("requestParameterValueTwo")) )) ); } |
HttpResponseToJavaSerializer implements ToJavaSerializer<HttpResponse> { @Override public String serialize(int numberOfSpacesToIndent, HttpResponse httpResponse) { StringBuffer output = new StringBuffer(); if (httpResponse != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("response()"); if (httpResponse.getStatusCode() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withStatusCode(").append(httpResponse.getStatusCode()).append(")"); } if (httpResponse.getReasonPhrase() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withReasonPhrase(\"").append(StringEscapeUtils.escapeJava(httpResponse.getReasonPhrase())).append("\")"); } outputHeaders(numberOfSpacesToIndent + 1, output, httpResponse.getHeaderList()); outputCookies(numberOfSpacesToIndent + 1, output, httpResponse.getCookieList()); if (isNotBlank(httpResponse.getBodyAsString())) { if (httpResponse.getBody() instanceof BinaryBody) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output); BinaryBody body = (BinaryBody) httpResponse.getBody(); output.append(".withBody(new Base64Converter().base64StringToBytes(\"").append(base64Converter.bytesToBase64String(body.getRawBytes())).append("\"))"); } else { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withBody(\"").append(StringEscapeUtils.escapeJava(httpResponse.getBodyAsString())).append("\")"); } } if (httpResponse.getDelay() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withDelay(").append(new DelayToJavaSerializer().serialize(0, httpResponse.getDelay())).append(")"); } if (httpResponse.getConnectionOptions() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withConnectionOptions("); output.append(new ConnectionOptionsToJavaSerializer().serialize(numberOfSpacesToIndent + 2, httpResponse.getConnectionOptions())); appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, HttpResponse httpResponse); } | @Test public void shouldSerializeFullObjectWithResponseAsJava() { assertEquals(NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(304)" + NEW_LINE + " .withReasonPhrase(\"someReason\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"responseHeaderNameOne\", \"responseHeaderValueOneOne\", \"responseHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"responseHeaderNameTwo\", \"responseHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"responseCookieNameOne\", \"responseCookieValueOne\")," + NEW_LINE + " new Cookie(\"responseCookieNameTwo\", \"responseCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(\"responseBody\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))", new HttpResponseToJavaSerializer().serialize(1, new HttpResponse() .withStatusCode(304) .withReasonPhrase("someReason") .withHeaders( new Header("responseHeaderNameOne", "responseHeaderValueOneOne", "responseHeaderValueOneTwo"), new Header("responseHeaderNameTwo", "responseHeaderValueTwo") ) .withCookies( new Cookie("responseCookieNameOne", "responseCookieValueOne"), new Cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withBody("responseBody") .withDelay(TimeUnit.MILLISECONDS, 100) ) ); }
@Test public void shouldSerializeObjectWithBinaryBodyResponseAsJava() { assertEquals(NEW_LINE + " response()" + NEW_LINE + " .withBody(new Base64Converter().base64StringToBytes(\"" + base64Converter.bytesToBase64String("responseBody".getBytes(UTF_8)) + "\"))", new HttpResponseToJavaSerializer().serialize(1, new HttpResponse() .withBody(binary("responseBody".getBytes(UTF_8))) ) ); }
@Test public void shouldEscapeJSONBodies() { assertEquals("" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(304)" + NEW_LINE + " .withBody(\"[" + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"1\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"Xenophon's imperial fiction : on the education of Cyrus\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"James Tatum\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"0691067570\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"1989\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"2\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"You are here : personal geographies and other maps of the imagination\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"Katharine A. Harmon\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"1568984308\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"2004\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"3\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"You just don't understand : women and men in conversation\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"Deborah Tannen\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"0345372050\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"1990\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }" + StringEscapeUtils.escapeJava(NEW_LINE) + "]\")", new HttpResponseToJavaSerializer().serialize(1, new HttpResponse() .withStatusCode(304) .withBody("[" + NEW_LINE + " {" + NEW_LINE + " \"id\": \"1\"," + NEW_LINE + " \"title\": \"Xenophon's imperial fiction : on the education of Cyrus\"," + NEW_LINE + " \"author\": \"James Tatum\"," + NEW_LINE + " \"isbn\": \"0691067570\"," + NEW_LINE + " \"publicationDate\": \"1989\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"id\": \"2\"," + NEW_LINE + " \"title\": \"You are here : personal geographies and other maps of the imagination\"," + NEW_LINE + " \"author\": \"Katharine A. Harmon\"," + NEW_LINE + " \"isbn\": \"1568984308\"," + NEW_LINE + " \"publicationDate\": \"2004\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"id\": \"3\"," + NEW_LINE + " \"title\": \"You just don't understand : women and men in conversation\"," + NEW_LINE + " \"author\": \"Deborah Tannen\"," + NEW_LINE + " \"isbn\": \"0345372050\"," + NEW_LINE + " \"publicationDate\": \"1990\"" + NEW_LINE + " }" + NEW_LINE + "]") ) ); }
@Test public void shouldSerializeMinimalObjectAsJava() { assertEquals(NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(304)" + NEW_LINE + " .withReasonPhrase(\"randomPhrase\")", new HttpResponseToJavaSerializer().serialize(1, new HttpResponse() .withStatusCode(304) .withReasonPhrase("randomPhrase") ) ); } |
HttpErrorToJavaSerializer implements ToJavaSerializer<HttpError> { @Override public String serialize(int numberOfSpacesToIndent, HttpError httpError) { StringBuffer output = new StringBuffer(); if (httpError != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("error()"); if (httpError.getDelay() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withDelay(").append(new DelayToJavaSerializer().serialize(0, httpError.getDelay())).append(")"); } if (httpError.getDropConnection() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withDropConnection(").append(httpError.getDropConnection()).append(")"); } if (httpError.getResponseBytes() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withResponseBytes(new Base64Converter().base64StringToBytes(\"").append(base64Converter.bytesToBase64String(httpError.getResponseBytes())).append("\"))"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, HttpError httpError); } | @Test public void shouldSerializeFullObjectWithForwardAsJava() { assertEquals(NEW_LINE + " error()" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))" + NEW_LINE + " .withDropConnection(true)" + NEW_LINE + " .withResponseBytes(new Base64Converter().base64StringToBytes(\"" + base64Converter.bytesToBase64String("example_bytes".getBytes(UTF_8)) + "\"))", new HttpErrorToJavaSerializer().serialize(1, new HttpError() .withDelay(TimeUnit.MILLISECONDS, 100) .withDropConnection(true) .withResponseBytes("example_bytes".getBytes(UTF_8)) ) ); } |
HttpForwardToJavaSerializer implements ToJavaSerializer<HttpForward> { @Override public String serialize(int numberOfSpacesToIndent, HttpForward httpForward) { StringBuffer output = new StringBuffer(); if (httpForward != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("forward()"); if (httpForward.getHost() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withHost(\"").append(httpForward.getHost()).append("\")"); } if (httpForward.getPort() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withPort(").append(httpForward.getPort()).append(")"); } if (httpForward.getScheme() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withScheme(HttpForward.Scheme.").append(httpForward.getScheme()).append(")"); } if (httpForward.getDelay() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withDelay(").append(new DelayToJavaSerializer().serialize(0, httpForward.getDelay())).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, HttpForward httpForward); } | @Test public void shouldSerializeFullObjectWithForwardAsJava() { assertEquals(NEW_LINE + " forward()" + NEW_LINE + " .withHost(\"some_host\")" + NEW_LINE + " .withPort(9090)" + NEW_LINE + " .withScheme(HttpForward.Scheme.HTTPS)" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))", new HttpForwardToJavaSerializer().serialize(1, new HttpForward() .withHost("some_host") .withPort(9090) .withScheme(HttpForward.Scheme.HTTPS) .withDelay(TimeUnit.MILLISECONDS, 100) ) ); } |
ExpectationToJavaSerializer implements ToJavaSerializer<Expectation> { public String serialize(List<Expectation> expectations) { StringBuilder output = new StringBuilder(); for (Expectation expectation : expectations) { output.append(serialize(0, expectation)); output.append(NEW_LINE); output.append(NEW_LINE); } return output.toString(); } String serialize(List<Expectation> expectations); @Override String serialize(int numberOfSpacesToIndent, Expectation expectation); static final int INDENT_SIZE; } | @Test public void shouldSerializeArrayOfObjectsAsJava() { assertEquals(NEW_LINE + "new MockServerClient(\"localhost\", 1080)" + NEW_LINE + ".when(" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePathOne\")," + NEW_LINE + " null," + NEW_LINE + " null," + NEW_LINE + " 0" + NEW_LINE + ")" + NEW_LINE + ".respond(" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(200)" + NEW_LINE + " .withReasonPhrase(\"OK\")" + NEW_LINE + " .withBody(\"responseBodyOne\")" + NEW_LINE + ");" + NEW_LINE + NEW_LINE + NEW_LINE + "new MockServerClient(\"localhost\", 1080)" + NEW_LINE + ".when(" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePathOne\")," + NEW_LINE + " Times.once()," + NEW_LINE + " null," + NEW_LINE + " 0" + NEW_LINE + ")" + NEW_LINE + ".respond(" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(200)" + NEW_LINE + " .withReasonPhrase(\"OK\")" + NEW_LINE + " .withBody(\"responseBodyOne\")" + NEW_LINE + ");" + NEW_LINE + NEW_LINE + NEW_LINE + "new MockServerClient(\"localhost\", 1080)" + NEW_LINE + ".when(" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePathOne\")," + NEW_LINE + " Times.exactly(2)," + NEW_LINE + " TimeToLive.exactly(TimeUnit.MINUTES, 1L)," + NEW_LINE + " 100" + NEW_LINE + ")" + NEW_LINE + ".respond(" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(200)" + NEW_LINE + " .withReasonPhrase(\"OK\")" + NEW_LINE + " .withBody(\"responseBodyOne\")" + NEW_LINE + ");" + NEW_LINE + NEW_LINE, new ExpectationToJavaSerializer().serialize( Arrays.asList( new Expectation( request("somePathOne"), null, null, 0) .thenRespond( response("responseBodyOne") ), new Expectation( request("somePathOne"), once(), null, 0) .thenRespond( response("responseBodyOne") ), new Expectation( request("somePathOne"), exactly(2), TimeToLive.exactly(TimeUnit.MINUTES, 1L), 100) .thenRespond( response("responseBodyOne") ) ) ) ); }
@Test public void shouldSerializeFullObjectWithResponseAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .respond(" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(304)" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"responseHeaderNameOne\", \"responseHeaderValueOneOne\", \"responseHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"responseHeaderNameTwo\", \"responseHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"responseCookieNameOne\", \"responseCookieValueOne\")," + NEW_LINE + " new Cookie(\"responseCookieNameTwo\", \"responseCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(\"responseBody\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MINUTES, 1))" + NEW_LINE + " .withConnectionOptions(" + NEW_LINE + " connectionOptions()" + NEW_LINE + " .withSuppressContentLengthHeader(true)" + NEW_LINE + " .withContentLengthHeaderOverride(10)" + NEW_LINE + " .withSuppressConnectionHeader(true)" + NEW_LINE + " .withKeepAliveOverride(true)" + NEW_LINE + " .withCloseSocket(true)" + NEW_LINE + " )" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenRespond( response() .withStatusCode(304) .withHeaders( new Header("responseHeaderNameOne", "responseHeaderValueOneOne", "responseHeaderValueOneTwo"), new Header("responseHeaderNameTwo", "responseHeaderValueTwo") ) .withCookies( new Cookie("responseCookieNameOne", "responseCookieValueOne"), new Cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withBody("responseBody") .withDelay(new Delay(TimeUnit.MINUTES, 1)) .withConnectionOptions( connectionOptions() .withSuppressContentLengthHeader(true) .withContentLengthHeaderOverride(10) .withSuppressConnectionHeader(true) .withKeepAliveOverride(true) .withCloseSocket(true) ) ) ) ); }
@Test public void shouldSerializeFullObjectWithResponseTemplateAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .respond(" + NEW_LINE + " template(HttpTemplate.TemplateType.JAVASCRIPT)" + NEW_LINE + " .withTemplate(\"if (request.method === 'POST' && request.path === '/somePath') {\\n return {\\n 'statusCode': 200,\\n 'body': JSON.stringify({name: 'value'})\\n };\\n} else {\\n return {\\n 'statusCode': 406,\\n 'body': request.body\\n };\\n}\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenRespond( template(HttpTemplate.TemplateType.JAVASCRIPT, "if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 200," + NEW_LINE + " 'body': JSON.stringify({name: 'value'})" + NEW_LINE + " };" + NEW_LINE + "} else {" + NEW_LINE + " return {" + NEW_LINE + " 'statusCode': 406," + NEW_LINE + " 'body': request.body" + NEW_LINE + " };" + NEW_LINE + "}") .withDelay(TimeUnit.MILLISECONDS, 100) ) ) ); }
@Test public void shouldSerializeFullObjectWithParameterBodyResponseAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withBody(" + NEW_LINE + " new ParameterBody(" + NEW_LINE + " new Parameter(\"requestBodyParameterNameOne\", \"requestBodyParameterValueOneOne\", \"requestBodyParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestBodyParameterNameTwo\", \"requestBodyParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " )," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .respond(" + NEW_LINE + " response()" + NEW_LINE + " .withBody(\"responseBody\")" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withBody( new ParameterBody( new Parameter("requestBodyParameterNameOne", "requestBodyParameterValueOneOne", "requestBodyParameterValueOneTwo"), new Parameter("requestBodyParameterNameTwo", "requestBodyParameterValueTwo") ) ), once(), unlimited(), 0) .thenRespond( response() .withBody("responseBody") ) ) ); }
@Test public void shouldSerializeFullObjectWithBinaryBodyResponseAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withBody(new Base64Converter().base64StringToBytes(\"" + base64Converter.bytesToBase64String("request body".getBytes(UTF_8)) + "\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .respond(" + NEW_LINE + " response()" + NEW_LINE + " .withBody(\"responseBody\")" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withBody( new BinaryBody("request body".getBytes(UTF_8)) ), once(), unlimited(), 0) .thenRespond( response() .withBody("responseBody") ) ) ); }
@Test public void shouldSerializeFullObjectWithResponseClassCallbackAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .respond(" + NEW_LINE + " callback()" + NEW_LINE + " .withCallbackClass(\"some_class\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenRespond( callback() .withCallbackClass("some_class") .withDelay(TimeUnit.MILLISECONDS, 100) ) ) ); }
@Test public void shouldSerializeFullObjectWithResponseObjectCallbackAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " ;", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenRespond( new HttpObjectCallback() .withClientId("some_client_id") .withDelay(TimeUnit.MILLISECONDS, 100) ) ) ); }
@Test public void shouldSerializeFullObjectWithForwardAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .forward(" + NEW_LINE + " forward()" + NEW_LINE + " .withHost(\"some_host\")" + NEW_LINE + " .withPort(9090)" + NEW_LINE + " .withScheme(HttpForward.Scheme.HTTPS)" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenForward( forward() .withHost("some_host") .withPort(9090) .withScheme(HttpForward.Scheme.HTTPS) .withDelay(TimeUnit.MILLISECONDS, 100) ) ) ); }
@Test public void shouldSerializeFullObjectWithForwardOverriddenRequestAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .forward(" + NEW_LINE + " forwardOverriddenRequest()" + NEW_LINE + " .withRequest(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))" + NEW_LINE + " )" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenForward( forwardOverriddenRequest() .withHttpRequest( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")) ) .withDelay(TimeUnit.MILLISECONDS, 100) ) ) ); }
@Test public void shouldSerializeFullObjectWithForwardTemplateAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .forward(" + NEW_LINE + " template(HttpTemplate.TemplateType.JAVASCRIPT)" + NEW_LINE + " .withTemplate(\"return { 'path': \\\"somePath\\\", 'body': JSON.stringify({name: 'value'}) };\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenForward( template(HttpTemplate.TemplateType.JAVASCRIPT) .withTemplate("return { 'path': \"somePath\", 'body': JSON.stringify({name: 'value'}) };") .withDelay(TimeUnit.MILLISECONDS, 100) ) ) ); }
@Test public void shouldSerializeFullObjectWithForwardClassCallbackAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .forward(" + NEW_LINE + " callback()" + NEW_LINE + " .withCallbackClass(\"some_class\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenForward( callback() .withCallbackClass("some_class") .withDelay(TimeUnit.MILLISECONDS, 100) ) ) ); }
@Test public void shouldSerializeFullObjectWithForwardObjectCallbackAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " ;", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenForward( new HttpObjectCallback() .withClientId("some_client_id") .withDelay(TimeUnit.MILLISECONDS, 100) ) ) ); }
@Test public void shouldSerializeFullObjectWithErrorAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"somebody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .error(" + NEW_LINE + " error()" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MINUTES, 1))" + NEW_LINE + " .withDropConnection(true)" + NEW_LINE + " .withResponseBytes(new Base64Converter().base64StringToBytes(\"" + base64Converter.bytesToBase64String("some_bytes".getBytes(UTF_8)) + "\"))" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withBody(new StringBody("somebody")), once(), unlimited(), 0) .thenError( error() .withDelay(new Delay(TimeUnit.MINUTES, 1)) .withDropConnection(true) .withResponseBytes("some_bytes".getBytes(UTF_8)) ) ) ); }
@Test public void shouldEscapeJsonBodies() { assertEquals("" + NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withBody(new JsonBody(\"[" + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"1\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"Xenophon's imperial fiction : on the education of Cyrus\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"James Tatum\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"0691067570\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"1989\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"2\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"You are here : personal geographies and other maps of the imagination\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"Katharine A. Harmon\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"1568984308\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"2004\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"3\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"You just don't understand : women and men in conversation\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"Deborah Tannen\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"0345372050\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"1990\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }" + StringEscapeUtils.escapeJava(NEW_LINE) + "]\", JsonBodyMatchType.ONLY_MATCHING_FIELDS))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .respond(" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(304)" + NEW_LINE + " .withBody(\"[" + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"1\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"Xenophon's imperial fiction : on the education of Cyrus\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"James Tatum\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"0691067570\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"1989\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"2\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"You are here : personal geographies and other maps of the imagination\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"Katharine A. Harmon\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"1568984308\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"2004\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"3\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"You just don't understand : women and men in conversation\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"Deborah Tannen\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"0345372050\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"1990\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }" + StringEscapeUtils.escapeJava(NEW_LINE) + "]\")" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withPath("somePath") .withBody(new JsonBody("[" + NEW_LINE + " {" + NEW_LINE + " \"id\": \"1\"," + NEW_LINE + " \"title\": \"Xenophon's imperial fiction : on the education of Cyrus\"," + NEW_LINE + " \"author\": \"James Tatum\"," + NEW_LINE + " \"isbn\": \"0691067570\"," + NEW_LINE + " \"publicationDate\": \"1989\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"id\": \"2\"," + NEW_LINE + " \"title\": \"You are here : personal geographies and other maps of the imagination\"," + NEW_LINE + " \"author\": \"Katharine A. Harmon\"," + NEW_LINE + " \"isbn\": \"1568984308\"," + NEW_LINE + " \"publicationDate\": \"2004\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"id\": \"3\"," + NEW_LINE + " \"title\": \"You just don't understand : women and men in conversation\"," + NEW_LINE + " \"author\": \"Deborah Tannen\"," + NEW_LINE + " \"isbn\": \"0345372050\"," + NEW_LINE + " \"publicationDate\": \"1990\"" + NEW_LINE + " }" + NEW_LINE + "]")), once(), unlimited(), 0) .thenRespond( response() .withStatusCode(304) .withBody("[" + NEW_LINE + " {" + NEW_LINE + " \"id\": \"1\"," + NEW_LINE + " \"title\": \"Xenophon's imperial fiction : on the education of Cyrus\"," + NEW_LINE + " \"author\": \"James Tatum\"," + NEW_LINE + " \"isbn\": \"0691067570\"," + NEW_LINE + " \"publicationDate\": \"1989\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"id\": \"2\"," + NEW_LINE + " \"title\": \"You are here : personal geographies and other maps of the imagination\"," + NEW_LINE + " \"author\": \"Katharine A. Harmon\"," + NEW_LINE + " \"isbn\": \"1568984308\"," + NEW_LINE + " \"publicationDate\": \"2004\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"id\": \"3\"," + NEW_LINE + " \"title\": \"You just don't understand : women and men in conversation\"," + NEW_LINE + " \"author\": \"Deborah Tannen\"," + NEW_LINE + " \"isbn\": \"0345372050\"," + NEW_LINE + " \"publicationDate\": \"1990\"" + NEW_LINE + " }" + NEW_LINE + "]") ) ) ); }
@Test public void shouldEscapeJsonSchemaBodies() { String jsonSchema = "{" + NEW_LINE + " \"$schema\": \"http: " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"; assertEquals("" + NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withBody(new JsonSchemaBody(\"" + StringEscapeUtils.escapeJava(jsonSchema) + "\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .respond(" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(304)" + NEW_LINE + " .withBody(\"responseBody\")" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withPath("somePath") .withBody(new JsonSchemaBody(jsonSchema)), once(), unlimited(), 0) .thenRespond( response() .withStatusCode(304) .withBody("responseBody") ) ) ); }
@Test public void shouldEscapeXmlSchemaBodies() { String xmlSchema = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http: " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http: " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>"; assertEquals("" + NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withBody(new XmlSchemaBody(\"" + StringEscapeUtils.escapeJava(xmlSchema) + "\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .respond(" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(304)" + NEW_LINE + " .withBody(\"responseBody\")" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withPath("somePath") .withBody(new XmlSchemaBody(xmlSchema)), once(), unlimited(), 0) .thenRespond( response() .withStatusCode(304) .withBody("responseBody") ) ) ); }
@Test public void shouldSerializeMinimalObjectAsJava() { assertEquals(NEW_LINE + " new MockServerClient(\"localhost\", 1080)" + NEW_LINE + " .when(" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withBody(new StringBody(\"responseBody\"))," + NEW_LINE + " Times.once()," + NEW_LINE + " TimeToLive.unlimited()," + NEW_LINE + " 0" + NEW_LINE + " )" + NEW_LINE + " .respond(" + NEW_LINE + " response()" + NEW_LINE + " .withStatusCode(304)" + NEW_LINE + " .withReasonPhrase(\"randomPhrase\")" + NEW_LINE + " );", new ExpectationToJavaSerializer().serialize(1, new Expectation( request() .withPath("somePath") .withBody(new StringBody("responseBody")), once(), unlimited(), 0) .thenRespond( response() .withStatusCode(304) .withReasonPhrase("randomPhrase") ) ) ); } |
MockServerClient implements Stoppable { public ForwardChainExpectation when(RequestDefinition requestDefinition) { return when(requestDefinition, Times.unlimited()); } MockServerClient(CompletableFuture<Integer> portFuture); MockServerClient(String host, int port); MockServerClient(String host, int port, String contextPath); MockServerClient setRequestOverride(HttpRequest requestOverride); boolean isSecure(); MockServerClient withSecure(boolean secure); InetSocketAddress remoteAddress(); String contextPath(); Integer getPort(); MockServerClient openUI(); MockServerClient openUI(TimeUnit timeUnit, long pause); @Deprecated @SuppressWarnings({"DeprecatedIsStillUsed", "RedundantSuppression"}) boolean isRunning(); @Deprecated boolean isRunning(int attempts, long timeout, TimeUnit timeUnit); boolean hasStopped(); boolean hasStopped(int attempts, long timeout, TimeUnit timeUnit); boolean hasStarted(); boolean hasStarted(int attempts, long timeout, TimeUnit timeUnit); List<Integer> bind(Integer... ports); Future<MockServerClient> stopAsync(); void stop(); Future<MockServerClient> stop(boolean ignoreFailure); @Override void close(); MockServerClient reset(); MockServerClient clear(RequestDefinition requestDefinition); MockServerClient clear(ExpectationId expectationId); MockServerClient clear(RequestDefinition requestDefinition, ClearType type); MockServerClient clear(ExpectationId expectationId, ClearType type); MockServerClient verify(RequestDefinition... requestDefinitions); MockServerClient verify(ExpectationId... expectationIds); @SuppressWarnings("DuplicatedCode") MockServerClient verify(RequestDefinition requestDefinition, VerificationTimes times); @SuppressWarnings("DuplicatedCode") MockServerClient verify(ExpectationId expectationId, VerificationTimes times); @SuppressWarnings({"DuplicatedCode", "UnusedReturnValue"}) MockServerClient verifyZeroInteractions(); RequestDefinition[] retrieveRecordedRequests(RequestDefinition requestDefinition); String retrieveRecordedRequests(RequestDefinition requestDefinition, Format format); LogEventRequestAndResponse[] retrieveRecordedRequestsAndResponses(RequestDefinition requestDefinition); String retrieveRecordedRequestsAndResponses(RequestDefinition requestDefinition, Format format); Expectation[] retrieveRecordedExpectations(RequestDefinition requestDefinition); String retrieveRecordedExpectations(RequestDefinition requestDefinition, Format format); String retrieveLogMessages(RequestDefinition requestDefinition); String[] retrieveLogMessagesArray(RequestDefinition requestDefinition); ForwardChainExpectation when(RequestDefinition requestDefinition); ForwardChainExpectation when(RequestDefinition requestDefinition, Times times); ForwardChainExpectation when(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive); ForwardChainExpectation when(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive, Integer priority); Expectation[] upsert(OpenAPIExpectation... openAPIExpectations); Expectation[] upsert(Expectation... expectations); @Deprecated Expectation[] sendExpectation(Expectation... expectations); Expectation[] retrieveActiveExpectations(RequestDefinition requestDefinition); String retrieveActiveExpectations(RequestDefinition requestDefinition, Format format); } | @Test public void shouldSetupExpectationWithResponse() { HttpRequest httpRequest = new HttpRequest() .withPath("/some_path") .withBody(new StringBody("some_request_body")); HttpResponse httpResponse = new HttpResponse() .withBody("some_response_body") .withHeaders(new Header("responseName", "responseValue")); ForwardChainExpectation forwardChainExpectation = mockServerClient.when(httpRequest); forwardChainExpectation.respond(httpResponse); Expectation expectation = forwardChainExpectation.getExpectation(); assertTrue(expectation.isActive()); assertSame(httpResponse, expectation.getHttpResponse()); assertEquals(Times.unlimited(), expectation.getTimes()); }
@Test public void shouldSetupExpectationWithResponseTemplate() { HttpRequest httpRequest = new HttpRequest() .withPath("/some_path") .withBody(new StringBody("some_request_body")); HttpTemplate template = new HttpTemplate(HttpTemplate.TemplateType.VELOCITY) .withTemplate("some_template"); ForwardChainExpectation forwardChainExpectation = mockServerClient.when(httpRequest); forwardChainExpectation.respond(template); Expectation expectation = forwardChainExpectation.getExpectation(); assertTrue(expectation.isActive()); assertSame(template, expectation.getHttpResponseTemplate()); assertEquals(Times.unlimited(), expectation.getTimes()); }
@Test public void shouldSetupExpectationWithResponseClassCallback() { HttpRequest httpRequest = new HttpRequest() .withPath("/some_path") .withBody(new StringBody("some_request_body")); HttpClassCallback httpClassCallback = new HttpClassCallback() .withCallbackClass("some_class"); ForwardChainExpectation forwardChainExpectation = mockServerClient.when(httpRequest); forwardChainExpectation.respond(httpClassCallback); Expectation expectation = forwardChainExpectation.getExpectation(); assertTrue(expectation.isActive()); assertSame(httpClassCallback, expectation.getHttpResponseClassCallback()); assertEquals(Times.unlimited(), expectation.getTimes()); }
@Test public void shouldSetupExpectationWithForward() { HttpRequest httpRequest = new HttpRequest() .withPath("/some_path") .withBody(new StringBody("some_request_body")); HttpForward httpForward = new HttpForward() .withHost("some_host") .withPort(9090) .withScheme(HttpForward.Scheme.HTTPS); ForwardChainExpectation forwardChainExpectation = mockServerClient.when(httpRequest); forwardChainExpectation.forward(httpForward); Expectation expectation = forwardChainExpectation.getExpectation(); assertTrue(expectation.isActive()); assertSame(httpForward, expectation.getHttpForward()); assertEquals(Times.unlimited(), expectation.getTimes()); }
@Test public void shouldSetupExpectationWithForwardTemplate() { HttpRequest httpRequest = new HttpRequest() .withPath("/some_path") .withBody(new StringBody("some_request_body")); HttpTemplate template = new HttpTemplate(HttpTemplate.TemplateType.VELOCITY) .withTemplate("some_template"); ForwardChainExpectation forwardChainExpectation = mockServerClient.when(httpRequest); forwardChainExpectation.forward(template); Expectation expectation = forwardChainExpectation.getExpectation(); assertTrue(expectation.isActive()); assertSame(template, expectation.getHttpForwardTemplate()); assertEquals(Times.unlimited(), expectation.getTimes()); }
@Test public void shouldSetupExpectationWithForwardClassCallback() { HttpRequest httpRequest = new HttpRequest() .withPath("/some_path") .withBody(new StringBody("some_request_body")); HttpClassCallback httpClassCallback = new HttpClassCallback() .withCallbackClass("some_class"); ForwardChainExpectation forwardChainExpectation = mockServerClient.when(httpRequest); forwardChainExpectation.forward(httpClassCallback); Expectation expectation = forwardChainExpectation.getExpectation(); assertTrue(expectation.isActive()); assertSame(httpClassCallback, expectation.getHttpForwardClassCallback()); assertEquals(Times.unlimited(), expectation.getTimes()); }
@Test public void shouldSetupExpectationWithOverrideForwardedRequest() { HttpRequest httpRequest = new HttpRequest() .withPath("/some_path") .withBody(new StringBody("some_request_body")); ForwardChainExpectation forwardChainExpectation = mockServerClient.when(httpRequest); forwardChainExpectation.forward(forwardOverriddenRequest(request().withBody("some_overridden_body"))); Expectation expectation = forwardChainExpectation.getExpectation(); assertTrue(expectation.isActive()); assertThat(expectation.getHttpForwardTemplate(), nullValue()); assertThat(expectation.getHttpOverrideForwardedRequest(), is(new HttpOverrideForwardedRequest() .withHttpRequest(request().withBody("some_overridden_body")) )); assertEquals(Times.unlimited(), expectation.getTimes()); }
@Test public void shouldSetupExpectationWithError() { HttpRequest httpRequest = new HttpRequest() .withPath("/some_path") .withBody(new StringBody("some_request_body")); HttpError httpError = new HttpError() .withDropConnection(true) .withResponseBytes("silly_bytes".getBytes(UTF_8)); ForwardChainExpectation forwardChainExpectation = mockServerClient.when(httpRequest); forwardChainExpectation.error(httpError); Expectation expectation = forwardChainExpectation.getExpectation(); assertTrue(expectation.isActive()); assertSame(httpError, expectation.getHttpError()); assertEquals(Times.unlimited(), expectation.getTimes()); } |
HttpClassCallbackToJavaSerializer implements ToJavaSerializer<HttpClassCallback> { @Override public String serialize(int numberOfSpacesToIndent, HttpClassCallback httpClassCallback) { StringBuffer output = new StringBuffer(); if (httpClassCallback != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("callback()"); if (httpClassCallback.getCallbackClass() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withCallbackClass(\"").append(httpClassCallback.getCallbackClass()).append("\")"); } if (httpClassCallback.getDelay() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withDelay(").append(new DelayToJavaSerializer().serialize(0, httpClassCallback.getDelay())).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, HttpClassCallback httpClassCallback); } | @Test public void shouldSerializeFullObjectWithCallbackAsJava() { assertEquals(NEW_LINE + " callback()" + NEW_LINE + " .withCallbackClass(\"some_class\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))", new HttpClassCallbackToJavaSerializer().serialize(1, new HttpClassCallback() .withCallbackClass("some_class") .withDelay(TimeUnit.MILLISECONDS, 100) ) ); } |
HttpRequestToJavaSerializer implements ToJavaSerializer<HttpRequest> { public String serialize(List<HttpRequest> httpRequests) { StringBuilder output = new StringBuilder(); for (HttpRequest httpRequest : httpRequests) { output.append(serialize(0, httpRequest)); output.append(";"); output.append(NEW_LINE); } return output.toString(); } String serialize(List<HttpRequest> httpRequests); @Override String serialize(int numberOfSpacesToIndent, HttpRequest request); } | @Test public void shouldSerializeArrayOfObjectsAsJava() { assertEquals(NEW_LINE + "request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePathOne\")" + NEW_LINE + " .withBody(new StringBody(\"responseBodyOne\"));" + NEW_LINE + NEW_LINE + "request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePathTwo\")" + NEW_LINE + " .withBody(new StringBody(\"responseBodyTwo\"));" + NEW_LINE, new HttpRequestToJavaSerializer().serialize( Arrays.asList( new HttpRequest() .withMethod("GET") .withPath("somePathOne") .withBody(new StringBody("responseBodyOne")), new HttpRequest() .withMethod("GET") .withPath("somePathTwo") .withBody(new StringBody("responseBodyTwo")) ) ) ); }
@Test public void shouldSerializeFullObjectAsJava() { assertEquals(NEW_LINE + " request()" + NEW_LINE + " .withMethod(\"GET\")" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withHeaders(" + NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withCookies(" + NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withQueryStringParameters(" + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameOne\", \"requestQueryStringParameterValueOneOne\", \"requestQueryStringParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestQueryStringParameterNameTwo\", \"requestQueryStringParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " .withSecure(true)" + NEW_LINE + " .withKeepAlive(false)" + NEW_LINE + " .withSocketAddress(" + NEW_LINE + " new SocketAddress()" + NEW_LINE + " .withHost(\"someHost\")" + NEW_LINE + " .withPort(1234)" + NEW_LINE + " .withScheme(SocketAddress.Scheme.HTTPS)" + NEW_LINE + " )" + NEW_LINE + " .withBody(new StringBody(\"responseBody\"))", new HttpRequestToJavaSerializer().serialize(1, new HttpRequest() .withMethod("GET") .withPath("somePath") .withQueryStringParameters( new Parameter("requestQueryStringParameterNameOne", "requestQueryStringParameterValueOneOne", "requestQueryStringParameterValueOneTwo"), new Parameter("requestQueryStringParameterNameTwo", "requestQueryStringParameterValueTwo") ) .withHeaders( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") ) .withSecure(true) .withKeepAlive(false) .withSocketAddress( new SocketAddress().withHost("someHost").withPort(1234).withScheme(SocketAddress.Scheme.HTTPS) ) .withBody(new StringBody("responseBody")) ) ); }
@Test public void shouldSerializeFullObjectWithParameterBodyRequestAsJava() { assertEquals(NEW_LINE + " request()" + NEW_LINE + " .withBody(" + NEW_LINE + " new ParameterBody(" + NEW_LINE + " new Parameter(\"requestBodyParameterNameOne\", \"requestBodyParameterValueOneOne\", \"requestBodyParameterValueOneTwo\")," + NEW_LINE + " new Parameter(\"requestBodyParameterNameTwo\", \"requestBodyParameterValueTwo\")" + NEW_LINE + " )" + NEW_LINE + " )", new HttpRequestToJavaSerializer().serialize(1, new HttpRequest() .withBody( new ParameterBody( new Parameter("requestBodyParameterNameOne", "requestBodyParameterValueOneOne", "requestBodyParameterValueOneTwo"), new Parameter("requestBodyParameterNameTwo", "requestBodyParameterValueTwo") ) ) ) ); }
@Test public void shouldSerializeFullObjectWithBinaryBodyRequestAsJava() { assertEquals(NEW_LINE + " request()" + NEW_LINE + " .withBody(new Base64Converter().base64StringToBytes(\"" + base64Converter.bytesToBase64String("responseBody".getBytes(UTF_8)) + "\"))", new HttpRequestToJavaSerializer().serialize(1, new HttpRequest() .withBody( new BinaryBody("responseBody".getBytes(UTF_8)) ) )); }
@Test public void shouldEscapeJsonBodies() { assertEquals("" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withBody(new JsonBody(\"[" + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"1\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"Xenophon's imperial fiction : on the education of Cyrus\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"James Tatum\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"0691067570\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"1989\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"2\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"You are here : personal geographies and other maps of the imagination\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"Katharine A. Harmon\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"1568984308\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"2004\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }," + StringEscapeUtils.escapeJava(NEW_LINE) + " {" + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"id\\\": \\\"3\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"title\\\": \\\"You just don't understand : women and men in conversation\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"author\\\": \\\"Deborah Tannen\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"isbn\\\": \\\"0345372050\\\"," + StringEscapeUtils.escapeJava(NEW_LINE) + " \\\"publicationDate\\\": \\\"1990\\\"" + StringEscapeUtils.escapeJava(NEW_LINE) + " }" + StringEscapeUtils.escapeJava(NEW_LINE) + "]\", JsonBodyMatchType.ONLY_MATCHING_FIELDS))", new HttpRequestToJavaSerializer().serialize(1, new HttpRequest() .withPath("somePath") .withBody(new JsonBody("[" + NEW_LINE + " {" + NEW_LINE + " \"id\": \"1\"," + NEW_LINE + " \"title\": \"Xenophon's imperial fiction : on the education of Cyrus\"," + NEW_LINE + " \"author\": \"James Tatum\"," + NEW_LINE + " \"isbn\": \"0691067570\"," + NEW_LINE + " \"publicationDate\": \"1989\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"id\": \"2\"," + NEW_LINE + " \"title\": \"You are here : personal geographies and other maps of the imagination\"," + NEW_LINE + " \"author\": \"Katharine A. Harmon\"," + NEW_LINE + " \"isbn\": \"1568984308\"," + NEW_LINE + " \"publicationDate\": \"2004\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"id\": \"3\"," + NEW_LINE + " \"title\": \"You just don't understand : women and men in conversation\"," + NEW_LINE + " \"author\": \"Deborah Tannen\"," + NEW_LINE + " \"isbn\": \"0345372050\"," + NEW_LINE + " \"publicationDate\": \"1990\"" + NEW_LINE + " }" + NEW_LINE + "]")) ) ); }
@Test public void shouldEscapeJsonSchemaBodies() { String jsonSchema = "{" + NEW_LINE + " \"$schema\": \"http: " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"; assertEquals("" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withBody(new JsonSchemaBody(\"" + StringEscapeUtils.escapeJava(jsonSchema) + "\"))", new HttpRequestToJavaSerializer().serialize(1, new HttpRequest() .withPath("somePath") .withBody(new JsonSchemaBody(jsonSchema)) ) ); }
@Test public void shouldEscapeXmlSchemaBodies() { String xmlSchema = "{" + NEW_LINE + " \"$schema\": \"http: " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"; assertEquals("" + NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withBody(new XmlSchemaBody(\"" + StringEscapeUtils.escapeJava(xmlSchema) + "\"))", new HttpRequestToJavaSerializer().serialize(1, new HttpRequest() .withPath("somePath") .withBody(new XmlSchemaBody(xmlSchema)) ) ); }
@Test public void shouldSerializeMinimalObjectAsJava() { assertEquals(NEW_LINE + " request()" + NEW_LINE + " .withPath(\"somePath\")" + NEW_LINE + " .withBody(new StringBody(\"responseBody\"))", new HttpRequestToJavaSerializer().serialize(1, new HttpRequest() .withPath("somePath") .withBody("responseBody") ) ); } |
SocketAddressToJavaSerializer implements ToJavaSerializer<SocketAddress> { @Override public String serialize(int numberOfSpacesToIndent, SocketAddress socketAddress) { StringBuffer output = new StringBuffer(); if (socketAddress != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("new SocketAddress()"); if (socketAddress.getHost() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withHost(\"").append(socketAddress.getHost()).append("\")"); } if (socketAddress.getPort() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withPort(").append(socketAddress.getPort()).append(")"); } if (socketAddress.getScheme() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withScheme(SocketAddress.Scheme.").append(socketAddress.getScheme()).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, SocketAddress socketAddress); } | @Test public void shouldSerializeFullObjectWithForwardAsJava() { assertEquals(NEW_LINE + " new SocketAddress()" + NEW_LINE + " .withHost(\"some_host\")" + NEW_LINE + " .withPort(9090)" + NEW_LINE + " .withScheme(SocketAddress.Scheme.HTTPS)", new SocketAddressToJavaSerializer().serialize(1, SocketAddress .socketAddress() .withHost("some_host") .withPort(9090) .withScheme(SocketAddress.Scheme.HTTPS) ) ); } |
CookieToJavaSerializer implements MultiValueToJavaSerializer<Cookie> { @Override public String serialize(int numberOfSpacesToIndent, Cookie cookie) { return NEW_LINE + Strings.padStart("", numberOfSpacesToIndent * INDENT_SIZE, ' ') + "new Cookie(" + NottableStringToJavaSerializer.serialize(cookie.getName(), false) + ", " + NottableStringToJavaSerializer.serialize(cookie.getValue(), false) + ")"; } @Override String serialize(int numberOfSpacesToIndent, Cookie cookie); @Override String serializeAsJava(int numberOfSpacesToIndent, List<Cookie> cookies); @Override String serializeAsJava(int numberOfSpacesToIndent, Cookie... object); } | @Test public void shouldSerializeCookie() { assertEquals(NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")", new CookieToJavaSerializer().serialize(1, new Cookie("requestCookieNameOne", "requestCookieValueOne")) ); } |
CookieToJavaSerializer implements MultiValueToJavaSerializer<Cookie> { @Override public String serializeAsJava(int numberOfSpacesToIndent, List<Cookie> cookies) { StringBuilder output = new StringBuilder(); for (int i = 0; i < cookies.size(); i++) { output.append(serialize(numberOfSpacesToIndent, cookies.get(i))); if (i < (cookies.size() - 1)) { output.append(","); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Cookie cookie); @Override String serializeAsJava(int numberOfSpacesToIndent, List<Cookie> cookies); @Override String serializeAsJava(int numberOfSpacesToIndent, Cookie... object); } | @Test public void shouldSerializeMultipleCookies() { assertEquals(NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")", new CookieToJavaSerializer().serializeAsJava(1, new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo")) ); }
@Test public void shouldSerializeListOfCookies() { assertEquals(NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(\"requestCookieNameTwo\", \"requestCookieValueTwo\")", new CookieToJavaSerializer().serializeAsJava(1, Arrays.asList( new Cookie("requestCookieNameOne", "requestCookieValueOne"), new Cookie("requestCookieNameTwo", "requestCookieValueTwo") )) ); }
@Test public void shouldSerializeListOfNottedAndOptionalCookies() { assertEquals(NEW_LINE + " new Cookie(not(\"requestCookieNameOne\"), \"requestCookieValueOne\")," + NEW_LINE + " new Cookie(optional(\"requestCookieNameTwo\"), \"requestCookieValueTwo\")", new CookieToJavaSerializer().serializeAsJava(1, Arrays.asList( new Cookie(not("requestCookieNameOne"), "requestCookieValueOne"), new Cookie(optional("requestCookieNameTwo"), "requestCookieValueTwo") )) ); } |
DelayToJavaSerializer implements ToJavaSerializer<Delay> { @Override public String serialize(int numberOfSpacesToIndent, Delay delay) { StringBuilder output = new StringBuilder(); if (delay != null) { output.append("new Delay(TimeUnit.").append(delay.getTimeUnit().name()).append(", ").append(delay.getValue()).append(")"); } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Delay delay); } | @Test public void shouldSerializeFullObjectWithForwardAsJava() { assertEquals("new Delay(TimeUnit.SECONDS, 10)", new DelayToJavaSerializer().serialize(1, new Delay(TimeUnit.SECONDS, 10) ) ); } |
HeaderToJavaSerializer implements MultiValueToJavaSerializer<Header> { @Override public String serialize(int numberOfSpacesToIndent, Header header) { StringBuilder output = new StringBuilder(); output.append(NEW_LINE).append(Strings.padStart("", numberOfSpacesToIndent * INDENT_SIZE, ' ')); String serializedKey = NottableStringToJavaSerializer.serialize(header.getName(), false); output.append("new Header(").append(serializedKey); for (NottableString value : header.getValues()) { output.append(", ").append(NottableStringToJavaSerializer.serialize(value, serializedKey.endsWith(")"))); } output.append(")"); return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Header header); @Override String serializeAsJava(int numberOfSpacesToIndent, List<Header> headers); @Override String serializeAsJava(int numberOfSpacesToIndent, Header... object); } | @Test public void shouldSerializeHeader() { assertEquals(NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")", new HeaderToJavaSerializer().serialize(1, new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo")) ); } |
HeaderToJavaSerializer implements MultiValueToJavaSerializer<Header> { @Override public String serializeAsJava(int numberOfSpacesToIndent, List<Header> headers) { StringBuilder output = new StringBuilder(); for (int i = 0; i < headers.size(); i++) { output.append(serialize(numberOfSpacesToIndent, headers.get(i))); if (i < (headers.size() - 1)) { output.append(","); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Header header); @Override String serializeAsJava(int numberOfSpacesToIndent, List<Header> headers); @Override String serializeAsJava(int numberOfSpacesToIndent, Header... object); } | @Test public void shouldSerializeMultipleHeaders() { assertEquals(NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")", new HeaderToJavaSerializer().serializeAsJava(1, new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo")) ); }
@Test public void shouldSerializeListOfHeaders() { assertEquals(NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")," + NEW_LINE + " new Header(\"requestHeaderNameTwo\", \"requestHeaderValueTwo\")", new HeaderToJavaSerializer().serializeAsJava(1, Arrays.asList( new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo"), new Header("requestHeaderNameTwo", "requestHeaderValueTwo") )) ); }
@Test public void shouldSerializeListOfNottedAndOptionalHeaders() { assertEquals(NEW_LINE + " new Header(not(\"requestHeaderNameOne\"), not(\"requestHeaderValueOneOne\"), string(\"requestHeaderValueOneTwo\"))," + NEW_LINE + " new Header(optional(\"requestHeaderNameTwo\"), not(\"requestHeaderValueTwo\"))", new HeaderToJavaSerializer().serializeAsJava(1, Arrays.asList( new Header(not("requestHeaderNameOne"), not("requestHeaderValueOneOne"), string("requestHeaderValueOneTwo")), new Header(optional("requestHeaderNameTwo"), not("requestHeaderValueTwo")) )) ); } |
HttpRequestToCurlSerializer { public String toCurl(HttpRequest request) { return toCurl(request, null); } HttpRequestToCurlSerializer(MockServerLogger mockServerLogger); String toCurl(HttpRequest request); String toCurl(HttpRequest request, @Nullable InetSocketAddress remoteAddress); } | @Test public void shouldGenerateCurlForSimpleRequest() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl( request(), new InetSocketAddress("localhost", 80) ); assertThat(curl, is("curl -v 'http: }
@Test public void shouldGenerateCurlForRequestWithPOST() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl( request() .withMethod("POST"), new InetSocketAddress("localhost", 80) ); assertThat(curl, is("curl -v 'http: }
@Test public void shouldGenerateCurlForRequestWithGETAndSocketAddress() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl( request() .withMethod("GET"), new InetSocketAddress("localhost", 80) ); assertThat(curl, is("curl -v 'http: }
@Test public void shouldGenerateCurlForRequestWithGETAndNullSocketAddress() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl( request() .withHeader(HOST.toString(), "localhost:" + 80) .withMethod("GET"), null ); assertThat(curl, is("curl -v 'http: }
@Test public void shouldGenerateCurlForRequestWithGETAndNullSocketAddressAndNoHostHeader() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl( request() .withMethod("GET"), null ); assertThat(curl, is("no host header or remote address specified")); }
@Test public void shouldGenerateCurlForRequestWithParameter() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl( request() .withQueryStringParameters( param("parameterName1", "parameterValue1_1", "parameterValue1_2"), param("another parameter with spaces", "a value with single 'quotes', double \"quotes\" and spaces") ), new InetSocketAddress("localhost", 80) ); assertThat(curl, is("curl -v 'http: }
@Test public void shouldGenerateCurlForRequestWithHeaders() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl( request() .withHeaders( new Header("headerName1", "headerValue1"), new Header("headerName2", "headerValue2_1", "headerValue2_2") ), new InetSocketAddress("localhost", 80) ); assertThat(curl, is("curl -v 'http: }
@Test public void shouldGenerateCurlForRequestWithCookies() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl( request() .withCookies( new Cookie("cookieName1", "cookieValue1"), new Cookie("cookieName2", "cookieValue2") ), new InetSocketAddress("localhost", 80) ); assertThat(curl, is("curl -v 'http: "-H 'cookie: cookieName1=cookieValue1; cookieName2=cookieValue2'")); }
@Test public void shouldGenerateCurlForRequestWithPOSTParameterHeadersAndCookies() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl( request() .withPath("/somePath") .withMethod("POST") .withQueryStringParameters( param("parameterName1", "parameterValue1_1", "parameterValue1_2"), param("another parameter with spaces", "a value with single 'quotes', double \"quotes\" and spaces") ) .withHeaders( new Header("headerName1", "headerValue1"), new Header("headerName2", "headerValue2_1", "headerValue2_2") ) .withCookies( new Cookie("cookieName1", "cookieValue1"), new Cookie("cookieName2", "cookieValue2") ), new InetSocketAddress("localhost", 80) ); assertThat(curl, is("curl -v " + "'http: "?parameterName1=parameterValue1_1¶meterName1=parameterValue1_2&another%20parameter%20with%20spaces=a%20value%20with%20single%20%27quotes%27%2C%20double%20%22quotes%22%20and%20spaces'" + " -X POST" + " -H 'headerName1: headerValue1'" + " -H 'headerName2: headerValue2_1'" + " -H 'headerName2: headerValue2_2'" + " -H 'cookie: cookieName1=cookieValue1; cookieName2=cookieValue2'")); }
@Test public void shouldHandleNullWhenGeneratingCurl() { HttpRequestToCurlSerializer httpRequestToCurlSerializer = new HttpRequestToCurlSerializer(mockServerLogger); String curl = httpRequestToCurlSerializer.toCurl(null, null); assertThat(curl, is("null HttpRequest")); } |
XmlSchemaBodyDTO extends BodyDTO { public String getXml() { return xmlSchema; } XmlSchemaBodyDTO(XmlSchemaBody xmlSchemaBody); XmlSchemaBodyDTO(XmlSchemaBody xmlSchemaBody, Boolean not); String getXml(); XmlSchemaBody buildObject(); } | @Test public void shouldReturnValuesSetInConstructor() { XmlSchemaBodyDTO xmlSchemaBodyDTO = new XmlSchemaBodyDTO(new XmlSchemaBody("some_body")); assertThat(xmlSchemaBodyDTO.getXml(), is("some_body")); assertThat(xmlSchemaBodyDTO.getType(), is(Body.Type.XML_SCHEMA)); } |
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(); } | @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)); } |
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); } | @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())); } |
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(); } | @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)); } |
BinaryBodyDTO extends BodyWithContentTypeDTO { public byte[] getBase64Bytes() { return base64Bytes; } BinaryBodyDTO(BinaryBody binaryBody); BinaryBodyDTO(BinaryBody binaryBody, Boolean not); byte[] getBase64Bytes(); BinaryBody buildObject(); } | @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)); } |
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(); } | @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)); } |
JsonPathBodyDTO extends BodyDTO { public String getJsonPath() { return jsonPath; } JsonPathBodyDTO(JsonPathBody jsonPathBody); JsonPathBodyDTO(JsonPathBody jsonPathBody, Boolean not); String getJsonPath(); JsonPathBody buildObject(); } | @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)); } |
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(); } | @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)); } |
XmlBodyDTO extends BodyWithContentTypeDTO { public String getXml() { return xml; } XmlBodyDTO(XmlBody xmlBody); XmlBodyDTO(XmlBody xmlBody, Boolean not); String getXml(); byte[] getRawBytes(); XmlBody buildObject(); } | @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"))); } |
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(); } | @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)); } |
ParameterDTO extends KeyToMultiValueDTO implements DTO<Parameter> { public Parameter buildObject() { return new Parameter(getName(), getValues()); } ParameterDTO(Parameter parameter); protected ParameterDTO(); Parameter buildObject(); } | @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"))); } |
ParameterBodyDTO extends BodyDTO { public Parameters getParameters() { return parameters; } ParameterBodyDTO(ParameterBody parameterBody); ParameterBodyDTO(ParameterBody parameterBody, Boolean not); Parameters getParameters(); ParameterBody buildObject(); } | @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)); } |
MockServerServlet extends HttpServlet implements ServletContextListener { @Override public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { ResponseWriter responseWriter = new ServletResponseWriter(new MockServerLogger(), httpServletResponse); HttpRequest request = null; try { request = httpServletRequestToMockServerRequestDecoder.mapHttpServletRequestToMockServerRequest(httpServletRequest); final String hostHeader = request.getFirstHeader(HOST.toString()); if (isNotBlank(hostHeader)) { scheduler.submit(() -> addSubjectAlternativeName(hostHeader)); } if (!httpStateHandler.handle(request, responseWriter, true)) { if (request.getPath().getValue().equals("/_mockserver_callback_websocket")) { responseWriter.writeResponse(request, NOT_IMPLEMENTED, "ExpectationResponseCallback, ExpectationForwardCallback or ExpectationForwardAndResponseCallback is not supported by MockServer deployed as a WAR", "text/plain"); } else if (request.matches("PUT", PATH_PREFIX + "/status", "/status") || isNotBlank(ConfigurationProperties.livenessHttpGetPath()) && request.matches("GET", ConfigurationProperties.livenessHttpGetPath())) { responseWriter.writeResponse(request, OK, portBindingSerializer.serialize(portBinding(httpServletRequest.getLocalPort())), "application/json"); } else if (request.matches("PUT", PATH_PREFIX + "/bind", "/bind")) { responseWriter.writeResponse(request, NOT_IMPLEMENTED); } else if (request.matches("PUT", PATH_PREFIX + "/stop", "/stop")) { responseWriter.writeResponse(request, NOT_IMPLEMENTED); } else { String portExtension = ""; if (!(httpServletRequest.getLocalPort() == 443 && httpServletRequest.isSecure() || httpServletRequest.getLocalPort() == 80)) { portExtension = ":" + httpServletRequest.getLocalPort(); } actionHandler.processAction(request, responseWriter, null, ImmutableSet.of( httpServletRequest.getLocalAddr() + portExtension, "localhost" + portExtension, "127.0.0.1" + portExtension ), false, true); } } } catch (IllegalArgumentException iae) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setHttpRequest(request) .setMessageFormat("exception processing request:{}error:{}") .setArguments(request, iae.getMessage()) ); responseWriter.writeResponse(request, BAD_REQUEST, iae.getMessage(), MediaType.create("text", "plain").toString()); } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setLogLevel(Level.ERROR) .setHttpRequest(request) .setMessageFormat("exception processing " + request) .setThrowable(e) ); responseWriter.writeResponse(request, response().withStatusCode(BAD_REQUEST.code()).withBody(e.getMessage()), true); } } @SuppressWarnings("WeakerAccess") MockServerServlet(); @Override void destroy(); @Override void contextInitialized(ServletContextEvent sce); @Override void contextDestroyed(ServletContextEvent sce); @Override void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); } | @Test public void shouldRetrieveRequests() { httpStateHandler.log( new LogEntry() .setType(RECEIVED_REQUEST) .setLogLevel(Level.INFO) .setHttpRequest(request("request_one")) .setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT) .setArguments(request("request_one")) ); httpStateHandler.log( new LogEntry() .setType(RECEIVED_REQUEST) .setLogLevel(Level.INFO) .setHttpRequest(request("request_two")) .setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT) .setArguments(request("request_two")) ); mockServerServlet .service( buildHttpServletRequest( "PUT", "/mockserver/retrieve", httpRequestSerializer.serialize(request("request_one")) ), response ); assertResponse(response, 200, httpRequestSerializer.serialize(Collections.singletonList( request("request_one") ))); }
@Test public void shouldClear() { httpStateHandler.add(new Expectation(request("request_one")).thenRespond(response("response_one"))); httpStateHandler.log( new LogEntry() .setHttpRequest(request("request_one")) .setType(EXPECTATION_MATCHED) ); MockHttpServletRequest clearRequest = buildHttpServletRequest( "PUT", "/mockserver/clear", httpRequestSerializer.serialize(request("request_one")) ); mockServerServlet.service(clearRequest, response); assertResponse(response, 200, ""); assertThat(httpStateHandler.firstMatchingExpectation(request("request_one")), is(nullValue())); assertThat(httpStateHandler.retrieve(request("/retrieve") .withMethod("PUT") .withBody( httpRequestSerializer.serialize(request("request_one")) )), is(response().withBody("[]", MediaType.JSON_UTF_8).withStatusCode(200))); }
@Test public void shouldReturnStatus() { MockHttpServletRequest statusRequest = buildHttpServletRequest( "PUT", "/mockserver/status", "" ); mockServerServlet.service(statusRequest, response); assertResponse(response, 200, portBindingSerializer.serialize( portBinding(80) )); }
@Test public void shouldReturnStatusOnCustomPath() { String originalStatusPath = ConfigurationProperties.livenessHttpGetPath(); try { ConfigurationProperties.livenessHttpGetPath("/livenessProbe"); MockHttpServletRequest statusRequest = buildHttpServletRequest( "GET", "/livenessProbe", "" ); mockServerServlet.service(statusRequest, response); assertResponse(response, 200, portBindingSerializer.serialize( portBinding(80) )); } finally { ConfigurationProperties.livenessHttpGetPath(originalStatusPath); } }
@Test public void shouldBindNewPorts() { MockHttpServletRequest statusRequest = buildHttpServletRequest( "PUT", "/mockserver/bind", portBindingSerializer.serialize( portBinding(1090, 1090) )); mockServerServlet.service(statusRequest, response); assertResponse(response, 501, ""); }
@Test public void shouldStop() { MockHttpServletRequest statusRequest = buildHttpServletRequest( "PUT", "/mockserver/stop", "" ); mockServerServlet.service(statusRequest, response); assertResponse(response, 501, ""); }
@Test public void shouldRetrieveRecordedExpectations() { httpStateHandler.log( new LogEntry() .setType(FORWARDED_REQUEST) .setHttpRequest(request("request_one")) .setHttpResponse(response("response_one")) .setExpectation(new Expectation(request("request_one"), Times.once(), TimeToLive.unlimited(), 0).withId("key_one").thenRespond(response("response_one"))) ); httpStateHandler.log( new LogEntry() .setType(FORWARDED_REQUEST) .setHttpRequest(request("request_two")) .setHttpResponse(response("response_two")) .setExpectation(new Expectation(request("request_two"), Times.once(), TimeToLive.unlimited(), 0).withId("key_two").thenRespond(response("response_two"))) ); MockHttpServletRequest expectationRetrieveExpectationsRequest = buildHttpServletRequest( "PUT", "/mockserver/retrieve", httpRequestSerializer.serialize(request("request_one")) ); expectationRetrieveExpectationsRequest.setQueryString("type=" + RetrieveType.RECORDED_EXPECTATIONS.name()); mockServerServlet.service(expectationRetrieveExpectationsRequest, response); assertResponse(response, 200, expectationSerializer.serialize(Collections.singletonList( new Expectation(request("request_one"), Times.once(), TimeToLive.unlimited(), 0).withId("key_one").thenRespond(response("response_one")) ))); }
@Test public void shouldAddExpectation() { Expectation expectationOne = new Expectation(request("request_one")).thenRespond(response("response_one")); MockHttpServletRequest request = buildHttpServletRequest( "PUT", "/mockserver/expectation", expectationSerializer.serialize(expectationOne) ); mockServerServlet.service(request, response); assertThat(response.getStatus(), is(201)); assertThat(new String(response.getContentAsByteArray(), UTF_8), containsString("[ {" + NEW_LINE + " \"id\" : \"")); assertThat(new String(response.getContentAsByteArray(), UTF_8), containsString("\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"request_one\"" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"statusCode\" : 200," + NEW_LINE + " \"reasonPhrase\" : \"OK\"," + NEW_LINE + " \"body\" : \"response_one\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }" + NEW_LINE + "} ]")); assertThat(httpStateHandler.firstMatchingExpectation(request("request_one")), is(expectationOne)); }
@Test public void shouldRetrieveActiveExpectations() { Expectation expectationOne = new Expectation(request("request_one")).thenRespond(response("response_one")); httpStateHandler.add(expectationOne); MockHttpServletRequest expectationRetrieveExpectationsRequest = buildHttpServletRequest( "PUT", "/mockserver/retrieve", httpRequestSerializer.serialize(request("request_one")) ); expectationRetrieveExpectationsRequest.setQueryString("type=" + RetrieveType.ACTIVE_EXPECTATIONS.name()); mockServerServlet.service(expectationRetrieveExpectationsRequest, response); assertResponse(response, 200, expectationSerializer.serialize(Collections.singletonList( expectationOne ))); }
@Test public void shouldRetrieveLogMessages() { Level originalLevel = ConfigurationProperties.logLevel(); try { ConfigurationProperties.logLevel("INFO"); UUIDService.fixedUUID = true; Expectation expectationOne = new Expectation(request("request_one")).thenRespond(response("response_one")); httpStateHandler.add(expectationOne); MockHttpServletRequest retrieveLogRequest = buildHttpServletRequest( "PUT", "/mockserver/retrieve", httpRequestSerializer.serialize(request("request_one")) ); retrieveLogRequest.setQueryString("type=" + RetrieveType.LOGS.name()); mockServerServlet.service(retrieveLogRequest, response); assertThat(response.getStatus(), is(200)); assertThat(new String(response.getContentAsByteArray(), UTF_8), containsString("creating expectation:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"id\" : \"" + UUIDService.getUUID() + "\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"request_one\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"statusCode\" : 200," + NEW_LINE + " \"reasonPhrase\" : \"OK\"," + NEW_LINE + " \"body\" : \"response_one\"" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE)); } finally { UUIDService.fixedUUID = false; ConfigurationProperties.logLevel(originalLevel.name()); } }
@Test public void shouldUseActionHandlerToHandleNonAPIRequestsOnDefaultPort() { MockHttpServletRequest request = buildHttpServletRequest( "GET", "request_one", "" ); request.setLocalAddr("local_address"); request.setLocalPort(80); mockServerServlet.service(request, response); verify(mockActionHandler).processAction( eq( request("request_one") .withMethod("GET") .withHeader("Content-Type", APPLICATION_JSON_UTF_8.toString()) .withKeepAlive(true) .withSecure(false) ), any(ServletResponseWriter.class), isNull(), eq(ImmutableSet.of( "local_address", "localhost", "127.0.0.1" )), eq(false), eq(true)); }
@Test public void shouldUseActionHandlerToHandleNonAPIRequestsOnNonDefaultPort() { MockHttpServletRequest request = buildHttpServletRequest( "GET", "request_one", "" ); request.setLocalAddr("local_address"); request.setLocalPort(666); mockServerServlet.service(request, response); verify(mockActionHandler).processAction( eq( request("request_one") .withMethod("GET") .withHeader("Content-Type", APPLICATION_JSON_UTF_8.toString()) .withKeepAlive(true) .withSecure(false) ), any(ServletResponseWriter.class), isNull(), eq(ImmutableSet.of( "local_address:666", "localhost:666", "127.0.0.1:666" )), eq(false), eq(true)); }
@Test public void shouldUseActionHandlerToHandleNonAPISecureRequestsOnDefaultPort() { MockHttpServletRequest request = buildHttpServletRequest( "GET", "request_one", "" ); request.setSecure(true); request.setLocalAddr("local_address"); request.setLocalPort(443); mockServerServlet.service(request, response); verify(mockActionHandler).processAction( eq( request("request_one") .withMethod("GET") .withHeader("Content-Type", APPLICATION_JSON_UTF_8.toString()) .withKeepAlive(true) .withSecure(true) ), any(ServletResponseWriter.class), isNull(), eq(ImmutableSet.of( "local_address", "localhost", "127.0.0.1" )), eq(false), eq(true)); }
@Test public void shouldUseActionHandlerToHandleNonAPISecureRequestsOnNonDefaultPort() { MockHttpServletRequest request = buildHttpServletRequest( "GET", "request_one", "" ); request.setSecure(true); request.setLocalAddr("local_address"); request.setLocalPort(666); mockServerServlet.service(request, response); verify(mockActionHandler).processAction( eq( request("request_one") .withMethod("GET") .withHeader("Content-Type", APPLICATION_JSON_UTF_8.toString()) .withKeepAlive(true) .withSecure(true) ), any(ServletResponseWriter.class), isNull(), eq(ImmutableSet.of( "local_address:666", "localhost:666", "127.0.0.1:666" )), eq(false), eq(true)); } |
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(); } | @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)); } |
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); } | @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())); } |
RegexBodyDTO extends BodyDTO { public String getRegex() { return regex; } RegexBodyDTO(RegexBody regexBody); RegexBodyDTO(RegexBody regexBody, Boolean not); String getRegex(); RegexBody buildObject(); } | @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)); } |
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(); } | @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)); } |
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(); } | @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)); } |
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); } | @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)); } |
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); } | @Test public void shouldHandleNullObjectInput() { HttpTemplateDTO httpTemplateDTO = new HttpTemplateDTO(null); assertThat(httpTemplateDTO.getTemplate(), is(nullValue())); } |
CookieDTO extends KeyAndValueDTO implements DTO<Cookie> { public Cookie buildObject() { return new Cookie(getName(), getValue()); } CookieDTO(Cookie cookie); protected CookieDTO(); Cookie buildObject(); } | @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"))); } |
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(); } | @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)); } |
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); } | @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())); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.