diff --git a/espresso/CHANGELOG.md b/espresso/CHANGELOG.md index a60a5d4aa..dae57f596 100644 --- a/espresso/CHANGELOG.md +++ b/espresso/CHANGELOG.md @@ -16,6 +16,12 @@ The following artifacts were released: **Bug Fixes** +* Avoid enqueuing redundant idle notifications in `IdlingResourceRegistry` + when an already-idle `IdlingResource` calls `onTransitionToIdle()`. +* Fix a race where Espresso could report the app as idle while the main + thread still had a task queued by background work that had just gone idle, + while preserving idling policy timeout enforcement across re-checks. + **New Features** **Breaking Changes** diff --git a/espresso/core/java/androidx/test/espresso/base/IdlingResourceRegistry.java b/espresso/core/java/androidx/test/espresso/base/IdlingResourceRegistry.java index f1a81f4b6..e8b49f1f1 100644 --- a/espresso/core/java/androidx/test/espresso/base/IdlingResourceRegistry.java +++ b/espresso/core/java/androidx/test/espresso/base/IdlingResourceRegistry.java @@ -447,6 +447,12 @@ public void setIdle(boolean idle) { tracerSpan = null; } + if (idle) { + // Drop any pending idle transition messages (e.g. from resources that invoke + // onTransitionToIdle() inside isIdleNow() or registerIdleTransitionCallback()) so they do + // not leave a redundant message on the main Looper queue after the state is already idle. + handler.removeMessages(DYNAMIC_RESOURCE_HAS_IDLED, this); + } this.idle = idle; } @@ -462,6 +468,12 @@ private Span createUnmanagedTracerSpan(String name) { @Override public void onTransitionToIdle() { // from app code - unknown thread + if (Looper.myLooper() == looper && idle) { + // Some IdlingResource implementations invoke onTransitionToIdle() inside isIdleNow() + // whenever they are idle. Ignore redundant notifications on the registry looper so polling + // isIdleNow() does not enqueue a message onto the main Looper. + return; + } Message m = handler.obtainMessage(DYNAMIC_RESOURCE_HAS_IDLED); m.obj = this; handler.sendMessage(m); diff --git a/espresso/core/java/androidx/test/espresso/base/UiControllerImpl.java b/espresso/core/java/androidx/test/espresso/base/UiControllerImpl.java index 27dad26da..b612bedbd 100644 --- a/espresso/core/java/androidx/test/espresso/base/UiControllerImpl.java +++ b/espresso/core/java/androidx/test/espresso/base/UiControllerImpl.java @@ -387,6 +387,12 @@ public IdlingResourceRegistry getIdlingResourceRegistry() { public void loopMainThreadUntilIdle() { checkState(Looper.myLooper() == mainLooper, "Expecting to be on main thread!"); IdleNotifier dynamicIdle = dynamicIdleProvider.get(); + IdlingPolicy masterIdlePolicy = IdlingPolicies.getMasterIdlingPolicy(); + long giveUpAtMs = + SystemClock.uptimeMillis() + + masterIdlePolicy.getIdleTimeoutUnit().toMillis(masterIdlePolicy.getIdleTimeout()); + MainThreadInterrogation mainThreadInterrogation = + new MainThreadInterrogation(EnumSet.noneOf(IdleCondition.class), conditionSet, giveUpAtMs); do { EnumSet condChecks = EnumSet.noneOf(IdleCondition.class); if (!asyncIdle.isIdleNow()) { @@ -429,13 +435,40 @@ public void allResourcesIdle() { } try { - dynamicIdle = loopUntil(condChecks, dynamicIdle); + mainThreadInterrogation.setConditions(condChecks); + dynamicIdle = loopUntil(condChecks, dynamicIdle, masterIdlePolicy, mainThreadInterrogation); + if (mainThreadInterrogation.get() == InterrogationStatus.TIMED_OUT) { + // The master IdlingPolicy handled the timeout without throwing (e.g. logWarning()); + // stop looping rather than spinning forever on a continuously busy main queue. + return; + } } finally { asyncIdle.cancelCallback(); compatIdle.cancelCallback(); dynamicIdle.cancelCallback(); } - } while (!asyncIdle.isIdleNow() || !compatIdle.isIdleNow() || !dynamicIdle.isIdleNow()); + } while (!asyncIdle.isIdleNow() + || !compatIdle.isIdleNow() + || !dynamicIdle.isIdleNow() + || mainQueueHasTaskDueSoon()); + } + + /** + * Returns whether the main queue has a task that {@link #loopUntil} would wait for. + * + *

Background work often posts a follow-up task to the main thread and then goes idle. If it + * goes idle after {@link #loopUntil} last checked the main queue but before the idle checks in + * {@link #loopMainThreadUntilIdle}, those checks report idle while the follow-up task is still + * queued. Checking the queue after the idle checks catches the task, because work that has gone + * idle has already posted it. + */ + private boolean mainQueueHasTaskDueSoon() { + TestLooperManagerCompat testLooperManager = TestLooperManagerCompat.acquire(mainLooper); + try { + return new Interrogator().peekAtQueueState(testLooperManager, new QueueHasTaskDueSoon()); + } finally { + testLooperManager.release(); + } } @Override @@ -464,7 +497,17 @@ public boolean handleMessage(Message msg) { private void loopUntil( IdleCondition condition, IdleNotifier dynamicIdle) { - loopUntil(EnumSet.of(condition), dynamicIdle); + EnumSet conditions = EnumSet.of(condition); + IdlingPolicy masterIdlePolicy = IdlingPolicies.getMasterIdlingPolicy(); + long end = + SystemClock.uptimeMillis() + + masterIdlePolicy.getIdleTimeoutUnit().toMillis(masterIdlePolicy.getIdleTimeout()); + IdleNotifier unused = + loopUntil( + conditions, + dynamicIdle, + masterIdlePolicy, + new MainThreadInterrogation(conditions, conditionSet, end)); } /** @@ -497,15 +540,14 @@ private void loopUntil( * } */ private IdleNotifier loopUntil( - EnumSet conditions, IdleNotifier dynamicIdle) { - IdlingPolicy masterIdlePolicy = IdlingPolicies.getMasterIdlingPolicy(); + EnumSet conditions, + IdleNotifier dynamicIdle, + IdlingPolicy masterIdlePolicy, + MainThreadInterrogation mainThreadInterrogation) { IdlingPolicy dynamicIdlePolicy = IdlingPolicies.getDynamicIdlingResourceErrorPolicy(); TestLooperManagerCompat testLooperManager = TestLooperManagerCompat.acquire(mainLooper); try { - long start = SystemClock.uptimeMillis(); - long end = - start + masterIdlePolicy.getIdleTimeoutUnit().toMillis(masterIdlePolicy.getIdleTimeout()); - interrogation = new MainThreadInterrogation(conditions, conditionSet, end); + interrogation = mainThreadInterrogation; InterrogationStatus result = new Interrogator().loopAndInterrogate(testLooperManager, interrogation); @@ -600,9 +642,42 @@ public void run() { }); } + /** Records whether a queue has a task that is due soon or is blocked on a sync barrier. */ + private static final class QueueHasTaskDueSoon + implements Interrogator.QueueInterrogationHandler { + private boolean hasTaskDueSoon = false; + + @Override + public boolean queueEmpty() { + return false; + } + + @Override + public boolean taskDueSoon() { + hasTaskDueSoon = true; + return false; + } + + @Override + public boolean taskDueLong() { + return false; + } + + @Override + public boolean barrierUp() { + hasTaskDueSoon = true; + return false; + } + + @Override + public Boolean get() { + return hasTaskDueSoon; + } + } + private static final class MainThreadInterrogation implements Interrogator.InterrogationHandler { - private final EnumSet conditions; + private EnumSet conditions; private final BitSet conditionSet; private final long giveUpAtMs; private String lastMessage; @@ -617,6 +692,11 @@ private static final class MainThreadInterrogation this.giveUpAtMs = giveUpAtMs; } + void setConditions(EnumSet conditions) { + this.conditions = conditions; + this.status = InterrogationStatus.COMPLETED; + } + @Override public void setMessage(Message m) { try { @@ -648,7 +728,7 @@ public boolean queueEmpty() { if (conditionsMet()) { return false; } - return true; + return continueOrTimeout(); } @Override @@ -661,7 +741,7 @@ public boolean taskDueLong() { if (conditionsMet()) { return false; } - return true; + return continueOrTimeout(); } @Override diff --git a/espresso/core/javatests/androidx/test/espresso/base/IdlingResourceRegistryTest.java b/espresso/core/javatests/androidx/test/espresso/base/IdlingResourceRegistryTest.java index de6808506..c25ce39ab 100644 --- a/espresso/core/javatests/androidx/test/espresso/base/IdlingResourceRegistryTest.java +++ b/espresso/core/javatests/androidx/test/espresso/base/IdlingResourceRegistryTest.java @@ -339,6 +339,69 @@ public void allResourcesAreIdle_RepeatingToIdleTransitions() throws Exception { .inOrder(); } + @Test + public void allResourcesAreIdle_resourceCallingOnTransitionToIdleWhenIdle_doesNotEnqueueMessage() + throws Exception { + HandlerThread ht = new HandlerThread("idling-registry-test"); + ht.start(); + try { + Looper registryLooper = ht.getLooper(); + Handler registryLooperHandler = new Handler(registryLooper); + IdlingResourceRegistry isolatedRegistry = + new IdlingResourceRegistry(registryLooper, Tracing.getInstance()); + AtomicReference callbackRef = new AtomicReference<>(); + IdlingResource resource = + new IdlingResource() { + @Override + public String getName() { + return "NotifiesWhenIdleResource"; + } + + @Override + public boolean isIdleNow() { + IdlingResource.ResourceCallback callback = callbackRef.get(); + if (callback != null) { + callback.onTransitionToIdle(); + } + return true; + } + + @Override + public void registerIdleTransitionCallback(ResourceCallback callback) { + callbackRef.set(callback); + } + }; + + FutureTask checkNoMessagesQueued = + new FutureTask<>(() -> { + TestLooperManagerCompat looperManager = TestLooperManagerCompat.acquire(registryLooper); + try { + // Registering on the registry looper polls isIdleNow() while the state is + // initially not idle, and setIdle(true) should remove the resulting idle message. + assertTrue(isolatedRegistry.registerResources(singletonList(resource))); + assertThat(looperManager.peekWhen()).isNull(); + + // Polling allResourcesAreIdle() when already idle should ignore the redundant + // onTransitionToIdle() callback rather than enqueuing a message. + assertTrue(isolatedRegistry.allResourcesAreIdle()); + assertThat(looperManager.peekWhen()).isNull(); + + // Calling onTransitionToIdle() directly on the registry looper while already idle + // should also be ignored. + callbackRef.get().onTransitionToIdle(); + assertThat(looperManager.peekWhen()).isNull(); + } finally { + looperManager.release(); + } + return null; + }); + registryLooperHandler.post(checkNoMessagesQueued); + checkNoMessagesQueued.get(5, TimeUnit.SECONDS); + } finally { + ht.quitSafely(); + } + } + @Test public void notifyWhenAllResourcesAreIdle_success() throws InterruptedException { final CountDownLatch busyWarningLatch = new CountDownLatch(4); diff --git a/espresso/core/javatests/androidx/test/espresso/base/UiControllerImplTest.java b/espresso/core/javatests/androidx/test/espresso/base/UiControllerImplTest.java index 75d6e198e..31cf1a6d7 100644 --- a/espresso/core/javatests/androidx/test/espresso/base/UiControllerImplTest.java +++ b/espresso/core/javatests/androidx/test/espresso/base/UiControllerImplTest.java @@ -31,6 +31,7 @@ import androidx.test.espresso.AppNotIdleException; import androidx.test.espresso.IdlingPolicies; import androidx.test.espresso.IdlingPolicy; +import androidx.test.espresso.IdlingResource; import androidx.test.espresso.IdlingResourceTimeoutException; import androidx.test.espresso.base.IdlingResourceRegistry.IdleNotificationCallback; import androidx.test.ext.junit.runners.AndroidJUnit4; @@ -41,6 +42,7 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.inject.Provider; import org.junit.After; @@ -438,6 +440,112 @@ public void loopMainThreadUntilIdle_racyIdleResource() throws InterruptedExcepti assertTrue("App should be interrupted.", interruptedLatch.await(5, TimeUnit.SECONDS)); } + @Test + public void loopMainThreadUntilIdle_runsTaskPostedByResourceGoingIdleDuringRecheck() + throws InterruptedException { + // Background work commonly posts a follow-up task to the main thread and then goes idle. If it + // goes idle after the main queue was last checked but before the idling resources are checked + // again, the resources report idle while the follow-up task is still queued. This resource + // reproduces that interleaving deterministically by posting from inside the second check. + CountDownLatch followUpTaskRan = new CountDownLatch(1); + PostsTaskWhenPolledIdlingResource resource = + new PostsTaskWhenPolledIdlingResource(testThread.getHandler(), followUpTaskRan::countDown); + idlingResourceRegistry.registerResources(singletonList(resource)); + AtomicBoolean ranBeforeIdle = new AtomicBoolean(); + CountDownLatch returned = new CountDownLatch(1); + assertTrue( + testThread + .getHandler() + .post(() -> { + // Runs while loopMainThreadUntilIdle() drains the queue, which is after the + // resource has been checked once. + testThread.getHandler().post(resource::postTaskOnNextPoll); + uiController.get().loopMainThreadUntilIdle(); + ranBeforeIdle.set(followUpTaskRan.getCount() == 0); + returned.countDown(); + })); + assertTrue( + "Never returned from UiControllerImpl.loopMainThreadUntilIdle();", + returned.await(10, TimeUnit.SECONDS)); + assertTrue( + "loopMainThreadUntilIdle() returned before running a task posted by an idle resource", + ranBeforeIdle.get()); + } + + @Test + public void loopMainThreadUntilIdle_resourceCallingOnTransitionToIdleWhenIdleDoesNotSpin() + throws InterruptedException { + IdlingResource resource = + new IdlingResource() { + private ResourceCallback callback; + + @Override + public String getName() { + return "NotifiesWhenIdleResource"; + } + + @Override + public boolean isIdleNow() { + if (callback != null) { + callback.onTransitionToIdle(); + } + return true; + } + + @Override + public void registerIdleTransitionCallback(ResourceCallback callback) { + this.callback = callback; + } + }; + idlingResourceRegistry.registerResources(singletonList(resource)); + CountDownLatch returned = new CountDownLatch(1); + assertTrue( + testThread + .getHandler() + .post(() -> { + uiController.get().loopMainThreadUntilIdle(); + returned.countDown(); + })); + assertTrue( + "Never returned from UiControllerImpl.loopMainThreadUntilIdle();", + returned.await(5, TimeUnit.SECONDS)); + } + + @Test + public void loopMainThreadUntilIdle_resourcePostingTaskWhenIdle_timesOut() + throws InterruptedException { + IdlingPolicies.setMasterPolicyTimeout(200, TimeUnit.MILLISECONDS); + IdlingResource resource = + new IdlingResource() { + @Override + public String getName() { + return "PostsOnEveryPollResource"; + } + + @Override + public boolean isIdleNow() { + testThread.getHandler().post(() -> {}); + return true; + } + + @Override + public void registerIdleTransitionCallback(ResourceCallback callback) {} + }; + idlingResourceRegistry.registerResources(singletonList(resource)); + CountDownLatch timedOut = new CountDownLatch(1); + assertTrue( + testThread + .getHandler() + .post(() -> { + assertThrows( + AppNotIdleException.class, () -> uiController.get().loopMainThreadUntilIdle()); + timedOut.countDown(); + })); + assertTrue( + "Expected idling policy timeout instead of spinning indefinitely", + timedOut.await(5, TimeUnit.SECONDS)); + } + @Test public void loopMainThreadUntilIdle_multipleIdlingResources() throws InterruptedException { OnDemandIdlingResource fakeResource1 = new OnDemandIdlingResource("FakeResource1"); @@ -581,4 +689,42 @@ public void run() { public void interruptInitialization() { uiController.get().interruptEspressoTasks(); } + + /** + * An idling resource that is always idle but, once armed, posts a task to the main thread the + * next time it's polled. This models background work that posts a follow-up task to the main + * thread just before going idle. + */ + private static final class PostsTaskWhenPolledIdlingResource implements IdlingResource { + private final Handler mainHandler; + private final Runnable task; + // Only accessed on the main thread. + private boolean armed = false; + + PostsTaskWhenPolledIdlingResource(Handler mainHandler, Runnable task) { + this.mainHandler = mainHandler; + this.task = task; + } + + void postTaskOnNextPoll() { + armed = true; + } + + @Override + public boolean isIdleNow() { + if (armed) { + armed = false; + mainHandler.post(task); + } + return true; + } + + @Override + public String getName() { + return "PostsTaskWhenPolledIdlingResource"; + } + + @Override + public void registerIdleTransitionCallback(ResourceCallback callback) {} + } }