org.robolectric.shadows.ShadowLooper Java Examples

The following examples show how to use org.robolectric.shadows.ShadowLooper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DemandFetcherTest.java    From prebid-mobile-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testBaseConditions() throws Exception {
    PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
    PublisherAdRequest request = builder.build();
    DemandFetcher demandFetcher = new DemandFetcher(request);
    demandFetcher.setPeriodMillis(0);
    HashSet<AdSize> sizes = new HashSet<>();
    sizes.add(new AdSize(300, 250));
    RequestParams requestParams = new RequestParams("12345", AdType.BANNER, sizes);
    demandFetcher.setRequestParams(requestParams);
    assertEquals(DemandFetcher.STATE.STOPPED, FieldUtils.readField(demandFetcher, "state", true));
    demandFetcher.start();
    assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
    ShadowLooper fetcherLooper = Shadows.shadowOf(demandFetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    demandFetcher.destroy();
    assertEquals(DemandFetcher.STATE.DESTROYED, FieldUtils.readField(demandFetcher, "state", true));
}
 
Example #2
Source File: BackgroundLayoutLooperRule.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      ShadowLooper layoutLooper =
          Shadows.shadowOf(
              (Looper)
                  Whitebox.invokeMethod(ComponentTree.class, "getDefaultLayoutThreadLooper"));
      mMessageQueue = new ArrayBlockingQueue<>(100);
      LayoutLooperThread layoutLooperThread = new LayoutLooperThread(layoutLooper, mMessageQueue);
      layoutLooperThread.start();
      try {
        base.evaluate();
      } finally {
        mMessageQueue.add(new Message(MessageType.QUIT));
      }
    }
  };
}
 
Example #3
Source File: StateUpdatesTestHelper.java    From litho with Apache License 2.0 6 votes vote down vote up
/**
 * Call a state update as specified in {@link StateUpdater#performStateUpdate(ComponentContext)}
 * on the component and return the updated view with the option to incrementally mount.
 *
 * @param context context
 * @param component the component to update
 * @param stateUpdater implementation of {@link StateUpdater} that triggers the state update
 * @param layoutThreadShadowLooper shadow looper to post messages to the main thread
 * @param incrementalMountEnabled whether or not to enable incremental mount for the component
 * @return the updated LithoView after the state update was applied
 */
public static LithoView getViewAfterStateUpdate(
    ComponentContext context,
    Component component,
    StateUpdater stateUpdater,
    ShadowLooper layoutThreadShadowLooper,
    boolean incrementalMountEnabled,
    boolean visibilityProcessingEnabled) {
  return getViewAfterStateUpdate(
      context,
      component,
      stateUpdater,
      new ShadowLooper[] {layoutThreadShadowLooper},
      incrementalMountEnabled,
      visibilityProcessingEnabled);
}
 
Example #4
Source File: StackPresenterTest.java    From react-native-navigation with MIT License 6 votes vote down vote up
@Test
public void mergeButtons_backButtonIsRemovedIfVisibleFalse() {
    ViewController pushedChild = spy(new SimpleViewController(activity, childRegistry, "child2", new Options()));
    disablePushAnimation(child, pushedChild);
    parent.push(child, new CommandListenerAdapter());

    assertThat(topBar.getTitleBar().getNavigationIcon()).isNull();

    parent.push(pushedChild, new CommandListenerAdapter());
    ShadowLooper.idleMainLooper();
    verify(pushedChild).onViewAppeared();
    assertThat(topBar.getTitleBar().getNavigationIcon()).isInstanceOf(BackDrawable.class);

    Options backButtonHidden = new Options();
    backButtonHidden.topBar.buttons.back.setHidden();
    uut.mergeChildOptions(backButtonHidden, backButtonHidden, parent, child);

    ShadowLooper.idleMainLooper();
    assertThat(topBar.getTitleBar().getNavigationIcon()).isNull();
}
 
Example #5
Source File: ChoreographerCompatTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreationFromMainThread() {
  ShadowLooper.pauseMainLooper();

  final AtomicBoolean firstCallback = new AtomicBoolean(false);
  final ChoreographerCompatImpl choreographerCompat = new ChoreographerCompatImpl();
  assertThat(choreographerCompat.isUsingChoreographer()).isTrue();
  new ChoreographerCompatImpl()
      .postFrameCallback(
          new FrameCallback() {
            @Override
            public void doFrame(long frameTimeNanos) {
              firstCallback.set(true);
            }
          });

  assertThat(firstCallback.get()).isFalse();

  ShadowLooper.runUiThreadTasks();

  assertThat(firstCallback.get()).isTrue();
}
 
