@Test public void onUnsubscribePostsOffMainThread() throws InterruptedException { ShadowLooper.pauseMainLooper(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean called = new AtomicBoolean(); new Thread(new Runnable() { @Override public void run() { new MainThreadDisposable() { @Override protected void onDispose() { called.set(true); } }.dispose(); latch.countDown(); } }).start(); assertTrue(latch.await(1, SECONDS)); assertFalse(called.get()); // Callback has not yet run. ShadowLooper.runMainLooperOneTask(); assertTrue(called.get()); }
/** * Test that disconnection from server is properly recognized. */ @Test public void testServerEventDisconnected() throws InterruptedException { ShadowBluetoothSocket.setTransmittedString(SERVER_VERSION_SUCCESS); final CountDownLatch messageReceived = new CountDownLatch(1); control = new BluetoothPresenterControl(new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == RemoteControl.ServiceState.NONE.ordinal()) { messageReceived.countDown(); } } }); BluetoothDevice bluetoothDevice = ShadowBluetoothAdapter.getDefaultAdapter() .getRemoteDevice(DEVICE_ADDRESS); control.connect(bluetoothDevice); waitForServiceStateChanged(control, RemoteControl.ServiceState.CONNECTED); ShadowBluetoothSocket.setFailReading(true); waitForServiceStateChanged(control, RemoteControl.ServiceState.NONE); ShadowLooper.runUiThreadTasks(); assertThat("Handler was not called", messageReceived.await(MESSAGE_RECEIVING_TIMEOUT, TimeUnit.MILLISECONDS), is(true)); }
@Test public void uiShouldNotCallActionUntilMainThreadIsPaused() throws Exception { // WHEN have UI action Consumer<String> uiAction = mock(Consumer.class); // AND produce binder func Function<Observable<String>, Disposable> binderFunc = RxUi.ui(uiAction); // AND main thread is paused ShadowLooper.pauseMainLooper(); // AND bind Observable via binder func binderFunc.apply(Observable.just("a", "b", "c")); // THEN action should not be called until main thread is paused verifyZeroInteractions(uiAction); }
@Test public void uiShouldPreventCallsToActionIfUnsubscribedBeforeExecution() throws Exception { // WHEN have UI action Consumer<String> uiAction = mock(Consumer.class); // AND produce binder func Function<Observable<String>, Disposable> binderFunc = RxUi.ui(uiAction); // AND pause Main Thread ShadowLooper.pauseMainLooper(); // AND bind Observable via binder func Disposable disposable = binderFunc.apply(Observable.just("a", "b", "c")); // AND dispose Disposable disposable.dispose(); // AND resume Main Thread ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); // THEN no calls to uiAction are expected verifyZeroInteractions(uiAction); }
@Test public void testWaitForFinishedDelayed() { CircleFlow engine = CircleFlow.getInternalInstance(); engine.injectServiceBuilder(new FlowServiceBuilderMock()); FlowExecutor executor = engine.prepareFlow(new Flow1()); executor.execute(); FlowContext context = engine.getLifecycleService().getFlowContext(executor.getFlowId()); Assert.assertEquals(FlowContext.STATUS_STARTED, context.getCurrentStatus()); DelayThread.delayRun(new Runnable() { @Override public void run() { ShadowLooper.unPauseMainLooper(); } }); context = executor.waitForFinished(); Assert.assertEquals(FlowContext.STATUS_ENDED, context.getCurrentStatus()); Assert.assertEquals(0, context.getCurrentNodes().size()); }
@Test public void testLastUpdated() { String expected = activity.getString(R.string.last_updated, DateUtils.getRelativeTimeSpanString(System.currentTimeMillis(), System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL)); activity.onRefreshed(); assertThat(activity.getSupportActionBar()).hasSubtitle(expected); activity.getSupportActionBar().setSubtitle(null); ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); assertThat(activity.getSupportActionBar()).hasSubtitle(expected); activity.getSupportActionBar().setSubtitle(null); controller.pause().resume(); assertThat(activity.getSupportActionBar()).hasSubtitle(expected); Bundle savedState = new Bundle(); activity.onSaveInstanceState(savedState); controller = Robolectric.buildActivity(TestListActivity.class); activity = controller.create(savedState).postCreate(null).start().resume().visible().get(); assertThat(activity.getSupportActionBar()).hasSubtitle(expected); }
@Before public void setUp() { initMocks(this); //noinspection ConstantConditions scheduler = ((ShadowLooper) extract(myLooper())).getScheduler(); updateDispatcherWithUpdatablesChanged = updateDispatcher(mockActivationHandler); updateDispatcher = updateDispatcher(); firstUpdateDispatcher = updateDispatcher(); secondUpdateDispatcher = updateDispatcher(); thirdUpdateDispatcher = updateDispatcher(); trueConditionalObservable = conditionalObservable(trueCondition(), firstUpdateDispatcher); falseConditionalObservable = conditionalObservable(falseCondition(), firstUpdateDispatcher); compositeObservableOfMany = compositeObservable(firstUpdateDispatcher, secondUpdateDispatcher); chainedCompositeObservableOfOne = compositeObservable( compositeObservable(firstUpdateDispatcher)); chainedCompositeObservable = compositeObservable(compositeObservable(firstUpdateDispatcher, secondUpdateDispatcher), thirdUpdateDispatcher); chainedDupeCompositeObservable = compositeObservable(firstUpdateDispatcher, compositeObservable(firstUpdateDispatcher, secondUpdateDispatcher), secondUpdateDispatcher, thirdUpdateDispatcher); updatable = mockUpdatable(); secondUpdatable = mockUpdatable(); looper = getShadowMainLooper(); }
public static void reset(Config config) { Robolectric.application = null; Robolectric.packageManager = null; Robolectric.activityThread = null; ShadowLooper.resetThreadLoopers(); ShadowChoreographer.resetThreadLoopers(); List<Class<?>> klasses = Lists.newArrayList(); klasses.addAll(Arrays.asList(Robolectric.DEFAULT_SHADOW_CLASSES)); klasses.addAll(Arrays.asList(config.shadows())); for (Class<?> klass : klasses) { if (klass.getAnnotation(Implements.class).resetStaticState()) { staticMethod("reset").in(klass).invoke(); } } }
@Test public void currentActivity() throws Exception { /* now select an activity */ DiaryActivity someAct = new DiaryActivity(1, "Test", Color.BLACK); ActivityHelper.helper.insertActivity(someAct); assertNotNull(someAct); ActivityHelper.helper.setCurrentActivity(someAct); assertEquals(ActivityHelper.helper.getCurrentActivity(), someAct); MainActivity activity = Robolectric.setupActivity(MainActivity.class); View card = activity.findViewById(R.id.card); TextView nameView = (TextView) card.findViewById(R.id.activity_name); assertNotNull("Current activity Text available", nameView); assertEquals(nameView.getText(), "Test"); FloatingActionButton fabNoteEdit = (FloatingActionButton) activity.findViewById(R.id.fab_edit_note); FloatingActionButton fabAttachPicture = (FloatingActionButton) activity.findViewById(R.id.fab_attach_picture); assertNotNull("we have two FABs", fabNoteEdit); assertNotNull("we have two FABs", fabAttachPicture); fabNoteEdit.performClick(); DialogFragment dialogFragment = (DialogFragment) activity.getSupportFragmentManager() .findFragmentByTag("NoteEditDialogFragment"); assertNotNull(dialogFragment); ShadowLooper.idleMainLooper(100, TimeUnit.MILLISECONDS); assertNull(ShadowToast.getTextOfLatestToast()); fabAttachPicture.performClick(); ShadowLooper.idleMainLooper(100, TimeUnit.MILLISECONDS); assertNull(ShadowToast.getTextOfLatestToast()); }
@Test public void testOnResourceReadyPassedToCallbacks() throws Exception { EngineJob<Object> job = harness.getJob(); job.start(harness.decodeJob); job.onResourceReady(harness.resource, harness.dataSource); ShadowLooper.runUiThreadTasks(); verify(harness.cb).onResourceReady(eq(harness.engineResource), eq(harness.dataSource)); }
@Test public void testListenerNotifiedJobCompleteOnOnResourceReady() { EngineJob<Object> job = harness.getJob(); job.start(harness.decodeJob); job.onResourceReady(harness.resource, harness.dataSource); ShadowLooper.runUiThreadTasks(); verify(harness.listener).onEngineJobComplete(eq(harness.key), eq(harness.engineResource)); }
@Test public void testListenerNotifiedJobCompleteOnException() { harness = new EngineJobHarness(); EngineJob<Object> job = harness.getJob(); job.start(harness.decodeJob); job.onLoadFailed(new GlideException("test")); ShadowLooper.runUiThreadTasks(); verify(harness.listener).onEngineJobComplete(eq(harness.key), isNull(EngineResource.class)); }
@Test public void testResourceIsCacheableWhenIsCacheableOnReady() { harness.isCacheable = true; EngineJob<Object> job = harness.getJob(); job.start(harness.decodeJob); job.onResourceReady(harness.resource, harness.dataSource); ShadowLooper.runUiThreadTasks(); verify(harness.factory).build(anyResource(), eq(harness.isCacheable)); }
@Test public void testResourceIsCacheableWhenNotIsCacheableOnReady() { harness.isCacheable = false; EngineJob<Object> job = harness.getJob(); job.start(harness.decodeJob); job.onResourceReady(harness.resource, harness.dataSource); ShadowLooper.runUiThreadTasks(); verify(harness.factory).build(anyResource(), eq(harness.isCacheable)); }
@Test public void testOnResourceReadyNotDeliveredAfterCancel() { EngineJob<Object> job = harness.getJob(); job.start(harness.decodeJob); job.cancel(); job.onResourceReady(harness.resource, harness.dataSource); ShadowLooper.runUiThreadTasks(); verify(harness.cb, never()).onResourceReady(anyResource(), isADataSource()); }
@Test public void testOnExceptionNotDeliveredAfterCancel() { harness = new EngineJobHarness(); EngineJob<Object> job = harness.getJob(); job.start(harness.decodeJob); job.cancel(); job.onLoadFailed(new GlideException("test")); ShadowLooper.runUiThreadTasks(); verify(harness.cb, never()).onLoadFailed(any(GlideException.class)); }
@Test public void testReleasesResourceIfCancelledOnReady() { ShadowLooper shadowLooper = Shadows.shadowOf(harness.mainHandler.getLooper()); shadowLooper.pause(); EngineJob<Object> job = harness.getJob(); job.start(harness.decodeJob); job.onResourceReady(harness.resource, harness.dataSource); job.cancel(); shadowLooper.runOneTask(); verify(harness.resource).recycle(); }
@Test public void onUnsubscribeRunsSyncOnMainThread() { ShadowLooper.pauseMainLooper(); final AtomicBoolean called = new AtomicBoolean(); new MainThreadDisposable() { @Override protected void onDispose() { called.set(true); } }.dispose(); assertTrue(called.get()); }
@Test public void testSimpleExecute() { ShadowLooper.pauseMainLooper(); mExecutorService.execute(mIncrementCounterRunnable); Assert.assertEquals(0, mCounter.get()); ShadowLooper.unPauseMainLooper(); Assert.assertEquals(1, mCounter.get()); }
@Test public void testDelay() { mExecutorService.schedule(mIncrementCounterRunnable, 30, TimeUnit.SECONDS); Assert.assertEquals(0, mCounter.get()); Shadows.shadowOf(ShadowLooper.getMainLooper()).getScheduler().advanceBy(30 * 1000); Assert.assertEquals(1, mCounter.get()); }
public static void setupRoot(WXSDKInstance instance){ WXDomObject domObject = new WXDomObject(); WXDomObject.prepareGod(domObject); WXVContainer comp = (WXVContainer) WXComponentFactory.newInstance(instance, domObject, null); WXComponent root = WXDivTest.create(comp); comp.addChild(root); comp.createView(null, -1); instance.onViewCreated(comp); ShadowLooper.idleMainLooper(); }
@Before public void setUp() throws Exception { WXSDKEngine.initialize(RuntimeEnvironment.application,new InitConfig.Builder().build()); ShadowLooper looper = WXBridgeManagerTest.getLooper(); looper.idle(); ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); instance = WXSDKInstanceTest.createInstance(); rednerManager = new WXRenderManager(); rednerManager.registerInstance(instance);// stmt = new WXDomStatement(instance.getInstanceId(),rednerManager ); }
public static void setupRoot(WXSDKInstance instance){ WXDomObject domObject = new WXDomObject(); WXVContainer comp = (WXVContainer) WXComponentFactory.newInstance(instance, domObject, null); WXComponent root = WXDivTest.create(comp); comp.addChild(root); comp.createView(); instance.onCreateFinish(); ShadowLooper.idleMainLooper(); }
@Before public void setUp() throws Exception { WXSDKEngine.initialize(RuntimeEnvironment.application,new InitConfig.Builder().build()); ShadowLooper looper = WXBridgeManagerTest.getLooper(); looper.idle(); ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); instance = WXSDKInstanceTest.createInstance(); rednerManager = new WXRenderManager(); rednerManager.registerInstance(instance);// WXSDKManagerTest.setRenderManager(rednerManager); stmt = new DOMActionContextImpl(instance.getInstanceId(),rednerManager ); }
/** * Test that "connecting" and "connected" event are sent successfully if the * connection succeeded. */ @Test public void testConnectedEventSuccess() throws InterruptedException { final CountDownLatch connectingMessageReceived = new CountDownLatch(1); final CountDownLatch connectedMessageReceived = new CountDownLatch(1); control = new BluetoothPresenterControl(new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == RemoteControl.ServiceState.CONNECTING.ordinal()) { connectingMessageReceived.countDown(); } else if (msg.what == RemoteControl.ServiceState.CONNECTED.ordinal()) { assertThat("Got wrong connection result", msg.getData().getBoolean(RemoteControl.RESULT_VALUES[0]), is(true)); assertThat("Got wrong device to which we are connected", msg.getData().getString(RemoteControl.RESULT_VALUES[1]), is(DEVICE_NAME)); connectedMessageReceived.countDown(); } } }); ShadowBluetoothSocket.setTransmittedString(SERVER_VERSION_SUCCESS); BluetoothDevice bluetoothDevice = ShadowBluetoothAdapter.getDefaultAdapter() .getRemoteDevice(DEVICE_ADDRESS); shadowOf(bluetoothDevice).setName(DEVICE_NAME); control.connect(bluetoothDevice); waitForServiceStateChanged(control, RemoteControl.ServiceState.CONNECTED); ShadowLooper.runUiThreadTasks(); assertThat("Did not receive 'connecting' message", connectingMessageReceived.await(MESSAGE_RECEIVING_TIMEOUT, TimeUnit.MILLISECONDS), is(true)); assertThat("Did not receive 'connected' message", connectedMessageReceived.await(MESSAGE_RECEIVING_TIMEOUT, TimeUnit.MILLISECONDS), is(true)); }
/** * Test that the "connecting" and "connected" event are sent successfully if the * connection fails and that the result state is correct. */ @Test public void testConnectedEventFailure() throws InterruptedException { ShadowBluetoothSocket.setConnectionSucceed(false); final CountDownLatch connectingMessageReceived = new CountDownLatch(1); final CountDownLatch connectedMessageReceived = new CountDownLatch(1); control = new BluetoothPresenterControl(new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == RemoteControl.ServiceState.CONNECTING.ordinal()) { connectingMessageReceived.countDown(); } else if (msg.what == RemoteControl.ServiceState.CONNECTED.ordinal()) { assertThat("Got wrong connection result", msg.getData().getBoolean(RemoteControl.RESULT_VALUES[0]), is(false)); connectedMessageReceived.countDown(); } } }); BluetoothDevice bluetoothDevice = ShadowBluetoothAdapter.getDefaultAdapter() .getRemoteDevice(DEVICE_ADDRESS); control.connect(bluetoothDevice); waitForServiceStateChanged(control, RemoteControl.ServiceState.CONNECTING); waitForServiceStateChanged(control, RemoteControl.ServiceState.NONE); ShadowLooper.runUiThreadTasks(); assertThat("Did not receive 'connecting' event", connectingMessageReceived.await(MESSAGE_RECEIVING_TIMEOUT, TimeUnit.MILLISECONDS), is(true)); assertThat("Did not receive 'connected' event", connectedMessageReceived.await(MESSAGE_RECEIVING_TIMEOUT, TimeUnit.MILLISECONDS), is(true)); }
/** * Test that the "error" event is sent successfully if the server sends incompatible version * information. */ @Test public void testConnectedEventIncompatibleVersion() throws InterruptedException { ShadowBluetoothSocket.setTransmittedString(SERVER_VERSION_FAILURE); final CountDownLatch messageReceived = new CountDownLatch(1); control = new BluetoothPresenterControl(new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == RemoteControl.ServiceState.ERROR.ordinal()) { assertThat("Got wrong error type", msg.getData().getString(RemoteControl.RESULT_VALUES[2]), is(RemoteControl.ERROR_TYPES.VERSION.toString())); messageReceived.countDown(); } } }); BluetoothDevice bluetoothDevice = ShadowBluetoothAdapter.getDefaultAdapter() .getRemoteDevice(DEVICE_ADDRESS); control.connect(bluetoothDevice); waitForServiceStateChanged(control, RemoteControl.ServiceState.CONNECTING); waitForServiceStateChanged(control, RemoteControl.ServiceState.NONE); ShadowLooper.runUiThreadTasks(); assertThat("Did not receive 'error' event", messageReceived.await(MESSAGE_RECEIVING_TIMEOUT, TimeUnit.MILLISECONDS), is(true)); }
/** * Test that the "error" event is sent successfully if the server sends invalid data. */ @Test public void testConnectedEventInvalidData() throws InterruptedException { ShadowBluetoothSocket.setTransmittedString("This is invalid json data\n\n"); final CountDownLatch messageReceived = new CountDownLatch(1); control = new BluetoothPresenterControl(new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == RemoteControl.ServiceState.ERROR.ordinal()) { assertThat("Got wrong error type", msg.getData().getString(RemoteControl.RESULT_VALUES[2]), is(RemoteControl.ERROR_TYPES.PARSING.toString())); messageReceived.countDown(); } } }); BluetoothDevice bluetoothDevice = ShadowBluetoothAdapter.getDefaultAdapter() .getRemoteDevice(DEVICE_ADDRESS); control.connect(bluetoothDevice); waitForServiceStateChanged(control, RemoteControl.ServiceState.CONNECTING); long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < startTime + MESSAGE_RECEIVING_TIMEOUT) { Thread.sleep(MESSAGE_CHECK_TIME); ShadowLooper.runUiThreadTasks(); if (messageReceived.await(MESSAGE_CHECK_TIME, TimeUnit.MILLISECONDS)) { return; } } fail("Did not receive 'error' event"); }
@Test public void testReceivedSignal() { final CallbackVerify receivedCallback = new CallbackVerify(); final CallbackVerify timeoutCallback = new CallbackVerify(); final SignalBasedNode node = new SignalBasedNode() { @Override protected Token onReceivedSignal(Signal signal) { receivedCallback.call(); return new Token(Token.TYPE_SUCCESS); } @Override protected Token onTimeout() { timeoutCallback.call(); return null; } }; node.setSignalName("test-signal"); DelayThread.delayRun(new Runnable() { @Override public void run() { CircleFlow.getServices().getSignalService().sendLocalEvent("test-signal"); ShadowLooper.unPauseMainLooper(); } }); Token token = node.execute(); Assert.assertTrue(receivedCallback.isCalled()); Assert.assertFalse(timeoutCallback.isCalled()); Assert.assertEquals(Token.TYPE_SUCCESS, token.getTokenType()); }
@Test public void testQueueSignalOnMainLooper() { Looper looper = ShadowLooper.getMainLooper(); SignalQueue queue = new SignalQueueImpl(looper); Assert.assertEquals(0, queue.getCurrentQueueSize()); ShadowLooper.pauseMainLooper(); queue.queueSignal(new LocalEvent()); queue.queueSignal(new LocalEvent()); queue.queueSignal(new DeviceEvent()); Assert.assertEquals(3, queue.getCurrentQueueSize()); ShadowLooper.unPauseMainLooper(); Assert.assertEquals(0, queue.getCurrentQueueSize()); }