okhttp: MockWebServer shuts down after timeout

I think I encountered a bug.

I wrote a custom retry handler, and I wanted to write a test for it. For the retry handler I followed some ideas from here. Basically I catch the IOException and retry.

However if I write a test like, the client will close without retrying.

       final MockResponse timeout1 = new MockResponse().setBodyDelay(20, TimeUnit.DAYS).setHeadersDelay(20, TimeUnit.DAYS);
// OR       
       final MockResponse timeout2 = new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE); //another way to timeout

        final MockResponse success = new MockResponse().setResponseCode(200);

        this.mockWebServer.enqueue(timeout1);
        this.mockWebServer.enqueue(timeout2);
        this.mockWebServer.enqueue(success);

        final Request request = new Request.Builder()
                .url("http://localhost:8080")
                .get()
                .build();

        final Response response = httpClient.newCall(request).execute();

Exception:

Dec 29, 2021 2:36:57 PM okhttp3.mockwebserver.MockWebServer$SocketHandler handle
WARNING: MockWebServer[8080] connection from /127.0.0.1 didn't make a request

java.io.InterruptedIOException: timeout

After that exception all requests are cancelled, thus retry is not possible.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 19 (1 by maintainers)

Most upvoted comments

I’ll have to wait for a release with the fix, as I cannot use unreleased packages in my project. I’ll just have to disable this test.

If anyone wants the cleanup code in java:

        Thread.getAllStackTraces().keySet().stream()
                .filter(i -> i.getName()
                        .contains("MockWebServer /127.0.0.1"))
                .forEach(k -> k.interrupt());

Are you sure I need to close the response manually in the test? The interceptor I wrote will close the response on failure always. And a success response will always end up closed I think.