Example #6
Source File: StackControllerTest.java    From react-native-navigation with MIT License 6 votes vote down vote up
@Test
public void push_waitForRender() {
    disablePushAnimation(child1);
    uut.push(child1, new CommandListenerAdapter());
    assertThat(child1.getView().getParent()).isEqualTo(uut.getView());

    child2.options.animations.push.waitForRender = new Bool(true);
    uut.push(child2, new CommandListenerAdapter());

    // Both children are attached
    assertThat(child1.getView().getParent()).isEqualTo(uut.getView());
    assertThat(child2.getView().getParent()).isEqualTo(uut.getView());
    assertThat(child2.isViewShown()).isFalse();
    verify(child2, times(0)).onViewAppeared();

    child2.getView().addView(new View(activity));
    ShadowLooper.idleMainLooper();
    verify(child2).onViewAppeared();
    assertThat(child2.isViewShown()).isTrue();
    animator.endPushAnimation(child2.getView());
    assertThat(child1.getView().getParent()).isNull();
}
 
Example #7
Source File: StackControllerTest.java    From react-native-navigation with MIT License 6 votes vote down vote up
@Test
public void setRoot_singleChild() {
    activity.setContentView(uut.getView());
    disablePushAnimation(child1, child2, child3);

    assertThat(uut.isEmpty()).isTrue();
    uut.push(child1, new CommandListenerAdapter());
    uut.push(child2, new CommandListenerAdapter());

    ShadowLooper.idleMainLooper();
    assertThat(uut.getTopBar().getTitleBar().getNavigationIcon()).isNotNull();
    uut.setRoot(Collections.singletonList(child3), new CommandListenerAdapter() {
        @Override
        public void onSuccess(String childId) {
            assertContainsOnlyId(child3.getId());
            ShadowLooper.idleMainLooper();
            assertThat(uut.getTopBar().getTitleBar().getNavigationIcon()).isNull();
        }
    });
}
 
Example #8
Source File: RequestOldTest.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
/**
 * Runs before every test case.
 */
@Before
public void setUp() throws Exception {
  Application context = RuntimeEnvironment.application;
  assertNotNull(context);

  Leanplum.setApplicationContext(context);

  ReflectionHelpers.setStaticField(LeanplumEventDataManager.class, "instance", null);
  LeanplumEventDataManager.sharedInstance();

  ShadowOperationQueue shadowOperationQueue = new ShadowOperationQueue();

  Field instance = OperationQueue.class.getDeclaredField("instance");
  instance.setAccessible(true);
  instance.set(instance, shadowOperationQueue);

  ShadowLooper.idleMainLooperConstantly(true);
}
 
Example #9
Source File: ObservablesTest.java    From agera with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #10
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void queueTestRetryCommand() throws Exception {
    BluetoothGattCallback callback = connectAndGetCallback();
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    BluetoothGattService service = new BluetoothGattService(SERVICE_UUID, 0);
    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"),PROPERTY_READ,0);
    BluetoothGattCharacteristic characteristic2 = new BluetoothGattCharacteristic(UUID.fromString("00002A1E-0000-1000-8000-00805f9b34fb"),PROPERTY_READ,0);
    service.addCharacteristic(characteristic);
    service.addCharacteristic(characteristic2);
    when(gatt.readCharacteristic(characteristic)).thenReturn(true);
    when(gatt.getServices()).thenReturn(Arrays.asList(service));

    peripheral.readCharacteristic(characteristic);

    verify(gatt).readCharacteristic(characteristic);

    // Trigger bonding to start
    callback.onCharacteristicRead(gatt, characteristic, 5);

    Field field = BluetoothPeripheral.class.getDeclaredField("bondStateReceiver");
    field.setAccessible(true);
    BroadcastReceiver broadcastReceiver = (BroadcastReceiver) field.get(peripheral);

    Intent intent = mock(Intent.class);
    when(intent.getAction()).thenReturn(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    when(intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)).thenReturn(BOND_BONDED);
    when(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)).thenReturn(device);

    broadcastReceiver.onReceive(context, intent);

    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    verify(gatt, times(2)).readCharacteristic(characteristic);
}
 
