com.google.mockwebserver.MockResponse Java Examples
The following examples show how to use
com.google.mockwebserver.MockResponse.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * Test a bug where gzip input streams weren't exhausting the input stream, * which corrupted the request that followed. * http://code.google.com/p/android/issues/detail?id=7059 */ private void testClientConfiguredGzipContentEncodingAndConnectionReuse( TransferKind transferKind) throws Exception { MockResponse responseOne = new MockResponse(); responseOne.addHeader("Content-Encoding: gzip"); transferKind.setBody(responseOne, gzip("one (gzipped)".getBytes("UTF-8")), 5); server.enqueue(responseOne); MockResponse responseTwo = new MockResponse(); transferKind.setBody(responseTwo, "two (identity)", 5); server.enqueue(responseTwo); server.play(); URLConnection connection = server.getUrl("/").openConnection(); connection.addRequestProperty("Accept-Encoding", "gzip"); InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream()); assertEquals("one (gzipped)", readAscii(gunzippedIn, Integer.MAX_VALUE)); assertEquals(0, server.takeRequest().getSequenceNumber()); connection = server.getUrl("/").openConnection(); assertEquals("two (identity)", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); assertEquals(1, server.takeRequest().getSequenceNumber()); }
Example #2
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testReadTimeoutsOnRecycledConnections() throws Exception { server.enqueue(new MockResponse().setBody("ABC")); server.play(); // The request should work once and then fail URLConnection connection = server.getUrl("").openConnection(); // Read timeout of a day, sure to cause the test to timeout and fail. connection.setReadTimeout(24 * 3600 * 1000); InputStream input = connection.getInputStream(); assertEquals("ABC", readAscii(input, Integer.MAX_VALUE)); input.close(); try { connection = server.getUrl("").openConnection(); // Set the read timeout back to 100ms, this request will time out // because we've only enqueued one response. connection.setReadTimeout(100); connection.getInputStream(); fail(); } catch (IOException expected) { } }
Example #3
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * We explicitly permit apps to close the upload stream even after it has * been transmitted. We also permit flush so that buffered streams can * do a no-op flush when they are closed. http://b/3038470 */ private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws IOException { server.enqueue(new MockResponse().setBody("abc")); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); connection.setDoOutput(true); byte[] upload = "def".getBytes("UTF-8"); if (transferKind == TransferKind.CHUNKED) { connection.setChunkedStreamingMode(0); } else if (transferKind == TransferKind.FIXED_LENGTH) { connection.setFixedLengthStreamingMode(upload.length); } OutputStream out = connection.getOutputStream(); out.write(upload); assertEquals("abc", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); out.flush(); // dubious but permitted try { out.write("ghi".getBytes("UTF-8")); fail(); } catch (IOException expected) { } }
Example #4
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testConnectionCloseWithRedirect() throws IOException, InterruptedException { MockResponse response = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: /foo") .addHeader("Connection: close"); server.enqueue(response); server.enqueue(new MockResponse().setBody("This is the new location!")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); assertEquals("This is the new location!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals("When connection: close is used, each request should get its own connection", 0, server.takeRequest().getSequenceNumber()); }
Example #5
Source File: HttpExecutorImplTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
private void assertRequestAndResponse(RecordedRequest serverRequest, MockResponse serverResponse, HttpRequest executorRequest, HttpResponse executorResponse) throws Exception { assertEquals(serverRequest.getMethod(), executorRequest.method()); Function<Map.Entry<String, String>, String> headersMapper = new Function<Map.Entry<String, String>, String>() { @Nullable @Override public String apply(@Nullable Map.Entry<String, String> input) { return input.getKey() + ": " + input.getValue(); } }; assertTrue(serverRequest.getHeaders().containsAll(Collections2.transform(executorRequest.headers().entries(), headersMapper))); assertEquals(serverRequest.getPath(), executorRequest.uri().getPath()); if (executorRequest.body() != null) { assertEquals(serverRequest.getBody(), executorRequest.body()); } else { assertEquals(serverRequest.getBody(), new byte[0]); } assertEquals(serverResponse.getBody(), ByteStreams.toByteArray(executorResponse.getContent())); assertTrue(serverResponse.getHeaders().containsAll(Collections2.transform(executorResponse.headers().entries(), headersMapper))); assertTrue(Collections2.transform(executorResponse.headers().entries(), headersMapper).containsAll(serverResponse.getHeaders())); }
Example #6
Source File: HttpExecutorImplTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test public void testHttpDeleteRequest() throws Exception { MockResponse serverResponse = new MockResponse().setResponseCode(200).addHeader(HTTP_RESPONSE_HEADER_KEY, HTTP_RESPONSE_HEADER_VALUE).setBody(HTTP_BODY); server.enqueue(serverResponse); HttpExecutor executor = factory.getHttpExecutor(getProps()); HttpRequest executorRequest = new HttpRequest.Builder() .method("DELETE") .uri(baseUrl.toURI()) .build(); HttpResponse executorResponse = executor.execute(executorRequest); assertRequestAndResponse(server.takeRequest(), serverResponse, executorRequest, executorResponse); // No Headers returned serverResponse = new MockResponse().setResponseCode(200).setBody(HTTP_BODY); server.enqueue(serverResponse); executor = factory.getHttpExecutor(getProps()); executorRequest = new HttpRequest.Builder() .method("DELETE") .uri(baseUrl.toURI()) .build(); executorResponse = executor.execute(executorRequest); assertRequestAndResponse(server.takeRequest(), serverResponse, executorRequest, executorResponse); }
Example #7
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 6 votes |
private void testResponseRedirectedWithPost(int redirectCode) throws Exception { server.enqueue(new MockResponse() .setResponseCode(redirectCode) .addHeader("Location: /page2") .setBody("This page has moved!")); server.enqueue(new MockResponse().setBody("Page 2")); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/page1").openConnection(); connection.setDoOutput(true); byte[] requestBody = { 'A', 'B', 'C', 'D' }; OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestBody); outputStream.close(); assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); assertTrue(connection.getDoOutput()); RecordedRequest page1 = server.takeRequest(); assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine()); assertEquals(Arrays.toString(requestBody), Arrays.toString(page1.getBody())); RecordedRequest page2 = server.takeRequest(); assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine()); }
Example #8
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 6 votes |
private void testRedirected(TransferKind transferKind, boolean reuse) throws Exception { MockResponse response = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: /foo"); transferKind.setBody(response, "This page has moved!", 10); server.enqueue(response); server.enqueue(new MockResponse().setBody("This is the new location!")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); assertEquals("This is the new location!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); RecordedRequest first = server.takeRequest(); assertEquals("GET / HTTP/1.1", first.getRequestLine()); RecordedRequest retry = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", retry.getRequestLine()); if (reuse) { assertEquals("Expected connection reuse", 1, retry.getSequenceNumber()); } }
Example #9
Source File: HttpFeedTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test public void testUsesExceptionHandlerOn4xxAndNoFailureHandler() throws Exception { if (server != null) server.shutdown(); server = BetterMockWebServer.newInstanceLocalhost(); for (int i = 0; i < 100; i++) { server.enqueue(new MockResponse() .setResponseCode(401) .setBody("Unauthorised")); } server.play(); feed = HttpFeed.builder() .entity(entity) .baseUrl(server.getUrl("/")) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode()) .onException(Functions.constant(-1))) .build(); assertSensorEventually(SENSOR_INT, -1, TIMEOUT_MS); server.shutdown(); }
Example #10
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testMissingChunkBody() throws IOException { server.enqueue(new MockResponse() .setBody("5") .clearHeaders() .addHeader("Transfer-encoding: chunked") .setSocketPolicy(DISCONNECT_AT_END)); server.play(); URLConnection connection = server.getUrl("/").openConnection(); // j2objc: See testNonHexChunkSize() above for why the timeout is needed. connection.setReadTimeout(1000); try { readAscii(connection.getInputStream(), Integer.MAX_VALUE); fail(); } catch (IOException e) { } }
Example #11
Source File: HttpFeedTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test public void testSetsConnectionTimeoutWhenServerDisconnects() throws Exception { if (server != null) server.shutdown(); server = BetterMockWebServer.newInstanceLocalhost(); for (int i = 0; i < 100; i++) { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); } server.play(); baseUrl = server.getUrl("/"); feed = HttpFeed.builder() .entity(entity) .baseUrl(baseUrl) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .connectionTimeout(Duration.TEN_SECONDS) .socketTimeout(Duration.TEN_SECONDS) .onSuccess(HttpValueFunctions.responseCode()) .onException(Functions.constant(-1))) .build(); assertSensorEventually(SENSOR_INT, -1, TIMEOUT_MS); }
Example #12
Source File: RebindEnricherTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test public void testHttpLatencyDetectorEnricher() throws Exception { webServer = BetterMockWebServer.newInstanceLocalhost(); for (int i = 0; i < 1000; i++) { webServer.enqueue(new MockResponse().setResponseCode(200).addHeader("content-type: application/json").setBody("{\"foo\":\"myfoo\"}")); } webServer.play(); URL baseUrl = webServer.getUrl("/"); origApp.enrichers().add(HttpLatencyDetector.builder() .rollup(Duration.of(50, TimeUnit.MILLISECONDS)) .period(Duration.of(10, TimeUnit.MILLISECONDS)) .url(baseUrl) .buildSpec()); origApp.sensors().set(Attributes.SERVICE_UP, true); TestApplication newApp = rebind(); newApp.sensors().set(HttpLatencyDetector.REQUEST_LATENCY_IN_SECONDS_MOST_RECENT, null); newApp.sensors().set(HttpLatencyDetector.REQUEST_LATENCY_IN_SECONDS_IN_WINDOW, null); EntityAsserts.assertAttributeEventuallyNonNull(newApp, HttpLatencyDetector.REQUEST_LATENCY_IN_SECONDS_MOST_RECENT); EntityAsserts.assertAttributeEventuallyNonNull(newApp, HttpLatencyDetector.REQUEST_LATENCY_IN_SECONDS_IN_WINDOW); }
Example #13
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 6 votes |
private void testMarkAndReset(TransferKind transferKind) throws IOException { MockResponse response = new MockResponse(); transferKind.setBody(response, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1024); server.enqueue(response); server.enqueue(response); server.play(); InputStream in = server.getUrl("/").openConnection().getInputStream(); assertFalse("This implementation claims to support mark().", in.markSupported()); in.mark(5); assertEquals("ABCDE", readAscii(in, 5)); try { in.reset(); fail(); } catch (IOException expected) { } assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE)); assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", server.getUrl("/").openConnection()); }
Example #14
Source File: ListenerTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testSuccessExecutionOnAbosoluteURI() throws IOException { MockWebServer server = new MockWebServer(); String content = "OK"; server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json") .setBody(content)); server.play(); IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "2000") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://localhost:" + server.getPort() + "/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + server.getPort()); List<Server> servers = Lists.newArrayList(goodServer, badServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.ConnectTimeout, 500); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); HttpClientResponse<ByteBuf> response = client.submit(request, null, overrideConfig).toBlocking().last(); assertEquals(200, response.getStatus().code()); assertEquals(1, listener.executionStartCounter.get()); assertEquals(1, listener.startWithServerCounter.get()); assertEquals(0, listener.exceptionWithServerCounter.get()); assertEquals(0, listener.executionFailedCounter.get()); assertEquals(1, listener.executionSuccessCounter.get()); assertEquals(500, listener.getContext().getClientProperty(CommonClientConfigKey.ConnectTimeout).intValue()); assertTrue(listener.isContextChecked()); assertTrue(listener.isCheckExecutionInfo()); assertSame(response, listener.getResponse()); }
Example #15
Source File: AbstractCookiesTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testRfc2109Response() throws Exception { CookieManager cookieManager = new CookieManager(createCookieStore(), ACCEPT_ORIGINAL_SERVER); CookieHandler.setDefault(cookieManager); server.play(); server.enqueue(new MockResponse().addHeader("Set-Cookie: a=android; " + "Comment=this cookie is delicious; " + "Domain=" + server.getCookieDomain() + "; " + "Max-Age=60; " + "Path=/path; " + "Secure; " + "Version=1")); get(server, "/path/foo"); List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); assertEquals(1, cookies.size()); HttpCookie cookie = cookies.get(0); assertEquals("a", cookie.getName()); assertEquals("android", cookie.getValue()); assertEquals("this cookie is delicious", cookie.getComment()); assertEquals(null, cookie.getCommentURL()); assertEquals(false, cookie.getDiscard()); assertEquals(server.getCookieDomain(), cookie.getDomain()); assertEquals(60, cookie.getMaxAge()); assertEquals("/path", cookie.getPath()); assertEquals(true, cookie.getSecure()); assertEquals(1, cookie.getVersion()); }
Example #16
Source File: ServerListRefreshTest.java From ribbon with Apache License 2.0 | 5 votes |
/** * This test ensures that when server list is refreshed in the load balancer, the set of servers * which equals to (oldList - newList) should be removed from the map of cached RxClient. Any server * that is not part of oldList should stay in the map. * * @throws IOException */ @Test public void testServerListRefresh() throws IOException { String content = "Hello world"; MockWebServer server1 = new MockWebServer(); MockWebServer server2 = new MockWebServer(); MockWebServer server3 = new MockWebServer(); MockResponse mockResponse = new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain") .setBody(content); server1.enqueue(mockResponse); server2.enqueue(mockResponse); server3.enqueue(mockResponse); server1.play(); server2.play(); server3.play(); try { BaseLoadBalancer lb = new BaseLoadBalancer(); List<Server> initialList = Lists.newArrayList(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort())); lb.setServersList(initialList); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/"); client.submit(request).toBlocking().last(); client.submit(request).toBlocking().last(); HttpClientRequest<ByteBuf> request2 = HttpClientRequest.createGet("http://localhost:" + server3.getPort()); client.submit(request2).toBlocking().last(); Set<Server> cachedServers = client.getRxClients().keySet(); assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort()), new Server("localhost", server3.getPort())), cachedServers); List<Server> newList = Lists.newArrayList(new Server("localhost", server1.getPort()), new Server("localhost", 99999)); lb.setServersList(newList); cachedServers = client.getRxClients().keySet(); assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server3.getPort())), cachedServers); } finally { server1.shutdown(); server2.shutdown(); server3.shutdown(); } }
Example #17
Source File: RibbonTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testCacheMiss() throws IOException, InterruptedException { MockWebServer server = new MockWebServer(); String content = "Hello world"; server.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody(content)); server.play(); HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create() .withConfigurationBasedServerList("localhost:" + server.getPort()) .withMaxAutoRetriesNextServer(1)); final String cacheKey = "somekey"; HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test") .withCacheProvider(cacheKey, new CacheProvider<ByteBuf>(){ @Override public Observable<ByteBuf> get(String key, Map<String, Object> vars) { return Observable.error(new Exception("Cache miss again")); } }) .withMethod("GET") .withUriTemplate("/").build(); RibbonRequest<ByteBuf> request = template .requestBuilder().build(); String result = toStringBlocking(request); assertEquals(content, result); }
Example #18
Source File: DiscoveryEnabledServerListTest.java From ribbon with Apache License 2.0 | 5 votes |
@BeforeClass public static void init() throws IOException { server = new MockWebServer(); String content = "Hello world"; MockResponse response = new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain") .setBody(content); server.enqueue(response); server.play(); }
Example #19
Source File: FollowRedirectTest.java From ribbon with Apache License 2.0 | 5 votes |
@Before public void setup() throws IOException { redirectedServer = new MockWebServer(); redirectedServer.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody("OK")); redirectingServer = new MockWebServer(); redirectedServer.play(); redirectingServer.enqueue(new MockResponse() .setResponseCode(302) .setHeader("Location", "http://localhost:" + redirectedServer.getPort())); redirectingServer.play(); }
Example #20
Source File: AbstractCookiesTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testQuotedAttributeValues() throws Exception { CookieManager cookieManager = new CookieManager(createCookieStore(), ACCEPT_ORIGINAL_SERVER); CookieHandler.setDefault(cookieManager); server.play(); server.enqueue(new MockResponse().addHeader("Set-Cookie2: a=\"android\"; " + "Comment=\"this cookie is delicious\"; " + "CommentURL=\"http://google.com/\"; " + "Discard; " + "Domain=\"" + server.getCookieDomain() + "\"; " + "Max-Age=\"60\"; " + "Path=\"/path\"; " + "Port=\"80,443," + server.getPort() + "\"; " + "Secure; " + "Version=\"1\"")); get(server, "/path/foo"); List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); assertEquals(1, cookies.size()); HttpCookie cookie = cookies.get(0); assertEquals("a", cookie.getName()); assertEquals("android", cookie.getValue()); assertEquals("this cookie is delicious", cookie.getComment()); assertEquals("http://google.com/", cookie.getCommentURL()); assertEquals(true, cookie.getDiscard()); assertEquals(server.getCookieDomain(), cookie.getDomain()); assertEquals(60, cookie.getMaxAge()); assertEquals("/path", cookie.getPath()); assertEquals("80,443," + server.getPort(), cookie.getPortlist()); assertEquals(true, cookie.getSecure()); assertEquals(1, cookie.getVersion()); }
Example #21
Source File: AbstractCookiesTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testRfc2965Response() throws Exception { CookieManager cookieManager = new CookieManager(createCookieStore(), ACCEPT_ORIGINAL_SERVER); CookieHandler.setDefault(cookieManager); server.play(); server.enqueue(new MockResponse().addHeader("Set-Cookie2: a=android; " + "Comment=this cookie is delicious; " + "CommentURL=http://google.com/; " + "Discard; " + "Domain=" + server.getCookieDomain() + "; " + "Max-Age=60; " + "Path=/path; " + "Port=\"80,443," + server.getPort() + "\"; " + "Secure; " + "Version=1")); get(server, "/path/foo"); List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); assertEquals(1, cookies.size()); HttpCookie cookie = cookies.get(0); assertEquals("a", cookie.getName()); assertEquals("android", cookie.getValue()); assertEquals("this cookie is delicious", cookie.getComment()); assertEquals("http://google.com/", cookie.getCommentURL()); assertEquals(true, cookie.getDiscard()); assertEquals(server.getCookieDomain(), cookie.getDomain()); assertEquals(60, cookie.getMaxAge()); assertEquals("/path", cookie.getPath()); assertEquals("80,443," + server.getPort(), cookie.getPortlist()); assertEquals(true, cookie.getSecure()); assertEquals(1, cookie.getVersion()); }
Example #22
Source File: RibbonTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testCommand() throws IOException, InterruptedException, ExecutionException { MockWebServer server = new MockWebServer(); String content = "Hello world"; MockResponse response = new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody(content); server.enqueue(response); server.enqueue(response); server.enqueue(response); server.play(); HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create() .withMaxAutoRetriesNextServer(3) .withReadTimeout(300000) .withConfigurationBasedServerList("localhost:12345, localhost:10092, localhost:" + server.getPort())); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class) .withUriTemplate("/") .withMethod("GET") .build(); RibbonRequest<ByteBuf> request = template.requestBuilder().build(); String result = request.execute().toString(Charset.defaultCharset()); assertEquals(content, result); // repeat the same request ByteBuf raw = request.execute(); result = raw.toString(Charset.defaultCharset()); raw.release(); assertEquals(content, result); result = request.queue().get().toString(Charset.defaultCharset()); assertEquals(content, result); }
Example #23
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testLastModified() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified", "Wed, 27 Nov 2013 11:26:00 GMT") .setBody("Hello")); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); connection.connect(); assertEquals(1385551560000L, connection.getLastModified()); assertEquals(1385551560000L, connection.getHeaderFieldDate("Last-Modified", -1)); }
Example #24
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * http://code.google.com/p/android/issues/detail?id=14562 */ public void testReadAfterLastByte() throws Exception { server.enqueue(new MockResponse() .setBody("ABC") .clearHeaders() .addHeader("Connection: close") .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); InputStream in = connection.getInputStream(); assertEquals("ABC", readAscii(in, 3)); assertEquals(-1, in.read()); assertEquals(-1, in.read()); // throws IOException in Gingerbread }
Example #25
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testSingleByteReadIsSigned() throws IOException { server.enqueue(new MockResponse().setBody(new byte[] { -2, -1 })); server.play(); URLConnection connection = server.getUrl("/").openConnection(); InputStream in = connection.getInputStream(); assertEquals(254, in.read()); assertEquals(255, in.read()); assertEquals(-1, in.read()); }
Example #26
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testCannotSetFixedLengthStreamingModeAfterConnect() throws Exception { server.enqueue(new MockResponse().setBody("A")); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); try { connection.setFixedLengthStreamingMode(1); fail(); } catch (IllegalStateException expected) { } }
Example #27
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testConnectionCloseInResponse() throws IOException, InterruptedException { server.enqueue(new MockResponse().addHeader("Connection: close")); server.enqueue(new MockResponse()); server.play(); HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals(200, a.getResponseCode()); HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals(200, b.getResponseCode()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals("When connection: close is used, each request should get its own connection", 0, server.takeRequest().getSequenceNumber()); }
Example #28
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testRedirectToAnotherOriginServer() throws Exception { MockWebServer server2 = new MockWebServer(); server2.enqueue(new MockResponse().setBody("This is the 2nd server!")); server2.play(); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: " + server2.getUrl("/").toString()) .setBody("This page has moved!")); server.enqueue(new MockResponse().setBody("This is the first server again!")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); assertEquals("This is the 2nd server!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); assertEquals(server2.getUrl("/"), connection.getURL()); // make sure the first server was careful to recycle the connection assertEquals("This is the first server again!", readAscii(server.getUrl("/").openStream(), Integer.MAX_VALUE)); RecordedRequest first = server.takeRequest(); assertContains(first.getHeaders(), "Host: " + hostName + ":" + server.getPort()); RecordedRequest second = server2.takeRequest(); assertContains(second.getHeaders(), "Host: " + hostName + ":" + server2.getPort()); RecordedRequest third = server.takeRequest(); // assertEquals("Expected connection reuse", 1, third.getSequenceNumber()); // JVM failure server2.shutdown(); }
Example #29
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testNotRedirectedFromHttpToHttps() throws IOException, InterruptedException { server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: https://anyhost/foo") .setBody("This page has moved!")); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals("This page has moved!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); }
Example #30
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testCannotSetChunkedStreamingModeAfterConnect() throws Exception { server.enqueue(new MockResponse().setBody("A")); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); try { connection.setChunkedStreamingMode(1); fail(); } catch (IllegalStateException expected) { } }