Search in sources :

Example 36 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project okhttp by square.

the class ResponseCacheTest method assertConditionallyCached.

/** @return the request with the conditional get headers. */
private RecordedRequest assertConditionallyCached(MockResponse response) throws Exception {
    // scenario 1: condition succeeds
    server.enqueue(response.setBody("A").setStatus("HTTP/1.1 200 A-OK"));
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
    // scenario 2: condition fails
    server.enqueue(response.setBody("B").setStatus("HTTP/1.1 200 B-OK"));
    server.enqueue(new MockResponse().setStatus("HTTP/1.1 200 C-OK").setBody("C"));
    URL valid = server.url("/valid").url();
    HttpURLConnection connection1 = openConnection(valid);
    assertEquals("A", readAscii(connection1));
    assertEquals(HttpURLConnection.HTTP_OK, connection1.getResponseCode());
    assertEquals("A-OK", connection1.getResponseMessage());
    HttpURLConnection connection2 = openConnection(valid);
    assertEquals("A", readAscii(connection2));
    assertEquals(HttpURLConnection.HTTP_OK, connection2.getResponseCode());
    assertEquals("A-OK", connection2.getResponseMessage());
    URL invalid = server.url("/invalid").url();
    HttpURLConnection connection3 = openConnection(invalid);
    assertEquals("B", readAscii(connection3));
    assertEquals(HttpURLConnection.HTTP_OK, connection3.getResponseCode());
    assertEquals("B-OK", connection3.getResponseMessage());
    HttpURLConnection connection4 = openConnection(invalid);
    assertEquals("C", readAscii(connection4));
    assertEquals(HttpURLConnection.HTTP_OK, connection4.getResponseCode());
    assertEquals("C-OK", connection4.getResponseMessage());
    // regular get
    server.takeRequest();
    // conditional get
    return server.takeRequest();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) URL(java.net.URL)

Example 37 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project okhttp by square.

the class ResponseCacheTest method etagAndExpirationDateInThePast.

/** If both If-Modified-Since and If-None-Match conditions apply, send only If-None-Match. */
@Test
public void etagAndExpirationDateInThePast() throws Exception {
    String lastModifiedDate = formatDate(-2, TimeUnit.HOURS);
    RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse().addHeader("ETag: v1").addHeader("Last-Modified: " + lastModifiedDate).addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS)));
    assertEquals("v1", conditionalRequest.getHeader("If-None-Match"));
    assertNull(conditionalRequest.getHeader("If-Modified-Since"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Test(org.junit.Test)

Example 38 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project okhttp by square.

the class HttpOverHttp2Test method redirect.

@Test
public void redirect() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP).addHeader("Location: /foo").setBody("This page has moved!"));
    server.enqueue(new MockResponse().setBody("This is the new location!"));
    Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
    Response response = call.execute();
    assertEquals("This is the new location!", response.body().string());
    RecordedRequest request1 = server.takeRequest();
    assertEquals("/", request1.getPath());
    RecordedRequest request2 = server.takeRequest();
    assertEquals("/foo", request2.getPath());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Response(okhttp3.Response) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Call(okhttp3.Call) Request(okhttp3.Request) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 39 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project okhttp by square.

the class HttpOverHttp2Test method closeAfterFlush.

