Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions espresso/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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);
Expand Down
104 changes: 92 additions & 12 deletions espresso/core/java/androidx/test/espresso/base/UiControllerImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,12 @@ public IdlingResourceRegistry getIdlingResourceRegistry() {
public void loopMainThreadUntilIdle() {
checkState(Looper.myLooper() == mainLooper, "Expecting to be on main thread!");
IdleNotifier<IdleNotificationCallback> 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<IdleCondition> condChecks = EnumSet.noneOf(IdleCondition.class);
if (!asyncIdle.isIdleNow()) {
Expand Down Expand Up @@ -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.
*
* <p>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
Expand Down Expand Up @@ -464,7 +497,17 @@ public boolean handleMessage(Message msg) {

private void loopUntil(
IdleCondition condition, IdleNotifier<IdleNotificationCallback> dynamicIdle) {
loopUntil(EnumSet.of(condition), dynamicIdle);
EnumSet<IdleCondition> conditions = EnumSet.of(condition);
IdlingPolicy masterIdlePolicy = IdlingPolicies.getMasterIdlingPolicy();
long end =
SystemClock.uptimeMillis()
+ masterIdlePolicy.getIdleTimeoutUnit().toMillis(masterIdlePolicy.getIdleTimeout());
IdleNotifier<IdleNotificationCallback> unused =
loopUntil(
conditions,
dynamicIdle,
masterIdlePolicy,
new MainThreadInterrogation(conditions, conditionSet, end));
}

/**
Expand Down Expand Up @@ -497,15 +540,14 @@ private void loopUntil(
* }</pre>
*/
private IdleNotifier<IdleNotificationCallback> loopUntil(
EnumSet<IdleCondition> conditions, IdleNotifier<IdleNotificationCallback> dynamicIdle) {
IdlingPolicy masterIdlePolicy = IdlingPolicies.getMasterIdlingPolicy();
EnumSet<IdleCondition> conditions,
IdleNotifier<IdleNotificationCallback> 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);
Expand Down Expand Up @@ -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<Boolean> {
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<InterrogationStatus> {
private final EnumSet<IdleCondition> conditions;
private EnumSet<IdleCondition> conditions;
private final BitSet conditionSet;
private final long giveUpAtMs;
private String lastMessage;
Expand All @@ -617,6 +692,11 @@ private static final class MainThreadInterrogation
this.giveUpAtMs = giveUpAtMs;
}

void setConditions(EnumSet<IdleCondition> conditions) {
this.conditions = conditions;
this.status = InterrogationStatus.COMPLETED;
}

@Override
public void setMessage(Message m) {
try {
Expand Down Expand Up @@ -648,7 +728,7 @@ public boolean queueEmpty() {
if (conditionsMet()) {
return false;
}
return true;
return continueOrTimeout();
}

@Override
Expand All @@ -661,7 +741,7 @@ public boolean taskDueLong() {
if (conditionsMet()) {
return false;
}
return true;
return continueOrTimeout();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<IdlingResource.ResourceCallback> 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<Void> 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);
Expand Down
Loading
Loading