Example #1
0
 protected void setUp() throws Exception {
   super.setUp();
   mInst = getInstrumentation();
   mContext = mInst.getTargetContext();
   mActivity = getActivity();
   mSolo = new Solo(mInst, mActivity);
 }
Example #2
0
 /**
  * Launches the preferences menu and starts the preferences activity named fragmentName. Returns
  * the activity that was started.
  */
 public static Preferences startPreferences(Instrumentation instrumentation, String fragmentName) {
   Context context = instrumentation.getTargetContext();
   Intent intent = PreferencesLauncher.createIntentForSettingsPage(context, fragmentName);
   Activity activity = instrumentation.startActivitySync(intent);
   assertTrue(activity instanceof Preferences);
   return (Preferences) activity;
 }
  /**
   * Checks the device has a valid Bootstrap (on parse.com via the example API), account, if not,
   * adds one using the test credentials found in system property 'bootstrap.test.api.key'.
   *
   * <p>The credentials can be passed on the command line like this: mvn
   * -bootstrap.test.api.key=0123456789abcdef0123456789abcdef install
   *
   * @param instrumentation taken from the test context
   * @return true if valid account credentials are available
   */
  public static boolean ensureValidAccountAvailable(Instrumentation instrumentation) {
    Context c = instrumentation.getContext();
    AccountManager accountManager = AccountManager.get(instrumentation.getTargetContext());

    for (Account account : accountManager.getAccountsByType(BOOTSTRAP_ACCOUNT_TYPE)) {
      if (accountManager.peekAuthToken(account, AUTHTOKEN_TYPE) != null) {
        Ln.i("Using existing account : " + account.name);
        return true; // we have a valid account that has successfully authenticated
      }
    }

    String testApiKey = c.getString(R.string.test_account_api_key);
    String truncatedApiKey = testApiKey.substring(0, 4) + "…";

    if (!testApiKey.matches("\\p{XDigit}{32}")) {
      Ln.w("No valid test account credentials in bootstrap.test.api.key : " + truncatedApiKey);
      return false;
    }

    Ln.i("Adding test account using supplied api key credential : " + truncatedApiKey);
    Account account = new Account("*****@*****.**", BOOTSTRAP_ACCOUNT_TYPE);
    accountManager.addAccountExplicitly(
        account, null, null); // this test account will not have a valid password
    accountManager.setAuthToken(account, AUTHTOKEN_TYPE, testApiKey);
    return true;
  }
  public void longPress(Coordinates where) {
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();
    Point point = where.getLocationOnScreen();
    // List<MotionEvent> motionEvents = new ArrayList<MotionEvent>();
    //
    // motionEvents.add(getMotionEvent(downTime, downTime, MotionEvent.ACTION_DOWN, point));
    // motionEvents.add(getMotionEvent(downTime, (downTime + 3000), MotionEvent.ACTION_UP, point));
    // sendMotionEvents(motionEvents);
    Instrumentation inst = instrumentation;

    MotionEvent event = null;
    boolean successfull = false;
    int retry = 0;
    while (!successfull && retry < 10) {
      try {
        if (event == null) {
          event =
              MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, point.x, point.y, 0);
        }
        System.out.println("trying to send pointer");
        inst.sendPointerSync(event);
        successfull = true;
      } catch (SecurityException e) {
        System.out.println("failed: " + retry);
        // activityUtils.hideSoftKeyboard(null, false, true);
        retry++;
      }
    }
    if (!successfull) {
      throw new SelendroidException("Click can not be completed!");
    }
    inst.sendPointerSync(event);
    inst.waitForIdleSync();

    eventTime = SystemClock.uptimeMillis();
    final int touchSlop = ViewConfiguration.get(inst.getTargetContext()).getScaledTouchSlop();
    event =
        MotionEvent.obtain(
            downTime,
            eventTime,
            MotionEvent.ACTION_MOVE,
            point.x + touchSlop / 2,
            point.y + touchSlop / 2,
            0);
    inst.sendPointerSync(event);
    inst.waitForIdleSync();

    try {
      Thread.sleep((long) (ViewConfiguration.getLongPressTimeout() * 1.5f));
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    eventTime = SystemClock.uptimeMillis();
    event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, point.x, point.y, 0);
    inst.sendPointerSync(event);
    inst.waitForIdleSync();
  }
 @Before
 public void setUp() throws Exception {
   super.setUp();
   Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
   Context context = instrumentation.getTargetContext();
   intent = new Intent(context, ImageDetailActivity.class);
   intent.putExtra(ImageDetailActivity.EXTRA_CONTENT, DataHolder.LIST_ITEM_JSON);
   intent.putExtra(ImageDetailActivity.EXTRA_CACHE_SIZE, "");
 }