Example #11
Source File: ResultCodeTest.java    From prebid-mobile-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessForMoPub() throws Exception {

    HttpUrl httpUrl = server.url("/");
    Host.CUSTOM.setHostUrl(httpUrl.toString());
    PrebidMobile.setPrebidServerHost(Host.CUSTOM);
    PrebidMobile.setApplicationContext(activity.getApplicationContext());
    PrebidMobile.setPrebidServerAccountId("123456");
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.oneBidFromAppNexus()));
    BannerAdUnit adUnit = new BannerAdUnit("123456", 300, 250);
    MoPubView testView = new MoPubView(activity);
    OnCompleteListener mockListener = mock(OnCompleteListener.class);
    adUnit.fetchDemand(testView, mockListener);
    DemandFetcher fetcher = (DemandFetcher) FieldUtils.readField(adUnit, "fetcher", true);
    PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
    ShadowLooper fetcherLooper = shadowOf(fetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    ShadowLooper demandLooper = shadowOf(fetcher.getDemandHandler().getLooper());
    demandLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    verify(mockListener).onComplete(ResultCode.SUCCESS);
    assertEquals("hb_pb:0.50,hb_env:mobile-app,hb_pb_appnexus:0.50,hb_size:300x250,hb_bidder_appnexus:appnexus,hb_bidder:appnexus,hb_cache_id:df4aba04-5e69-44b8-8608-058ab21600b8,hb_env_appnexus:mobile-app,hb_size_appnexus:300x250,hb_cache_id_appnexus:df4aba04-5e69-44b8-8608-058ab21600b8,", testView.getKeywords());

}
 
Example #12
Source File: ResultCodeTest.java    From prebid-mobile-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoBids() throws Exception {
    HttpUrl httpUrl = server.url("/");
    Host.CUSTOM.setHostUrl(httpUrl.toString());
    PrebidMobile.setPrebidServerHost(Host.CUSTOM);
    PrebidMobile.setApplicationContext(activity.getApplicationContext());
    PrebidMobile.setPrebidServerAccountId("123456");
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
    BannerAdUnit adUnit = new BannerAdUnit("123456", 300, 250);
    MoPubView testView = new MoPubView(activity);
    OnCompleteListener mockListener = mock(OnCompleteListener.class);
    adUnit.fetchDemand(testView, mockListener);
    DemandFetcher fetcher = (DemandFetcher) FieldUtils.readField(adUnit, "fetcher", true);
    PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
    ShadowLooper fetcherLooper = shadowOf(fetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    ShadowLooper demandLooper = shadowOf(fetcher.getDemandHandler().getLooper());
    demandLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    verify(mockListener).onComplete(ResultCode.NO_BIDS);
    assertEquals(null, testView.getKeywords());
}
 
Example #13
Source File: ResultCodeTest.java    From prebid-mobile-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoBidsRubicon() throws Exception {
    HttpUrl httpUrl = server.url("/");
    Host.CUSTOM.setHostUrl(httpUrl.toString());
    PrebidMobile.setPrebidServerHost(Host.CUSTOM);
    PrebidMobile.setApplicationContext(activity.getApplicationContext());
    PrebidMobile.setPrebidServerAccountId("123456");
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBidFromRubicon()));
    BannerAdUnit adUnit = new BannerAdUnit("123456", 300, 250);
    MoPubView testView = new MoPubView(activity);
    OnCompleteListener mockListener = mock(OnCompleteListener.class);
    adUnit.fetchDemand(testView, mockListener);
    DemandFetcher fetcher = (DemandFetcher) FieldUtils.readField(adUnit, "fetcher", true);
    PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
    ShadowLooper fetcherLooper = shadowOf(fetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    ShadowLooper demandLooper = shadowOf(fetcher.getDemandHandler().getLooper());
    demandLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    verify(mockListener).onComplete(ResultCode.NO_BIDS);

    assertNull(testView.getKeywords());
}
 
