Search in sources :

Example 31 with MockResponse

use of mockwebserver3.MockResponse in project okhttp by square.

the class CacheTest method assertCached.

private void assertCached(boolean shouldPut, int responseCode) throws Exception {
    int expectedResponseCode = responseCode;
    server = new MockWebServer();
    MockResponse mockResponse = new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setResponseCode(responseCode).setBody("ABCDE").addHeader("WWW-Authenticate: challenge");
    if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
        mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
    } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
    } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT || responseCode == HttpURLConnection.HTTP_RESET) {
        // We forbid bodies for 204 and 205.
        mockResponse.setBody("");
    }
    server.enqueue(mockResponse);
    if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
        // 408's are a bit of an outlier because we may repeat the request if we encounter this
        // response code. In this scenario, there are 2 responses: the initial 408 and then the 200
        // because of the retry. We just want to ensure the initial 408 isn't cached.
        expectedResponseCode = 200;
        server.enqueue(new MockResponse().setHeader("Cache-Control", "no-store").setBody("FGHIJ"));
    }
    server.start();
    Request request = new Request.Builder().url(server.url("/")).build();
    Response response = client.newCall(request).execute();
    assertThat(response.code()).isEqualTo(expectedResponseCode);
    // Exhaust the content stream.
    response.body().string();
    Response cached = cacheGet(cache, request);
    if (shouldPut) {
        assertThat(cached).isNotNull();
        cached.body().close();
    } else {
        assertThat(cached).isNull();
    }
    // tearDown() isn't sufficient; this test starts multiple servers
    server.shutdown();
}
Also used : MockResponse(mockwebserver3.MockResponse) MockResponse(mockwebserver3.MockResponse) MockWebServer(mockwebserver3.MockWebServer) RecordedRequest(mockwebserver3.RecordedRequest)

Example 32 with MockResponse

use of mockwebserver3.MockResponse in project okhttp by square.

the class CacheTest method secureResponseCachingAndProtocolRedirects.

/**
 * We've had bugs where caching and cross-protocol redirects yield class cast exceptions internal
 * to the cache because we incorrectly assumed that HttpsURLConnection was always HTTPS and
 * HttpURLConnection was always HTTP; in practice redirects mean that each can do either.
 *
 * https://github.com/square/okhttp/issues/214
 */
@Test
public void secureResponseCachingAndProtocolRedirects() throws IOException {
    server2.useHttps(handshakeCertificates.sslSocketFactory(), false);
    server2.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setBody("ABC"));
    server2.enqueue(new MockResponse().setBody("DEF"));
    server.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setResponseCode(HttpURLConnection.HTTP_MOVED_PERM).addHeader("Location: " + server2.url("/")));
    client = client.newBuilder().sslSocketFactory(handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager()).hostnameVerifier(NULL_HOSTNAME_VERIFIER).build();
    Response response1 = get(server.url("/"));
    assertThat(response1.body().string()).isEqualTo("ABC");
    // Cached!
    Response response2 = get(server.url("/"));
    assertThat(response2.body().string()).isEqualTo("ABC");
    // 2 direct + 2 redirect = 4
    assertThat(cache.requestCount()).isEqualTo(4);
    assertThat(cache.hitCount()).isEqualTo(2);
}
Also used : MockResponse(mockwebserver3.MockResponse) MockResponse(mockwebserver3.MockResponse) Test(org.junit.jupiter.api.Test)

Example 33 with MockResponse

use of mockwebserver3.MockResponse in project okhttp by square.

the class CacheTest method varyMatchesChangedRequestHeaderField.

@Test
public void varyMatchesChangedRequestHeaderField() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: Accept-Language").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    HttpUrl url = server.url("/");
    Request frRequest = new Request.Builder().url(url).header("Accept-Language", "fr-CA").build();
    Response frResponse = client.newCall(frRequest).execute();
    assertThat(frResponse.body().string()).isEqualTo("A");
    Request enRequest = new Request.Builder().url(url).header("Accept-Language", "en-US").build();
    Response enResponse = client.newCall(enRequest).execute();
    assertThat(enResponse.body().string()).isEqualTo("B");
}
Also used : MockResponse(mockwebserver3.MockResponse) MockResponse(mockwebserver3.MockResponse) RecordedRequest(mockwebserver3.RecordedRequest) Test(org.junit.jupiter.api.Test)