Example #6
0
 /**
  * Returns a localized string
  *
  * @param id the resource ID for the string
  * @return the localized string
  */
 public String getString(String id) {
   Context targetContext = instrumentation.getTargetContext();
   String packageName = targetContext.getPackageName();
   int viewId = targetContext.getResources().getIdentifier(id, "string", packageName);
   if (viewId == 0) {
     viewId = targetContext.getResources().getIdentifier(id, "string", "android");
   }
   return getString(viewId);
 }
Example #7
0
  @Override
  protected void setUp() throws Exception {
    Instrumentation instrumentation = getInstrumentation();
    mockSupport = new MozcMockSupport(instrumentation);

    activity =
        Preconditions.checkNotNull(
            launchActivity("org.mozc.android.inputmethod.japanese", Activity.class, null));
    instrumentation.runOnMainSync(new OnCreateRunner());
    context = instrumentation.getTargetContext();
  }
Example #8
0
  /**
   * Scrolls horizontally.
   *
   * @param side the side to which to scroll; {@link Side#RIGHT} or {@link Side#LEFT}
   * @param scrollPosition the position to scroll to, from 0 to 1 where 1 is all the way. Example
   *     is: 0.55.
   * @param stepCount how many move steps to include in the scroll. Less steps results in a faster
   *     scroll
   */
  @SuppressWarnings("deprecation")
  public void scrollToSide(Side side, float scrollPosition, int stepCount) {
    WindowManager windowManager =
        (WindowManager) inst.getTargetContext().getSystemService(Context.WINDOW_SERVICE);

    int screenHeight = windowManager.getDefaultDisplay().getHeight();
    int screenWidth = windowManager.getDefaultDisplay().getWidth();
    float x = screenWidth * scrollPosition;
    float y = screenHeight / 2.0f;
    if (side == Side.LEFT) drag(70, x, y, y, stepCount);
    else if (side == Side.RIGHT) drag(x, 0, y, y, stepCount);
  }
  /*
   * Sets up the test environment before each test.
   */
  @Override
  protected void setUp() throws Exception {

    super.setUp();

    setActivityInitialTouchMode(false);

    mInst = getInstrumentation();

    mContext = mInst.getTargetContext();

    mPreference = mContext.getSharedPreferences(OTA_PREFERENCE, Context.MODE_PRIVATE);
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    mInstrumentation = getInstrumentation();
    mContext = mInstrumentation.getTargetContext();

    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    mContext.registerReceiver(mReceiver, filter);
  }
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   Instrumentation instrumentation = getInstrumentation();
   mContext = instrumentation.getTargetContext();
   mPackageManager = mContext.getPackageManager();
   mAvailableFeatures = new HashSet<String>();
   if (mPackageManager.getSystemAvailableFeatures() != null) {
     for (FeatureInfo feature : mPackageManager.getSystemAvailableFeatures()) {
       mAvailableFeatures.add(feature.name);
     }
   }
   mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
   mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
   mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
   mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
   mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
 }
  private void setupMockServer(HashMap<String, String> override_map) {
    HashMap<String, String> map = new HashMap<>(Util.RESPONSE_MAP);

    if (override_map != null) {
      for (String key : override_map.keySet()) {
        map.put(key, override_map.get(key));
      }
    }

    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    AndroidApplication app =
        (AndroidApplication) instrumentation.getTargetContext().getApplicationContext();

    // setup objectGraph to inject Mock API
    List modules = Collections.singletonList(new DummyAPIModule(map));
    ObjectGraph graph = ObjectGraph.create(modules.toArray());
    app.setObjectGraph(graph);
    app.getObjectGraph().inject(app);
  }
