Search in sources :

Example 1 with RecordingEventListener

use of okhttp3.RecordingEventListener in project okhttp by square.

the class EventListenerTest method assertBytesReadWritten.

private void assertBytesReadWritten(RecordingEventListener listener, @Nullable Matcher<Long> requestHeaderLength, @Nullable Matcher<Long> requestBodyBytes, @Nullable Matcher<Long> responseHeaderLength, @Nullable Matcher<Long> responseBodyBytes) {
    if (requestHeaderLength != null) {
        RequestHeadersEnd responseHeadersEnd = listener.removeUpToEvent(RequestHeadersEnd.class);
        MatcherAssert.assertThat("request header length", responseHeadersEnd.getHeaderLength(), requestHeaderLength);
    } else {
        assertThat(listener.recordedEventTypes()).doesNotContain("RequestHeadersEnd");
    }
    if (requestBodyBytes != null) {
        RequestBodyEnd responseBodyEnd = listener.removeUpToEvent(RequestBodyEnd.class);
        MatcherAssert.assertThat("request body bytes", responseBodyEnd.getBytesWritten(), requestBodyBytes);
    } else {
        assertThat(listener.recordedEventTypes()).doesNotContain("RequestBodyEnd");
    }
    if (responseHeaderLength != null) {
        ResponseHeadersEnd responseHeadersEnd = listener.removeUpToEvent(ResponseHeadersEnd.class);
        MatcherAssert.assertThat("response header length", responseHeadersEnd.getHeaderLength(), responseHeaderLength);
    } else {
        assertThat(listener.recordedEventTypes()).doesNotContain("ResponseHeadersEnd");
    }
    if (responseBodyBytes != null) {
        ResponseBodyEnd responseBodyEnd = listener.removeUpToEvent(ResponseBodyEnd.class);
        MatcherAssert.assertThat("response body bytes", responseBodyEnd.getBytesRead(), responseBodyBytes);
    } else {
        assertThat(listener.recordedEventTypes()).doesNotContain("ResponseBodyEnd");
    }
}
Also used : RequestBodyEnd(okhttp3.CallEvent.RequestBodyEnd) ResponseHeadersEnd(okhttp3.CallEvent.ResponseHeadersEnd) RequestHeadersEnd(okhttp3.CallEvent.RequestHeadersEnd) ResponseBodyEnd(okhttp3.CallEvent.ResponseBodyEnd)

Example 2 with RecordingEventListener

use of okhttp3.RecordingEventListener in project okhttp by square.

the class WebSocketHttpTest method webSocketsDontTriggerEventListener.

@Test
public void webSocketsDontTriggerEventListener() {
    RecordingEventListener listener = new RecordingEventListener();
    client = client.newBuilder().eventListenerFactory(clientTestRule.wrap(listener)).build();
    webServer.enqueue(new MockResponse().withWebSocketUpgrade(serverListener));
    WebSocket webSocket = newWebSocket();
    clientListener.assertOpen();
    WebSocket server = serverListener.assertOpen();
    webSocket.send("Web Sockets and Events?!");
    serverListener.assertTextMessage("Web Sockets and Events?!");
    webSocket.close(1000, "");
    serverListener.assertClosing(1000, "");
    server.close(1000, "");
    clientListener.assertClosing(1000, "");
    clientListener.assertClosed(1000, "");
    serverListener.assertClosed(1000, "");
    assertThat(listener.recordedEventTypes()).isEmpty();
}
Also used : MockResponse(mockwebserver3.MockResponse) RecordingEventListener(okhttp3.RecordingEventListener) WebSocket(okhttp3.WebSocket) Test(org.junit.jupiter.api.Test)

Example 3 with RecordingEventListener

use of okhttp3.RecordingEventListener in project okhttp by square.

the class DuplexTest method duplexWithRedirect.

/**
 * Duplex calls that have follow-ups are weird. By the time we know there's a follow-up we've
 * already split off another thread to stream the request body. Because we permit at most one
 * exchange at a time we break the request stream out from under that writer.
 */
