Format Java code in xplat/js/react-native-github

Summary:
This diff formats the Java class files inside xplat/js/react-native-github. Since google-java-format was enabled in D16071401 we want to codemode the existing code so that users don't have to deal with formatter lint noise at diff-time.

```arc f --paths-cmd 'hg files -I "**/*.java"'```

drop-conflicts

Reviewed By: cpojer

Differential Revision: D16071725

fbshipit-source-id: fc6e3852e45742c109f0c5ac4065d64201c74204
This commit is contained in:
Oleksandr Melnykov
2019-07-02 04:16:46 -07:00
committed by Facebook Github Bot
parent 61e95e5cbf
commit 6c0f73b322
681 changed files with 14082 additions and 16365 deletions
@@ -1,25 +1,21 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
/**
* Shared by {@link ReactScrollViewTestCase} and {@link ReactHorizontalScrollViewTestCase}.
* See also ScrollViewTestModule.js
* Shared by {@link ReactScrollViewTestCase} and {@link ReactHorizontalScrollViewTestCase}. See also
* ScrollViewTestModule.js
*/
public abstract class AbstractScrollViewTestCase extends ReactAppInstrumentationTestCase {
@@ -38,8 +34,7 @@ public abstract class AbstractScrollViewTestCase extends ReactAppInstrumentation
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mScrollListenerModule = new ScrollListenerModule();
return super.createReactInstanceSpecForTest()
.addNativeModule(mScrollListenerModule);
return super.createReactInstanceSpecForTest().addNativeModule(mScrollListenerModule);
}
// See ScrollViewListenerModule.js
@@ -1,23 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import javax.annotation.Nullable;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
/**
* NativeModule for tests that allows assertions from JS to propagate to Java.
*/
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import javax.annotation.Nullable;
/** NativeModule for tests that allows assertions from JS to propagate to Java. */
public class AssertModule extends BaseJavaModule {
private boolean mGotSuccess;
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import com.facebook.react.bridge.Arguments;
@@ -14,12 +13,11 @@ import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.WritableMap;
/**
* Dummy implementation of storage module, used for testing
*/
/** Dummy implementation of storage module, used for testing */
public final class FakeAsyncLocalStorage extends BaseJavaModule {
private static WritableMap errorMessage;
static {
errorMessage = Arguments.createMap();
errorMessage.putString("message", "Fake Async Local Storage");
@@ -1,22 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import javax.annotation.Nullable;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import javax.annotation.Nullable;
/**
* Dummy implementation of storage module, used for testing
*/
/** Dummy implementation of storage module, used for testing */
public final class FakeWebSocketModule extends BaseJavaModule {
@Override
@@ -31,21 +27,17 @@ public final class FakeWebSocketModule extends BaseJavaModule {
@ReactMethod
public void connect(
final String url,
@Nullable final ReadableArray protocols,
@Nullable final ReadableMap headers,
final int id) {
}
final String url,
@Nullable final ReadableArray protocols,
@Nullable final ReadableMap headers,
final int id) {}
@ReactMethod
public void close(int code, String reason, int id) {
}
public void close(int code, String reason, int id) {}
@ReactMethod
public void send(String message, int id) {
}
public void send(String message, int id) {}
@ReactMethod
public void sendBinary(String base64String, int id) {
}
public void sendBinary(String base64String, int id) {}
}
@@ -1,21 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import java.util.List;
import android.view.View;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.ReactPackage;
import java.util.List;
/**
* This class wraps {@class ReactInstanceSpecForTest} in {@class ReactPackage} interface.
@@ -1,23 +1,21 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
/**
* Native module provides single method {@link #record} which records its single int argument
* in calls array
* Native module provides single method {@link #record} which records its single int argument in
* calls array
*/
public class IntRecordingModule extends BaseJavaModule {
@@ -1,26 +1,23 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactMethod;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* This class is used to verify that some JS integration tests have completed successfully.
* The JS integration tests can be started from a ReactIntegrationTestCase and upon
* finishing successfully the {@link JSIntegrationTestChecker#testDone()} method will be called.
* To verify if the test has completed successfully, call {#link JSIntegrationTestChecker#await()}
* to wait for the test to run, and {#link JSIntegrationTestChecker#isTestDone()} to check if it
* completed successfully.
* This class is used to verify that some JS integration tests have completed successfully. The JS
* integration tests can be started from a ReactIntegrationTestCase and upon finishing successfully
* the {@link JSIntegrationTestChecker#testDone()} method will be called. To verify if the test has
* completed successfully, call {#link JSIntegrationTestChecker#await()} to wait for the test to
* run, and {#link JSIntegrationTestChecker#isTestDone()} to check if it completed successfully.
*/
public class JSIntegrationTestChecker extends BaseJavaModule {
@@ -41,8 +38,7 @@ public class JSIntegrationTestChecker extends BaseJavaModule {
}
@ReactMethod
public void verifySnapshot(Callback callback) {
}
public void verifySnapshot(Callback callback) {}
public boolean await(long ms) {
try {
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import java.io.PrintWriter;
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import android.content.Intent;
@@ -19,11 +18,9 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* Base class for instrumentation tests that runs React based react application in UI mode
*/
public abstract class ReactAppInstrumentationTestCase extends
ActivityInstrumentationTestCase2<ReactAppTestActivity> implements IdleWaiter {
/** Base class for instrumentation tests that runs React based react application in UI mode */
public abstract class ReactAppInstrumentationTestCase
extends ActivityInstrumentationTestCase2<ReactAppTestActivity> implements IdleWaiter {
public ReactAppInstrumentationTestCase() {
super(ReactAppTestActivity.class);
@@ -38,9 +35,7 @@ public abstract class ReactAppInstrumentationTestCase extends
setActivityIntent(intent);
final ReactAppTestActivity activity = getActivity();
activity.loadApp(
getReactApplicationKeyUnderTest(),
createReactInstanceSpecForTest(),
getEnableDevSupport());
getReactApplicationKeyUnderTest(), createReactInstanceSpecForTest(), getEnableDevSupport());
waitForBridgeAndUIIdle();
}
@@ -56,8 +51,8 @@ public abstract class ReactAppInstrumentationTestCase extends
}
/**
* This method isn't safe since it doesn't factor in layout-only view removal. Use
* {@link #getViewByTestId(String)} instead.
* This method isn't safe since it doesn't factor in layout-only view removal. Use {@link
* #getViewByTestId(String)} instead.
*/
@Deprecated
public <T extends View> T getViewAtPath(int... path) {
@@ -65,8 +60,8 @@ public abstract class ReactAppInstrumentationTestCase extends
}
public <T extends View> T getViewByTestId(String testID) {
return (T) ReactTestHelper
.getViewWithReactTestId((ViewGroup) getRootView().getParent(), testID);
return (T)
ReactTestHelper.getViewWithReactTestId((ViewGroup) getRootView().getParent(), testID);
}
public SingleTouchGestureGenerator createGestureGenerator() {
@@ -87,31 +82,32 @@ public abstract class ReactAppInstrumentationTestCase extends
final CountDownLatch latch = new CountDownLatch(1);
final BitmapHolder bitmapHolder = new BitmapHolder();
final Runnable getScreenshotRunnable = new Runnable() {
final Runnable getScreenshotRunnable =
new Runnable() {
private static final int MAX_TRIES = 1000;
// This is the constant used in the support library for APIs that don't have Choreographer
private static final int FRAME_DELAY_MS = 10;
private static final int MAX_TRIES = 1000;
// This is the constant used in the support library for APIs that don't have Choreographer
private static final int FRAME_DELAY_MS = 10;
private int mNumRuns = 0;
private int mNumRuns = 0;
@Override
public void run() {
mNumRuns++;
ReactAppTestActivity activity = getActivity();
if (!activity.isScreenshotReady()) {
if (mNumRuns > MAX_TRIES) {
throw new RuntimeException(
"Waited " + MAX_TRIES + " frames to get screenshot but it's still not ready!");
@Override
public void run() {
mNumRuns++;
ReactAppTestActivity activity = getActivity();
if (!activity.isScreenshotReady()) {
if (mNumRuns > MAX_TRIES) {
throw new RuntimeException(
"Waited " + MAX_TRIES + " frames to get screenshot but it's still not ready!");
}
activity.postDelayed(this, FRAME_DELAY_MS);
return;
}
bitmapHolder.bitmap = getActivity().getCurrentScreenshot();
latch.countDown();
}
activity.postDelayed(this, FRAME_DELAY_MS);
return;
}
bitmapHolder.bitmap = getActivity().getCurrentScreenshot();
latch.countDown();
}
};
};
getActivity().runOnUiThread(getScreenshotRunnable);
try {
@@ -125,8 +121,8 @@ public abstract class ReactAppInstrumentationTestCase extends
}
/**
* Implement this method to provide application key to be launched. List of available
* application is located in TestBundle.js file
* Implement this method to provide application key to be launched. List of available application
* is located in TestBundle.js file
*/
protected abstract String getReactApplicationKeyUnderTest();
@@ -138,9 +134,7 @@ public abstract class ReactAppInstrumentationTestCase extends
return false;
}
/**
* Override this method to provide extra native modules to be loaded before the app starts
*/
/** Override this method to provide extra native modules to be loaded before the app starts */
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return new ReactInstanceSpecForTest();
}
@@ -149,9 +143,7 @@ public abstract class ReactAppInstrumentationTestCase extends
return getActivity().getReactContext();
}
/**
* Helper class to pass the bitmap between execution scopes in {@link #getScreenshot()}.
*/
/** Helper class to pass the bitmap between execution scopes in {@link #getScreenshot()}. */
private static class BitmapHolder {
public @Nullable volatile Bitmap bitmap;
@@ -11,15 +11,14 @@ import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import androidx.fragment.app.FragmentActivity;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.JSIModule;
import com.facebook.react.bridge.JSIModulePackage;
import com.facebook.react.bridge.JSIModuleProvider;
import com.facebook.react.bridge.JSIModuleSpec;
@@ -35,17 +34,13 @@ import com.facebook.react.modules.core.PermissionListener;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler;
import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.uimanager.ViewManagerRegistry;
import com.facebook.react.uimanager.events.EventDispatcher;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
public class ReactAppTestActivity extends FragmentActivity
implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {
@@ -190,14 +185,16 @@ public class ReactAppTestActivity extends FragmentActivity
.startReactApplication(mReactInstanceManager, appKey, initialProps);
}
});
try {
waitForBridgeAndUIIdle();
waitForLayout(5000);
} catch (InterruptedException e) {
throw new RuntimeException("Layout never occurred for component " + appKey, e);}
try {
waitForBridgeAndUIIdle();
waitForLayout(5000);
} catch (InterruptedException e) {
throw new RuntimeException("Layout never occurred for component " + appKey, e);
}
}
public void loadBundle(final ReactInstanceSpecForTest spec, String bundleName, boolean useDevSupport) {
public void loadBundle(
final ReactInstanceSpecForTest spec, String bundleName, boolean useDevSupport) {
mBridgeIdleSignaler = new ReactBridgeIdleSignaler();
@@ -215,11 +212,11 @@ public class ReactAppTestActivity extends FragmentActivity
builder.addPackage(new MainReactPackage());
}
/**
* The {@link ReactContext#mCurrentActivity} never to be set if initial lifecycle state is resumed.
* So we should call {@link ReactInstanceManagerBuilder#setCurrentActivity}.
* The {@link ReactContext#mCurrentActivity} never to be set if initial lifecycle state is
* resumed. So we should call {@link ReactInstanceManagerBuilder#setCurrentActivity}.
*
* Finally,{@link ReactInstanceManagerBuilder#build()} will create instance of {@link ReactInstanceManager}.
* And also will set {@link ReactContext#mCurrentActivity}.
* <p>Finally,{@link ReactInstanceManagerBuilder#build()} will create instance of {@link
* ReactInstanceManager}. And also will set {@link ReactContext#mCurrentActivity}.
*/
builder.setCurrentActivity(this);
builder
@@ -250,11 +247,15 @@ public class ReactAppTestActivity extends FragmentActivity
@Override
public UIManager get() {
ViewManagerRegistry viewManagerRegistry =
new ViewManagerRegistry(
mReactInstanceManager.getOrCreateViewManagers(reactApplicationContext));
new ViewManagerRegistry(
mReactInstanceManager.getOrCreateViewManagers(
reactApplicationContext));
FabricUIManagerFactory factory = spec.getFabricUIManagerFactory();
return factory != null ? factory.getFabricUIManager(reactApplicationContext, viewManagerRegistry, jsContext) : null;
return factory != null
? factory.getFabricUIManager(
reactApplicationContext, viewManagerRegistry, jsContext)
: null;
}
};
}
@@ -53,7 +53,8 @@ public class ReactInstanceSpecForTest {
return this;
}
public ReactInstanceSpecForTest setFabricUIManagerFactory(@Nullable FabricUIManagerFactory fabricUIManagerFactory) {
public ReactInstanceSpecForTest setFabricUIManagerFactory(
@Nullable FabricUIManagerFactory fabricUIManagerFactory) {
mFabricUIManagerFactory = fabricUIManagerFactory;
return this;
}
@@ -1,24 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import com.facebook.react.modules.core.ReactChoreographer;
import javax.annotation.Nullable;
import static org.mockito.Mockito.mock;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import android.app.Application;
import android.test.AndroidTestCase;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.CatalystInstance;
@@ -29,26 +21,27 @@ import com.facebook.react.bridge.SoftAssertions;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.common.futures.SimpleSettableFuture;
import com.facebook.react.devsupport.interfaces.DevSupportManager;
import com.facebook.react.modules.core.ReactChoreographer;
import com.facebook.react.modules.core.Timing;
import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler;
import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil;
import com.facebook.soloader.SoLoader;
import static org.mockito.Mockito.mock;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* Use this class for writing integration tests of catalyst. This class will run all JNI call
* within separate android looper, thus you don't need to care about starting your own looper.
* Use this class for writing integration tests of catalyst. This class will run all JNI call within
* separate android looper, thus you don't need to care about starting your own looper.
*
* Keep in mind that all JS remote method calls and script load calls are asynchronous and you
* <p>Keep in mind that all JS remote method calls and script load calls are asynchronous and you
* should not expect them to return results immediately.
*
* In order to write catalyst integration:
* 1) Make {@link ReactIntegrationTestCase} a base class of your test case
* 2) Use {@link ReactTestHelper#catalystInstanceBuilder()}
* instead of {@link com.facebook.react.bridge.CatalystInstanceImpl.Builder} to build catalyst
* instance for testing purposes
*
* <p>In order to write catalyst integration: 1) Make {@link ReactIntegrationTestCase} a base class
* of your test case 2) Use {@link ReactTestHelper#catalystInstanceBuilder()} instead of {@link
* com.facebook.react.bridge.CatalystInstanceImpl.Builder} to build catalyst instance for testing
* purposes
*/
public abstract class ReactIntegrationTestCase extends AndroidTestCase {
@@ -76,22 +69,23 @@ public abstract class ReactIntegrationTestCase extends AndroidTestCase {
mInstance = null;
final SimpleSettableFuture<Void> semaphore = new SimpleSettableFuture<>();
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
if (contextToDestroy != null) {
contextToDestroy.destroy();
}
semaphore.set(null);
}
});
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
if (contextToDestroy != null) {
contextToDestroy.destroy();
}
semaphore.set(null);
}
});
semaphore.getOrThrow();
}
}
/**
* This method isn't safe since it doesn't factor in layout-only view removal. Use
* {@link #getViewByTestId} instead.
* This method isn't safe since it doesn't factor in layout-only view removal. Use {@link
* #getViewByTestId} instead.
*/
@Deprecated
public <T extends View> T getViewAtPath(ViewGroup rootView, int... path) {
@@ -165,14 +159,12 @@ public abstract class ReactIntegrationTestCase extends AndroidTestCase {
public void waitForIdleSync() {
return;
// TODO: re-enable after cleanup of android-x migration
//InstrumentationRegistry.getInstrumentation().waitForIdleSync();
// InstrumentationRegistry.getInstrumentation().waitForIdleSync();
}
public void waitForBridgeAndUIIdle() {
ReactIdleDetectionUtil.waitForBridgeAndUIIdle(
Assertions.assertNotNull(mBridgeIdleSignaler),
getContext(),
IDLE_TIMEOUT_MS);
Assertions.assertNotNull(mBridgeIdleSignaler), getContext(), IDLE_TIMEOUT_MS);
}
@Override
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import com.facebook.react.modules.debug.interfaces.DeveloperSettings;
@@ -47,7 +46,5 @@ public class ReactSettingsForTests implements DeveloperSettings {
}
@Override
public void setRemoteJSDebugEnabled(boolean remoteJSDebugEnabled) {
}
public void setRemoteJSDebugEnabled(boolean remoteJSDebugEnabled) {}
}
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import com.facebook.buck.android.support.exopackage.ApplicationLike;
@@ -15,9 +14,9 @@ import com.facebook.soloader.SoLoader;
/**
* Application class for the Catalyst Launcher to allow it to work as an exopackage.
*
* Any app-specific code that should run before secondary dex files are loaded
* (like setting up crash reporting) should go in onBaseContextAttached.
* Anything that should run after secondary dex should go in CatalystApplicationImpl.onCreate.
* <p>Any app-specific code that should run before secondary dex files are loaded (like setting up
* crash reporting) should go in onBaseContextAttached. Anything that should run after secondary dex
* should go in CatalystApplicationImpl.onCreate.
*/
public class ReactTestAppShell extends ExopackageApplication<ApplicationLike> {
@@ -1,14 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import android.app.Application;
import com.facebook.buck.android.support.exopackage.DefaultApplicationLike;
public class ReactTestApplicationImpl extends DefaultApplicationLike {
@@ -1,14 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import android.content.Context;
import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.bridge.NativeModule;
@@ -16,10 +14,13 @@ import com.facebook.react.bridge.NativeModule;
public interface ReactTestFactory {
interface ReactInstanceEasyBuilder {
ReactInstanceEasyBuilder setContext(Context context);
ReactInstanceEasyBuilder addNativeModule(NativeModule module);
CatalystInstance build();
}
ReactInstanceEasyBuilder getCatalystInstanceBuilder();
ReactInstanceManagerBuilder getReactInstanceManagerBuilder();
}
@@ -1,23 +1,15 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import android.app.Instrumentation;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.android.internal.util.Predicate;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.NativeModuleRegistryBuilder;
import com.facebook.react.R;
@@ -25,19 +17,20 @@ import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.bridge.JavaScriptModuleRegistry;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.NativeModuleCallExceptionHandler;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec;
import com.facebook.react.bridge.CatalystInstanceImpl;
import com.facebook.react.bridge.JSBundleLoader;
import com.facebook.react.bridge.JavaScriptExecutor;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.NativeModuleCallExceptionHandler;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec;
import com.facebook.react.jscexecutor.JSCExecutorFactory;
import com.facebook.react.modules.core.ReactChoreographer;
import com.facebook.react.uimanager.ViewManager;
import com.android.internal.util.Predicate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
public class ReactTestHelper {
private static class DefaultReactTestFactory implements ReactTestFactory {
@@ -56,31 +49,30 @@ public class ReactTestHelper {
@Override
public ReactInstanceEasyBuilder addNativeModule(final NativeModule nativeModule) {
if (mNativeModuleRegistryBuilder == null) {
mNativeModuleRegistryBuilder = new NativeModuleRegistryBuilder(
(ReactApplicationContext) mContext,
null);
mNativeModuleRegistryBuilder =
new NativeModuleRegistryBuilder((ReactApplicationContext) mContext, null);
}
Assertions.assertNotNull(nativeModule);
mNativeModuleRegistryBuilder.processPackage(new ReactPackage(){
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
mNativeModuleRegistryBuilder.processPackage(
new ReactPackage() {
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.asList(nativeModule);
}
});
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.asList(nativeModule);
}
});
return this;
}
@Override
public CatalystInstance build() {
if (mNativeModuleRegistryBuilder == null) {
mNativeModuleRegistryBuilder = new NativeModuleRegistryBuilder(
(ReactApplicationContext) mContext,
null);
mNativeModuleRegistryBuilder =
new NativeModuleRegistryBuilder((ReactApplicationContext) mContext, null);
}
JavaScriptExecutor executor = null;
try {
@@ -89,21 +81,20 @@ public class ReactTestHelper {
throw new RuntimeException(e);
}
return new CatalystInstanceImpl.Builder()
.setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault())
.setJSExecutor(executor)
.setRegistry(mNativeModuleRegistryBuilder.build())
.setJSBundleLoader(JSBundleLoader.createAssetLoader(
mContext,
"assets://AndroidTestBundle.js",
false/* Asynchronous */))
.setNativeModuleCallExceptionHandler(
new NativeModuleCallExceptionHandler() {
@Override
public void handleException(Exception e) {
throw new RuntimeException(e);
}
})
.build();
.setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault())
.setJSExecutor(executor)
.setRegistry(mNativeModuleRegistryBuilder.build())
.setJSBundleLoader(
JSBundleLoader.createAssetLoader(
mContext, "assets://AndroidTestBundle.js", false /* Asynchronous */))
.setNativeModuleCallExceptionHandler(
new NativeModuleCallExceptionHandler() {
@Override
public void handleException(Exception e) {
throw new RuntimeException(e);
}
})
.build();
}
}
@@ -119,58 +110,56 @@ public class ReactTestHelper {
}
public static ReactTestFactory getReactTestFactory() {
// TODO: re-enable after cleanup of android-x migration
// Instrumentation inst = InstrumentationRegistry.getInstrumentation();
// if (!(inst instanceof ReactTestFactory)) {
return new DefaultReactTestFactory();
// }
//
// return (ReactTestFactory) inst;
// TODO: re-enable after cleanup of android-x migration
// Instrumentation inst = InstrumentationRegistry.getInstrumentation();
// if (!(inst instanceof ReactTestFactory)) {
return new DefaultReactTestFactory();
// }
//
// return (ReactTestFactory) inst;
}
public static ReactTestFactory.ReactInstanceEasyBuilder catalystInstanceBuilder(
final ReactIntegrationTestCase testCase) {
final ReactTestFactory.ReactInstanceEasyBuilder builder =
getReactTestFactory().getCatalystInstanceBuilder();
getReactTestFactory().getCatalystInstanceBuilder();
ReactTestFactory.ReactInstanceEasyBuilder postBuilder =
new ReactTestFactory.ReactInstanceEasyBuilder() {
@Override
public ReactTestFactory.ReactInstanceEasyBuilder setContext(Context context) {
builder.setContext(context);
return this;
}
new ReactTestFactory.ReactInstanceEasyBuilder() {
@Override
public ReactTestFactory.ReactInstanceEasyBuilder setContext(Context context) {
builder.setContext(context);
return this;
}
@Override
public ReactTestFactory.ReactInstanceEasyBuilder addNativeModule(NativeModule module) {
builder.addNativeModule(module);
return this;
}
@Override
public ReactTestFactory.ReactInstanceEasyBuilder addNativeModule(NativeModule module) {
builder.addNativeModule(module);
return this;
}
@Override
public CatalystInstance build() {
final CatalystInstance instance = builder.build();
testCase.initializeWithInstance(instance);
instance.runJSBundle();
// TODO: re-enable after cleanup of android-x migration
// InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
// @Override
// public void run() {
ReactChoreographer.initialize();
instance.initialize();
// }
// });
testCase.waitForBridgeAndUIIdle();
return instance;
}
};
@Override
public CatalystInstance build() {
final CatalystInstance instance = builder.build();
testCase.initializeWithInstance(instance);
instance.runJSBundle();
// TODO: re-enable after cleanup of android-x migration
// InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
// @Override
// public void run() {
ReactChoreographer.initialize();
instance.initialize();
// }
// });
testCase.waitForBridgeAndUIIdle();
return instance;
}
};
postBuilder.setContext(testCase.getContext());
return postBuilder;
}
/**
* Gets the view at given path in the UI hierarchy, ignoring modals.
*/
/** Gets the view at given path in the UI hierarchy, ignoring modals. */
public static <T extends View> T getViewAtPath(ViewGroup rootView, int... path) {
// The application root element is wrapped in a helper view in order
// to be able to display modals. See renderApplication.js.
@@ -192,8 +181,8 @@ public class ReactTestHelper {
public static String getTestId(View view) {
return view.getTag(R.id.react_test_id) instanceof String
? (String) view.getTag(R.id.react_test_id)
: null;
? (String) view.getTag(R.id.react_test_id)
: null;
}
private static View findChild(View root, Predicate<View> predicate) {
@@ -1,19 +1,17 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import javax.annotation.Nullable;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Looper;
import android.widget.FrameLayout;
import javax.annotation.Nullable;
/**
* A FrameLayout that allows you to access the result of the last time its hierarchy was drawn. It
@@ -35,8 +33,8 @@ public class ScreenshotingFrameLayout extends FrameLayout {
if (mBitmap == null) {
mBitmap = createNewBitmap(canvas);
mCanvas.setBitmap(mBitmap);
} else if (mBitmap.getWidth() != canvas.getWidth() ||
mBitmap.getHeight() != canvas.getHeight()) {
} else if (mBitmap.getWidth() != canvas.getWidth()
|| mBitmap.getHeight() != canvas.getHeight()) {
mBitmap.recycle();
mBitmap = createNewBitmap(canvas);
mCanvas.setBitmap(mBitmap);
@@ -1,28 +1,26 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import com.facebook.react.testing.idledetection.IdleWaiter;
/**
* Provides methods for generating touch events and dispatching them directly to a given view.
* Events scenarios are based on {@link android.test.TouchUtils} but they get gets dispatched
* directly through the view hierarchy using {@link View#dispatchTouchEvent} method instead of
* using instrumentation API.
* <p>
* All the events for a gesture are dispatched immediately which makes tests run very fast.
* The eventTime for each event is still set correctly. Android's gesture recognizers check
* eventTime in order to figure out gesture speed, and therefore scroll vs fling is recognized.
* directly through the view hierarchy using {@link View#dispatchTouchEvent} method instead of using
* instrumentation API.
*
* <p>All the events for a gesture are dispatched immediately which makes tests run very fast. The
* eventTime for each event is still set correctly. Android's gesture recognizers check eventTime in
* order to figure out gesture speed, and therefore scroll vs fling is recognized.
*/
public class SingleTouchGestureGenerator {
@@ -44,10 +42,7 @@ public class SingleTouchGestureGenerator {
}
private SingleTouchGestureGenerator dispatchEvent(
final int action,
final float x,
final float y,
long eventTime) {
final int action, final float x, final float y, long eventTime) {
mEventTime = eventTime;
if (action == MotionEvent.ACTION_DOWN) {
mLastDownTime = eventTime;
@@ -90,10 +85,7 @@ public class SingleTouchGestureGenerator {
}
private SingleTouchGestureGenerator dispatchDelayedEvent(
int action,
float x,
float y,
long delay) {
int action, float x, float y, long delay) {
return dispatchEvent(action, x, y, mEventTime + delay);
}
@@ -127,12 +119,7 @@ public class SingleTouchGestureGenerator {
}
public SingleTouchGestureGenerator drag(
float fromX,
float fromY,
float toX,
float toY,
int stepCount,
long totalDelay) {
float fromX, float fromY, float toX, float toY, int stepCount, long totalDelay) {
float xStep = (toX - fromX) / stepCount;
float yStep = (toY - fromY) / stepCount;
@@ -1,21 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import java.util.ArrayList;
import java.util.List;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.ArrayList;
import java.util.List;
/**
* Native module provides single method {@link #record} which records its single string argument
* in calls array
* Native module provides single method {@link #record} which records its single string argument in
* calls array
*/
public class StringRecordingModule extends BaseJavaModule {
@@ -1,15 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing.idledetection;
/**
* Interface for something that knows how to wait for bridge and UI idle.
*/
/** Interface for something that knows how to wait for bridge and UI idle. */
public interface IdleWaiter {
void waitForBridgeAndUIIdle();
@@ -1,17 +1,15 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing.idledetection;
import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener;
/**
* Utility class that uses {@link NotThreadSafeBridgeIdleDebugListener} interface to allow callers
* to wait for the bridge to be idle.
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing.idledetection;
import com.facebook.react.bridge.ReactContext;
@@ -16,104 +15,102 @@ public class ReactIdleDetectionUtil {
* bridge to become idle, then waiting for the UI thread to become idle, then checking if the
* bridge is idle again (if the bridge was idle before and is still idle after running the UI
* thread to idle, then there are no more events to process in either place).
* <p/>
* Also waits for any Choreographer callbacks to run after the initial sync since things like UI
* events are initiated from Choreographer callbacks.
*
* <p>Also waits for any Choreographer callbacks to run after the initial sync since things like
* UI events are initiated from Choreographer callbacks.
*/
public static void waitForBridgeAndUIIdle(
ReactBridgeIdleSignaler idleSignaler,
final ReactContext reactContext,
long timeoutMs) {
ReactBridgeIdleSignaler idleSignaler, final ReactContext reactContext, long timeoutMs) {
return ;
return;
// TODO: re-enable after cleanup of android-x migration
// UiThreadUtil.assertNotOnUiThread();
//
// long startTime = SystemClock.uptimeMillis();
// waitInner(idleSignaler, timeoutMs);
//
// long timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime));
// waitForChoreographer(timeToWait);
// waitForJSIdle(reactContext);
//
// timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime));
// waitInner(idleSignaler, timeToWait);
// timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime));
// waitForChoreographer(timeToWait);
// UiThreadUtil.assertNotOnUiThread();
//
// long startTime = SystemClock.uptimeMillis();
// waitInner(idleSignaler, timeoutMs);
//
// long timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime));
// waitForChoreographer(timeToWait);
// waitForJSIdle(reactContext);
//
// timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime));
// waitInner(idleSignaler, timeToWait);
// timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime));
// waitForChoreographer(timeToWait);
}
// private static void waitForChoreographer(long timeToWait) {
// final int waitFrameCount = 2;
// final CountDownLatch latch = new CountDownLatch(1);
// UiThreadUtil.runOnUiThread(
// new Runnable() {
// @Override
// public void run() {
// final ChoreographerCompat choreographerCompat = ChoreographerCompat.getInstance();
// choreographerCompat.postFrameCallback(
// new ChoreographerCompat.FrameCallback() {
//
// private int frameCount = 0;
//
// @Override
// public void doFrame(long frameTimeNanos) {
// frameCount++;
// if (frameCount == waitFrameCount) {
// latch.countDown();
// } else {
// choreographerCompat.postFrameCallback(this);
// }
// }
// });
// }
// });
// try {
// if (!latch.await(timeToWait, TimeUnit.MILLISECONDS)) {
// throw new RuntimeException("Timed out waiting for Choreographer");
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// private static void waitForJSIdle(ReactContext reactContext) {
// if (!reactContext.hasActiveCatalystInstance()) {
// return;
// }
// final CountDownLatch latch = new CountDownLatch(1);
//
// reactContext.runOnJSQueueThread(
// new Runnable() {
// @Override
// public void run() {
// latch.countDown();
// }
// });
//
// try {
// if (!latch.await(5000, TimeUnit.MILLISECONDS)) {
// throw new RuntimeException("Timed out waiting for JS thread");
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// private static void waitInner(ReactBridgeIdleSignaler idleSignaler, long timeToWait) {
// // TODO gets broken in gradle, do we need it?
// Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
// long startTime = SystemClock.uptimeMillis();
// boolean bridgeWasIdle = false;
// while (SystemClock.uptimeMillis() - startTime < timeToWait) {
// boolean bridgeIsIdle = idleSignaler.isBridgeIdle();
// if (bridgeIsIdle && bridgeWasIdle) {
// return;
// }
// bridgeWasIdle = bridgeIsIdle;
// long newTimeToWait = Math.max(1, timeToWait - (SystemClock.uptimeMillis() - startTime));
// idleSignaler.waitForIdle(newTimeToWait);
// instrumentation.waitForIdleSync();
// }
// throw new RuntimeException("Timed out waiting for bridge and UI idle!");
// }
// private static void waitForChoreographer(long timeToWait) {
// final int waitFrameCount = 2;
// final CountDownLatch latch = new CountDownLatch(1);
// UiThreadUtil.runOnUiThread(
// new Runnable() {
// @Override
// public void run() {
// final ChoreographerCompat choreographerCompat = ChoreographerCompat.getInstance();
// choreographerCompat.postFrameCallback(
// new ChoreographerCompat.FrameCallback() {
//
// private int frameCount = 0;
//
// @Override
// public void doFrame(long frameTimeNanos) {
// frameCount++;
// if (frameCount == waitFrameCount) {
// latch.countDown();
// } else {
// choreographerCompat.postFrameCallback(this);
// }
// }
// });
// }
// });
// try {
// if (!latch.await(timeToWait, TimeUnit.MILLISECONDS)) {
// throw new RuntimeException("Timed out waiting for Choreographer");
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// private static void waitForJSIdle(ReactContext reactContext) {
// if (!reactContext.hasActiveCatalystInstance()) {
// return;
// }
// final CountDownLatch latch = new CountDownLatch(1);
//
// reactContext.runOnJSQueueThread(
// new Runnable() {
// @Override
// public void run() {
// latch.countDown();
// }
// });
//
// try {
// if (!latch.await(5000, TimeUnit.MILLISECONDS)) {
// throw new RuntimeException("Timed out waiting for JS thread");
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// private static void waitInner(ReactBridgeIdleSignaler idleSignaler, long timeToWait) {
// // TODO gets broken in gradle, do we need it?
// Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
// long startTime = SystemClock.uptimeMillis();
// boolean bridgeWasIdle = false;
// while (SystemClock.uptimeMillis() - startTime < timeToWait) {
// boolean bridgeIsIdle = idleSignaler.isBridgeIdle();
// if (bridgeIsIdle && bridgeWasIdle) {
// return;
// }
// bridgeWasIdle = bridgeIsIdle;
// long newTimeToWait = Math.max(1, timeToWait - (SystemClock.uptimeMillis() - startTime));
// idleSignaler.waitForIdle(newTimeToWait);
// instrumentation.waitForIdleSync();
// }
// throw new RuntimeException("Timed out waiting for bridge and UI idle!");
// }
}
@@ -1,14 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing.network;
import javax.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
@@ -20,6 +17,7 @@ import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import javax.annotation.Nullable;
/**
* Mock Networking module that records last request received by {@link #sendRequest} method and
@@ -70,10 +68,7 @@ public class NetworkRecordingModuleMock extends ReactContextBaseJavaModule {
}
private void fireReactCallback(
Callback callback,
int status,
@Nullable String headers,
@Nullable String body) {
Callback callback, int status, @Nullable String headers, @Nullable String body) {
callback.invoke(status, headers, body);
}
@@ -6,16 +6,14 @@
package com.facebook.react.testing.rule;
import android.app.Activity;
import android.os.Build;
import androidx.test.rule.ActivityTestRule;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import androidx.test.rule.ActivityTestRule;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactPackage;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactTestHelper;
import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler;
import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil;
@@ -164,9 +162,7 @@ public class ReactNativeTestRule implements TestRule {
public void waitForIdleSync() {
ReactIdleDetectionUtil.waitForBridgeAndUIIdle(
mBridgeIdleSignaler,
mReactInstanceManager.getCurrentReactContext(),
IDLE_TIMEOUT_MS);
mBridgeIdleSignaler, mReactInstanceManager.getCurrentReactContext(), IDLE_TIMEOUT_MS);
}
/** Returns the react view */
@@ -1,20 +1,16 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.StringRecordingModule;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactTestHelper;
import com.facebook.react.testing.StringRecordingModule;
/**
* Integration test for {@code removeClippedSubviews} property that verify correct scrollview
@@ -32,18 +28,16 @@ public class AnimatedTransformTest extends ReactAppInstrumentationTestCase {
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mStringRecordingModule = new StringRecordingModule();
return super.createReactInstanceSpecForTest()
.addNativeModule(mStringRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule);
}
public void testAnimatedRotation() {
waitForBridgeAndUIIdle();
View button = ReactTestHelper.getViewWithReactTestId(
getActivity().getRootView(),
"TouchableOpacity");
View button =
ReactTestHelper.getViewWithReactTestId(getActivity().getRootView(), "TouchableOpacity");
// Tap the button which triggers the animated transform containing the
// Tap the button which triggers the animated transform containing the
// rotation strings.
createGestureGenerator().startGesture(button).endGesture();
waitForBridgeAndUIIdle();
@@ -51,5 +45,4 @@ public class AnimatedTransformTest extends ReactAppInstrumentationTestCase {
// The previous cast error will prevent it from getting here
assertEquals(2, mStringRecordingModule.getCalls().size());
}
}
@@ -1,58 +1,54 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.testing.AssertModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.uimanager.UIManagerModule;
/**
* Tests for {@link UIManagerModule#measure}, {@link UIManagerModule#measureLayout}, and
* {@link UIManagerModule#measureLayoutRelativeToParent}. Tests measurement for views in the
* following hierarchy:
* Tests for {@link UIManagerModule#measure}, {@link UIManagerModule#measureLayout}, and {@link
* UIManagerModule#measureLayoutRelativeToParent}. Tests measurement for views in the following
* hierarchy:
*
* +---------------------------------------------+
* | A |
* | |
* | +-----------+ +---------+ |
* | | B | | D | |
* | | +---+ | | | |
* | | | C | | | | |
* | | | | | +---------+ |
* | | +---+ | |
* | +-----------+ |
* | |
* | |
* | |
* +---------------------------------------------+
* <p>+---------------------------------------------+ | A | | | | +-----------+ +---------+ | | | B
* | | D | | | | +---+ | | | | | | | C | | | | | | | | | | +---------+ | | | +---+ | | |
* +-----------+ | | | | | | | +---------------------------------------------+
*
* View locations and dimensions:
* A - (0,0) to (500, 500) (500x500)
* B - (50,80) to (250, 380) (200x300)
* C - (150,150) to (200, 300) (50x150)
* D - (400,100) to (450, 300) (50x200)
* <p>View locations and dimensions: A - (0,0) to (500, 500) (500x500) B - (50,80) to (250, 380)
* (200x300) C - (150,150) to (200, 300) (50x150) D - (400,100) to (450, 300) (50x200)
*/
public class CatalystMeasureLayoutTest extends ReactAppInstrumentationTestCase {
private static interface MeasureLayoutTestModule extends JavaScriptModule {
public void verifyMeasureOnViewA();
public void verifyMeasureOnViewC();
public void verifyMeasureLayoutCRelativeToA();
public void verifyMeasureLayoutCRelativeToB();
public void verifyMeasureLayoutCRelativeToSelf();
public void verifyMeasureLayoutRelativeToParentOnViewA();
public void verifyMeasureLayoutRelativeToParentOnViewB();
public void verifyMeasureLayoutRelativeToParentOnViewC();
public void verifyMeasureLayoutDRelativeToB();
public void verifyMeasureLayoutNonExistentTag();
public void verifyMeasureLayoutNonExistentAncestor();
public void verifyMeasureLayoutRelativeToParentNonExistentTag();
}
@@ -73,8 +69,7 @@ public class CatalystMeasureLayoutTest extends ReactAppInstrumentationTestCase {
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mAssertModule = new AssertModule();
return super.createReactInstanceSpecForTest()
.addNativeModule(mAssertModule);
return super.createReactInstanceSpecForTest().addNativeModule(mAssertModule);
}
private void waitForBridgeIdleAndVerifyAsserts() {
@@ -1,19 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.List;
import android.view.MotionEvent;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.StringRecordingModule;
import java.util.List;
/**
* Test case for verifying that multitouch events are directed to the React's view touch handlers
@@ -30,8 +27,7 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return new ReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return new ReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
/**
@@ -102,27 +98,41 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
final int pointerCount,
final MotionEvent.PointerProperties[] pointerProps,
final MotionEvent.PointerCoords[] pointerCoords) {
getRootView().post(
new Runnable() {
@Override
public void run() {
MotionEvent event =
MotionEvent.obtain(start, when, action, pointerCount, pointerProps, pointerCoords, 0, 0, 1.0f, 1.0f, 0, 0, 0, 0);
getRootView().dispatchTouchEvent(event);
event.recycle();
}
});
getRootView()
.post(
new Runnable() {
@Override
public void run() {
MotionEvent event =
MotionEvent.obtain(
start,
when,
action,
pointerCount,
pointerProps,
pointerCoords,
0,
0,
1.0f,
1.0f,
0,
0,
0,
0);
getRootView().dispatchTouchEvent(event);
event.recycle();
}
});
getInstrumentation().waitForIdleSync();
}
/**
* This method "replay" multi-touch gesture recorded with modified TouchesHelper class that
* generated this piece of code (see https://phabricator.fb.com/P19756940).
* This is not intended to be copied/reused and once we need to have more multitouch gestures
* in instrumentation tests we should either:
* - implement nice generator similar to {@link SingleTouchGestureGenerator}
* - implement gesture recorded that will record touch data using arbitrary format and then read
* this recorded touch sequence during tests instead of generating code like this
* generated this piece of code (see https://phabricator.fb.com/P19756940). This is not intended
* to be copied/reused and once we need to have more multitouch gestures in instrumentation tests
* we should either: - implement nice generator similar to {@link SingleTouchGestureGenerator} -
* implement gesture recorded that will record touch data using arbitrary format and then read
* this recorded touch sequence during tests instead of generating code like this
*/
private void generateRecordedPinchTouchEvents() {
// START OF GENERATED CODE
@@ -149,7 +159,13 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
pointerCoords[0] = createPointerCoords(267.0f, 346.0f);
pointerProps[1] = createPointerProps(1, 1);
pointerCoords[1] = createPointerCoords(225.0f, 542.0f);
dispatchEvent(MotionEvent.ACTION_POINTER_DOWN | (1 << MotionEvent.ACTION_POINTER_INDEX_SHIFT), 446560605, 446560630, 2, pointerProps, pointerCoords);
dispatchEvent(
MotionEvent.ACTION_POINTER_DOWN | (1 << MotionEvent.ACTION_POINTER_INDEX_SHIFT),
446560605,
446560630,
2,
pointerProps,
pointerCoords);
}
{
@@ -639,7 +655,13 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
pointerCoords[0] = createPointerCoords(349.0f, 110.0f);
pointerProps[1] = createPointerProps(1, 1);
pointerCoords[1] = createPointerCoords(151.0f, 680.0f);
dispatchEvent(MotionEvent.ACTION_POINTER_UP | (0 << MotionEvent.ACTION_POINTER_INDEX_SHIFT), 446560605, 446561443, 2, pointerProps, pointerCoords);
dispatchEvent(
MotionEvent.ACTION_POINTER_UP | (0 << MotionEvent.ACTION_POINTER_INDEX_SHIFT),
446560605,
446561443,
2,
pointerProps,
pointerCoords);
}
{
@@ -651,5 +673,4 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
}
// END OF GENERATED CODE
}
}
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import com.facebook.react.bridge.BaseJavaModule;
@@ -44,35 +43,45 @@ import org.junit.Ignore;
/**
* Integration test to verify passing various types of parameters from JS to Java works
*
* TODO: we should run these tests with isBlockingSynchronousMethod = true as well,
* since they currently use a completely different codepath
* <p>TODO: we should run these tests with isBlockingSynchronousMethod = true as well, since they
* currently use a completely different codepath
*/
@Ignore("Fix prop types and view managers.")
public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTestCase {
private interface TestJSToJavaParametersModule extends JavaScriptModule {
void returnBasicTypes();
void returnBoxedTypes();
void returnDynamicTypes();
void returnArrayWithBasicTypes();
void returnNestedArray();
void returnArrayWithMaps();
void returnMapWithBasicTypes();
void returnNestedMap();
void returnMapWithArrays();
void returnArrayWithStringDoubleIntMapArrayBooleanNull();
void returnMapWithStringDoubleIntMapArrayBooleanNull();
void returnMapForMerge1();
void returnMapForMerge2();
void returnMapWithMultibyteUTF8CharacterString();
void returnArrayWithMultibyteUTF8CharacterString();
void returnArrayWithLargeInts();
void returnMapWithLargeInts();
}
@@ -83,10 +92,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
protected void setUp() throws Exception {
super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(
new ReactViewManager());
final UIManagerModule mUIManager =
new UIManagerModule(getContext(), viewManagers, 0);
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
@@ -97,14 +104,15 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
waitForIdleSync();
mRecordingTestModule = new RecordingTestModule();
mCatalystInstance = ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mRecordingTestModule)
.addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.addNativeModule(mUIManager)
.build();
mCatalystInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mRecordingTestModule)
.addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.addNativeModule(mUIManager)
.build();
}
public void testBasicTypes() {
@@ -314,7 +322,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
}
public void testGetTypeFromArray() {
mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class)
mCatalystInstance
.getJSModule(TestJSToJavaParametersModule.class)
.returnArrayWithStringDoubleIntMapArrayBooleanNull();
waitForBridgeAndUIIdle();
@@ -332,7 +341,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
}
public void testGetTypeFromMap() {
mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class)
mCatalystInstance
.getJSModule(TestJSToJavaParametersModule.class)
.returnMapWithStringDoubleIntMapArrayBooleanNull();
waitForBridgeAndUIIdle();
@@ -350,7 +360,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
}
public void testGetWrongTypeFromArray() {
mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class)
mCatalystInstance
.getJSModule(TestJSToJavaParametersModule.class)
.returnArrayWithStringDoubleIntMapArrayBooleanNull();
waitForBridgeAndUIIdle();
@@ -367,7 +378,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
}
public void testGetWrongTypeFromMap() {
mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class)
mCatalystInstance
.getJSModule(TestJSToJavaParametersModule.class)
.returnMapWithStringDoubleIntMapArrayBooleanNull();
waitForBridgeAndUIIdle();
@@ -595,8 +607,9 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
keys.add(mapIterator.nextKey());
}
Set<String> expectedKeys = new HashSet<String>(
Arrays.asList("stringKey", "doubleKey", "intKey", "booleanKey", "nullKey"));
Set<String> expectedKeys =
new HashSet<String>(
Arrays.asList("stringKey", "doubleKey", "intKey", "booleanKey", "nullKey"));
assertEquals(keys, expectedKeys);
}
@@ -669,9 +682,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
}
private void assertUnexpectedTypeExceptionThrown(
ReadableArray array,
int index,
String typeToAskFor) {
ReadableArray array, int index, String typeToAskFor) {
boolean gotException = false;
try {
arrayGetByType(array, index, typeToAskFor);
@@ -683,9 +694,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
}
private void assertUnexpectedTypeExceptionThrown(
ReadableMap map,
String key,
String typeToAskFor) {
ReadableMap map, String key, String typeToAskFor) {
boolean gotException = false;
try {
mapGetByType(map, key, typeToAskFor);
@@ -697,9 +706,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
}
private void assertArrayOutOfBoundsExceptionThrown(
ReadableArray array,
int index,
String typeToAskFor) {
ReadableArray array, int index, String typeToAskFor) {
boolean gotException = false;
try {
arrayGetByType(array, index, typeToAskFor);
@@ -710,10 +717,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
assertTrue(gotException);
}
private void assertNoSuchKeyExceptionThrown(
ReadableMap map,
String key,
String typeToAskFor) {
private void assertNoSuchKeyExceptionThrown(ReadableMap map, String key, String typeToAskFor) {
boolean gotException = false;
try {
mapGetByType(map, key, typeToAskFor);
@@ -724,8 +728,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
assertTrue(gotException);
}
private static void assertInvalidIteratorExceptionThrown(
ReadableMapKeySetIterator iterator) {
private static void assertInvalidIteratorExceptionThrown(ReadableMapKeySetIterator iterator) {
boolean gotException = false;
try {
iterator.nextKey();
@@ -787,12 +790,12 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
@ReactMethod
public void receiveBasicTypes(String s, double d, boolean b, String nullableString) {
mBasicTypesCalls.add(new Object[]{s, d, b, nullableString});
mBasicTypesCalls.add(new Object[] {s, d, b, nullableString});
}
@ReactMethod
public void receiveBoxedTypes(Integer i, Double d, Boolean b) {
mBoxedTypesCalls.add(new Object[]{i, d, b});
mBoxedTypesCalls.add(new Object[] {i, d, b});
}
@ReactMethod
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import com.facebook.react.bridge.CatalystInstance;
@@ -28,9 +27,7 @@ import java.util.Arrays;
import java.util.List;
import org.junit.Ignore;
/**
* Test marshalling arguments from Java to JS to appropriate native classes.
*/
/** Test marshalling arguments from Java to JS to appropriate native classes. */
@Ignore("Fix prop types and view managers.")
public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTestCase {
@@ -38,16 +35,21 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
void receiveBasicTypes(String s, double d, boolean b, String nullString);
void receiveArrayWithBasicTypes(WritableArray array);
void receiveNestedArray(WritableArray nestedArray);
void receiveArrayWithMaps(WritableArray arrayWithMaps);
void receiveMapWithBasicTypes(WritableMap map);
void receiveNestedMap(WritableMap nestedMap);
void receiveMapWithArrays(WritableMap mapWithArrays);
void receiveMapAndArrayWithNullValues(
WritableMap map,
WritableArray array);
void receiveMapAndArrayWithNullValues(WritableMap map, WritableArray array);
void receiveMapWithMultibyteUTF8CharacterString(WritableMap map);
void receiveArrayWithMultibyteUTF8CharacterString(WritableArray array);
}
@@ -58,10 +60,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
protected void setUp() throws Exception {
super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(
new ReactViewManager());
final UIManagerModule mUIManager =
new UIManagerModule(getContext(), viewManagers, 0);
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
@@ -73,17 +73,19 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
mAssertModule = new AssertModule();
mInstance = ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mAssertModule)
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.addNativeModule(mUIManager)
.build();
mInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mAssertModule)
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.addNativeModule(mUIManager)
.build();
}
public void testBasicTypes() {
mInstance.getJSModule(TestJavaToJSArgumentsModule.class)
mInstance
.getJSModule(TestJavaToJSArgumentsModule.class)
.receiveBasicTypes("foo", 3.14, true, null);
waitForBridgeAndUIIdle();
mAssertModule.verifyAssertsAndReset();
@@ -182,7 +184,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
array.pushArray(null);
array.pushMap(null);
mInstance.getJSModule(TestJavaToJSArgumentsModule.class)
mInstance
.getJSModule(TestJavaToJSArgumentsModule.class)
.receiveMapAndArrayWithNullValues(map, array);
waitForBridgeAndUIIdle();
mAssertModule.verifyAssertsAndReset();
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import com.facebook.react.bridge.BaseJavaModule;
@@ -27,14 +26,13 @@ import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import org.junit.Ignore;
/**
* Test marshalling return values from Java to JS
*/
/** Test marshalling return values from Java to JS */
@Ignore("Fix prop types and view managers.")
public class CatalystNativeJavaToJSReturnValuesTestCase extends ReactIntegrationTestCase {
private interface TestJavaToJSReturnValuesModule extends JavaScriptModule {
void callMethod(String methodName, String expectedReturnType, String expectedJSON);
void triggerException();
}
@@ -110,19 +108,19 @@ public class CatalystNativeJavaToJSReturnValuesTestCase extends ReactIntegration
super.setUp();
final UIManagerModule mUIManager =
new UIManagerModule(
getContext(), new ArrayList<ViewManager>(), 0);
new UIManagerModule(getContext(), new ArrayList<ViewManager>(), 0);
mAssertModule = new AssertModule();
mInstance = ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mAssertModule)
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.addNativeModule(mUIManager)
.addNativeModule(new TestModule())
.build();
mInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mAssertModule)
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.addNativeModule(mUIManager)
.addNativeModule(new TestModule())
.build();
}
public void testGetPrimitives() {
@@ -1,30 +1,25 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import javax.annotation.Nullable;
import android.widget.ScrollView;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.view.ReactViewGroup;
import com.facebook.react.views.view.ReactViewManager;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.Assert;
import org.junit.Ignore;
/**
* Integration test for {@code removeClippedSubviews} property that verify correct scrollview
@@ -34,9 +29,13 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
private interface SubviewsClippingTestModule extends JavaScriptModule {
void renderClippingSample1();
void renderClippingSample2();
void renderScrollViewTest();
void renderUpdatingSample1(boolean update1, boolean update2);
void renderUpdatingSample2(boolean update);
}
@@ -49,78 +48,50 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest()
.addViewManager(new ClippableViewManager(mEvents));
return super.createReactInstanceSpecForTest().addViewManager(new ClippableViewManager(mEvents));
}
/**
* In this test view are layout in a following way:
* +-----------------------------+
* | |
* | +---------------------+ |
* | | inner1 | |
* | +---------------------+ |
* | +-------------------------+ |
* | | outer (clip=true) | |
* | | +---------------------+ | |
* | | | inner2 | | |
* | | +---------------------+ | |
* | | | |
* | +-------------------------+ |
* | +---------------------+ |
* | | inner3 | |
* | +---------------------+ |
* | |
* In this test view are layout in a following way: +-----------------------------+ | | |
* +---------------------+ | | | inner1 | | | +---------------------+ | |
* +-------------------------+ | | | outer (clip=true) | | | | +---------------------+ | | | | |
* inner2 | | | | | +---------------------+ | | | | | | | +-------------------------+ | |
* +---------------------+ | | | inner3 | | | +---------------------+ | | |
* +-----------------------------+
*
* We expect only outer and inner2 to be attached
* <p>We expect only outer and inner2 to be attached
*/
public void XtestOneLevelClippingInView() throws Throwable {
mEvents.clear();
getReactContext().getJSModule(SubviewsClippingTestModule.class).renderClippingSample1();
waitForBridgeAndUIIdle();
Assert.assertArrayEquals(new String[]{"Attach_outer", "Attach_inner2"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Attach_outer", "Attach_inner2"}, mEvents.toArray());
}
/**
* In this test view are layout in a following way:
* +-----------------------------+
* | outer (clip=true) |
* | |
* | |
* | |
* | +-----------------------------+
* | | complexInner (clip=true) |
* | | +----------+ | +---------+ |
* | | | inner1 | | | inner2 | |
* | | | | | | | |
* | | +----------+ | +---------+ |
* +--------------+--------------+ |
* | +----------+ +---------+ |
* | | inner3 | | inner4 | |
* | | | | | |
* | +----------+ +---------+ |
* | |
* +-----------------------------+
* In this test view are layout in a following way: +-----------------------------+ | outer
* (clip=true) | | | | | | | | +-----------------------------+ | | complexInner (clip=true) | | |
* +----------+ | +---------+ | | | | inner1 | | | inner2 | | | | | | | | | | | | +----------+ |
* +---------+ | +--------------+--------------+ | | +----------+ +---------+ | | | inner3 | |
* inner4 | | | | | | | | | +----------+ +---------+ | | | +-----------------------------+
*
* We expect outer, complexInner & inner1 to be attached
* <p>We expect outer, complexInner & inner1 to be attached
*/
public void XtestTwoLevelClippingInView() throws Throwable {
mEvents.clear();
getReactContext().getJSModule(SubviewsClippingTestModule.class).renderClippingSample2();
waitForBridgeAndUIIdle();
Assert.assertArrayEquals(
new String[]{"Attach_outer", "Attach_complexInner", "Attach_inner1"},
mEvents.toArray());
new String[] {"Attach_outer", "Attach_complexInner", "Attach_inner1"}, mEvents.toArray());
}
/**
* This test verifies that we update clipped subviews appropriately when some of them gets
* re-layouted.
*
* In this test scenario we render clipping view ("outer") with two subviews, one is outside and
* clipped and one is inside (absolutely positioned). By updating view props we first change the
* height of the first element so that it should intersect with clipping "outer" view. Then we
* <p>In this test scenario we render clipping view ("outer") with two subviews, one is outside
* and clipped and one is inside (absolutely positioned). By updating view props we first change
* the height of the first element so that it should intersect with clipping "outer" view. Then we
* update top position of the second view so that is should go off screen.
*/
public void testClippingAfterLayoutInner() {
@@ -130,24 +101,24 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
mEvents.clear();
subviewsClippingTestModule.renderUpdatingSample1(false, false);
waitForBridgeAndUIIdle();
Assert.assertArrayEquals(new String[]{"Attach_outer", "Attach_inner2"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Attach_outer", "Attach_inner2"}, mEvents.toArray());
mEvents.clear();
subviewsClippingTestModule.renderUpdatingSample1(true, false);
waitForBridgeAndUIIdle();
Assert.assertArrayEquals(new String[]{"Attach_inner1"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Attach_inner1"}, mEvents.toArray());
mEvents.clear();
subviewsClippingTestModule.renderUpdatingSample1(true, true);
waitForBridgeAndUIIdle();
Assert.assertArrayEquals(new String[]{"Detach_inner2"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Detach_inner2"}, mEvents.toArray());
}
/**
* This test verifies that we update clipping views appropriately when parent view layout changes
* in a way that affects clipping.
*
* In this test we render clipping view ("outer") set to be 100x100dp with inner view that is
* <p>In this test we render clipping view ("outer") set to be 100x100dp with inner view that is
* absolutely positioned out of the clipping area of the parent view. Then we resize parent view
* so that inner view should be visible.
*/
@@ -158,12 +129,12 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
mEvents.clear();
subviewsClippingTestModule.renderUpdatingSample2(false);
waitForBridgeAndUIIdle();
Assert.assertArrayEquals(new String[]{"Attach_outer"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Attach_outer"}, mEvents.toArray());
mEvents.clear();
subviewsClippingTestModule.renderUpdatingSample2(true);
waitForBridgeAndUIIdle();
Assert.assertArrayEquals(new String[]{"Attach_inner"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Attach_inner"}, mEvents.toArray());
}
public void testOneLevelClippingInScrollView() throws Throwable {
@@ -171,13 +142,13 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
waitForBridgeAndUIIdle();
// Only 3 first views should be attached at the beginning
Assert.assertArrayEquals(new String[]{"Attach_0", "Attach_1", "Attach_2"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Attach_0", "Attach_1", "Attach_2"}, mEvents.toArray());
mEvents.clear();
// We scroll down such that first view get out of the bounds, we expect the first view to be
// detached and 4th view to get attached
scrollToDpInUIThread(120);
Assert.assertArrayEquals(new String[]{"Detach_0", "Attach_3"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Detach_0", "Attach_3"}, mEvents.toArray());
}
public void testTwoLevelClippingInScrollView() throws Throwable {
@@ -197,38 +168,38 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
// Scroll a little bit so that "complex" view is visible, but it's inner views are not
scrollToDpInUIThread(complexViewOffset + 5);
Assert.assertArrayEquals(new String[]{"Attach_C0"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Attach_C0"}, mEvents.toArray());
mEvents.clear();
// Step 3
// Scroll even more so that first subview of "complex" view is visible, view 1 will get off
// screen
scrollToDpInUIThread(complexViewOffset + 100);
Assert.assertArrayEquals(new String[]{"Detach_1", "Attach_C0.1"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Detach_1", "Attach_C0.1"}, mEvents.toArray());
mEvents.clear();
// Step 4
// Scroll even more to reveal second subview of "complex" view
scrollToDpInUIThread(complexViewOffset + 150);
Assert.assertArrayEquals(new String[]{"Attach_C0.2"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Attach_C0.2"}, mEvents.toArray());
mEvents.clear();
// Step 5
// Scroll back to previous position (Step 3), second view should get detached
scrollToDpInUIThread(complexViewOffset + 100);
Assert.assertArrayEquals(new String[]{"Detach_C0.2"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Detach_C0.2"}, mEvents.toArray());
mEvents.clear();
// Step 6
// Scroll back to Step 2, complex view should be visible but all subviews should be detached
scrollToDpInUIThread(complexViewOffset + 5);
Assert.assertArrayEquals(new String[]{"Attach_1", "Detach_C0.1"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Attach_1", "Detach_C0.1"}, mEvents.toArray());
mEvents.clear();
// Step 7
// Scroll back to Step 1, complex view should be gone
scrollToDpInUIThread(complexViewOffset);
Assert.assertArrayEquals(new String[]{"Detach_C0"}, mEvents.toArray());
Assert.assertArrayEquals(new String[] {"Detach_C0"}, mEvents.toArray());
}
private void scrollToDpInUIThread(final int yPositionInDP) throws Throwable {
@@ -1,51 +1,35 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.SingleTouchGestureGenerator;
import com.facebook.react.testing.StringRecordingModule;
/**
* This test is to verify that touch events bubbles up to the right handler. We emulate couple
* of different gestures on top of the application reflecting following layout:
* This test is to verify that touch events bubbles up to the right handler. We emulate couple of
* different gestures on top of the application reflecting following layout:
*
* +---------------------------------------------------------------------------------------+
* | |
* | +----------------------------------------------------------------------------------+ |
* | | +-------------+ +----------------+ | |
* | | | +---+ | | | | |
* | | | | A | | | | | |
* | | | +---+ | | C | | |
* | | | {B} | | | | |
* | | | | {D} | | | |
* | | +-------------+ +----------------+ | |
* | | | |
* | | | |
* | +----------------------------------------------------------------------------------+ |
* |
* | +----------------------------------------------------------------------------------+ |
* | | | |
* | | | |
* | | | |
* | | {E} | |
* | | | |
* | | | |
* | +----------------------------------------------------------------------------------+ |
* <p>+---------------------------------------------------------------------------------------+ | |
* | +----------------------------------------------------------------------------------+ | | |
* +-------------+ +----------------+ | | | | | +---+ | | | | | | | | | A | | | | | | | | | +---+ |
* | C | | | | | | {B} | | | | | | | | | {D} | | | | | | +-------------+ +----------------+ | | | |
* | | | | | | |
* +----------------------------------------------------------------------------------+ | | |
* +----------------------------------------------------------------------------------+ | | | | | |
* | | | | | | | | | {E} | | | | | | | | | | |
* +----------------------------------------------------------------------------------+ |
* +---------------------------------------------------------------------------------------+
*
* Then in each test case we either tap the center of a particular view (from A to E) or we start
* a gesture in one view and end it with another.
* View with names in brackets (e.g. {D}) have touch handlers set whereas all other views are not
* declared to handler touch events.
* <p>Then in each test case we either tap the center of a particular view (from A to E) or we start
* a gesture in one view and end it with another. View with names in brackets (e.g. {D}) have touch
* handlers set whereas all other views are not declared to handler touch events.
*/
public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCase {
@@ -57,8 +41,8 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa
}
/**
* 1) Simulate touch event at view A, expect {B} touch handler to fire
* 2) Simulate touch event at view C, expect {D} touch handler to fire
* 1) Simulate touch event at view A, expect {B} touch handler to fire 2) Simulate touch event at
* view C, expect {D} touch handler to fire
*/
public void testSimpleClickAtInnerElements() {
mRecordingModule.reset();
@@ -80,8 +64,7 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa
/**
* 1) Start touch at view A, then drag and release on view {B} (but outside of A), expect {B}'s
* touch handler to fire
* 2) Do the same with view C and {D}
* touch handler to fire 2) Do the same with view C and {D}
*/
public void testDownOnInnerUpOnTouchableParent() {
View innerButton = getViewByTestId("A");
@@ -151,7 +134,6 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return new ReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return new ReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
}
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.util.DisplayMetrics;
@@ -30,17 +29,21 @@ import com.facebook.react.views.view.ReactViewManager;
import java.util.Arrays;
import java.util.List;
/**
* Test case for basic {@link UIManagerModule} functionality.
*/
/** Test case for basic {@link UIManagerModule} functionality. */
public class CatalystUIManagerTestCase extends ReactIntegrationTestCase {
private interface UIManagerTestModule extends JavaScriptModule {
void renderFlexTestApplication(int rootTag);
void renderFlexWithTextApplication(int rootTag);
void renderAbsolutePositionTestApplication(int rootTag);
void renderAbsolutePositionBottomRightTestApplication(int rootTag);
void renderCenteredTextViewTestApplication(int rootTag, String text);
void renderUpdatePositionInListTestApplication(int rootTag);
void flushUpdatePositionInList();
}
@@ -71,28 +74,28 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase {
protected void setUp() throws Exception {
super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(
new ReactViewManager(),
new ReactTextViewManager(),
new ReactRawTextManager());
uiManager =
new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
uiManager.onHostResume();
}
});
List<ViewManager> viewManagers =
Arrays.<ViewManager>asList(
new ReactViewManager(), new ReactTextViewManager(), new ReactRawTextManager());
uiManager = new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
uiManager.onHostResume();
}
});
waitForIdleSync();
jsModule = ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(uiManager)
.addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.build()
.getJSModule(UIManagerTestModule.class);
jsModule =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(uiManager)
.addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.build()
.getJSModule(UIManagerTestModule.class);
}
public void testFlexUIRendered() {
@@ -134,7 +137,8 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase {
// assertEquals(inPixelRounded(300), row.getHeight());
// assertEquals(2, row.getChildCount());
//
// // Text measurement adds padding that isn't completely dependent on density so we can't easily
// // Text measurement adds padding that isn't completely dependent on density so we can't
// easily
// // get an exact value here
// float approximateExpectedTextHeight = inPixelRounded(19);
// View leftText = row.getChildAt(0);
@@ -240,10 +244,10 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase {
}
public void testCenteredTextCases() {
String[] cases = new String[] {
"test",
"with whitespace",
};
String[] cases =
new String[] {
"test", "with whitespace",
};
for (String text : cases) {
_testCenteredText(text);
}
@@ -1,34 +1,29 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.widget.DatePicker;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import android.widget.DatePicker;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.datepicker.DatePickerDialogModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Test case for {@link DatePickerDialogModule} options and callbacks.
*/
/** Test case for {@link DatePickerDialogModule} options and callbacks. */
public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
private static interface DatePickerDialogTestModule extends JavaScriptModule {
@@ -78,8 +73,7 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
@Override
@@ -105,8 +99,10 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
waitForBridgeAndUIIdle();
getInstrumentation().waitForIdleSync();
return (DialogFragment) getActivity().getSupportFragmentManager()
.findFragmentByTag(DatePickerDialogModule.FRAGMENT_TAG);
return (DialogFragment)
getActivity()
.getSupportFragmentManager()
.findFragmentByTag(DatePickerDialogModule.FRAGMENT_TAG);
}
public void testShowBasicDatePicker() {
@@ -139,7 +135,8 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
@Override
public void run() {
((DatePickerDialog) datePickerFragment.getDialog())
.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
.getButton(DialogInterface.BUTTON_POSITIVE)
.performClick();
}
});
@@ -171,5 +168,4 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
assertEquals(0, mRecordingModule.getDates().size());
assertEquals(1, mRecordingModule.getDismissed());
}
}
@@ -1,20 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.StringRecordingModule;
/**
* Simple test case to check that onError does not get called with undefined
*/
/** Simple test case to check that onError does not get called with undefined */
public class ImageErrorTestCase extends ReactAppInstrumentationTestCase {
private StringRecordingModule mStringRecordingModule;
@@ -30,17 +26,21 @@ public class ImageErrorTestCase extends ReactAppInstrumentationTestCase {
assertNotNull(getViewByTestId("image-3"));
Thread.sleep(3000);
assertEquals(3, mStringRecordingModule.getCalls().size());
assertEquals("Got error: Unsupported uri scheme! Uri is: ", mStringRecordingModule.getCalls().get(0));
assertEquals("Got error: /does/not/exist: open failed: ENOENT (No such file or directory)", mStringRecordingModule.getCalls().get(1));
assertEquals("Got error: Unexpected HTTP code Response{protocol=http/1.1, code=404, message=Not Found, url=https://typo_error_facebook.github.io/react/logo-og.png}", mStringRecordingModule.getCalls().get(2));
assertEquals(
"Got error: Unsupported uri scheme! Uri is: ", mStringRecordingModule.getCalls().get(0));
assertEquals(
"Got error: /does/not/exist: open failed: ENOENT (No such file or directory)",
mStringRecordingModule.getCalls().get(1));
assertEquals(
"Got error: Unexpected HTTP code Response{protocol=http/1.1, code=404, message=Not Found, url=https://typo_error_facebook.github.io/react/logo-og.png}",
mStringRecordingModule.getCalls().get(2));
}
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mStringRecordingModule = new StringRecordingModule();
return super.createReactInstanceSpecForTest()
.addNativeModule(mStringRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule);
}
}
@@ -1,18 +1,15 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
/**
* Simple test case for passing overlayColor prop to the Image component
*/
/** Simple test case for passing overlayColor prop to the Image component */
public class ImageOverlayColorTestCase extends ReactAppInstrumentationTestCase {
@Override
@@ -1,28 +1,23 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.os.Bundle;
import android.test.ActivityInstrumentationTestCase2;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.FakeWebSocketModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.testing.FakeWebSocketModule;
import com.facebook.react.testing.ReactAppTestActivity;
import com.facebook.react.testing.ReactInstanceSpecForTest;
/**
* Simple test case for passing initial props to the root React application.
*/
public class InitialPropsTestCase extends
ActivityInstrumentationTestCase2<ReactAppTestActivity> {
/** Simple test case for passing initial props to the root React application. */
public class InitialPropsTestCase extends ActivityInstrumentationTestCase2<ReactAppTestActivity> {
public static final String DEFAULT_JS_BUNDLE = "AndroidTestBundle.js";
@@ -78,17 +73,13 @@ public class InitialPropsTestCase extends
props.putDouble("key3", 5.5);
props.putFloat("key4", 5.6f);
props.putBoolean("key5", true);
props.putStringArray("key6", new String[]{"one", "two", "three"});
props.putIntArray("key7", new int[]{1, 2, 3});
props.putDoubleArray("key8", new double[]{1.5, 2.5, 3.5});
props.putFloatArray("key9", new float[]{1.6f, 2.6f, 3.6f});
props.putBooleanArray("key10", new boolean[]{true, false});
props.putStringArray("key6", new String[] {"one", "two", "three"});
props.putIntArray("key7", new int[] {1, 2, 3});
props.putDoubleArray("key8", new double[] {1.5, 2.5, 3.5});
props.putFloatArray("key9", new float[] {1.6f, 2.6f, 3.6f});
props.putBooleanArray("key10", new boolean[] {true, false});
activity.loadApp(
"InitialPropsTestApp",
catalystInstanceSpec,
props,
DEFAULT_JS_BUNDLE,
false);
"InitialPropsTestApp", catalystInstanceSpec, props, DEFAULT_JS_BUNDLE, false);
}
});
activity.waitForBridgeAndUIIdle();
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import com.facebook.react.bridge.CatalystInstance;
@@ -23,13 +22,12 @@ import com.facebook.react.views.view.ReactViewManager;
import java.util.Arrays;
import java.util.List;
/**
* Test locale-based functionality of JS VM
*/
/** Test locale-based functionality of JS VM */
public class JSLocaleTest extends ReactIntegrationTestCase {
private interface TestJSLocaleModule extends JavaScriptModule {
void toUpper(String string);
void toLower(String string);
}
@@ -41,12 +39,8 @@ public class JSLocaleTest extends ReactIntegrationTestCase {
protected void setUp() throws Exception {
super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(
new ReactViewManager());
final UIManagerModule mUIManager = new UIManagerModule(
getContext(),
viewManagers,
0);
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
@@ -58,13 +52,14 @@ public class JSLocaleTest extends ReactIntegrationTestCase {
waitForIdleSync();
mStringRecordingModule = new StringRecordingModule();
mInstance = ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mStringRecordingModule)
.addNativeModule(mUIManager)
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.build();
mInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mStringRecordingModule)
.addNativeModule(mUIManager)
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.build();
}
public void testToUpper() {
@@ -1,25 +1,23 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.widget.ScrollView;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.SingleTouchGestureGenerator;
import com.facebook.react.uimanager.PixelUtil;
/**
* Test case to verify that JSResponder flow work correctly.
*
* In a single test case scenario we have a view with pan gesture recognizer containing a scrollview
* We verify that by vertical drags affects a scrollview while horizontal drags are suppose to
* be recognized by pan responder and setJSResponder should be triggered resulting in scrollview
* events being intercepted.
* <p>In a single test case scenario we have a view with pan gesture recognizer containing a
* scrollview We verify that by vertical drags affects a scrollview while horizontal drags are
* suppose to be recognized by pan responder and setJSResponder should be triggered resulting in
* scrollview events being intercepted.
*/
public class JSResponderTestCase extends ReactAppInstrumentationTestCase {
@@ -55,13 +53,9 @@ public class JSResponderTestCase extends ReactAppInstrumentationTestCase {
waitForBridgeAndUIIdle();
gestureGenerator
.dragTo(30 + inpx40dp, 30, 10, 1200)
.endGesture();
gestureGenerator.dragTo(30 + inpx40dp, 30, 10, 1200).endGesture();
waitForBridgeAndUIIdle();
assertEquals("Expected not to scroll", scrollView.getScrollY(), previousScroll);
}
}
@@ -1,19 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.StringRecordingModule;
/**
* Simple test to verify that layout events (onLayout) propagate to JS from native.
*/
/** Simple test to verify that layout events (onLayout) propagate to JS from native. */
public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase {
private StringRecordingModule mStringRecordingModule;
@@ -23,9 +20,7 @@ public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase {
return "LayoutEventsTestApp";
}
/**
* Creates a UI in JS and verifies the onLayout handler is called.
*/
/** Creates a UI in JS and verifies the onLayout handler is called. */
public void testOnLayoutCalled() {
assertEquals(3, mStringRecordingModule.getCalls().size());
assertEquals("10,10-100x100", mStringRecordingModule.getCalls().get(0));
@@ -36,7 +31,6 @@ public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase {
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mStringRecordingModule = new StringRecordingModule();
return super.createReactInstanceSpecForTest()
.addNativeModule(mStringRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule);
}
}
@@ -1,23 +1,20 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.uimanager.util.ReactFindViewUtil;
import java.util.Arrays;
import java.util.List;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.uimanager.util.ReactFindViewUtil;
/**
* Tests that the 'nativeID' property can be set on various views.
* The 'nativeID' property is used to reference react managed views from native code.
* Tests that the 'nativeID' property can be set on various views. The 'nativeID' property is used
* to reference react managed views from native code.
*/
public class NativeIdTestCase extends ReactAppInstrumentationTestCase {
@@ -26,43 +23,43 @@ public class NativeIdTestCase extends ReactAppInstrumentationTestCase {
return "NativeIdTestApp";
}
private final List<String> viewTags = Arrays.asList(
"Image",
"Text",
"TouchableBounce",
"TouchableHighlight",
"TouchableOpacity",
"TouchableWithoutFeedback",
"TextInput",
"View");
private final List<String> viewTags =
Arrays.asList(
"Image",
"Text",
"TouchableBounce",
"TouchableHighlight",
"TouchableOpacity",
"TouchableWithoutFeedback",
"TextInput",
"View");
private boolean mViewFound;
@Override
protected void setUp() throws Exception {
mViewFound = false;
ReactFindViewUtil.addViewListener(new ReactFindViewUtil.OnViewFoundListener() {
@Override
public String getNativeId() {
return viewTags.get(0);
}
ReactFindViewUtil.addViewListener(
new ReactFindViewUtil.OnViewFoundListener() {
@Override
public String getNativeId() {
return viewTags.get(0);
}
@Override
public void onViewFound(View view) {
mViewFound = true;
}
});
@Override
public void onViewFound(View view) {
mViewFound = true;
}
});
super.setUp();
}
public void testPropertyIsSetForViews() {
for (String nativeId : viewTags) {
View viewWithTag = ReactFindViewUtil.findView(
getActivity().getRootView(),
nativeId);
View viewWithTag = ReactFindViewUtil.findView(getActivity().getRootView(), nativeId);
assertNotNull(
"View with nativeID " + nativeId + " was not found. Check NativeIdTestModule.js.",
viewWithTag);
"View with nativeID " + nativeId + " was not found. Check NativeIdTestModule.js.",
viewWithTag);
}
}
@@ -73,20 +70,19 @@ public class NativeIdTestCase extends ReactAppInstrumentationTestCase {
public void testFindView() {
mViewFound = false;
ReactFindViewUtil.findView(
getActivity().getRootView(),
new ReactFindViewUtil.OnViewFoundListener() {
@Override
public String getNativeId() {
return viewTags.get(0);
}
getActivity().getRootView(),
new ReactFindViewUtil.OnViewFoundListener() {
@Override
public String getNativeId() {
return viewTags.get(0);
}
@Override
public void onViewFound(View view) {
mViewFound = true;
}
});
@Override
public void onViewFound(View view) {
mViewFound = true;
}
});
assertTrue(
"OnViewFound callback should have successfully been invoked synchronously",
mViewFound);
"OnViewFound callback should have successfully been invoked synchronously", mViewFound);
}
}
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.content.res.Resources;
@@ -32,9 +31,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Test to verify that Progress bar renders as a view of the right size
*/
/** Test to verify that Progress bar renders as a view of the right size */
public class ProgressBarTestCase extends ReactIntegrationTestCase {
// Has same order of progressBars in ProgressBarTestModule
@@ -49,7 +46,7 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase {
styles.put("Inverse", android.R.attr.progressBarStyleInverse);
styles.put("SmallInverse", android.R.attr.progressBarStyleSmallInverse);
styles.put("LargeInverse", android.R.attr.progressBarStyleLargeInverse);
}
}
private static interface ProgressBarTestModule extends JavaScriptModule {
public void renderProgressBarApplication(int rootTag);
@@ -63,11 +60,9 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase {
protected void setUp() throws Exception {
super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(
new ReactViewManager(),
new ReactProgressBarViewManager());
mUIManager =
new UIManagerModule(getContext(), viewManagers, 0);
List<ViewManager> viewManagers =
Arrays.<ViewManager>asList(new ReactViewManager(), new ReactProgressBarViewManager());
mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
@@ -77,13 +72,14 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase {
});
waitForIdleSync();
mInstance = ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mUIManager)
.addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.build();
mInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mUIManager)
.addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.build();
mRootView = new ReactRootView(getContext());
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
@@ -94,16 +90,13 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase {
waitForBridgeAndUIIdle();
}
/**
* Test that the sizes of the progressBars are setup correctly
*/
/** Test that the sizes of the progressBars are setup correctly */
public void testProgressBarSizes() {
for (String style : styleList) {
ProgressBar newProgressBar =
new ProgressBar(getContext(), null, styles.get(style));
final int spec = View.MeasureSpec.makeMeasureSpec(
ViewGroup.LayoutParams.WRAP_CONTENT,
View.MeasureSpec.UNSPECIFIED);
ProgressBar newProgressBar = new ProgressBar(getContext(), null, styles.get(style));
final int spec =
View.MeasureSpec.makeMeasureSpec(
ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
newProgressBar.measure(spec, spec);
final int expectedHeight = newProgressBar.getMeasuredHeight();
@@ -1,25 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import android.view.View;
import android.widget.HorizontalScrollView;
import com.facebook.react.testing.AbstractScrollViewTestCase;
import com.facebook.react.testing.SingleTouchGestureGenerator;
import com.facebook.react.uimanager.PixelUtil;
import java.util.ArrayList;
/**
* Integration test for horizontal ScrollView.
* See ScrollViewTestModule.js
*/
/** Integration test for horizontal ScrollView. See ScrollViewTestModule.js */
public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCase {
@Override
@@ -61,8 +55,7 @@ public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCas
assertFalse("Expected to receive at least one scroll event", xOffsets.isEmpty());
assertTrue("Expected offset to be greater than 0", xOffsets.get(xOffsets.size() - 1) > 0);
assertTrue(
"Expected no item click event fired",
mScrollListenerModule.getItemsPressed().isEmpty());
"Expected no item click event fired", mScrollListenerModule.getItemsPressed().isEmpty());
assertEquals(
"Expected last offset to be offset of scroll view",
PixelUtil.toDIPFromPixel(scrollView.getScrollX()),
@@ -103,9 +96,7 @@ public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCas
assertEquals(visibleItemNumber, (int) itemIds.get(0));
}
/**
* Verify that 'scrollTo' command makes ScrollView start scrolling
*/
/** Verify that 'scrollTo' command makes ScrollView start scrolling */
public void testScrollToCommand() throws Exception {
HorizontalScrollView scrollView = getViewAtPath(0);
ScrollViewTestModule jsModule =
@@ -1,29 +1,26 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.views.picker.ReactDialogPickerManager;
import com.facebook.react.views.picker.ReactDropdownPickerManager;
import com.facebook.react.views.picker.ReactPicker;
import com.facebook.react.views.picker.ReactPickerManager;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import java.util.ArrayList;
import java.util.List;
/**
* Integration test for {@link ReactDialogPickerManager} and {@link ReactDropdownPickerManager}
@@ -34,7 +31,9 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
private static interface PickerAndroidTestModule extends JavaScriptModule {
public void selectItem(int position);
public void setMode(String mode);
public void setPrimaryColor(String color);
}
@@ -66,8 +65,7 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mRecordingModule = new PickerAndroidRecordingModule();
return super.createReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
public void testBasicProperties() {
@@ -88,29 +86,22 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
assertEquals(Color.GREEN, ((TextView) adapter.getView(1, null, null)).getCurrentTextColor());
assertEquals(Color.BLUE, ((TextView) adapter.getView(2, null, null)).getCurrentTextColor());
assertEquals(
Color.RED,
((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
Color.RED, ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
assertEquals(
Color.GREEN,
((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
Color.GREEN, ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
assertEquals(
Color.BLUE,
((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
Color.BLUE, ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
getTestModule().setPrimaryColor("black");
waitForBridgeAndUIIdle();
assertEquals(Color.BLACK, ((TextView) adapter.getView(0, null, null)).getCurrentTextColor());
assertEquals(Color.BLACK, ((TextView) adapter.getView(1, null, null)).getCurrentTextColor());
assertEquals(Color.BLACK, ((TextView) adapter.getView(2, null, null)).getCurrentTextColor());
assertEquals(
Color.RED,
((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
Color.RED, ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
assertEquals(
Color.GREEN,
((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
Color.GREEN, ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
assertEquals(
Color.BLUE,
((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
Color.BLUE, ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
}
public void testDropdownPicker() {
@@ -176,9 +167,8 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
updateFirstSpinnerAndCheckLastSpinnerMatches(2);
}
private void updateFirstSpinnerAndCheckLastSpinnerMatches(
final int indexToSelect
) throws Throwable {
private void updateFirstSpinnerAndCheckLastSpinnerMatches(final int indexToSelect)
throws Throwable {
// The last spinner has the same selected value as the first one.
// Test that user selection is propagated correctly to JS, to setState, and to Spinners.
runTestOnUiThread(
@@ -194,13 +184,12 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
ReactPicker spinnerInSync = getViewAtPath(0, 3);
assertEquals(
"Picker selection was not updated correctly via setState.",
indexToSelect,
spinnerInSync.getSelectedItemPosition());
"Picker selection was not updated correctly via setState.",
indexToSelect,
spinnerInSync.getSelectedItemPosition());
}
private PickerAndroidTestModule getTestModule() {
return getReactContext().getCatalystInstance().getJSModule(PickerAndroidTestModule.class);
}
}
@@ -1,25 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import android.view.View;
import android.widget.ScrollView;
import com.facebook.react.testing.AbstractScrollViewTestCase;
import com.facebook.react.testing.SingleTouchGestureGenerator;
import com.facebook.react.uimanager.PixelUtil;
import java.util.ArrayList;
/**
* Integration test for vertical ScrollView.
* See ScrollViewTestModule.js
*/
/** Integration test for vertical ScrollView. See ScrollViewTestModule.js */
public class ReactScrollViewTestCase extends AbstractScrollViewTestCase {
@Override
@@ -61,8 +55,7 @@ public class ReactScrollViewTestCase extends AbstractScrollViewTestCase {
assertFalse("Expected to receive at least one scroll event", yOffsets.isEmpty());
assertTrue("Expected offset to be greater than 0", yOffsets.get(yOffsets.size() - 1) > 0);
assertTrue(
"Expected no item click event fired",
mScrollListenerModule.getItemsPressed().isEmpty());
"Expected no item click event fired", mScrollListenerModule.getItemsPressed().isEmpty());
assertEquals(
"Expected last offset to be offset of scroll view",
PixelUtil.toDIPFromPixel(scrollView.getScrollY()),
@@ -104,9 +97,7 @@ public class ReactScrollViewTestCase extends AbstractScrollViewTestCase {
assertEquals(visibleItemNumber, (int) itemIds.get(0));
}
/**
* Verify that 'scrollTo' command makes ScrollView start scrolling
*/
/** Verify that 'scrollTo' command makes ScrollView start scrolling */
public void testScrollToCommand() throws Exception {
ScrollView scrollView = getViewAtPath(0);
ScrollViewTestModule jsModule =
@@ -1,24 +1,20 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.views.swiperefresh.ReactSwipeRefreshLayout;
/**
* Test case for {@link ReactSwipeRefreshLayout}.
*/
/** Test case for {@link ReactSwipeRefreshLayout}. */
public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTestCase {
private class SwipeRefreshLayoutRecordingModule extends BaseJavaModule {
@@ -53,8 +49,7 @@ public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTest
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
public void testRefreshNoScroll() {
@@ -98,5 +93,4 @@ public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTest
waitForBridgeAndUIIdle();
assertEquals(0, mRecordingModule.getCount());
}
}
@@ -1,36 +1,24 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation.ActivityMonitor;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import androidx.fragment.app.DialogFragment;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.share.ShareModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
/**
* Test case for {@link ShareModule}.
*/
/** Test case for {@link ShareModule}. */
public class ShareTestCase extends ReactAppInstrumentationTestCase {
private static interface ShareTestModule extends JavaScriptModule {
@@ -64,15 +52,13 @@ public class ShareTestCase extends ReactAppInstrumentationTestCase {
public int getErrors() {
return mErrors;
}
}
final ShareRecordingModule mRecordingModule = new ShareRecordingModule();
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
@Override
@@ -101,7 +87,5 @@ public class ShareTestCase extends ReactAppInstrumentationTestCase {
assertEquals(1, monitor.getHits());
assertEquals(1, mRecordingModule.getOpened());
assertEquals(0, mRecordingModule.getErrors());
}
}
@@ -1,25 +1,20 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactTestHelper;
import java.util.Arrays;
import java.util.List;
import android.view.View;
import com.facebook.react.views.picker.ReactDropdownPickerManager;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactTestHelper;
/**
* Tests that the 'testID' property can be set on various views.
* The 'testID' property is used to locate views in UI tests.
* Tests that the 'testID' property can be set on various views. The 'testID' property is used to
* locate views in UI tests.
*/
public class TestIdTestCase extends ReactAppInstrumentationTestCase {
@@ -28,22 +23,20 @@ public class TestIdTestCase extends ReactAppInstrumentationTestCase {
return "TestIdTestApp";
}
private final List<String> viewTags = Arrays.asList(
"Image",
"Text",
"TouchableBounce",
"TouchableHighlight",
"TouchableOpacity",
"TouchableWithoutFeedback",
"TextInput",
"View"
);
private final List<String> viewTags =
Arrays.asList(
"Image",
"Text",
"TouchableBounce",
"TouchableHighlight",
"TouchableOpacity",
"TouchableWithoutFeedback",
"TextInput",
"View");
public void testPropertyIsSetForViews() {
for (String tag : viewTags) {
View viewWithTag = ReactTestHelper.getViewWithReactTestId(
getActivity().getRootView(),
tag);
View viewWithTag = ReactTestHelper.getViewWithReactTestId(getActivity().getRootView(), tag);
assertNotNull(
"View with testID tag " + tag + " was not found. Check TestIdTestModule.js.",
viewWithTag);
@@ -1,21 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.graphics.Color;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
@@ -23,9 +20,7 @@ import com.facebook.react.testing.StringRecordingModule;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.views.textinput.ReactEditText;
/**
* Test to verify that TextInput renders correctly
*/
/** Test to verify that TextInput renders correctly */
public class TextInputTestCase extends ReactAppInstrumentationTestCase {
private final StringRecordingModule mRecordingModule = new StringRecordingModule();
@@ -47,20 +42,17 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
EditText editText = new EditText(textInputViewNoHeight.getContext());
editText.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
(float) Math.ceil(PixelUtil.toPixelFromSP(21.f)));
TypedValue.COMPLEX_UNIT_PX, (float) Math.ceil(PixelUtil.toPixelFromSP(21.f)));
editText.setPadding(0, 0, 0, 0);
int measureSpec = View.MeasureSpec.makeMeasureSpec(
ViewGroup.LayoutParams.WRAP_CONTENT,
View.MeasureSpec.UNSPECIFIED);
int measureSpec =
View.MeasureSpec.makeMeasureSpec(
ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
editText.measure(measureSpec, measureSpec);
assertEquals(editText.getMeasuredHeight(), textInputViewNoHeight.getHeight());
}
/**
* Test that the cursor moves to the end of the word.
*/
/** Test that the cursor moves to the end of the word. */
public void testTextInputCursorPosition() throws Throwable {
final EditText textInputWithText = getViewByTestId("textInput3");
@@ -71,7 +63,8 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
textInputWithText.setSelection(3);
}
});
getReactContext().getJSModule(TextInputTestModule.class)
getReactContext()
.getJSModule(TextInputTestModule.class)
.setValueRef("textInput3", "Some other value");
waitForBridgeAndUIIdle();
@@ -79,9 +72,7 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
assertEquals(4, textInputWithText.getSelectionEnd());
}
/**
* Test that the colors are applied to new text
*/
/** Test that the colors are applied to new text */
public void testTextInputColors() throws Throwable {
String testIDs[] = new String[] {"textInput4", "textInput5", "textInput6"};
@@ -94,7 +85,9 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
ReactEditText reactEditText = getViewByTestId(testID);
assertEquals(
Color.GREEN,
reactEditText.getText().getSpans(0, 1, ForegroundColorSpan.class)[0]
reactEditText
.getText()
.getSpans(0, 1, ForegroundColorSpan.class)[0]
.getForegroundColor());
}
}
@@ -113,26 +106,26 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
fireEditorActionAndCheckRecording(reactEditText, EditorInfo.IME_ACTION_NONE);
}
private void fireEditorActionAndCheckRecording(final ReactEditText reactEditText,
final int actionId) throws Throwable {
private void fireEditorActionAndCheckRecording(
final ReactEditText reactEditText, final int actionId) throws Throwable {
fireEditorActionAndCheckRecording(reactEditText, actionId, true);
fireEditorActionAndCheckRecording(reactEditText, actionId, false);
}
private void fireEditorActionAndCheckRecording(final ReactEditText reactEditText,
final int actionId,
final boolean blurOnSubmit) throws Throwable {
private void fireEditorActionAndCheckRecording(
final ReactEditText reactEditText, final int actionId, final boolean blurOnSubmit)
throws Throwable {
mRecordingModule.reset();
runTestOnUiThread(
new Runnable() {
@Override
public void run() {
reactEditText.requestFocusFromJS();
reactEditText.setBlurOnSubmit(blurOnSubmit);
reactEditText.onEditorAction(actionId);
}
});
new Runnable() {
@Override
public void run() {
reactEditText.requestFocusFromJS();
reactEditText.setBlurOnSubmit(blurOnSubmit);
reactEditText.onEditorAction(actionId);
}
});
waitForBridgeAndUIIdle();
assertEquals(1, mRecordingModule.getCalls().size());
@@ -140,114 +133,68 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
}
/**
* Test that the mentions input has colors displayed correctly.
* Removed for being flaky in open source, December 2016
public void testMetionsInputColors() throws Throwable {
EventDispatcher eventDispatcher =
getReactContext().getNativeModule(UIManagerModule.class).getEventDispatcher();
ReactEditText reactEditText = getViewByTestId("tokenizedInput");
String newText = "#Things and more #things";
int contentWidth = reactEditText.getWidth();
int contentHeight = reactEditText.getHeight();
int start = 0;
int count = newText.length();
eventDispatcher.dispatchEvent(
new ReactTextChangedEvent(
reactEditText.getId(),
newText.toString(),
(int) PixelUtil.toDIPFromPixel(contentWidth),
(int) PixelUtil.toDIPFromPixel(contentHeight),
reactEditText.incrementAndGetEventCounter()));
eventDispatcher.dispatchEvent(
new ReactTextInputEvent(
reactEditText.getId(),
newText.toString(),
"",
start,
start + count - 1));
waitForBridgeAndUIIdle();
ForegroundColorSpan[] spans = reactEditText
.getText().getSpans(0, reactEditText.getText().length(), ForegroundColorSpan.class);
assertEquals(2, spans.length);
assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor());
assertEquals(0, reactEditText.getText().getSpanStart(spans[1]));
assertEquals(7, reactEditText.getText().getSpanEnd(spans[1]));
assertEquals(newText.length() - 7, reactEditText.getText().getSpanStart(spans[0]));
assertEquals(newText.length(), reactEditText.getText().getSpanEnd(spans[0]));
String moreText = "andsuch ";
String previousText = newText;
newText += moreText;
count = moreText.length();
start = previousText.length();
eventDispatcher.dispatchEvent(
new ReactTextChangedEvent(
reactEditText.getId(),
newText.toString(),
(int) PixelUtil.toDIPFromPixel(contentWidth),
(int) PixelUtil.toDIPFromPixel(contentHeight),
reactEditText.incrementAndGetEventCounter()));
eventDispatcher.dispatchEvent(
new ReactTextInputEvent(
reactEditText.getId(),
moreText,
"",
start,
start + count - 1));
waitForBridgeAndUIIdle();
spans = reactEditText.getText()
.getSpans(0, reactEditText.getText().length(), ForegroundColorSpan.class);
assertEquals(2, spans.length);
assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor());
assertEquals(0, reactEditText.getText().getSpanStart(spans[1]));
assertEquals(7, reactEditText.getText().getSpanEnd(spans[1]));
assertEquals(newText.length() - 15, reactEditText.getText().getSpanStart(spans[0]));
assertEquals(newText.length() - 1, reactEditText.getText().getSpanEnd(spans[0]));
moreText = "morethings";
previousText = newText;
newText += moreText;
count = moreText.length();
start = previousText.length();
eventDispatcher.dispatchEvent(
new ReactTextChangedEvent(
reactEditText.getId(),
newText.toString(),
(int) PixelUtil.toDIPFromPixel(contentWidth),
(int) PixelUtil.toDIPFromPixel(contentHeight),
reactEditText.incrementAndGetEventCounter()));
eventDispatcher.dispatchEvent(
new ReactTextInputEvent(
reactEditText.getId(),
moreText,
"",
start,
start + count - 1));
waitForBridgeAndUIIdle();
spans = reactEditText.getText()
.getSpans(0, reactEditText.getText().length(), ForegroundColorSpan.class);
assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor());
assertEquals(2, spans.length);
assertEquals(0, reactEditText.getText().getSpanStart(spans[1]));
assertEquals(7, reactEditText.getText().getSpanEnd(spans[1]));
assertEquals(newText.length() - 25, reactEditText.getText().getSpanStart(spans[0]));
assertEquals(newText.length() - 11, reactEditText.getText().getSpanEnd(spans[0]));
}
*/
* Test that the mentions input has colors displayed correctly. Removed for being flaky in open
* source, December 2016 public void testMetionsInputColors() throws Throwable { EventDispatcher
* eventDispatcher =
* getReactContext().getNativeModule(UIManagerModule.class).getEventDispatcher(); ReactEditText
* reactEditText = getViewByTestId("tokenizedInput"); String newText = "#Things and more #things";
* int contentWidth = reactEditText.getWidth(); int contentHeight = reactEditText.getHeight(); int
* start = 0; int count = newText.length();
*
* <p>eventDispatcher.dispatchEvent( new ReactTextChangedEvent( reactEditText.getId(),
* newText.toString(), (int) PixelUtil.toDIPFromPixel(contentWidth), (int)
* PixelUtil.toDIPFromPixel(contentHeight), reactEditText.incrementAndGetEventCounter()));
*
* <p>eventDispatcher.dispatchEvent( new ReactTextInputEvent( reactEditText.getId(),
* newText.toString(), "", start, start + count - 1)); waitForBridgeAndUIIdle();
*
* <p>ForegroundColorSpan[] spans = reactEditText .getText().getSpans(0,
* reactEditText.getText().length(), ForegroundColorSpan.class); assertEquals(2, spans.length);
* assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); assertEquals(0,
* reactEditText.getText().getSpanStart(spans[1])); assertEquals(7,
* reactEditText.getText().getSpanEnd(spans[1])); assertEquals(newText.length() - 7,
* reactEditText.getText().getSpanStart(spans[0])); assertEquals(newText.length(),
* reactEditText.getText().getSpanEnd(spans[0]));
*
* <p>String moreText = "andsuch "; String previousText = newText; newText += moreText; count =
* moreText.length(); start = previousText.length();
*
* <p>eventDispatcher.dispatchEvent( new ReactTextChangedEvent( reactEditText.getId(),
* newText.toString(), (int) PixelUtil.toDIPFromPixel(contentWidth), (int)
* PixelUtil.toDIPFromPixel(contentHeight), reactEditText.incrementAndGetEventCounter()));
*
* <p>eventDispatcher.dispatchEvent( new ReactTextInputEvent( reactEditText.getId(), moreText, "",
* start, start + count - 1)); waitForBridgeAndUIIdle();
*
* <p>spans = reactEditText.getText() .getSpans(0, reactEditText.getText().length(),
* ForegroundColorSpan.class); assertEquals(2, spans.length);
* assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); assertEquals(0,
* reactEditText.getText().getSpanStart(spans[1])); assertEquals(7,
* reactEditText.getText().getSpanEnd(spans[1])); assertEquals(newText.length() - 15,
* reactEditText.getText().getSpanStart(spans[0])); assertEquals(newText.length() - 1,
* reactEditText.getText().getSpanEnd(spans[0]));
*
* <p>moreText = "morethings"; previousText = newText; newText += moreText; count =
* moreText.length(); start = previousText.length();
*
* <p>eventDispatcher.dispatchEvent( new ReactTextChangedEvent( reactEditText.getId(),
* newText.toString(), (int) PixelUtil.toDIPFromPixel(contentWidth), (int)
* PixelUtil.toDIPFromPixel(contentHeight), reactEditText.incrementAndGetEventCounter()));
*
* <p>eventDispatcher.dispatchEvent( new ReactTextInputEvent( reactEditText.getId(), moreText, "",
* start, start + count - 1)); waitForBridgeAndUIIdle();
*
* <p>spans = reactEditText.getText() .getSpans(0, reactEditText.getText().length(),
* ForegroundColorSpan.class); assertEquals(spans[0].getForegroundColor(),
* spans[1].getForegroundColor()); assertEquals(2, spans.length); assertEquals(0,
* reactEditText.getText().getSpanStart(spans[1])); assertEquals(7,
* reactEditText.getText().getSpanEnd(spans[1])); assertEquals(newText.length() - 25,
* reactEditText.getText().getSpanStart(spans[0])); assertEquals(newText.length() - 11,
* reactEditText.getText().getSpanEnd(spans[0])); }
*/
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
@Override
@@ -1,31 +1,26 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.List;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import androidx.fragment.app.DialogFragment;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.timepicker.TimePickerDialogModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import java.util.ArrayList;
import java.util.List;
/**
* Test case for {@link TimePickerDialogModule} options and callbacks.
*/
/** Test case for {@link TimePickerDialogModule} options and callbacks. */
public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
private static interface TimePickerDialogTestModule extends JavaScriptModule {
@@ -75,8 +70,7 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
@Override
@@ -94,8 +88,10 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
waitForBridgeAndUIIdle();
getInstrumentation().waitForIdleSync();
return (DialogFragment) getActivity().getSupportFragmentManager()
.findFragmentByTag(TimePickerDialogModule.FRAGMENT_TAG);
return (DialogFragment)
getActivity()
.getSupportFragmentManager()
.findFragmentByTag(TimePickerDialogModule.FRAGMENT_TAG);
}
public void testShowBasicTimePicker() {
@@ -119,7 +115,8 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
@Override
public void run() {
((TimePickerDialog) fragment.getDialog())
.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
.getButton(DialogInterface.BUTTON_POSITIVE)
.performClick();
}
});
@@ -155,5 +152,4 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
assertEquals(0, mRecordingModule.getTimes().size());
assertEquals(1, mRecordingModule.getDismissed());
}
}
@@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.graphics.Color;
@@ -32,9 +31,13 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase {
private interface ViewRenderingTestModule extends JavaScriptModule {
void renderViewApplication(int rootTag);
void renderMarginApplication(int rootTag);
void renderBorderApplication(int rootTag);
void updateMargins();
void renderTransformApplication(int rootTag);
}
@@ -47,8 +50,7 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase {
super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
final UIManagerModule uiManager =
new UIManagerModule(getContext(), viewManagers, 0);
final UIManagerModule uiManager = new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
@@ -58,13 +60,14 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase {
});
waitForIdleSync();
mCatalystInstance = ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(uiManager)
.addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.build();
mCatalystInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(uiManager)
.addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
.addNativeModule(new FakeWebSocketModule())
.build();
mRootView = new ReactRootView(getContext());
mRootTag = uiManager.addRootView(mRootView);
@@ -131,7 +134,8 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase {
}
public void testTransformations() {
mCatalystInstance.getJSModule(ViewRenderingTestModule.class)
mCatalystInstance
.getJSModule(ViewRenderingTestModule.class)
.renderTransformApplication(mRootTag);
waitForBridgeAndUIIdle();
@@ -36,26 +36,28 @@ public class ReactInstanceManagerTest {
Activity activity = mActivityRule.getActivity();
mReactRootView = new ReactRootView(activity);
mReactInstanceManager =
ReactTestHelper.getReactTestFactory()
.getReactInstanceManagerBuilder()
.setApplication(activity.getApplication())
.setBundleAssetName("AndroidTestBundle.js")
.setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
.addPackage(new MainReactPackage())
.build();
ReactTestHelper.getReactTestFactory()
.getReactInstanceManagerBuilder()
.setApplication(activity.getApplication())
.setBundleAssetName("AndroidTestBundle.js")
.setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
.addPackage(new MainReactPackage())
.build();
}
@After
public void tearDown() {
final ReactRootView reactRootView = mReactRootView;
final ReactInstanceManager reactInstanceManager = mReactInstanceManager;
InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
reactRootView.unmountReactApplication();
reactInstanceManager.destroy();
}
});
InstrumentationRegistry.getInstrumentation()
.runOnMainSync(
new Runnable() {
@Override
public void run() {
reactRootView.unmountReactApplication();
reactInstanceManager.destroy();
}
});
}
@Test
@@ -8,34 +8,29 @@ package com.facebook.react.tests.core;
import static org.fest.assertions.api.Assertions.assertThat;
import android.app.Instrumentation;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import com.facebook.react.ReactPackage;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ModuleSpec;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.react.testing.StringRecordingModule;
import com.facebook.react.testing.rule.ReactNativeTestRule;
import com.facebook.react.uimanager.PixelUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Provider;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.module.annotations.ReactModule;
@RunWith(AndroidJUnit4.class)
public class ReactRootViewTest {
@@ -45,55 +40,56 @@ public class ReactRootViewTest {
}
final StringRecordingModule mRecordingModule = new StringRecordingModule();
final ReactPackage mReactPackage = new MainReactPackage() {
@Override
public NativeModule getModule(String name, ReactApplicationContext context) {
if (name.equals(StringRecordingModule.NAME)) {
return mRecordingModule;
}
return super.getModule(name, context);
}
@Override
public ReactModuleInfoProvider getReactModuleInfoProvider() {
final ReactModuleInfoProvider provider = super.getReactModuleInfoProvider();
return new ReactModuleInfoProvider() {
private Map<String, ReactModuleInfo> mModuleInfos = null;
final ReactPackage mReactPackage =
new MainReactPackage() {
@Override
public Map<String, ReactModuleInfo> getReactModuleInfos() {
if (mModuleInfos != null) {
return mModuleInfos;
public NativeModule getModule(String name, ReactApplicationContext context) {
if (name.equals(StringRecordingModule.NAME)) {
return mRecordingModule;
}
mModuleInfos = new HashMap<>();
mModuleInfos.putAll(provider.getReactModuleInfos());
return super.getModule(name, context);
}
Class<? extends NativeModule> moduleClass = StringRecordingModule.class;
ReactModule reactModule = moduleClass.getAnnotation(ReactModule.class);
@Override
public ReactModuleInfoProvider getReactModuleInfoProvider() {
final ReactModuleInfoProvider provider = super.getReactModuleInfoProvider();
mModuleInfos.put(
reactModule.name(),
new ReactModuleInfo(
reactModule.name(),
moduleClass.getName(),
reactModule.canOverrideExistingModule(),
reactModule.needsEagerInit(),
reactModule.hasConstants(),
reactModule.isCxxModule(),
false));
return new ReactModuleInfoProvider() {
private Map<String, ReactModuleInfo> mModuleInfos = null;
return mModuleInfos;
@Override
public Map<String, ReactModuleInfo> getReactModuleInfos() {
if (mModuleInfos != null) {
return mModuleInfos;
}
mModuleInfos = new HashMap<>();
mModuleInfos.putAll(provider.getReactModuleInfos());
Class<? extends NativeModule> moduleClass = StringRecordingModule.class;
ReactModule reactModule = moduleClass.getAnnotation(ReactModule.class);
mModuleInfos.put(
reactModule.name(),
new ReactModuleInfo(
reactModule.name(),
moduleClass.getName(),
reactModule.canOverrideExistingModule(),
reactModule.needsEagerInit(),
reactModule.hasConstants(),
reactModule.isCxxModule(),
false));
return mModuleInfos;
}
};
}
};
}
};
@Rule
public ReactNativeTestRule mReactNativeRule =
new ReactNativeTestRule("AndroidTestBundle.js", mReactPackage);
new ReactNativeTestRule("AndroidTestBundle.js", mReactPackage);
@Before
public void setup() {
@@ -111,14 +107,13 @@ public class ReactRootViewTest {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
instrumentation.runOnMainSync(
new Runnable() {
@Override
public void run() {
rootView.setLayoutParams(new FrameLayout.LayoutParams(
newWidth,
ViewGroup.LayoutParams.MATCH_PARENT));
}
});
new Runnable() {
@Override
public void run() {
rootView.setLayoutParams(
new FrameLayout.LayoutParams(newWidth, ViewGroup.LayoutParams.MATCH_PARENT));
}
});
instrumentation.waitForIdleSync();
mReactNativeRule.waitForIdleSync();
@@ -132,24 +127,23 @@ public class ReactRootViewTest {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
instrumentation.runOnMainSync(
new Runnable() {
@Override
public void run() {
rootView.setLayoutParams(
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
});
new Runnable() {
@Override
public void run() {
rootView.setLayoutParams(
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
});
instrumentation.waitForIdleSync();
mReactNativeRule.waitForIdleSync();
int newComponentHeight = 500;
mReactNativeRule
.getContext()
.getJSModule(ReactRootViewTestModule.class)
.setHeight(newComponentHeight);
.getContext()
.getJSModule(ReactRootViewTestModule.class)
.setHeight(newComponentHeight);
instrumentation.waitForIdleSync();
mReactNativeRule.waitForIdleSync();
@@ -157,7 +151,7 @@ public class ReactRootViewTest {
// added 0.5 to account for rounding issues
assertThat(rootView.getMeasuredHeight())
.isEqualTo((int) (PixelUtil.toPixelFromDIP(newComponentHeight) + 0.5));
.isEqualTo((int) (PixelUtil.toPixelFromDIP(newComponentHeight) + 0.5));
}
/**
@@ -172,32 +166,32 @@ public class ReactRootViewTest {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
instrumentation.runOnMainSync(
new Runnable() {
@Override
public void run() {
ViewGroup parent = (ViewGroup) rootView.getParent();
parent.removeView(rootView);
// removing from parent should not remove child views, child views should be removed as
// an effect of native call to UIManager.removeRootView
assertThat(rootView.getChildCount()).isEqualTo(1);
}
});
new Runnable() {
@Override
public void run() {
ViewGroup parent = (ViewGroup) rootView.getParent();
parent.removeView(rootView);
// removing from parent should not remove child views, child views should be removed as
// an effect of native call to UIManager.removeRootView
assertThat(rootView.getChildCount()).isEqualTo(1);
}
});
instrumentation.waitForIdleSync();
mReactNativeRule.waitForIdleSync();
assertThat(mRecordingModule.getCalls().size())
.isEqualTo(0)
.overridingErrorMessage("root component should not be automatically unmounted");
.isEqualTo(0)
.overridingErrorMessage("root component should not be automatically unmounted");
assertThat(rootView.getChildCount()).isEqualTo(1);
instrumentation.runOnMainSync(
new Runnable() {
@Override
public void run() {
rootView.unmountReactApplication();
}
});
new Runnable() {
@Override
public void run() {
rootView.unmountReactApplication();
}
});
mReactNativeRule.waitForIdleSync();
assertThat(mRecordingModule.getCalls().size()).isEqualTo(1);
@@ -5,13 +5,11 @@ import static org.fest.assertions.api.Assertions.assertThat;
import androidx.test.runner.AndroidJUnit4;
import com.facebook.react.bridge.NoSuchKeyException;
import com.facebook.react.bridge.UnexpectedNativeTypeException;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;