Example #13
0
  /**
   * Returns a {@code View} with a given id.
   *
   * @param id the id of the {@link View} to return
   * @param index the index of the {@link View}. {@code 0} if only one is available
   * @return a {@code View} with a given id
   */
  public View getView(String id, int index) {
    View viewToReturn = null;
    Context targetContext = instrumentation.getTargetContext();
    String packageName = targetContext.getPackageName();
    int viewId = targetContext.getResources().getIdentifier(id, "id", packageName);

    if (viewId != 0) {
      viewToReturn = getView(viewId, index, TIMEOUT);
    }

    if (viewToReturn == null) {
      int androidViewId = targetContext.getResources().getIdentifier(id, "id", "android");
      if (androidViewId != 0) {
        viewToReturn = getView(androidViewId, index, TIMEOUT);
      }
    }

    if (viewToReturn != null) {
      return viewToReturn;
    }
    return getView(viewId, index);
  }
 @Before
 public void before() {
   Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
   ctx = instrumentation.getTargetContext();
   Intents.init();
 }
 /**
  * Create main application
  *
  * @param instrumentation
  */
 public BootstrapApplication(final Instrumentation instrumentation) {
   this();
   attachBaseContext(instrumentation.getTargetContext());
 }
 private void hackMockito() {
   mOldProperty =
       System.setProperty(
           "dexmaker.dexcache", mInstrumentation.getTargetContext().getCacheDir().getPath());
 }
 public static void deleteDatabase(Instrumentation instrumentation) {
   instrumentation.getTargetContext().deleteDatabase(CrimeBaseHelper.DATABASE_NAME);
 }
  @Override
  public void setUp() throws Exception {

    if (testResults == null || !testResults.containsKey(jsSuite)) {
      if (testResults == null) {
        testResults = new HashMap<String, Map<String, TestResult>>();
      }

      if (!testResults.containsKey(jsSuite)) {
        testResults.put(jsSuite, new HashMap<String, TestResult>());
      }

      // Wait for app initialization to complete
      EventsListenerQueue eq = new EventsListenerQueue();
      if (!SalesforceSDKManager.hasInstance()) {
        eq.waitForEvent(EventType.AppCreateComplete, 5000);
      }

      // Start main activity
      Instrumentation instrumentation = getInstrumentation();
      final Intent intent = new Intent(Intent.ACTION_MAIN);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.setClassName(
          instrumentation.getTargetContext(),
          SalesforceSDKManager.getInstance().getMainActivityClass().getName());
      SalesforceDroidGapActivity activity =
          (SalesforceDroidGapActivity) instrumentation.startActivitySync(intent);

      // Block until the javascript has notified the container that it's ready
      TestRunnerPlugin.readyForTests.take();

      // Now run all the tests and collect the resuts in testResults
      for (String testName : getTestNames()) {
        final String jsCmd =
            "javascript:"
                + "navigator.testrunner.setTestSuite('"
                + jsSuite
                + "');"
                + "navigator.testrunner.startTest('"
                + testName
                + "');";
        final CordovaWebView appView = activity.getAppView();
        if (appView != null) {
          appView
              .getView()
              .post(
                  new Runnable() {
                    @Override
                    public void run() {
                      appView.loadUrl(jsCmd);
                    }
                  });
        }
        Log.i(getClass().getSimpleName(), "running test:" + testName);

        // Block until test completes or times out
        TestResult result = null;
        int timeout = getMaxRuntimeInSecondsForTest(testName);
        try {
          result = TestRunnerPlugin.testResults.poll(timeout, TimeUnit.SECONDS);
          if (result == null) {
            result =
                new TestResult(
                    testName, false, "Timeout (" + timeout + " seconds) exceeded", timeout);
          }
        } catch (Exception e) {
          result = new TestResult(testName, false, "Test failed", timeout);
        }
        Log.i(getClass().getSimpleName(), "done running test:" + testName);

        // Save result
        testResults.get(jsSuite).put(testName, result);
      }

      // Cleanup
      eq.tearDown();
      activity.finish();
    }
  }