@Test
public void duplexWithRedirect() throws Exception {
    enableProtocol(Protocol.HTTP_2);
    CountDownLatch duplexResponseSent = new CountDownLatch(1);
    listener = new RecordingEventListener() {

        @Override
        public void responseHeadersEnd(Call call, Response response) {
            try {
                // Wait for the server to send the duplex response before acting on the 301 response
                // and resetting the stream.
                duplexResponseSent.await();
            } catch (InterruptedException e) {
                throw new AssertionError();
            }
            super.responseHeadersEnd(call, response);
        }
    };
    client = client.newBuilder().eventListener(listener).build();
    MockDuplexResponseBody mockDuplexResponseBody = enqueueResponseWithBody(new MockResponse().clearHeaders().setResponseCode(HttpURLConnection.HTTP_MOVED_PERM).addHeader("Location: /b"), new MockDuplexResponseBody().sendResponse("/a has moved!\n", duplexResponseSent).requestIOException().exhaustResponse());
    server.enqueue(new MockResponse().setBody("this is /b"));
    Call call = client.newCall(new Request.Builder().url(server.url("/")).post(new AsyncRequestBody()).build());
    try (Response response = call.execute()) {
        BufferedSource responseBody = response.body().source();
        assertThat(responseBody.readUtf8Line()).isEqualTo("this is /b");
    }
    BufferedSink requestBody = ((AsyncRequestBody) call.request().body()).takeSink();
    try {
        requestBody.writeUtf8("request body\n");
        requestBody.flush();
        fail();
    } catch (IOException expected) {
        assertThat(expected.getMessage()).isEqualTo("stream was reset: CANCEL");
    }
    mockDuplexResponseBody.awaitSuccess();
    assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "ProxySelectStart", "ProxySelectEnd", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd", "RequestFailed");
}
Also used : MockResponse(mockwebserver3.MockResponse) AsyncRequestBody(okhttp3.internal.duplex.AsyncRequestBody) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) MockResponse(mockwebserver3.MockResponse) MockDuplexResponseBody(mockwebserver3.internal.duplex.MockDuplexResponseBody) BufferedSource(okio.BufferedSource) Test(org.junit.jupiter.api.Test)

Example 4 with RecordingEventListener

use of okhttp3.RecordingEventListener in project okhttp by square.

the class ClientAuthTest method invalidClientAuthEvents.

@Test
public void invalidClientAuthEvents() throws Throwable {
    server.enqueue(new MockResponse().setBody("abc"));
    clientCert = new HeldCertificate.Builder().signedBy(clientIntermediateCa).serialNumber(4L).commonName("Jethro Willis").addSubjectAlternativeName("jethrowillis.com").validityInterval(1, 2).build();
    OkHttpClient client = buildClient(clientCert, clientIntermediateCa.certificate());
    RecordingEventListener listener = new RecordingEventListener();
    client = client.newBuilder().eventListener(listener).build();
    SSLSocketFactory socketFactory = buildServerSslSocketFactory();
    server.useHttps(socketFactory, false);
    server.requireClientAuth();
    Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
    try {
        call.execute();
        fail();
    } catch (IOException expected) {
    }
    // Observed Events are variable
    // JDK 14
    // CallStart, ProxySelectStart, ProxySelectEnd, DnsStart, DnsEnd, ConnectStart, SecureConnectStart,
    // SecureConnectEnd, ConnectEnd, ConnectionAcquired, RequestHeadersStart, RequestHeadersEnd,
    // ResponseFailed, ConnectionReleased, CallFailed
    // JDK 8
    // CallStart, ProxySelectStart, ProxySelectEnd, DnsStart, DnsEnd, ConnectStart, SecureConnectStart,
    // ConnectFailed, CallFailed
    // Gradle - JDK 11
    // CallStart, ProxySelectStart, ProxySelectEnd, DnsStart, DnsEnd, ConnectStart, SecureConnectStart,
    // SecureConnectEnd, ConnectFailed, CallFailed
    List<String> recordedEventTypes = listener.recordedEventTypes();
    assertThat(recordedEventTypes).startsWith("CallStart", "ProxySelectStart", "ProxySelectEnd", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart");
    assertThat(recordedEventTypes).endsWith("CallFailed");
}
Also used : MockResponse(mockwebserver3.MockResponse) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) HeldCertificate(okhttp3.tls.HeldCertificate) Request(okhttp3.Request) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) RecordingEventListener(okhttp3.RecordingEventListener) Test(org.junit.jupiter.api.Test)

Aggregations

MockResponse (mockwebserver3.MockResponse)3 Test (org.junit.jupiter.api.Test)3 IOException (java.io.IOException)2 RecordingEventListener (okhttp3.RecordingEventListener)2 CountDownLatch (java.util.concurrent.CountDownLatch)1 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)1 MockDuplexResponseBody (mockwebserver3.internal.duplex.MockDuplexResponseBody)1 Call (okhttp3.Call)1 RequestBodyEnd (okhttp3.CallEvent.RequestBodyEnd)1 RequestHeadersEnd (okhttp3.CallEvent.RequestHeadersEnd)1 ResponseBodyEnd (okhttp3.CallEvent.ResponseBodyEnd)1 ResponseHeadersEnd (okhttp3.CallEvent.ResponseHeadersEnd)1 OkHttpClient (okhttp3.OkHttpClient)1 Request (okhttp3.Request)1 WebSocket (okhttp3.WebSocket)1 AsyncRequestBody (okhttp3.internal.duplex.AsyncRequestBody)1 HeldCertificate (okhttp3.tls.HeldCertificate)1 BufferedSink (okio.BufferedSink)1 BufferedSource (okio.BufferedSource)1