Example #14
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 5 votes vote down vote up
private BluetoothGattCallback connectAndGetCallback() {
    peripheral.connect();

    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    ArgumentCaptor<BluetoothGattCallback> bluetoothGattCallbackCaptor = ArgumentCaptor.forClass(BluetoothGattCallback.class);
    verify(device).connectGatt(any(Context.class), anyBoolean(), bluetoothGattCallbackCaptor.capture(), anyInt());

    List<BluetoothGattCallback> capturedGatts = bluetoothGattCallbackCaptor.getAllValues();
    return capturedGatts.get(0);
}
 
Example #15
Source File: WXDomStatementTest.java    From ucar-weex-core with Apache License 2.0 5 votes vote down vote up
@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 );
}
 
Example #16
Source File: GlyphWarmerImplTest.java    From TextLayoutBuilder with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  MockitoAnnotations.initMocks(this);

  mGlyphWarmerImpl = new GlyphWarmerImpl();
  mShadowLooper = (ShadowLooper) Shadow.extract(mGlyphWarmerImpl.getWarmHandlerLooper());
}
 
Example #17
Source File: MainActivityTest.java    From ActivityDiary with GNU General Public License v3.0 5 votes vote down vote up
@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());
}
 
Example #18
Source File: WXSDKInstanceTest.java    From weex-uikit with MIT License 5 votes vote down vote up
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();
  }
 
Example #19
Source File: NavigationModuleTest.java    From react-native-navigation with MIT License 5 votes vote down vote up
@Test
public void postCommandsOnMainThread_doesNotCrashIfActivityIsNull() {
    NavigationModule spy = spy(uut);
    when(spy.activity()).thenReturn(mock(NavigationActivity.class));
    Runnable runnable = mock(Runnable.class);
    spy.handle(runnable);
    ShadowLooper.idleMainLooper();
    verify(runnable).run();

    when(spy.activity()).thenReturn(null);
    Runnable dontRun = mock(Runnable.class);
    spy.handle(dontRun);
    ShadowLooper.idleMainLooper();
    verify(dontRun, times(0)).run();
}
 
