@Test public void testReposActivityFragments() { ActivityTestRule rule = new ActivityTestRule<>(ReposActivity.class, true, false); shelfTestUtils.setupBook("book-one", "Preface\n\n* Note"); shelfTestUtils.setupRepo("file:/"); shelfTestUtils.setupRepo("dropbox:/orgzly"); rule.launchActivity(null); // List of repos fragmentTest(rule, false, withId(R.id.fragment_repos_flipper)); // Directory repo onListItem(1).perform(click()); fragmentTest(rule, false, withId(R.id.fragment_repo_directory_container)); pressBack(); // Dropbox repo onListItem(0).perform(click()); fragmentTest(rule, false, withId(R.id.fragment_repo_dropbox_container)); }
private void fragmentTest(ActivityTestRule rule, boolean hasSearchMenuItem, Matcher<View> matcher) { onView(matcher).check(matches(isDisplayed())); toPortrait(rule); onView(matcher).check(matches(isDisplayed())); toLandscape(rule); onView(matcher).check(matches(isDisplayed())); toPortrait(rule); onView(matcher).check(matches(isDisplayed())); toLandscape(rule); onView(matcher).check(matches(isDisplayed())); toPortrait(rule); if (hasSearchMenuItem) { onView(withId(R.id.activity_action_search)).check(matches(isDisplayed())); } else { onView(withId(R.id.activity_action_search)).check(doesNotExist()); } }
ActivityTestRule<CounterActivity> createRule(){ return new ActivityTestRule<CounterActivity>(CounterActivity.class) { @Override protected void beforeActivityLaunched() { //get hold of the application CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext(); customApp.injectSynchronousObjectGraph(); //inject our mocks so our UI layer will pick them up customApp.injectMockObject(CounterWithLambdas.class, mockCounterWithLambdas); customApp.injectMockObject(CounterWithProgress.class, mockCounterWithProgress); } }; }
ActivityTestRule<FruitActivity> createRule(){ return new ActivityTestRule<FruitActivity>(FruitActivity.class) { @Override protected void beforeActivityLaunched() { new SystemLogger().i("FruitViewRotationTestStateBuilder", "beforeActivityLaunched()"); CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext(); customApp.injectSynchronousObjectGraph(); //inject our test model customApp.injectMockObject(FruitFetcher.class, fruitViewRotationTest.fruitFetcher); customApp.registerActivityLifecycleCallbacks(new ProgressBarIdler()); } @Override protected void afterActivityFinished() { super.afterActivityFinished(); this.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } }; }
ActivityTestRule<FruitActivity> createRule(){ return new ActivityTestRule<FruitActivity>(FruitActivity.class) { @Override protected void beforeActivityLaunched() { //get hold of the application CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext(); customApp.injectSynchronousObjectGraph(); //inject our mocks so our UI layer will pick them up customApp.injectMockObject(FruitFetcher.class, mockFruitFetcher); customApp.registerActivityLifecycleCallbacks(new ProgressBarIdler()); } }; }
ActivityTestRule<WalletsActivity> createRule(){ return new ActivityTestRule<WalletsActivity>(WalletsActivity.class) { @Override protected void beforeActivityLaunched() { //get hold of the application CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext(); customApp.injectSynchronousObjectGraph(); //inject our mocks so our UI layer will pick them up customApp.injectMockObject(Wallet.class, mockWallet); } }; }
ActivityTestRule<PlaylistsActivity> createRule(){ return new ActivityTestRule<PlaylistsActivity>(PlaylistsActivity.class) { @Override protected void beforeActivityLaunched() { //get hold of the application CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext(); customApp.injectSynchronousObjectGraph(); //inject our mocks so our UI layer will pick them up customApp.injectMockObject(PlaylistAdvancedModel.class, mockPlaylistAdvancedModel); customApp.injectMockObject(PlaylistSimpleModel.class, mockPlaylistSimpleModel); } }; }
/** * Restarts the RecreatedAppCompatActivity and waits for the new activity to be resumed. * * @return The newly-restarted RecreatedAppCompatActivity */ @SuppressWarnings("unchecked") // The type of the recreated activity is guaranteed to be T public static <T extends RecreatableAppCompatActivity> T recreateActivity( ActivityTestRule<? extends RecreatableAppCompatActivity> rule, final T activity) throws InterruptedException { // Now switch the orientation RecreatableAppCompatActivity.resumedLatch = new CountDownLatch(1); RecreatableAppCompatActivity.destroyedLatch = new CountDownLatch(1); runOnUiThreadRethrow( rule, new Runnable() { @Override public void run() { activity.recreate(); } }); assertTrue(RecreatableAppCompatActivity.resumedLatch.await(1, TimeUnit.SECONDS)); assertTrue(RecreatableAppCompatActivity.destroyedLatch.await(1, TimeUnit.SECONDS)); T newActivity = (T) RecreatableAppCompatActivity.activity; waitForExecution(rule); RecreatableAppCompatActivity.clearState(); return newActivity; }
/** * Gets an instance of the currently active (displayed) activity. * @param activityTestRule test rule * @param <T> activity class * @return activity instance */ public static <T extends Activity> T getCurrentActivity(@NonNull ActivityTestRule activityTestRule) { getInstrumentation().waitForIdleSync(); final Activity[] activity = new Activity[1]; try { activityTestRule.runOnUiThread(new Runnable() { @Override public void run() { java.util.Collection<Activity> activites = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); activity[0] = Iterables.getOnlyElement(activites); }}); } catch (Throwable throwable) { throwable.printStackTrace(); } //noinspection unchecked return (T) activity[0]; }
public static void Disconnect(ActivityTestRule<SnippetListActivity> snippetListActivityTestRule) { SnippetListActivity snippetListActivity = snippetListActivityTestRule.launchActivity(null); openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext()); // Espresso can't find menu items by id. We'll use the text property. onView(withText(R.string.disconnect_menu_item)) .perform(click()); intended(allOf( hasComponent(hasShortClassName(".SignInActivity")), toPackage("com.microsoft.graph.snippets") )); snippetListActivity.finish(); }
public static List<Integer> getSnippetsIndexes(ActivityTestRule<SnippetListActivity> snippetListActivityRule) { SnippetListActivity snippetListActivity = snippetListActivityRule.launchActivity(null); ListAdapter listAdapter = getListAdapter(snippetListActivity); int numItems = listAdapter.getCount(); List<Integer> snippetIndexes = new ArrayList<>(); // Get the index of items in the adapter that // are actual snippets and not categories, which don't have a Url for (int i = 0; i < numItems; i++) { if(((AbstractSnippet)listAdapter.getItem(i)).getUrl() != null) { snippetIndexes.add(i); } } snippetListActivity.finish(); return snippetIndexes; }
public static void rotateOrientation(ActivityTestRule<? extends Activity> testRule) { switch (testRule.getActivity().getResources().getConfiguration().orientation) { case Configuration.ORIENTATION_LANDSCAPE: testRule.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; default: testRule.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } }
private static void toOrientation(ActivityTestRule activityRule, int requestedOrientation) { activityRule.getActivity().setRequestedOrientation(requestedOrientation); /* Not pretty, but it does seem to fix testFragments from randomly failing. */ try { // Thread.sleep(1000); Thread.sleep(750); } catch (InterruptedException e) { e.printStackTrace(); } }
/** * Disables progress bar animations for the views of the given activity rule * * @param activityTestRule The activity rule whose views will be checked */ public static void disableProgressBarAnimations( ActivityTestRule<? extends FragmentActivity> activityTestRule) { activityTestRule.getActivity().getSupportFragmentManager() .registerFragmentLifecycleCallbacks( new FragmentManager.FragmentLifecycleCallbacks() { @Override public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v, Bundle savedInstanceState) { // traverse all views, if any is a progress bar, replace its animation traverseViews(v); } }, true); }
/** * Disables progress bar animations for the views of the given activity rule * * @param activityTestRule The activity rule whose views will be checked */ public static void disableAnimations( ActivityTestRule<? extends FragmentActivity> activityTestRule) { activityTestRule.getActivity().getSupportFragmentManager() .registerFragmentLifecycleCallbacks( new FragmentManager.FragmentLifecycleCallbacks() { @Override public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v, Bundle savedInstanceState) { // traverse all views, if any is a progress bar, replace its animation traverseViews(v); } }, true); }
private void rotateScreen(ActivityTestRule<?> activityRule) { Context context = InstrumentationRegistry.getTargetContext(); int orientation = context.getResources().getConfiguration().orientation; Activity activity = activityRule.getActivity(); activity.setRequestedOrientation( (orientation == Configuration.ORIENTATION_PORTRAIT) ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }
public static void rotateScreen(ActivityTestRule<? extends Activity> activityRule) { Context context = InstrumentationRegistry.getTargetContext(); int orientation = context.getResources().getConfiguration().orientation; Activity activity = activityRule.getActivity(); activity.setRequestedOrientation( (orientation == Configuration.ORIENTATION_PORTRAIT) ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }
/** * Brings activity to foreground, if it is already launched, or launches it. * * @param rule activity rule for the activity to operate on. * @param <T> activity class. */ public static <T extends Activity> void bringToFront(final ActivityTestRule<T> rule) { final T runningActivity = rule.getActivity(); if (runningActivity == null) { rule.launchActivity(null); } else { // TODO(dotdoom): launch using runningActivity.getIntent()? E.g. to preserve username // and save roundtrip to login window. final Intent intent = new Intent(runningActivity, runningActivity.getClass()); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); runningActivity.startActivity(intent); } }
public static void rotateOrientation(ActivityTestRule<? extends Activity> activityTestRule) { int currentOrientation = activityTestRule.getActivity().getResources().getConfiguration().orientation; switch (currentOrientation) { case Configuration.ORIENTATION_LANDSCAPE: rotateToPortrait(activityTestRule); break; case Configuration.ORIENTATION_PORTRAIT: rotateToLandscape(activityTestRule); break; default: rotateToLandscape(activityTestRule); } }
protected Activity waitForActivityStart (final ActivityTestRule rule) { final ConditionVariable cv = new ConditionVariable(); WebViewApp.setCurrentApp(new WebViewApp() { private boolean allowEvents = false; @Override public boolean sendEvent(Enum eventCategory, Enum eventId, Object... params) { if ("CREATED".equals(eventId.name())) { allowEvents = true; } if (allowEvents && params[0].equals("com.unity3d.ads.test.unit.LifecycleListenerTestActivity")) { DeviceLog.debug(eventId.name() + " " + params[0]); EVENTS.add(eventId); EVENT_PARAMS.add(params); EVENT_COUNT++; } return true; } }); new Thread(new Runnable() { @Override public void run() { rule.launchActivity(new Intent()); cv.open(); } }).start(); boolean success = cv.block(30000); return rule.getActivity(); }
public static void waitForExecution( final ActivityTestRule<? extends RecreatableAppCompatActivity> rule) { // Wait for two cycles. When starting a postponed transition, it will post to // the UI thread and then the execution will be added onto the queue after that. // The two-cycle wait makes sure fragments have the opportunity to complete both // before returning. try { rule.runOnUiThread(DO_NOTHING); rule.runOnUiThread(DO_NOTHING); } catch (Throwable throwable) { throw new RuntimeException(throwable); } }
private static void runOnUiThreadRethrow( ActivityTestRule<? extends RecreatableAppCompatActivity> rule, Runnable r) { if (Looper.getMainLooper() == Looper.myLooper()) { r.run(); } else { try { rule.runOnUiThread(r); } catch (Throwable t) { throw new RuntimeException(t); } } }
/** * Sets up the necessary members for this test class from a BackLayerLayoutActivity. Call this * method from a {@code @Before} method on the subclass. */ public void setUp( ActivityTestRule<? extends Activity> activityTestRule, @IdRes int coordinatorLayoutId, @IdRes int backLayerId, @IdRes int contentLayerId, @IdRes int primaryButtonId, @IdRes int secondaryButtonId, @IdRes int primaryExtraContentId, @IdRes int secondaryExtraContentId) throws Exception { this.backLayerId = backLayerId; this.contentLayerId = contentLayerId; activity = activityTestRule.getActivity(); resources = activity.getResources(); coordinatorLayout = activity.findViewById(coordinatorLayoutId); backLayer = activity.findViewById(backLayerId); contentLayer = activity.findViewById(contentLayerId); primaryExtraContent = activity.findViewById(primaryExtraContentId); secondaryExtraContent = activity.findViewById(secondaryExtraContentId); this.primaryButtonId = primaryButtonId; this.secondaryButtonId = secondaryButtonId; this.primaryExtraContentId = primaryExtraContentId; this.secondaryExtraContentId = secondaryExtraContentId; CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) backLayer.getLayoutParams(); int absoluteGravity = Gravity.getAbsoluteGravity(layoutParams.gravity, ViewCompat.getLayoutDirection(backLayer)); isBackLayerAtEndSide = absoluteGravity == Gravity.RIGHT || absoluteGravity == Gravity.BOTTOM; isHorizontal = absoluteGravity == Gravity.RIGHT || absoluteGravity == Gravity.LEFT; if (backLayer.isExpanded()) { onView(withId(backLayerId)).perform(collapse()); } }
@Override protected void init(ActivityTestRule activityTestRule) { super.init(activityTestRule); userRepo = (MemoryUserRepository) app.getUserRepository(); dataRepo = (MemoryDataRepository) app.getDataRepository(); }
@Before public void setUp() throws Exception { MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext(); backend = (ConfigurableBackend) ((TestPopularMoviesComponent) movieApplication.getPopularMoviesComponent()).backend(); rule = new ActivityTestRule<>(PopularMoviesActivity.class); apiMoviePoster = createApiMoviePoster(MOVIE_ID, POSTER_PATH); movieDetails = createMovieDetails(MOVIE_ID, MOVIE_TITLE, MOVIE_DESCRIPTION, POSTER_PATH, RELEASE_DATE); }
@Before public void setUp() throws Exception { MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext(); backend = (ConfigurableBackend) ((TestMovieDetailsComponent) movieApplication.getMovieDetailsComponent()).backend(); apiMovieDetails = createApiMovieDetails(MOVIE_ID, MOVIE_TITLE, MOVIE_DESCRIPTION, POSTER_PATH, RELEASE_DATE); rule = new ActivityTestRule<>(MovieDetailsActivity.class); }
@Before public void startMainActivityFromHomeScreen() { // Initialize UiDevice instance mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); // Start from the home screen mDevice.pressHome(); // Wait for launcher final String launcherPackage = mDevice.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); // Launch the app appContext = InstrumentationRegistry.getContext(); final Intent intent = appContext.getPackageManager() .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE); // Clear out any previous instances intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); appContext.startActivity(intent); // Wait for the app to appear mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT); ActivityTestRule<Activity> mActivityRule = new ActivityTestRule<>( Activity.class); database_functions = Database_Functions.getInstance(appContext, mActivityRule.getActivity()); }
@Test public void getInstance() throws Exception { ActivityTestRule<Activity> mActivityRule = new ActivityTestRule<>( Activity.class); database_functions = Database_Functions.getInstance(appContext, mActivityRule.getActivity()); }
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) @ColorInt private static int getAccentColor(@NonNull ActivityTestRule<MainDialog> activityTestRule, boolean light) { Configuration configuration = new Configuration(); configuration.uiMode = light ? Configuration.UI_MODE_NIGHT_NO : Configuration.UI_MODE_NIGHT_YES; return ContextCompat.getColor(activityTestRule.getActivity().createConfigurationContext(configuration), R.color.accent); }
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) @ColorInt private static int getBackgroundColor(@NonNull ActivityTestRule<MainDialog> activityTestRule, boolean light) { Configuration configuration = new Configuration(); configuration.uiMode = light ? Configuration.UI_MODE_NIGHT_NO : Configuration.UI_MODE_NIGHT_YES; return ContextCompat.getColor(activityTestRule.getActivity().createConfigurationContext(configuration), R.color.background); }
private void launchDatePickerInFragmentActivity(List<ActivityTheme> activityThemeList, final Class<DatePickerInFragmentActivity> clazz){ for(DatePickerMode datePickerMode : DatePickerMode.values()){ for(int i = 0; i < 2; i++){ boolean isCalendarViewShown = i == 0; for(int j = 0; j < 2; j++){ boolean isSpinnersShown = j == 0; for(ActivityTheme activityTheme : activityThemeList){ if(datePickerMode == DatePickerMode.Calendar && activityTheme == ActivityTheme.Theme_Black){ continue; } final Intent intent = MainActivity.createIntent(activityTestRule.getActivity(), clazz, datePickerMode.layout, isCalendarViewShown, isSpinnersShown, activityTheme.theme); ActivityTestRule<DatePickerInFragmentActivity> rule = new ActivityTestRule<>(clazz, false); String fileName = String.format("%s_%s_%s_%s_%s_%s_%s.png", clazz.getSimpleName(), datePickerMode.name(), "isCalendarViewShown", isCalendarViewShown, "isSpinnersShown", isSpinnersShown, activityTheme.name()); Log.d(clazz.getSimpleName(), fileName); rule.launchActivity(intent); takeScreenshot(rule.getActivity(), fileName); } } } } }
private void launchDatePickerInAppCompatActivity(List<ActivityTheme> activityThemeList, final Class<DatePickerInAppCompatActivity> clazz){ for(DatePickerMode datePickerMode : DatePickerMode.values()){ for(int i = 0; i < 2; i++){ boolean isCalendarViewShown = i == 0; for(int j = 0; j < 2; j++){ boolean isSpinnersShown = j == 0; for(ActivityTheme activityTheme : activityThemeList){ if(datePickerMode == DatePickerMode.Calendar && activityTheme == ActivityTheme.Theme_Black){ continue; } final Intent intent = MainActivity.createIntent(activityTestRule.getActivity(), clazz, datePickerMode.layout, isCalendarViewShown, isSpinnersShown, activityTheme.theme); ActivityTestRule<DatePickerInAppCompatActivity> rule = new ActivityTestRule<>(clazz, false); String fileName = String.format("%s_%s_%s_%s_%s_%s_%s.png", clazz.getSimpleName(), datePickerMode.name(), "isCalendarViewShown", isCalendarViewShown, "isSpinnersShown", isSpinnersShown, activityTheme.name()); Log.d(clazz.getSimpleName(), fileName); rule.launchActivity(intent); takeScreenshot(rule.getActivity(), fileName); } } } } }
public static <ACTIVITY extends Activity> ActivityTestRule<ACTIVITY> getActivityRule(final AppComponentProvider mainComponentProv, Class<ACTIVITY> clazz) { final Handler mainHandler = new Handler(Looper.getMainLooper()); return new DaggerActivityTestRule<>(clazz, (application, activity) -> { final KickMaterialApp app = (KickMaterialApp) application; final AppComponent appComponent = mainComponentProv.getComponent(app); final GlobalComponent globalComponent = DaggerGlobalComponent.builder() .globalModule(new GlobalModule(app, appComponent.getBus(), appComponent.getAccessTokenProvider())) .build(); mainHandler.post(() -> app.setComponents(globalComponent, appComponent)); }); }
public void changeOrientation(ActivityTestRule<DrawerActivity> testRule) { int current = testRule.getActivity().getRequestedOrientation(); int change; if (current == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { change = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; } else if (current == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) { change = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; testRule.getActivity().setRequestedOrientation(change); change = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; } else { change = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; } testRule.getActivity().setRequestedOrientation(change); }
@Override ActivityTestRule getActivityRule() { return activityRule; }