@Test
public void closeAfterFlush() throws Exception {
    final byte[] postBytes = "FGHIJ".getBytes(Util.UTF_8);
    server.enqueue(new MockResponse().setBody("ABCDE"));
    Call call = client.newCall(new Request.Builder().url(server.url("/foo")).post(new RequestBody() {

        @Override
        public MediaType contentType() {
            return MediaType.parse("text/plain; charset=utf-8");
        }

        @Override
        public long contentLength() throws IOException {
            return postBytes.length;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            // push bytes into the stream's buffer
            sink.write(postBytes);
            // Http2Connection.writeData subject to write window
            sink.flush();
            // Http2Connection.writeData empty frame
            sink.close();
        }
    }).build());
    Response response = call.execute();
    assertEquals("ABCDE", response.body().string());
    RecordedRequest request = server.takeRequest();
    assertEquals("POST /foo HTTP/1.1", request.getRequestLine());
    assertArrayEquals(postBytes, request.getBody().readByteArray());
    assertEquals(postBytes.length, Integer.parseInt(request.getHeader("Content-Length")));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Response(okhttp3.Response) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Call(okhttp3.Call) MediaType(okhttp3.MediaType) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

Example 40 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project okhttp by square.

the class HttpOverHttp2Test method concurrentHttp2ConnectionsDeduplicated.

/**
   * We don't know if the connection will support HTTP/2 until after we've connected. When multiple
   * connections are requested concurrently OkHttp will pessimistically connect multiple times, then
   * close any unnecessary connections. This test confirms that behavior works as intended.
   *
   * <p>This test uses proxy tunnels to get a hook while a connection is being established.
   */
@Test
public void concurrentHttp2ConnectionsDeduplicated() throws Exception {
    server.useHttps(sslClient.socketFactory, true);
    // Force a fresh connection pool for the test.
    client.connectionPool().evictAll();
    final QueueDispatcher queueDispatcher = new QueueDispatcher();
    queueDispatcher.enqueueResponse(new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders());
    queueDispatcher.enqueueResponse(new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders());
    queueDispatcher.enqueueResponse(new MockResponse().setBody("call2 response"));
    queueDispatcher.enqueueResponse(new MockResponse().setBody("call1 response"));
    // We use a re-entrant dispatcher to initiate one HTTPS connection while the other is in flight.
    server.setDispatcher(new Dispatcher() {

        int requestCount;

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            MockResponse result = queueDispatcher.dispatch(request);
            requestCount++;
            if (requestCount == 1) {
                // Before handling call1's CONNECT we do all of call2. This part re-entrant!
                try {
                    Call call2 = client.newCall(new Request.Builder().url("https://android.com/call2").build());
                    Response response2 = call2.execute();
                    assertEquals("call2 response", response2.body().string());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return result;
        }

        @Override
        public MockResponse peek() {
            return queueDispatcher.peek();
        }

        @Override
        public void shutdown() {
            queueDispatcher.shutdown();
        }
    });
    client = client.newBuilder().proxy(server.toProxyAddress()).build();
    Call call1 = client.newCall(new Request.Builder().url("https://android.com/call1").build());
    Response response2 = call1.execute();
    assertEquals("call1 response", response2.body().string());
    RecordedRequest call1Connect = server.takeRequest();
    assertEquals("CONNECT", call1Connect.getMethod());
    assertEquals(0, call1Connect.getSequenceNumber());
    RecordedRequest call2Connect = server.takeRequest();
    assertEquals("CONNECT", call2Connect.getMethod());
    assertEquals(0, call2Connect.getSequenceNumber());
    RecordedRequest call2Get = server.takeRequest();
    assertEquals("GET", call2Get.getMethod());
    assertEquals("/call2", call2Get.getPath());
    assertEquals(0, call2Get.getSequenceNumber());
    RecordedRequest call1Get = server.takeRequest();
    assertEquals("GET", call1Get.getMethod());
    assertEquals("/call1", call1Get.getPath());
    assertEquals(1, call1Get.getSequenceNumber());
    assertEquals(1, client.connectionPool().connectionCount());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Call(okhttp3.Call) Request(okhttp3.Request) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) QueueDispatcher(okhttp3.mockwebserver.QueueDispatcher) IOException(java.io.IOException) QueueDispatcher(okhttp3.mockwebserver.QueueDispatcher) Dispatcher(okhttp3.mockwebserver.Dispatcher) MockResponse(okhttp3.mockwebserver.MockResponse) Response(okhttp3.Response) Test(org.junit.Test)

Aggregations

RecordedRequest (okhttp3.mockwebserver.RecordedRequest)206 MockResponse (okhttp3.mockwebserver.MockResponse)188 Test (org.junit.Test)168 HttpURLConnection (java.net.HttpURLConnection)18 MockWebServer (okhttp3.mockwebserver.MockWebServer)14 IOException (java.io.IOException)13 URL (java.net.URL)13 OutputStream (java.io.OutputStream)12 Response (okhttp3.Response)12 OkHttpURLConnection (okhttp3.internal.huc.OkHttpURLConnection)12 AbstractTest (org.openstack4j.api.AbstractTest)12 Test (org.testng.annotations.Test)12 Call (okhttp3.Call)11 Buffer (okio.Buffer)11 Request (okhttp3.Request)8 RecordingOkAuthenticator (okhttp3.internal.RecordingOkAuthenticator)7 Dispatcher (okhttp3.mockwebserver.Dispatcher)6 ByteString (okio.ByteString)6 CookieManager (java.net.CookieManager)5 URLConnection (java.net.URLConnection)5