Example #20
Source File: DemandFetcherTest.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testDestroyAutoRefresh() throws Exception {
    HttpUrl httpUrl = server.url("/");
    PrebidMobile.setApplicationContext(activity);
    Host.CUSTOM.setHostUrl(httpUrl.toString());
    PrebidMobile.setPrebidServerHost(Host.CUSTOM);
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
    PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
    PublisherAdRequest request = builder.build();
    DemandFetcher demandFetcher = new DemandFetcher(request);
    PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
    demandFetcher.setPeriodMillis(30);
    HashSet<AdSize> sizes = new HashSet<>();
    sizes.add(new AdSize(300, 250));
    RequestParams requestParams = new RequestParams("12345", AdType.BANNER, sizes);
    demandFetcher.setRequestParams(requestParams);
    OnCompleteListener mockListener = mock(OnCompleteListener.class);
    demandFetcher.setListener(mockListener);
    assertEquals(DemandFetcher.STATE.STOPPED, FieldUtils.readField(demandFetcher, "state", true));
    demandFetcher.start();
    assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
    ShadowLooper fetcherLooper = Shadows.shadowOf(demandFetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    ShadowLooper demandLooper = Shadows.shadowOf(demandFetcher.getDemandHandler().getLooper());
    demandLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
    demandFetcher.destroy();
    assertTrue(!Robolectric.getForegroundThreadScheduler().areAnyRunnable());
    assertTrue(!Robolectric.getBackgroundThreadScheduler().areAnyRunnable());
    assertEquals(DemandFetcher.STATE.DESTROYED, FieldUtils.readField(demandFetcher, "state", true));
    verify(mockListener, Mockito.times(1)).onComplete(ResultCode.NO_BIDS);
}
 
Example #21
Source File: RobolectricTestBase.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private <T extends Form> void setUpForm(Class<T> clazz) {
  ShadowLooper.getShadowMainLooper().getScheduler().setIdleState(IdleState.PAUSED);
  ActivityController<T> activityController = Robolectric.buildActivity(clazz)
      .create().start().resume().visible();
  form = activityController.get();
  // Unfortunately Robolectric won't handle laying out the view hierarchy and because of how
  // we use runOnUiThread in the Initialize() method, tests will enter an infinite loop. This
  // code simulates enough of the layout process so that we don't loop forever.
  View v = ((ViewGroup) form.findViewById(android.R.id.content)).getChildAt(0);
  v = ((ViewGroup) v).getChildAt(1);  // frameLayoutWithTitle in Form
  v = ((ViewGroup) v).getChildAt(0);  // frameLayout in Form
  v.layout(0, 0, 240, 320);
  v.measure(240, 320);
  v.invalidate();
  v.requestLayout();
  ShadowLooper.getShadowMainLooper().getScheduler().setIdleState(IdleState.UNPAUSED);
  ShadowEventDispatcher.clearEvents();  // start with a clean slate
}
 
Example #22
Source File: ComponentTreeTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetSizeSpecAsyncFollowedBySetSizeSpecSyncBeforeStartReturnsCorrectSize() {
  final Component component =
      SimpleMountSpecTester.create(mContext).flexGrow(1).color(1234).build();
  ComponentTree componentTree = ComponentTree.create(mContext, component).build();
  componentTree.setLithoView(new LithoView(mContext));

  int widthSpec1 = SizeSpec.makeSizeSpec(1000, SizeSpec.EXACTLY);
  int heightSpec1 = SizeSpec.makeSizeSpec(1000, SizeSpec.AT_MOST);
  int widthSpec2 = SizeSpec.makeSizeSpec(500, SizeSpec.EXACTLY);
  int heightSpec2 = SizeSpec.makeSizeSpec(500, SizeSpec.AT_MOST);

  componentTree.attach();
  componentTree.measure(widthSpec1, heightSpec1, new int[2], false);

  componentTree.setSizeSpecAsync(widthSpec2, heightSpec2);

  Size size = new Size();
  componentTree.setSizeSpec(widthSpec2, heightSpec2, size);
  assertThat(size).isEqualToComparingFieldByField(new Size(500, 500));

  mBackgroundLayoutLooperRule.runToEndOfTasksSync();
  ShadowLooper.runUiThreadTasks();

  assertThat(componentTree.getRoot()).isEqualTo(component);
  assertThat(componentTree.hasCompatibleLayout(widthSpec2, heightSpec2)).isTrue();
  assertThat(componentTree.getMainThreadLayoutState().getHeight()).isEqualTo(500);
  assertThat(componentTree.getMainThreadLayoutState().getWidth()).isEqualTo(500);

  assertThat(mLithoStatsRule.getComponentCalculateLayoutCount())
      .describedAs("We expect one initial layout and the async layout.")
      .isEqualTo(2);
}
 
Example #23
Source File: LayoutDiffingTest.java    From litho with Apache License 2.0 5 votes vote down vote up
/**
 * In this scenario, we make sure that if a state update happens in the background followed by a
 * second state update in the background before the first can commit on the main thread, that we
 * still properly diff at mount time and don't unmount and remount and MountSpecs
 * with @ShouldUpdate(onMount = true).
 */
@Test
public void
    layoutDiffing_multipleStateUpdatesInParallelWithShouldUpdateFalse_mountContentIsNotRemounted() {
  final SimpleStateUpdateEmulatorSpec.Caller stateUpdater =
      new SimpleStateUpdateEmulatorSpec.Caller();
  final ArrayList<LifecycleStep> operations = new ArrayList<>();
  final Object firstObjectForShouldUpdate = new Object();

  mLithoViewRule
      .setRoot(
          createRootComponentWithStateUpdater(
              mLithoViewRule.getContext(), firstObjectForShouldUpdate, operations, stateUpdater))
      .setSizePx(100, 100)
      .measure()
      .layout()
      .attachToWindow();

  assertThat(operations)
      .describedAs("Test setup, there should be an initial mount")
      .containsExactly(LifecycleStep.ON_MOUNT);
  operations.clear();

  // Do two state updates sequentially without draining the main thread queue
  stateUpdater.incrementAsync();
  mBackgroundLayoutLooperRule.runToEndOfTasksSync();

  stateUpdater.incrementAsync();
  mBackgroundLayoutLooperRule.runToEndOfTasksSync();

  // Now drain the main thread queue and mount the result
  ShadowLooper.idleMainLooper();
  mLithoViewRule.layout();

  assertThat(operations).isEmpty();
}
 
Example #24
Source File: LayoutDiffingTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void
    layoutDiffing_multipleSetRootsInParallelWithShouldUpdateFalse_mountContentIsNotRemounted() {
  final ArrayList<LifecycleStep> operations = new ArrayList<>();
  final Object firstObjectForShouldUpdate = new Object();

  mLithoViewRule
      .setRoot(
          createRootComponent(
              mLithoViewRule.getContext(), firstObjectForShouldUpdate, operations))
      .setSizePx(100, 100)
      .measure()
      .layout()
      .attachToWindow();

  assertThat(operations)
      .describedAs("Test setup, there should be an initial mount")
      .containsExactly(LifecycleStep.ON_MOUNT);
  operations.clear();

  // Do two prop updates sequentially without draining the main thread queue
  mLithoViewRule.setRootAsync(
      createRootComponent(mLithoViewRule.getContext(), firstObjectForShouldUpdate, operations));
  mBackgroundLayoutLooperRule.runToEndOfTasksSync();

  mLithoViewRule.setRootAsync(
      createRootComponent(mLithoViewRule.getContext(), firstObjectForShouldUpdate, operations));
  mBackgroundLayoutLooperRule.runToEndOfTasksSync();

  // Now drain the main thread queue and mount the result
  ShadowLooper.idleMainLooper();
  mLithoViewRule.layout();

  assertThat(operations).isEmpty();
}
 
Example #25
Source File: ButtonPresenterTest.java    From react-native-navigation with MIT License 5 votes vote down vote up
@Test
public void applyOptions_appliesColorOnButtonTextView() {
    MenuItem menuItem = buttonController.createAndAddButtonToTitleBar(titleBar, 0);
    uut.applyOptions(titleBar, menuItem, buttonController::getView);

    ShadowLooper.idleMainLooper();
    List<TextView> textualButtons = ViewUtils.findChildrenByClass(
            requireNonNull(ViewUtils.findChildByClass(titleBar, ActionMenuView.class)),
            TextView.class,
            child -> true
    );
    assertThat(textualButtons.get(0).getCurrentTextColor()).isEqualTo(Color.RED);
}
 
Example #26
Source File: LayoutDiffingTest.java    From litho with Apache License 2.0 5 votes vote down vote up
/**
 * In this scenario, we make sure that if a setRoot happens in the background followed by a second
 * setRoot in the background before the first can commit on the main thread, that we still
 * properly diff at mount time and don't unmount and remount and MountSpecs
 * with @ShouldUpdate(onMount = true).
 */
@Test
public void
    layoutDiffing_multipleSetRootsInParallelWithShouldUpdateTrueForFirstLayout_mountContentIsRemounted() {
  final ArrayList<LifecycleStep> operations = new ArrayList<>();
  final Object firstObjectForShouldUpdate = new Object();

  mLithoViewRule
      .setRoot(
          createRootComponent(
              mLithoViewRule.getContext(), firstObjectForShouldUpdate, operations))
      .setSizePx(100, 100)
      .measure()
      .layout()
      .attachToWindow();

  assertThat(operations).containsExactly(LifecycleStep.ON_MOUNT);
  operations.clear();

  final Object secondObjectForShouldUpdate = new Object();

  // Do two prop updates sequentially without draining the main thread queue
  mLithoViewRule.setRootAsync(
      createRootComponent(mLithoViewRule.getContext(), secondObjectForShouldUpdate, operations));
  mBackgroundLayoutLooperRule.runToEndOfTasksSync();

  mLithoViewRule.setRootAsync(
      createRootComponent(mLithoViewRule.getContext(), secondObjectForShouldUpdate, operations));
  mBackgroundLayoutLooperRule.runToEndOfTasksSync();

  // Now drain the main thread queue and mount the result
  ShadowLooper.idleMainLooper();
  mLithoViewRule.layout();

  // In this case, we did change the object for shouldUpdate in layout 1 even though
  // it was the same for layouts 2. We expect to see unmount and mount.
  assertThat(operations).containsExactly(LifecycleStep.ON_UNMOUNT, LifecycleStep.ON_MOUNT);
  operations.clear();
}
 
Example #27
Source File: LayoutDiffingTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void
    layoutDiffing_multipleSetRootsInParallelWithShouldUpdateTrueForSecondLayout_mountContentIsRemounted() {
  final ArrayList<LifecycleStep> operations = new ArrayList<>();
  final Object firstObjectForShouldUpdate = new Object();

  mLithoViewRule
      .setRoot(
          createRootComponent(
              mLithoViewRule.getContext(), firstObjectForShouldUpdate, operations))
      .setSizePx(100, 100)
      .measure()
      .layout()
      .attachToWindow();

  assertThat(operations).containsExactly(LifecycleStep.ON_MOUNT);
  operations.clear();

  final Object secondObjectForShouldUpdate = new Object();

  // Do two prop updates sequentially without draining the main thread queue
  mLithoViewRule.setRootAsync(
      createRootComponent(mLithoViewRule.getContext(), firstObjectForShouldUpdate, operations));
  mBackgroundLayoutLooperRule.runToEndOfTasksSync();

  mLithoViewRule.setRootAsync(
      createRootComponent(mLithoViewRule.getContext(), secondObjectForShouldUpdate, operations));
  mBackgroundLayoutLooperRule.runToEndOfTasksSync();

  // Now drain the main thread queue and mount the result
  ShadowLooper.idleMainLooper();
  mLithoViewRule.layout();

  // Similar to the previous test, but the object changes on the second layout instead.
  assertThat(operations).containsExactly(LifecycleStep.ON_UNMOUNT, LifecycleStep.ON_MOUNT);
}
 
Example #28
Source File: SectionTreeTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncChangesetWithoutBackgroundChangesetSupportCalledFromMainThread()
    throws InterruptedException {
  final Section leaf1 =
      TestSectionCreator.createChangeSetComponent(
          "leaf1", Change.insert(0, makeComponentInfo()), Change.insert(1, makeComponentInfo()));

  final Section node1 = TestSectionCreator.createSectionComponent("node1", leaf1);

  final ThreadCheckingTarget target = new ThreadCheckingTarget(false);

  final Section root = TestSectionCreator.createSectionComponent("root", node1);
  final SectionTree tree = SectionTree.create(mSectionContext, target).build();
  final CountDownLatch latch = new CountDownLatch(1);
  final long mainThreadId = Thread.currentThread().getId();

  new Thread(
          new Runnable() {
            @Override
            public void run() {
              tree.setRoot(root);
              latch.countDown();
            }
          })
      .start();

  assertThat(latch.await(5000, TimeUnit.MILLISECONDS)).isTrue();

  ShadowLooper.runMainLooperOneTask();

  assertThat(target.getNumInserts()).isEqualTo(2);

  final List<Long> interactionThreadIds = target.getInteractionThreadIds();
  assertThat(interactionThreadIds).isNotEmpty();
  for (long id : interactionThreadIds) {
    assertThat(id).isEqualTo(mainThreadId);
  }
}
 
Example #29
Source File: WXSDKInstanceTest.java    From ucar-weex-core with Apache License 2.0 5 votes vote down vote up
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();
  }
 
