android.app.Instrumentation Java Examples
The following examples show how to use
android.app.Instrumentation.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MotionEventUtils.java From ListViewAnimations with Apache License 2.0 | 6 votes |
public static void dispatchMotionEvents(final Instrumentation instrumentation, final Iterable<MotionEvent> motionEvents, final boolean wait) throws InterruptedException { for (final MotionEvent event : motionEvents) { int i = 0; boolean success = false; do { try { instrumentation.sendPointerSync(event); success = true; } catch (SecurityException e) { i++; if (i > 3) { throw e; } } } while (i < 3 && !success); Thread.sleep(100); } if (wait) { /* We need to wait for the fling animation to complete */ Thread.sleep(1500); } }
Example #2
Source File: AndroidTestOrchestrator.java From android-test with Apache License 2.0 | 6 votes |
@Override public void onStart() { super.onStart(); try { registerUserTracker(); grantRuntimePermissions(RUNTIME_PERMISSIONS); connectOrchestratorService(); } catch (RuntimeException e) { final String msg = "Fatal exception when setting up."; Log.e(TAG, msg, e); // Report the startup exception to instrumentation out. Bundle failureBundle = createResultBundle(); failureBundle.putString( Instrumentation.REPORT_KEY_STREAMRESULT, msg + "\n" + Log.getStackTraceString(e)); finish(Activity.RESULT_OK, failureBundle); } }
Example #3
Source File: InstrumentationResultPrinter.java From android-test with Apache License 2.0 | 6 votes |
private void reportFailure(Failure failure) { String trace = failure.getTrace(); if (trace.length() > MAX_TRACE_SIZE) { // Since AJUR needs to report failures back to AM via a binder IPC, we need to make sure that // we don't exceed the Binder transaction limit - which is 1MB per process. Log.w( TAG, String.format("Stack trace too long, trimmed to first %s characters.", MAX_TRACE_SIZE)); trace = trace.substring(0, MAX_TRACE_SIZE) + "\n"; } testResult.putString(REPORT_KEY_STACK, trace); // pretty printing testResult.putString( Instrumentation.REPORT_KEY_STREAMRESULT, String.format( "\nError in %s:\n%s", failure.getDescription().getDisplayName(), failure.getTrace())); }
Example #4
Source File: LoginActivityTest.java From android-galaxyzoo with GNU General Public License v3.0 | 6 votes |
@Test public void testStateDestroy() { //final String TEST_SOMETHING = "test123456789"; //TODO: mActivity.setSomething(); mActivity.finish(); // Based on this: // http://stackoverflow.com/a/33213279/1123654 final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); instrumentation.runOnMainSync(new Runnable() { @Override public void run() { mActivity.recreate(); } }); //TODOassertEquals(TEST_SOMETHING, mActivity.getSomething()); //TODO: Do something like this too: //onView(withText("a string depending on XXX value")).check(doesNotExist()) }
Example #5
Source File: ReactIdleDetectionUtil.java From react-native-GPay with MIT License | 6 votes |
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!"); }
Example #6
Source File: MotionEventUtils.java From ListViewAnimations with Apache License 2.0 | 6 votes |
public static void dispatchDragScrollDownMotionEvents(final Instrumentation instrumentation, final DynamicListView dynamicListView, final int fromPosition) throws InterruptedException { int[] location = new int[2]; dynamicListView.getLocationOnScreen(location); View view = dynamicListView.getChildAt(fromPosition); float fromY = (int) (view.getY()) + location[1]; View toView = dynamicListView.getChildAt(dynamicListView.getLastVisiblePosition()); float toY = (int) (toView.getY() + toView.getHeight()) + location[1] + 2; List<MotionEvent> motionEvents = createMotionEvents(dynamicListView, fromY, toY); MotionEvent upEvent = motionEvents.remove(motionEvents.size() - 1); dispatchMotionEvents(instrumentation, motionEvents, true); Thread.sleep(10000); dispatchMotionEvents(instrumentation, Arrays.asList(upEvent), true); }
Example #7
Source File: OrchestrationResultPrinter.java From android-test with Apache License 2.0 | 6 votes |
/** * Produce a more meaningful crash report including stack trace and report it back to * Instrumentation results. */ public void reportProcessCrash(Throwable t) { try { testResultCode = REPORT_VALUE_RESULT_FAILURE; ParcelableFailure failure = new ParcelableFailure(description, t); testResult.putString(REPORT_KEY_STACK, failure.getTrace()); // pretty printing testResult.putString( Instrumentation.REPORT_KEY_STREAMRESULT, String.format( "\nProcess crashed while executing %s:\n%s", description.getDisplayName(), failure.getTrace())); testFinished(description); } catch (Exception e) { if (null == description) { Log.e(LOG_TAG, "Failed to initialize test before process crash"); } else { Log.e( LOG_TAG, "Failed to mark test " + description.getDisplayName() + " as finished after process crash"); } } }
Example #8
Source File: AndroidJUnitRunnerTest.java From android-test with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); doReturn("/apps/foo.apk").when(mockContext).getPackageCodePath(); androidJUnitRunner = new AndroidJUnitRunner() { @Override public Context getContext() { return mockContext; } @Override InstrumentationResultPrinter getInstrumentationResultPrinter() { return instrumentationResultPrinter; } @Override TestRequestBuilder createTestRequestBuilder(Instrumentation instr, Bundle arguments) { return testRequestBuilder; } }; }
Example #9
Source File: InstrumentationHooker.java From ArgusAPM with Apache License 2.0 | 6 votes |
private static void hookInstrumentation() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { Class<?> c = Class.forName("android.app.ActivityThread"); Method currentActivityThread = c.getDeclaredMethod("currentActivityThread"); boolean acc = currentActivityThread.isAccessible(); if (!acc) { currentActivityThread.setAccessible(true); } Object o = currentActivityThread.invoke(null); if (!acc) { currentActivityThread.setAccessible(acc); } Field f = c.getDeclaredField("mInstrumentation"); acc = f.isAccessible(); if (!acc) { f.setAccessible(true); } Instrumentation currentInstrumentation = (Instrumentation) f.get(o); Instrumentation ins = new ApmInstrumentation(currentInstrumentation); f.set(o, ins); if (!acc) { f.setAccessible(acc); } }
Example #10
Source File: PluginLoadedApk.java From Neptune with Apache License 2.0 | 6 votes |
/** * 反射获取ActivityThread中的Instrumentation对象 * 从而拦截Activity跳转 */ @Deprecated private void hookInstrumentation() { try { Context contextImpl = ((ContextWrapper) mHostContext).getBaseContext(); Object activityThread = ReflectionUtils.getFieldValue(contextImpl, "mMainThread"); Field instrumentationF = activityThread.getClass().getDeclaredField("mInstrumentation"); instrumentationF.setAccessible(true); Instrumentation hostInstr = (Instrumentation) instrumentationF.get(activityThread); mPluginInstrument = new PluginInstrument(hostInstr, mPluginPackageName); } catch (Exception e) { ErrorUtil.throwErrorIfNeed(e); PluginManager.deliver(mHostContext, false, mPluginPackageName, ErrorType.ERROR_PLUGIN_HOOK_INSTRUMENTATION, "hookInstrumentation failed"); } }
Example #11
Source File: SessionDetailActivityTest.java From droidkaigi2016 with Apache License 2.0 | 6 votes |
@Before public void setUp() { Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); Intent intent = SessionDetailActivity.createIntent(context, SESSION); // The third argument of the constructor for ActivityTestRule needs to be false as explained // in the Javadoc for ActivityTestRule#launchActivity // http://developer.android.com/reference/android/support/test/rule/ActivityTestRule.html#launchActivity(android.content.Intent) activityRule.launchActivity(intent); // By default Espresso Intents does not stub any Intents. Stubbing needs to be setup before // every test run. In this case all external Intents will be blocked. intending(not(isInternal())) .respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null)); }
Example #12
Source File: CameraHelperTest.java From android-sdk with Apache License 2.0 | 6 votes |
@Test public void testCameraFlow() { Bitmap icon = BitmapFactory.decodeResource( InstrumentationRegistry.getTargetContext().getResources(), R.mipmap.ic_launcher); Intent resultData = new Intent(); resultData.putExtra("data", icon); Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData); intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result); Espresso.onView(withId(R.id.camera_button)).perform(click()); intended(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)); }
Example #13
Source File: PluginInstrumentionWrapper.java From PluginLoader with Apache License 2.0 | 5 votes |
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode) { PluginIntentResolver.resolveActivity(intent); Object result = RefInvoker.invokeMethod(realInstrumention, android.app.Instrumentation.class.getName(), "execStartActivity", new Class[] { Context.class, IBinder.class, IBinder.class, Activity.class, Intent.class, int.class }, new Object[] { who, contextThread, token, target, intent, requestCode }); return (ActivityResult) result; }
Example #14
Source File: ComponentActivityTestRule.java From litho with Apache License 2.0 | 5 votes |
/** Set ComponentTree for the Activity to display. */ public void setComponentTree(final ComponentTree componentTree) { final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); instrumentation.runOnMainSync( new Runnable() { @Override public void run() { getActivity().setComponentTree(componentTree); } }); instrumentation.waitForIdleSync(); }
Example #15
Source File: PluginActivityControl.java From Neptune with Apache License 2.0 | 5 votes |
/** * 反射调用2.x上的Activity#attach()方法 * <href>http://androidxref.com/2.3.6/xref/frameworks/base/core/java/android/app/Activity.java#3739</href> */ private void callAttachV4(Instrumentation pluginInstr) { mPluginRef.call( // 方法名 "attach", sMethods, null, // Context context // contextWrapper, mProxy, // ActivityThread aThread mProxyRef.get("mMainThread"), // Instrumentation instr pluginInstr, // IBinder token mProxyRef.get("mToken"), // int ident mProxyRef.get("mIdent"), // Application application mApplication == null ? mProxy.getApplication() : mApplication, // Intent intent mProxy.getIntent(), // ActivityInfo info mProxyRef.get("mActivityInfo"), // CharSequence title mProxy.getTitle(), // Activity parent mProxy.getParent(), // String id mProxyRef.get("mEmbeddedID"), // Object lastNonConfigurationInstances mProxy.getLastNonConfigurationInstance(), // HashMap<String, Object> lastNonConfigurationChildInstances null, // Configuration config mProxyRef.get("mCurrentConfig")); }
Example #16
Source File: LoginInstrumentedTest.java From flowless with Apache License 2.0 | 5 votes |
@Before public void setup() { Espresso.registerIdlingResources(EspressoIdlingResource.getIdlingResource()); mainActivityActivityTestRule.launchActivity(null); Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); MainActivity mainActivity = mainActivityActivityTestRule.getActivity(); instrumentation.runOnMainSync(() -> { Flow.get(mainActivity.getBaseContext()).setHistory(History.single(LoginKey.create()), Direction.REPLACE); }); ServiceProvider serviceProvider = ServiceProvider.get(mainActivity.getBaseContext()); LoginComponent loginComponent = serviceProvider.getService(LoginKey.create(), DaggerService.TAG); loginPresenter = loginComponent.loginPresenter(); }
Example #17
Source File: KeyBoardTools.java From githot with Apache License 2.0 | 5 votes |
/** * 模拟键盘事件方法 */ public static void actionKey(final int keyCode) { new Thread() { public void run() { try { Instrumentation inst = new Instrumentation(); inst.sendKeyDownUpSync(keyCode); } catch (Exception e) { e.printStackTrace(); } } }.start(); }
Example #18
Source File: PluginInstrumentionWrapper.java From PluginLoader with Apache License 2.0 | 5 votes |
public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { PluginIntentResolver.resolveActivity(intent); Object result = RefInvoker.invokeMethod(realInstrumention, android.app.Instrumentation.class.getName(), "execStartActivity", new Class[] { Context.class, IBinder.class, IBinder.class, Activity.class, Intent.class, int.class, Bundle.class }, new Object[] { who, contextThread, token, target, intent, requestCode, options }); return (ActivityResult) result; }
Example #19
Source File: ReflectAccelerator.java From Small with Apache License 2.0 | 5 votes |
public static Instrumentation.ActivityResult execStartActivity( Instrumentation instrumentation, Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { if (sInstrumentation_execStartActivityV21_method == null) { Class[] types = new Class[] {Context.class, IBinder.class, IBinder.class, Activity.class, Intent.class, int.class, android.os.Bundle.class}; sInstrumentation_execStartActivityV21_method = getMethod(Instrumentation.class, "execStartActivity", types); } if (sInstrumentation_execStartActivityV21_method == null) return null; return invoke(sInstrumentation_execStartActivityV21_method, instrumentation, who, contextThread, token, target, intent, requestCode, options); }
Example #20
Source File: TestUtilities.java From google-authenticator-android with Apache License 2.0 | 5 votes |
public static String enterText( Instrumentation instr, final EditText editText, final String text) { runOnMainSyncWithTimeout( new Callable<Void>() { @Override public Void call() { editText.requestFocus(); return null; } }); // TODO: Decide on using touch mode and how to do it consistently. e.g. the above could be // replaced by "TouchUtils.tapView(this, editText);" instr.sendStringSync(text); return editText.getText().toString(); }
Example #21
Source File: AppBarHorizontalScrollingTest.java From material-components-android with Apache License 2.0 | 5 votes |
private void emulateButtonClick( Instrumentation instrumentation, float emulatedTapX, float emulatedTapY) { // Note that the reason to not use Espresso's click() view action is so that we can // faithfully emulate what was happening in the reported bug. We don't want the events // to be sent directly to the button, but rather be processed by the parent coordinator // layout, so that we reproduce what is happening as the events are processed at the level // of that parent. // Inject DOWN event long downTime = SystemClock.uptimeMillis(); MotionEvent eventDown = MotionEvent.obtain( downTime, downTime, MotionEvent.ACTION_DOWN, emulatedTapX, emulatedTapY, 1); instrumentation.sendPointerSync(eventDown); // Inject MOVE event long moveTime = SystemClock.uptimeMillis(); MotionEvent eventMove = MotionEvent.obtain( moveTime, moveTime, MotionEvent.ACTION_MOVE, emulatedTapX, emulatedTapY, 1); instrumentation.sendPointerSync(eventMove); // Inject UP event long upTime = SystemClock.uptimeMillis(); MotionEvent eventUp = MotionEvent.obtain(upTime, upTime, MotionEvent.ACTION_UP, emulatedTapX, emulatedTapY, 1); instrumentation.sendPointerSync(eventUp); // Wait for the system to process all events in the queue instrumentation.waitForIdleSync(); }
Example #22
Source File: TestUtilities.java From google-authenticator-android with Apache License 2.0 | 5 votes |
public static boolean clickView(Instrumentation instr, final View view) { boolean result = runOnMainSyncWithTimeout( new Callable<Boolean>() { @Override public Boolean call() { return view.performClick(); } }); // this shouldn't be needed but without it or sleep, there isn't time for view refresh, etc. instr.waitForIdleSync(); return result; }
Example #23
Source File: HelperSteps.java From CleanGUITestArchitecture with MIT License | 5 votes |
private static void grantWritePermissionsForScreenshots() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); String appPackage = getTargetContext().getPackageName(); instrumentation.getUiAutomation().executeShellCommand("pm grant " + appPackage + " android.permission.READ_EXTERNAL_STORAGE"); instrumentation.getUiAutomation().executeShellCommand("pm grant " + appPackage + " android.permission.WRITE_EXTERNAL_STORAGE"); } catch (Exception e) { throw new RuntimeException( "Exception while granting external storage access to application apk", e); } } }
Example #24
Source File: Neptune.java From Neptune with Apache License 2.0 | 5 votes |
/** * 获取ActivityThread的Instrumentation对象 */ public static Instrumentation getHostInstrumentation() { if (mHostInstr == null) { ActivityThread activityThread = ActivityThread.currentActivityThread(); Instrumentation hostInstr = activityThread.getInstrumentation(); mHostInstr = PluginInstrument.unwrap(hostInstr); } return mHostInstr; }
Example #25
Source File: MyUiAutomatorTestRunner.java From PUMA with Apache License 2.0 | 5 votes |
@Override public void addFailure(Test test, AssertionFailedError t) { mTestResult.putString(REPORT_KEY_STACK, BaseTestRunner.getFilteredTrace(t)); mTestResultCode = REPORT_VALUE_RESULT_FAILURE; // pretty printing mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, String.format("\nFailure in %s:\n%s", ((TestCase) test).getName(), BaseTestRunner.getFilteredTrace(t))); mPrinter.addFailure(test, t); }
Example #26
Source File: AuthenticatorActivityTest.java From google-authenticator-android with Apache License 2.0 | 5 votes |
@Test public void testClickEmptySpaceOnListUnselectItem() throws InterruptedException { accountDb.add( "first", "7777777777777777", OtpType.HOTP, null, null, AccountDb.GOOGLE_ISSUER_NAME); AuthenticatorActivity activity = activityTestRule.launchActivity(null); EmptySpaceClickableDragSortListView userList = activity.findViewById(R.id.user_list); assertThat(activity.actionMode).isNull(); onView(equalTo(userList.getChildAt(0))).perform(longClick()); assertThat(activity.actionMode).isNotNull(); Point size = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(size); int height = size.y; int width = size.x; Instrumentation instr = InstrumentationRegistry.getInstrumentation(); long downTime = SystemClock.uptimeMillis(); long eventTime = SystemClock.uptimeMillis(); instr.sendPointerSync( MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, height / 2, width / 2, 0)); instr.sendPointerSync( MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, height / 2, width / 2, 0)); // We need to delay to wait for the contextual action bar is completely removed. Thread.sleep(CLICK_DELAY_INTERVAL); assertThat(activity.actionMode).isNull(); }
Example #27
Source File: PermissiveTesting.java From permissive with Apache License 2.0 | 5 votes |
private void applyActivityResult(Instrumentation.ActivityResult result) { String[] permissions = result.getResultData().getStringArrayExtra(EXTRA_REQUEST_PERMISSIONS_NAMES); int[] resultPermissions = result.getResultData().getIntArrayExtra(EXTRA_REQUEST_PERMISSIONS_RESULTS); for (int i = 0; i < permissions.length; ++i) { if (resultPermissions[i] == PackageManager.PERMISSION_GRANTED) { grantFakePermission(permissions[i]); } else { revokeFakePermission(permissions[i]); } } }
Example #28
Source File: TestUtilities.java From google-authenticator-android with Apache License 2.0 | 5 votes |
/** Sets the text of the provided {@link TextView} widget on the UI thread. */ public static void setText(Instrumentation instr, final TextView view, final String text) { runOnMainSyncWithTimeout( new Callable<Void>() { @Override public Void call() { view.setText(text); return null; } }); instr.waitForIdleSync(); Assert.assertEquals(text, view.getText().toString()); }
Example #29
Source File: ImageCapture.java From Camera2 with Apache License 2.0 | 5 votes |
public void captureImages(String reportTag, Instrumentation inst) { int total_num_of_images = CameraStressTestRunner.mImageIterations; Log.v(TAG, "no of images = " + total_num_of_images); //TODO(yslau): Need to integrate the outoput with the central dashboard, //write to a txt file as a temp solution boolean memoryResult = false; KeyEvent focusEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_FOCUS); try { testUtil.writeReportHeader(reportTag, total_num_of_images); for (int i = 0; i < total_num_of_images; i++) { Thread.sleep(WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN); inst.sendKeySync(focusEvent); inst.sendCharacterSync(KeyEvent.KEYCODE_CAMERA); Thread.sleep(WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN); testUtil.writeResult(i); } } catch (Exception e) { Log.v(TAG, "Got exception: " + e.toString()); assertTrue("testImageCapture", false); } }
Example #30
Source File: ActivityFinisherRunListener.java From android-test with Apache License 2.0 | 5 votes |
public ActivityFinisherRunListener( Instrumentation instrumentation, MonitoringInstrumentation.ActivityFinisher finisher, Runnable waitForActivitiesToFinishRunnable) { this.instrumentation = checkNotNull(instrumentation); activityFinisher = checkNotNull(finisher); this.waitForActivitiesToFinishRunnable = checkNotNull(waitForActivitiesToFinishRunnable); }