summaryrefslogtreecommitdiff
path: root/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/UiControllerImplTest.java
blob: 2b95fc8b8c8d32ded6b93f5dd1538975505c2d6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.apps.common.testing.ui.espresso.base;

import com.google.android.apps.common.testing.ui.espresso.IdlingResourceTimeoutException;
import com.google.common.base.Optional;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;

import junit.framework.TestCase;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Unit test for {@link UiControllerImpl}.
 */
public class UiControllerImplTest extends TestCase {

  private static final String TAG = UiControllerImplTest.class.getSimpleName();

  private LooperThread testThread;
  private AtomicReference<UiControllerImpl> uiController = new AtomicReference<UiControllerImpl>();
  private ThreadPoolExecutor asyncPool;
  private IdlingResourceRegistry idlingResourceRegistry;

  private static class LooperThread extends Thread {
    private final CountDownLatch init = new CountDownLatch(1);
    private Handler handler;
    private Looper looper;

    @Override
    public void run() {
      Looper.prepare();
      handler = new Handler();
      looper = Looper.myLooper();
      init.countDown();
      Looper.loop();
    }

    public void quitLooper() {
      looper.quit();
    }

    public Looper getLooper() {
      try {
        init.await();
      } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
      }
      return looper;
    }

    public Handler getHandler() {
      try {
        init.await();
      } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
      }
      return handler;
    }
  }

  @Override
  public void setUp() throws Exception {
    super.setUp();
    testThread = new LooperThread();
    testThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      @Override
      public void uncaughtException(Thread thread, Throwable ex) {
        Log.e(TAG, "Looper died: ", ex);
      }
    });
    testThread.start();
    idlingResourceRegistry = new IdlingResourceRegistry(testThread.getLooper());
    asyncPool = new ThreadPoolExecutor(3, 3, 1, TimeUnit.SECONDS,
        new LinkedBlockingQueue<Runnable>());
    EventInjector injector = null;
    if (Build.VERSION.SDK_INT > 15) {
      InputManagerEventInjectionStrategy strat = new InputManagerEventInjectionStrategy();
      strat.initialize();
      injector = new EventInjector(strat);
    } else {
      WindowManagerEventInjectionStrategy strat = new WindowManagerEventInjectionStrategy();
      strat.initialize();
      injector = new EventInjector(strat);
    }
    uiController.set(new UiControllerImpl(
        injector,
        new AsyncTaskPoolMonitor(asyncPool),
        Optional.<AsyncTaskPoolMonitor>absent(),
        idlingResourceRegistry,
        testThread.getLooper()
        ));


  }

  @Override
  public void tearDown() throws Exception {
    testThread.quitLooper();
    asyncPool.shutdown();
    super.tearDown();
  }

  public void testLoopMainThreadTillIdle_sendsMessageToRightHandler() {
    final CountDownLatch latch = new CountDownLatch(3);
    testThread.getHandler(); // blocks till initialized;
    final Handler firstHandler = new Handler(
        testThread.looper,
        new Handler.Callback() {
          private boolean counted = false;
          @Override
          public boolean handleMessage(Message me) {
            if (counted) {
              fail("Called 2x!!!!");
            }
            counted = true;
            latch.countDown();
            return true;
          }
        });

    final Handler secondHandler = new Handler(
        testThread.looper,
        new Handler.Callback() {
          private boolean counted = false;
          @Override
          public boolean handleMessage(Message me) {
            if (counted) {
              fail("Called 2x!!!!");
            }
            counted = true;
            latch.countDown();
            return true;
          }
        });

    assertTrue(testThread.getHandler().post(new Runnable() {
      @Override
      public void run() {
        firstHandler.sendEmptyMessage(1);
        secondHandler.sendEmptyMessage(1);
        uiController.get().loopMainThreadUntilIdle();

        latch.countDown();
      }
    }));

    try {
      assertTrue(
          "Timed out waiting for looper to process all events", latch.await(10, TimeUnit.SECONDS));
    } catch (InterruptedException e) {
      fail("Failed with exception " + e);
    }
  }

  public void testLoopForAtLeast() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    assertTrue(testThread.getHandler().post(new Runnable() {
      @Override
      public void run() {
        testThread.getHandler().post(new Runnable() {
          @Override
          public void run() {
            latch.countDown();
          }

        });
        uiController.get().loopMainThreadForAtLeast(1000);
        latch.countDown();
      }
    }));
    assertTrue("Never returned from UiControllerImpl.loopMainThreadForAtLeast();",
        latch.await(10, TimeUnit.SECONDS));
  }

  public void testLoopMainThreadUntilIdle_fullQueue() {
    final CountDownLatch latch = new CountDownLatch(3);
    assertTrue(testThread.getHandler().post(new Runnable() {
      @Override
      public void run() {
        Log.i(TAG, "On main thread");
        Handler handler = new Handler();
        Log.i(TAG, "Equeueing test runnable 1");
        handler.post(new Runnable() {
          @Override
          public void run() {
            Log.i(TAG, "Running test runnable 1");
            latch.countDown();
          }
        });
        Log.i(TAG, "Equeueing test runnable 2");
        handler.post(new Runnable() {
          @Override
          public void run() {
            Log.i(TAG, "Running test runnable 2");
            latch.countDown();
          }
        });
        Log.i(TAG, "Hijacking thread and looping it.");
        uiController.get().loopMainThreadUntilIdle();
        latch.countDown();
      }
    }));

    try {
      assertTrue(
          "Timed out waiting for looper to process all events", latch.await(10, TimeUnit.SECONDS));
    } catch (InterruptedException e) {
      fail("Failed with exception " + e);
    }
  }

  public void testLoopMainThreadUntilIdle_fullQueueAndAsyncTasks() throws Exception {
    final CountDownLatch latch = new CountDownLatch(3);
    final CountDownLatch asyncTaskStarted = new CountDownLatch(1);
    final CountDownLatch asyncTaskShouldComplete = new CountDownLatch(1);
    asyncPool.execute(new Runnable() {
      @Override
      public void run() {
        asyncTaskStarted.countDown();
        while (true) {
          try {
            asyncTaskShouldComplete.await();
            return;
          } catch (InterruptedException ie) {
            // cant interrupt me. ignore.
          }
        }
      }
    });
    assertTrue("async task is not starting!", asyncTaskStarted.await(2, TimeUnit.SECONDS));

    assertTrue(testThread.getHandler().post(new Runnable() {
      @Override
      public void run() {
        Log.i(TAG, "On main thread");
        Handler handler = new Handler();
        Log.i(TAG, "Equeueing test runnable 1");
        handler.post(new Runnable() {
          @Override
          public void run() {
            Log.i(TAG, "Running test runnable 1");
            latch.countDown();
          }
        });
        Log.i(TAG, "Equeueing test runnable 2");
        handler.post(new Runnable() {
          @Override
          public void run() {
            Log.i(TAG, "Running test runnable 2");
            latch.countDown();
          }
        });
        Log.i(TAG, "Hijacking thread and looping it.");
        uiController.get().loopMainThreadUntilIdle();
        latch.countDown();
      }
    }));
    assertFalse(
        "Should not have stopped looping the main thread yet!", latch.await(2, TimeUnit.SECONDS));
    assertEquals("Not all main thread tasks have checked in", 1L, latch.getCount());
    asyncTaskShouldComplete.countDown();
    assertTrue("App should be idle.", latch.await(5, TimeUnit.SECONDS));
  }


  public void testLoopMainThreadUntilIdle_emptyQueue() {
    final CountDownLatch latch = new CountDownLatch(1);
    assertTrue(testThread.getHandler().post(new Runnable() {
      @Override
      public void run() {
        uiController.get().loopMainThreadUntilIdle();
        latch.countDown();
      }
    }));
    try {
      assertTrue("Never returned from UiControllerImpl.loopMainThreadUntilIdle();",
          latch.await(10, TimeUnit.SECONDS));
    } catch (InterruptedException e) {
      fail("Failed with exception " + e);
    }
  }

  public void testLoopMainThreadUntilIdle_oneIdlingResource() throws InterruptedException {
    OnDemandIdlingResource fakeResource = new OnDemandIdlingResource("FakeResource");
    idlingResourceRegistry.register(fakeResource);
    final CountDownLatch latch = new CountDownLatch(1);
    assertTrue(testThread.getHandler().post(new Runnable() {
      @Override
      public void run() {
        Log.i(TAG, "Hijacking thread and looping it.");
        uiController.get().loopMainThreadUntilIdle();
        latch.countDown();
      }
    }));
    assertFalse(
        "Should not have stopped looping the main thread yet!", latch.await(2, TimeUnit.SECONDS));
    fakeResource.forceIdleNow();
    assertTrue("App should be idle.", latch.await(5, TimeUnit.SECONDS));
  }

  public void testLoopMainThreadUntilIdle_multipleIdlingResources() throws InterruptedException {
    OnDemandIdlingResource fakeResource1 = new OnDemandIdlingResource("FakeResource1");
    OnDemandIdlingResource fakeResource2 = new OnDemandIdlingResource("FakeResource2");
    OnDemandIdlingResource fakeResource3 = new OnDemandIdlingResource("FakeResource3");
    // Register the first two right away and one later (once the wait for the first two begins).
    idlingResourceRegistry.register(fakeResource1);
    idlingResourceRegistry.register(fakeResource2);
    final CountDownLatch latch = new CountDownLatch(1);
    assertTrue(testThread.getHandler().post(new Runnable() {
      @Override
      public void run() {
        Log.i(TAG, "Hijacking thread and looping it.");
        uiController.get().loopMainThreadUntilIdle();
        latch.countDown();
      }
    }));
    assertFalse(
        "Should not have stopped looping the main thread yet!", latch.await(1, TimeUnit.SECONDS));
    fakeResource1.forceIdleNow();
    assertFalse(
        "Should not have stopped looping the main thread yet!", latch.await(1, TimeUnit.SECONDS));
    idlingResourceRegistry.register(fakeResource3);
    assertFalse(
        "Should not have stopped looping the main thread yet!", latch.await(1, TimeUnit.SECONDS));
    fakeResource2.forceIdleNow();
    assertFalse(
        "Should not have stopped looping the main thread yet!", latch.await(1, TimeUnit.SECONDS));
    fakeResource3.forceIdleNow();
    assertTrue("App should be idle.", latch.await(5, TimeUnit.SECONDS));
  }

  @LargeTest
  public void testLoopMainThreadUntilIdle_timeout() throws InterruptedException {
    OnDemandIdlingResource goodResource =
        new OnDemandIdlingResource("GoodResource");
    OnDemandIdlingResource kindaCrappyResource =
        new OnDemandIdlingResource("KindaCrappyResource");
    OnDemandIdlingResource badResource =
        new OnDemandIdlingResource("VeryBadResource");
    idlingResourceRegistry.register(goodResource);
    idlingResourceRegistry.register(kindaCrappyResource);
    idlingResourceRegistry.register(badResource);
    final CountDownLatch latch = new CountDownLatch(1);
    assertTrue(testThread.getHandler().post(new Runnable() {
      @Override
      public void run() {
        Log.i(TAG, "Hijacking thread and looping it.");
        try {
          uiController.get().loopMainThreadUntilIdle();
        } catch (IdlingResourceTimeoutException e) {
          latch.countDown();
        }
      }
    }));
    assertFalse(
        "Should not have stopped looping the main thread yet!", latch.await(4, TimeUnit.SECONDS));
    goodResource.forceIdleNow();
    assertFalse(
        "Should not have stopped looping the main thread yet!", latch.await(12, TimeUnit.SECONDS));
    kindaCrappyResource.forceIdleNow();
    assertTrue(
        "Should have caught IdlingResourceTimeoutException", latch.await(11, TimeUnit.SECONDS));
  }

}