Example 34 with MockResponse

use of mockwebserver3.MockResponse in project okhttp by square.

the class CacheTest method conditionalHitUpdatesCache.

@Test
public void conditionalHitUpdatesCache() throws Exception {
    server.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(0, TimeUnit.SECONDS)).addHeader("Cache-Control: max-age=0").setBody("A"));
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=30").addHeader("Allow: GET, HEAD").setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
    server.enqueue(new MockResponse().setBody("B"));
    // A cache miss writes the cache.
    long t0 = System.currentTimeMillis();
    Response response1 = get(server.url("/a"));
    assertThat(response1.body().string()).isEqualTo("A");
    assertThat(response1.header("Allow")).isNull();
    assertThat((double) (response1.receivedResponseAtMillis() - t0)).isCloseTo(0, offset(250.0));
    // A conditional cache hit updates the cache.
    // Make sure t0 and t1 are distinct.
    Thread.sleep(500);
    long t1 = System.currentTimeMillis();
    Response response2 = get(server.url("/a"));
    assertThat(response2.code()).isEqualTo(HttpURLConnection.HTTP_OK);
    assertThat(response2.body().string()).isEqualTo("A");
    assertThat(response2.header("Allow")).isEqualTo("GET, HEAD");
    Long updatedTimestamp = response2.receivedResponseAtMillis();
    assertThat((double) (updatedTimestamp - t1)).isCloseTo(0, offset(250.0));
    // A full cache hit reads the cache.
    Thread.sleep(10);
    Response response3 = get(server.url("/a"));
    assertThat(response3.body().string()).isEqualTo("A");
    assertThat(response3.header("Allow")).isEqualTo("GET, HEAD");
    assertThat(response3.receivedResponseAtMillis()).isEqualTo(updatedTimestamp);
    assertThat(server.getRequestCount()).isEqualTo(2);
}
Also used : MockResponse(mockwebserver3.MockResponse) MockResponse(mockwebserver3.MockResponse) Test(org.junit.jupiter.api.Test)

Example 35 with MockResponse

use of mockwebserver3.MockResponse in project okhttp by square.

the class CacheTest method cachedRedirect.

/**
 * https://github.com/square/okhttp/issues/2198
 */
@Test
public void cachedRedirect() throws IOException {
    server.enqueue(new MockResponse().setResponseCode(301).addHeader("Cache-Control: max-age=60").addHeader("Location: /bar"));
    server.enqueue(new MockResponse().setBody("ABC"));
    server.enqueue(new MockResponse().setBody("ABC"));
    Request request1 = new Request.Builder().url(server.url("/")).build();
    Response response1 = client.newCall(request1).execute();
    assertThat(response1.body().string()).isEqualTo("ABC");
    Request request2 = new Request.Builder().url(server.url("/")).build();
    Response response2 = client.newCall(request2).execute();
    assertThat(response2.body().string()).isEqualTo("ABC");
}
Also used : MockResponse(mockwebserver3.MockResponse) MockResponse(mockwebserver3.MockResponse) RecordedRequest(mockwebserver3.RecordedRequest) Test(org.junit.jupiter.api.Test)

Aggregations

MockResponse (mockwebserver3.MockResponse)283 Test (org.junit.jupiter.api.Test)261 RecordedRequest (mockwebserver3.RecordedRequest)79 IOException (java.io.IOException)41 Response (okhttp3.Response)39 BufferedSink (okio.BufferedSink)28 WebSocket (okhttp3.WebSocket)27 AtomicReference (java.util.concurrent.atomic.AtomicReference)22 MockWebServer (mockwebserver3.MockWebServer)22 Request (okhttp3.Request)21 Buffer (okio.Buffer)21 InetAddress (java.net.InetAddress)20 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)17 Assertions.fail (org.junit.jupiter.api.Assertions.fail)17 BeforeEach (org.junit.jupiter.api.BeforeEach)17 Tag (org.junit.jupiter.api.Tag)17 RegisterExtension (org.junit.jupiter.api.extension.RegisterExtension)17 SocketTimeoutException (java.net.SocketTimeoutException)15 Duration (java.time.Duration)15 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)15