From 7576c10e949252a3aad58cbee75ce0d8b57c48bb Mon Sep 17 00:00:00 2001 From: jwilson Date: Sun, 15 Mar 2015 14:16:29 -0400 Subject: [PATCH] Fix a flaky test by waiting until the Okio watchdog is caught up. We had tests that flake because they expected the watchdog to have completed closing a connection, but we weren't blocking until that work was done. Closes https://github.com/square/okhttp/issues/1328 --- .../internal/spdy/Spdy3ConnectionTest.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java index 074d9ad6f377..eb53e35ee6f6 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java @@ -21,8 +21,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import okio.AsyncTimeout; import okio.Buffer; import okio.BufferedSink; import okio.ByteString; @@ -884,6 +886,7 @@ public final class Spdy3ConnectionTest { } catch (InterruptedIOException expected) { } long elapsedNanos = System.nanoTime() - startNanos; + awaitWatchdogIdle(); assertEquals(500d, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), 200d /* 200ms delta */); assertEquals(0, connection.openStreamCount()); @@ -911,6 +914,7 @@ public final class Spdy3ConnectionTest { } catch (InterruptedIOException expected) { } long elapsedNanos = System.nanoTime() - startNanos; + awaitWatchdogIdle(); assertEquals(500d, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), 200d /* 200ms delta */); assertEquals(0, connection.openStreamCount()); @@ -948,6 +952,7 @@ public final class Spdy3ConnectionTest { } catch (InterruptedIOException expected) { } long elapsedNanos = System.nanoTime() - startNanos; + awaitWatchdogIdle(); assertEquals(500d, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), 200d /* 200ms delta */); assertEquals(0, connection.openStreamCount()); @@ -1301,6 +1306,23 @@ private void interruptAfterDelay(final long delayMillis) { }.start(); } + /** + * Returns true when all work currently in progress by the watchdog have completed. This method + * creates more work for the watchdog and waits for that work to be executed. When it is, we know + * work that preceded this call is complete. + */ + private void awaitWatchdogIdle() throws InterruptedException { + final CountDownLatch latch = new CountDownLatch(1); + AsyncTimeout watchdogJob = new AsyncTimeout() { + @Override protected void timedOut() { + latch.countDown(); + } + }; + watchdogJob.deadlineNanoTime(System.nanoTime()); // Due immediately! + watchdogJob.enter(); + latch.await(); + } + static int roundUp(int num, int divisor) { return (num + divisor - 1) / divisor; }