Example #30
Source File: DemandFetcherTest.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleRequestNoBidsResponse() throws Exception {
    HttpUrl httpUrl = server.url("/");
    PrebidMobile.setApplicationContext(activity);
    Host.CUSTOM.setHostUrl(httpUrl.toString());
    PrebidMobile.setPrebidServerHost(Host.CUSTOM);
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
    PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
    PublisherAdRequest request = builder.build();
    DemandFetcher demandFetcher = new DemandFetcher(request);
    PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
    demandFetcher.setPeriodMillis(0);
    HashSet<AdSize> sizes = new HashSet<>();
    sizes.add(new AdSize(300, 250));
    RequestParams requestParams = new RequestParams("12345", AdType.BANNER, sizes);
    demandFetcher.setRequestParams(requestParams);
    OnCompleteListener mockListener = mock(OnCompleteListener.class);
    demandFetcher.setListener(mockListener);
    assertEquals(DemandFetcher.STATE.STOPPED, FieldUtils.readField(demandFetcher, "state", true));
    demandFetcher.start();
    assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
    ShadowLooper fetcherLooper = Shadows.shadowOf(demandFetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    ShadowLooper demandLooper = Shadows.shadowOf(demandFetcher.getDemandHandler().getLooper());
    demandLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    verify(mockListener).onComplete(ResultCode.NO_BIDS);
    assertEquals(DemandFetcher.STATE.DESTROYED, FieldUtils.readField(demandFetcher, "state", true));
}