Skip to content

Commit

Permalink
Only drain main looper when it is paused.
Browse files Browse the repository at this point in the history
ControlledLooper.drainMainThreadUntilIdle was created
so Robolectric can manually execute tasks when main looper is paused.

Now with the introduction of INSTRUMENTATION_TEST looper mode with a
free running looper, it doesn't make sense to always idle the main looper,
and could lead to deviation of behavior between a test run with Robolectric
INSTRUMENTATION_TEST mode and real android.

This commit changes drainMainThreadUntilIdle so its a no-op if main looper
is not paused.

PiperOrigin-RevId: 703634485
  • Loading branch information
brettchabot authored and copybara-androidxtest committed Dec 7, 2024
1 parent f5ff2c3 commit 654fcd5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
2 changes: 2 additions & 0 deletions espresso/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ The following artifacts were released:

**Bug Fixes**

* Fix deadlock in espresso in Robolectric INSTRUMENTATION_TEST + paused looper.

**New Features**

**Breaking Changes**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.Nullable;
import androidx.test.internal.platform.ServiceLoaderWrapper;
import androidx.test.internal.platform.os.ControlledLooper;
import java.lang.reflect.Field;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
Expand All @@ -42,6 +44,10 @@ final class ThreadPoolExecutorExtractor {
private static final String MODERN_ASYNC_TASK_FIELD_NAME = "THREAD_POOL_EXECUTOR";
private final Handler mainHandler;

private final ControlledLooper controlledLooper =
ServiceLoaderWrapper.loadSingleService(
ControlledLooper.class, () -> ControlledLooper.NO_OP_CONTROLLED_LOOPER);

@Inject
ThreadPoolExecutorExtractor(Looper looper) {
mainHandler = new Handler(looper);
Expand Down Expand Up @@ -85,6 +91,7 @@ public void run() {
}
});
try {
controlledLooper.drainMainThreadUntilIdle();
latch.await();
} catch (InterruptedException ie) {
if (!futureToRun.isDone()) {
Expand Down

0 comments on commit 654fcd5

Please sign in to comment.