summaryrefslogtreecommitdiff
path: root/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui
diff options
context:
space:
mode:
authorGuang Zhu <guangzhu@google.com>2014-11-13 19:45:26 +0000
committerGerrit Code Review <noreply-gerritcodereview@google.com>2014-11-13 19:45:27 +0000
commitf9b3351f18ae617ea4debddce931a9381ab76a4c (patch)
tree860c5d00013dbf6de4c80019e33bd7e87e0c8cce /espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui
parent61a929bd4642b9042bfb05b85340c1761ab90733 (diff)
parenta693520e12c4a00813e3dc3b4ad2ca2edc9e8f38 (diff)
downloadtesting-master.tar.gz
Diffstat (limited to 'espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui')
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/AmbiguousViewMatcherExceptionTest.java90
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/AppNotIdleExceptionTest.java77
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/EspressoEdgeCaseTest.java308
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/EspressoTest.java152
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/NoMatchingViewExceptionTest.java64
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/UnitTests.java34
-rwxr-xr-xespresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/ViewInteractionTest.java208
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/AdapterDataIntegrationTest.java93
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/ClearTextActionIntegrationTest.java63
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EditorActionIntegrationTest.java79
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EspressoKeyBuilderTest.java77
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EventActionIntegrationTest.java118
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/GeneralLocationTest.java109
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/KeyEventActionIntegrationTest.java151
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/ScrollToActionIntegrationTest.java76
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/SwipeActionIntegrationTest.java110
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/TypeTextActionIntegrationTest.java97
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/TypeTextActionTest.java93
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/WindowOrderingIntegrationTest.java95
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/assertion/ViewAssertionsTest.java170
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/AsyncTaskPoolMonitorTest.java179
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/DefaultFailureHandlerTest.java116
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/EventInjectorTest.java207
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/IdlingResourceIntegrationTest.java127
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/IdlingResourceRegistryTest.java237
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/OnDemandIdlingResource.java59
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/UiControllerImplIntegrationTest.java295
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/UiControllerImplTest.java390
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/ViewFinderImplTest.java112
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/contrib/CountingIdlingResourceTest.java120
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/matcher/PreferenceMatchersTest.java84
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/matcher/ViewMatchersTest.java456
-rw-r--r--espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/util/TreeIterablesTest.java221
33 files changed, 0 insertions, 4867 deletions
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/AmbiguousViewMatcherExceptionTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/AmbiguousViewMatcherExceptionTest.java
deleted file mode 100644
index 650c426..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/AmbiguousViewMatcherExceptionTest.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.containsString;
-
-import android.test.AndroidTestCase;
-import android.view.View;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-
-import org.hamcrest.Matcher;
-import org.hamcrest.Matchers;
-import org.hamcrest.StringDescription;
-
-/** Unit tests for {@link AmbiguousViewMatcherException}. */
-public class AmbiguousViewMatcherExceptionTest extends AndroidTestCase {
- private Matcher<View> alwaysTrueMatcher;
-
- private RelativeLayout testView;
- private View child1;
- private View child2;
- private View child3;
- private View child4;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- alwaysTrueMatcher = Matchers.<View>notNullValue();
- testView = new RelativeLayout(getContext());
- child1 = new TextView(getContext());
- child1.setId(1);
- child2 = new TextView(getContext());
- child2.setId(2);
- child3 = new TextView(getContext());
- child3.setId(3);
- child4 = new TextView(getContext());
- child4.setId(4);
- testView.addView(child1);
- testView.addView(child2);
- testView.addView(child3);
- testView.addView(child4);
- }
-
- public void testExceptionContainsMatcherDescription() {
- StringBuilder matcherDescription = new StringBuilder();
- alwaysTrueMatcher.describeTo(new StringDescription(matcherDescription));
- assertThat(createException().getMessage(), containsString(matcherDescription.toString()));
- }
-
- @SuppressWarnings("unchecked")
- public void testExceptionContainsView() {
- String exceptionMessage = createException().getMessage();
-
- assertThat("missing elements", exceptionMessage,
- allOf(
- containsString("{id=1,"), // child1
- containsString("{id=2,"), // child2
- containsString("{id=3,"), // child3
- containsString("{id=4,"), // child4
- containsString("{id=-1,"))); // root
- }
-
- private AmbiguousViewMatcherException createException() {
-
- return new AmbiguousViewMatcherException.Builder()
- .withViewMatcher(alwaysTrueMatcher)
- .withRootView(testView)
- .withView1(testView)
- .withView2(child1)
- .withOtherAmbiguousViews(child2, child3, child4)
- .build();
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/AppNotIdleExceptionTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/AppNotIdleExceptionTest.java
deleted file mode 100644
index 48fe347..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/AppNotIdleExceptionTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SyncActivity;
-
-import android.os.Handler;
-import android.os.Looper;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Test case for {@link AppNotIdleException}.
- */
-@LargeTest
-public class AppNotIdleExceptionTest extends ActivityInstrumentationTestCase2<SyncActivity> {
-
- @SuppressWarnings("deprecation")
- public AppNotIdleExceptionTest() {
- // This constructor was deprecated - but we want to support lower API levels.
- super("com.google.android.apps.common.testing.ui.testapp", SyncActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- public void testAppIdleException() throws Exception {
- final AtomicBoolean continueBeingBusy = new AtomicBoolean(true);
- try {
- final Handler handler = new Handler(Looper.getMainLooper());
- Runnable runnable = new Runnable() {
- @Override
- public void run() {
- if (!continueBeingBusy.get()) {
- return;
- } else {
- handler.post(this);
- }
- }
- };
- FutureTask<Void> task = new FutureTask<Void>(runnable, null);
- handler.post(task);
- task.get(); // Will Make sure that the first post is sent before we do a lookup.
- // Request the "hello world!" text by clicking on the request button.
- onView(withId(R.id.request_button)).perform(click());
- fail("Espresso failed to throw AppNotIdleException");
- } catch (AppNotIdleException e) {
- // Do Nothing. Test pass.
- continueBeingBusy.getAndSet(false);
- }
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/EspressoEdgeCaseTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/EspressoEdgeCaseTest.java
deleted file mode 100644
index 8439a96..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/EspressoEdgeCaseTest.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.typeText;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isAssignableFrom;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SendActivity;
-
-import android.os.AsyncTask;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.SystemClock;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.view.View;
-
-import org.hamcrest.Matcher;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * Collection of some nasty edge cases.
- */
-@LargeTest
-public class EspressoEdgeCaseTest extends ActivityInstrumentationTestCase2<SendActivity> {
- @SuppressWarnings("deprecation")
- public EspressoEdgeCaseTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", SendActivity.class);
- }
-
- private static final Callable<Void> NO_OP = new Callable<Void>() {
- @Override
- public Void call() {
- return null;
- }
- };
-
- private Handler mainHandler;
- private OneShotResource oneShotResource;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- mainHandler = new Handler(Looper.getMainLooper());
- oneShotResource = new OneShotResource();
- }
-
- @Override
- public void tearDown() throws Exception {
- IdlingPolicies.setMasterPolicyTimeout(60, TimeUnit.SECONDS);
- IdlingPolicies.setIdlingResourceTimeout(26, TimeUnit.SECONDS);
- oneShotResource.setIdle(true);
- super.tearDown();
- }
-
- @SuppressWarnings("unchecked")
- public void testRecoveryFromExceptionOnMainThreadLoopMainThreadUntilIdle() throws Exception {
- final RuntimeException poison = new RuntimeException("oops");
- try {
- onView(withId(R.id.enter_data_edit_text))
- .perform(
- new TestAction() {
-
- @Override
- public void perform(UiController controller, View view) {
- mainHandler.post(new Runnable() {
- @Override
- public void run() {
- throw poison;
- }});
- controller.loopMainThreadUntilIdle();
- }
- });
- fail("should throw");
- } catch (RuntimeException re) {
- if (re == poison) {
- // expected
- } else {
- // something else.
- throw re;
- }
- }
- // life should continue normally.
- onView(withId(R.id.enter_data_edit_text))
- .perform(typeText("Hello World111"));
- onView(withId(R.id.enter_data_edit_text))
- .check(matches(withText("Hello World111")));
- }
-
- @SuppressWarnings("unchecked")
- public void testRecoveryFromExceptionOnMainThreadLoopMainThreadForAtLeast() throws Exception {
- final RuntimeException poison = new RuntimeException("oops");
- final FutureTask<Void> syncTask = new FutureTask<Void>(NO_OP);
- try {
- onView(withId(R.id.enter_data_edit_text))
- .perform(
- new TestAction() {
- @Override
- public void perform(UiController controller, View view) {
- mainHandler.post(new Runnable() {
- @Override
- public void run() {
- throw poison;
- }});
- // block test execution until loopMainThreadForAtLeast call
- // would be satisified
- mainHandler.postDelayed(syncTask, 2500);
- controller.loopMainThreadForAtLeast(2000);
- }
- });
- fail("should throw");
- } catch (RuntimeException re) {
- if (re == poison) {
- // expected
- } else {
- // something else.
- throw re;
- }
- }
- syncTask.get();
-
- // life should continue normally.
- onView(withId(R.id.enter_data_edit_text))
- .perform(typeText("baz bar"));
- onView(withId(R.id.enter_data_edit_text))
- .check(matches(withText("baz bar")));
- }
-
- @SuppressWarnings("unchecked")
- public void testRecoveryFromTimeOutExceptionMaster() throws Exception {
- IdlingPolicies.setMasterPolicyTimeout(2, TimeUnit.SECONDS);
- final FutureTask<Void> syncTask = new FutureTask<Void>(NO_OP);
- try {
- onView(withId(R.id.enter_data_edit_text))
- .perform(
- new TestAction() {
- @Override
- public void perform(UiController controller, View view) {
- mainHandler.post(new Runnable() {
- @Override
- public void run() {
- SystemClock.sleep(TimeUnit.SECONDS.toMillis(8));
- }
- });
- // block test execution until loopMainThreadForAtLeast call
- // would be satisified
- mainHandler.postDelayed(syncTask, 2500);
- controller.loopMainThreadForAtLeast(1000);
- }
- });
- fail("should throw");
- } catch (RuntimeException re) {
- if (re instanceof EspressoException) {
- // expected
- } else {
- // something else.
- throw re;
- }
- }
- syncTask.get();
-
- // life should continue normally.
- onView(withId(R.id.enter_data_edit_text))
- .perform(typeText("one two three"));
- onView(withId(R.id.enter_data_edit_text))
- .check(matches(withText("one two three")));
- }
-
- @SuppressWarnings("unchecked")
- public void testRecoveryFromTimeOutExceptionDynamic() {
- IdlingPolicies.setIdlingResourceTimeout(2, TimeUnit.SECONDS);
-
- Espresso.registerIdlingResources(oneShotResource);
- oneShotResource.setIdle(false);
-
- try {
- onView(withId(R.id.enter_data_edit_text))
- .perform(click());
- fail("should throw");
- } catch (RuntimeException re) {
- if (re instanceof EspressoException) {
- // expected
- } else {
- // something else.
- throw re;
- }
- }
- oneShotResource.setIdle(true);
-
- // life should continue normally.
- onView(withId(R.id.enter_data_edit_text))
- .perform(typeText("Doh"));
- onView(withId(R.id.enter_data_edit_text))
- .check(matches(withText("Doh")));
- }
-
- public void testRecoveryFromAsyncTaskTimeout() throws Exception {
- IdlingPolicies.setMasterPolicyTimeout(2, TimeUnit.SECONDS);
- try {
- onView(withId(R.id.enter_data_edit_text))
- .perform(new TestAction() {
- @Override
- public void perform(UiController controller, View view) {
- new AsyncTask<Void, Void, Void>() {
- @Override
- public Void doInBackground(Void... params) {
- SystemClock.sleep(TimeUnit.SECONDS.toMillis(8));
- return null;
- }
- }.execute();
- // block test execution until loopMainThreadForAtLeast call
- // would be satisified
- controller.loopMainThreadForAtLeast(1000);
- }
- });
- fail("should throw");
- } catch (RuntimeException re) {
- if (re instanceof EspressoException) {
- // expected
- } else {
- // something else.
- throw re;
- }
- }
- IdlingPolicies.setMasterPolicyTimeout(60, TimeUnit.SECONDS);
- // life should continue normally.
- onView(withId(R.id.enter_data_edit_text))
- .perform(typeText("Har Har"));
- onView(withId(R.id.enter_data_edit_text))
- .check(matches(withText("Har Har")));
- }
-
-
-
-
- private abstract static class TestAction implements ViewAction {
- @Override
- public String getDescription() {
- return "A random test action.";
- }
-
- @Override
- public Matcher<View> getConstraints() {
- return isAssignableFrom(View.class);
- }
- }
-
-
- private static class OneShotResource implements IdlingResource {
- private static AtomicInteger counter = new AtomicInteger(0);
-
- private final int instance;
- private volatile IdlingResource.ResourceCallback callback;
- private volatile boolean isIdle = true;
-
- private OneShotResource() {
- instance = counter.incrementAndGet();
- }
-
- @Override
- public String getName() {
- return "TestOneShotResource_" + counter;
- }
-
- public void setIdle(boolean idle) {
- isIdle = idle;
- if (isIdle && callback != null) {
- callback.onTransitionToIdle();
- }
- }
-
- @Override
- public boolean isIdleNow() {
- return isIdle;
- }
-
- @Override
- public void registerIdleTransitionCallback(IdlingResource.ResourceCallback callback) {
- this.callback = callback;
- }
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/EspressoTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/EspressoTest.java
deleted file mode 100644
index ff4ff39..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/EspressoTest.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onData;
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.openContextualActionModeOverflowMenu;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.anything;
-import static org.hamcrest.Matchers.hasValue;
-import static org.hamcrest.Matchers.instanceOf;
-
-import com.google.android.apps.common.testing.ui.espresso.action.ViewActions;
-import com.google.android.apps.common.testing.ui.testapp.ActionBarTestActivity;
-import com.google.android.apps.common.testing.ui.testapp.MainActivity;
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SendActivity;
-
-import android.content.Context;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.view.View;
-import android.view.inputmethod.InputMethodManager;
-
-import org.hamcrest.Matcher;
-
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Tests Espresso top level (i.e. ones not specific to a view) actions like pressBack and
- * closeSoftKeyboard.
- */
-@LargeTest
-public class EspressoTest extends ActivityInstrumentationTestCase2<MainActivity> {
- @SuppressWarnings("deprecation")
- public EspressoTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", MainActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- @SuppressWarnings("unchecked")
- public void testOpenOverflowInActionMode() {
- onData(allOf(instanceOf(Map.class), hasValue(ActionBarTestActivity.class.getSimpleName())))
- .perform(click());
- openContextualActionModeOverflowMenu();
- onView(withText("Key"))
- .perform(click());
- onView(withId(R.id.text_action_bar_result))
- .check(matches(withText("Key")));
- }
-
- @SuppressWarnings("unchecked")
- public void testOpenOverflowFromActionBar() {
- onData(allOf(instanceOf(Map.class), hasValue(ActionBarTestActivity.class.getSimpleName())))
- .perform(click());
- onView(withId(R.id.hide_contextual_action_bar))
- .perform(click());
- openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
- onView(withText("World"))
- .perform(click());
- onView(withId(R.id.text_action_bar_result))
- .check(matches(withText("World")));
- }
-
- @SuppressWarnings("unchecked")
- public void testCloseSoftKeyboard() {
- onData(allOf(instanceOf(Map.class), hasValue(SendActivity.class.getSimpleName())))
- .perform(click());
-
- onView(withId(R.id.enter_data_edit_text)).perform(new ViewAction() {
- @Override
- public Matcher<View> getConstraints() {
- return anything();
- }
-
- @Override
- public void perform(UiController uiController, View view) {
- InputMethodManager imm = (InputMethodManager) getInstrumentation().getTargetContext()
- .getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.showSoftInput(view, 0);
- uiController.loopMainThreadUntilIdle();
- }
-
- @Override
- public String getDescription() {
- return "show soft input";
- }
- });
-
- onView(withId(R.id.enter_data_edit_text)).perform(ViewActions.closeSoftKeyboard());
- }
-
- public void testSetFailureHandler() {
- final AtomicBoolean handled = new AtomicBoolean(false);
- Espresso.setFailureHandler(new FailureHandler() {
- @Override
- public void handle(Throwable error, Matcher<View> viewMatcher) {
- handled.set(true);
- }
- });
- onView(withText("does not exist")).perform(click());
- assertTrue(handled.get());
- }
-
- public void testRegisterResourceWithNullName() {
- try {
- Espresso.registerIdlingResources(new IdlingResource() {
- @Override
- public boolean isIdleNow() {
- return true;
- }
-
- @Override
- public String getName() {
- return null;
- }
-
- @Override
- public void registerIdleTransitionCallback(ResourceCallback callback) {
- // ignore
- }
- });
- fail("Should have thrown NPE");
- } catch (NullPointerException expected) {}
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/NoMatchingViewExceptionTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/NoMatchingViewExceptionTest.java
deleted file mode 100644
index 16571e3..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/NoMatchingViewExceptionTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsString;
-
-import android.test.AndroidTestCase;
-import android.view.View;
-
-import org.hamcrest.Matcher;
-import org.hamcrest.Matchers;
-import org.hamcrest.StringDescription;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-/** Unit tests for {@link NoMatchingViewException}. */
-public class NoMatchingViewExceptionTest extends AndroidTestCase {
- private Matcher<View> alwaysFailingMatcher;
-
- @Mock
- private View testView;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- MockitoAnnotations.initMocks(this);
- alwaysFailingMatcher = Matchers.<View>nullValue();
- }
-
- public void testExceptionContainsMatcherDescription() {
- StringBuilder matcherDescription = new StringBuilder();
- alwaysFailingMatcher.describeTo(new StringDescription(matcherDescription));
- assertThat(createException().getMessage(), containsString(matcherDescription.toString()));
- }
-
- public void testExceptionContainsView() {
- String exceptionMessage = createException().getMessage();
-
- assertThat("missing root element" + exceptionMessage, exceptionMessage,
- containsString("{id=0,"));
- }
-
- private NoMatchingViewException createException() {
- return new NoMatchingViewException.Builder()
- .withViewMatcher(alwaysFailingMatcher)
- .withRootView(testView)
- .build();
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/UnitTests.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/UnitTests.java
deleted file mode 100644
index b3c3f98..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/UnitTests.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso;
-
-import android.test.suitebuilder.TestSuiteBuilder;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * TestSuite containing "unit tests" for the UI Framework.
- *
- */
-public class UnitTests extends TestSuite {
- public static Test suite() {
- return new TestSuiteBuilder(UnitTests.class)
- .includeAllPackagesUnderHere()
- .build();
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/ViewInteractionTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/ViewInteractionTest.java
deleted file mode 100755
index 295572c..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/ViewInteractionTest.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso;
-
-import static com.google.common.base.Throwables.propagate;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
-import static org.hamcrest.Matchers.nullValue;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-import com.google.android.apps.common.testing.testrunner.ActivityLifecycleMonitor;
-import com.google.android.apps.common.testing.testrunner.ActivityLifecycleMonitorRegistry;
-import com.google.android.apps.common.testing.ui.espresso.matcher.RootMatchers;
-import com.google.common.util.concurrent.MoreExecutors;
-
-import android.test.AndroidTestCase;
-import android.view.View;
-
-import org.hamcrest.Matcher;
-import org.hamcrest.Matchers;
-import org.mockito.Mock;
-
-import java.util.concurrent.Executor;
-import java.util.concurrent.atomic.AtomicReference;
-
-/** Unit tests for {@link ViewInteraction}. */
-public class ViewInteractionTest extends AndroidTestCase {
- @Mock
- private ViewFinder mockViewFinder;
- @Mock
- private ViewAssertion mockAssertion;
- @Mock
- private ViewAction mockAction;
- @Mock
- private UiController mockUiController;
-
-
- private FailureHandler failureHandler;
- private Executor testExecutor = MoreExecutors.sameThreadExecutor();
-
- private ActivityLifecycleMonitor realLifecycleMonitor;
- private ViewInteraction testInteraction;
- private View rootView;
- private View targetView;
- private Matcher<View> viewMatcher;
- private Matcher<View> actionConstraint;
- private AtomicReference<Matcher<Root>> rootMatcherRef;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- initMocks(this);
- realLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance();
- rootView = new View(getContext());
- targetView = new View(getContext());
- viewMatcher = is(targetView);
- actionConstraint = Matchers.<View>notNullValue();
- rootMatcherRef = new AtomicReference<Matcher<Root>>(RootMatchers.DEFAULT);
- when(mockAction.getDescription()).thenReturn("A Mock!");
- failureHandler = new FailureHandler() {
- @Override
- public void handle(Throwable error, Matcher<View> viewMatcher) {
- propagate(error);
- }
- };
- }
-
- @Override
- public void tearDown() throws Exception {
- ActivityLifecycleMonitorRegistry.registerInstance(realLifecycleMonitor);
- super.tearDown();
- }
-
- public void testPerformViewViolatesConstraints() {
- actionConstraint = not(viewMatcher);
- when(mockViewFinder.getView()).thenReturn(targetView);
- initInteraction();
- try {
- testInteraction.perform(mockAction);
- fail("should propagate constraint violation!");
- } catch (RuntimeException re) {
- if (!PerformException.class.isAssignableFrom(re.getClass())) {
- throw re;
- }
- }
- }
-
- public void testPerformPropagatesException() {
- RuntimeException exceptionToRaise = new RuntimeException();
- when(mockViewFinder.getView()).thenReturn(targetView);
- doThrow(exceptionToRaise)
- .when(mockAction)
- .perform(mockUiController, targetView);
- initInteraction();
- try {
- testInteraction.perform(mockAction);
- fail("Should propagate exception stored in view operation!");
- } catch (RuntimeException re) {
- verify(mockAction).perform(mockUiController, targetView);
- assertThat(exceptionToRaise, is(re));
- }
- }
-
- public void testCheckPropagatesException() {
- RuntimeException exceptionToRaise = new RuntimeException();
- when(mockViewFinder.getView()).thenReturn(targetView);
- doThrow(exceptionToRaise)
- .when(mockAssertion)
- .check(targetView, null);
-
- initInteraction();
- try {
- testInteraction.check(mockAssertion);
- fail("Should propagate exception stored in view operation!");
- } catch (RuntimeException re) {
- verify(mockAssertion).check(targetView, null);
- assertThat(exceptionToRaise, is(re));
- }
- }
-
- public void testPerformTwiceUpdatesPreviouslyMatched() {
- View firstView = new View(getContext());
- View secondView = new View(getContext());
- when(mockViewFinder.getView()).thenReturn(firstView);
- initInteraction();
- testInteraction.perform(mockAction);
- verify(mockAction).perform(mockUiController, firstView);
-
- when(mockViewFinder.getView()).thenReturn(secondView);
- testInteraction.perform(mockAction);
- verify(mockAction).perform(mockUiController, secondView);
-
- testInteraction.check(mockAssertion);
- verify(mockAssertion).check(secondView, null);
-
- }
-
- public void testPerformAndCheck() {
- when(mockViewFinder.getView()).thenReturn(targetView);
- initInteraction();
- testInteraction.perform(mockAction);
- verify(mockAction).perform(mockUiController, targetView);
-
- testInteraction.check(mockAssertion);
- verify(mockAssertion).check(targetView, null);
- }
-
- public void testCheck() {
- when(mockViewFinder.getView()).thenReturn(targetView);
- initInteraction();
- testInteraction.check(mockAssertion);
- verify(mockAssertion).check(targetView, null);
- }
-
- public void testInRootUpdatesRef() {
- initInteraction();
- Matcher<Root> testMatcher = nullValue();
- testInteraction.inRoot(testMatcher);
- assertEquals(testMatcher, rootMatcherRef.get());
- }
-
- public void testInRoot_NullHandling() {
- initInteraction();
- try {
- testInteraction.inRoot(null);
- fail("should throw");
- } catch (NullPointerException expected) {
- }
- }
-
- public void testCheck_ViewCannotBeFound() {
- NoMatchingViewException noViewException = new NoMatchingViewException.Builder()
- .withViewMatcher(viewMatcher)
- .withRootView(rootView)
- .build();
-
- when(mockViewFinder.getView()).thenThrow(noViewException);
- initInteraction();
- testInteraction.check(mockAssertion);
- verify(mockAssertion).check(null, noViewException);
- }
-
- private void initInteraction() {
- when(mockAction.getConstraints()).thenReturn(actionConstraint);
-
- testInteraction = new ViewInteraction(mockUiController, mockViewFinder, testExecutor,
- failureHandler, viewMatcher, rootMatcherRef);
-
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/AdapterDataIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/AdapterDataIntegrationTest.java
deleted file mode 100644
index fe37fc5..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/AdapterDataIntegrationTest.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onData;
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.hasSibling;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.hasEntry;
-import static org.hamcrest.Matchers.instanceOf;
-import static org.hamcrest.Matchers.is;
-
-import com.google.android.apps.common.testing.ui.testapp.LongListActivity;
-import com.google.android.apps.common.testing.ui.testapp.R;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-
-import java.util.Map;
-
-/**
- * Integration tests for operating on data displayed in an adapter.
- */
-@LargeTest
-public class AdapterDataIntegrationTest extends ActivityInstrumentationTestCase2<LongListActivity> {
- @SuppressWarnings("deprecation")
- public AdapterDataIntegrationTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", LongListActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- @SuppressWarnings("unchecked")
- public void testClickAroundList() {
- onData(allOf(is(instanceOf(Map.class)), hasEntry(is(LongListActivity.STR), is("item: 99"))))
- .perform(click());
- onView(withId(R.id.selection_row_value))
- .check(matches(withText("99")));
-
- onData(allOf(is(instanceOf(Map.class)), hasEntry(is(LongListActivity.STR), is("item: 1"))))
- .perform(click());
-
- onView(withId(R.id.selection_row_value))
- .check(matches(withText("1")));
-
- onData(allOf(is(instanceOf(Map.class))))
- .atPosition(20)
- .perform(click());
-
- onView(withId(R.id.selection_row_value))
- .check(matches(withText("20")));
-
- // lets operate on a specific child of a row...
- onData(allOf(is(instanceOf(Map.class)), hasEntry(is(LongListActivity.STR), is("item: 50"))))
- .onChildView(withId(R.id.item_size))
- .perform(click())
- .check(matches(withText(String.valueOf("item: 50".length()))));
-
- onView(withId(R.id.selection_row_value))
- .check(matches(withText("50")));
- }
-
- @SuppressWarnings("unchecked")
- public void testSelectItemWithSibling() {
- onView(allOf(withText("7"), hasSibling(withText("item: 0"))))
- .perform(click());
- onView(withId(R.id.selection_row_value))
- .check(matches(withText("0")));
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/ClearTextActionIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/ClearTextActionIntegrationTest.java
deleted file mode 100644
index cf2835f..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/ClearTextActionIntegrationTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.clearText;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.typeText;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.is;
-
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SendActivity;
-
-import android.app.Activity;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-
-/**
- * {@link ClearTextAction} integration tests.
- */
-@LargeTest
-public class ClearTextActionIntegrationTest extends ActivityInstrumentationTestCase2<SendActivity> {
- @SuppressWarnings("deprecation")
- public ClearTextActionIntegrationTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", SendActivity.class);
- }
-
- @LargeTest
- public void testClearTextActionPerform() {
- Activity activity = getActivity();
- String text = activity.getText(R.string.send_data_to_message_edit_text).toString();
- onView(withId(is(R.id.send_data_to_message_edit_text))).check(matches(withText(is(text))));
- onView(withId(is(R.id.send_data_to_message_edit_text))).perform(clearText());
- onView(withId(is(R.id.send_data_to_message_edit_text))).check(matches(withText(is(""))));
- }
-
- @LargeTest
- public void testClearTextActionPerformWithTypeText() {
- Activity activity = getActivity();
- String text = activity.getText(R.string.send_data_to_message_edit_text).toString();
- onView(withId(is(R.id.send_data_to_call_edit_text))).perform(typeText(text));
- onView(withId(is(R.id.send_data_to_call_edit_text))).check(matches(withText(is(text))));
- onView(withId(is(R.id.send_data_to_call_edit_text))).perform(clearText());
- onView(withId(is(R.id.send_data_to_call_edit_text))).check(matches(withText(is(""))));
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EditorActionIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EditorActionIntegrationTest.java
deleted file mode 100644
index 0a99be9..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EditorActionIntegrationTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.pressImeActionButton;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.scrollTo;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.hasImeAction;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.containsString;
-
-import com.google.android.apps.common.testing.ui.espresso.PerformException;
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SendActivity;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.view.inputmethod.EditorInfo;
-
-/**
- * Tests for {@link EditorAction}.
- */
-@LargeTest
-public class EditorActionIntegrationTest extends ActivityInstrumentationTestCase2<SendActivity> {
- @SuppressWarnings("deprecation")
- public EditorActionIntegrationTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", SendActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- @SuppressWarnings("unchecked")
- public void testPressImeActionButtonOnSearchBox() {
- String searchFor = "rainbows and unicorns";
- onView(withId(R.id.search_box)).perform(scrollTo(), ViewActions.typeText(searchFor));
- onView(withId(R.id.search_box))
- .check(matches(hasImeAction(EditorInfo.IME_ACTION_SEARCH)))
- .perform(pressImeActionButton());
- onView(withId(R.id.search_result)).perform(scrollTo());
- onView(withId(R.id.search_result))
- .check(matches(allOf(isDisplayed(), withText(containsString(searchFor)))));
- }
-
- public void testPressImeActionButtonOnNonEditorWidget() {
- try {
- onView(withId(R.id.send_button)).perform(pressImeActionButton());
- fail("Expected exception on previous call");
- } catch (PerformException expected) {
- assertTrue(expected.getCause() instanceof IllegalStateException);
- }
- }
-
- public void testPressSearchOnDefaultEditText() {
- onView(withId(R.id.enter_data_edit_text)).perform(pressImeActionButton());
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EspressoKeyBuilderTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EspressoKeyBuilderTest.java
deleted file mode 100644
index 6df907d..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EspressoKeyBuilderTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import com.google.android.apps.common.testing.ui.espresso.action.EspressoKey.Builder;
-
-import android.os.Build;
-import android.view.KeyEvent;
-
-import junit.framework.TestCase;
-
-/**
- * Unit tests for {@link Builder}.
- */
-public class EspressoKeyBuilderTest extends TestCase {
-
- static final int KEY_CODE = KeyEvent.KEYCODE_X;
-
- public void testBuildWithNoMetaState() {
- EspressoKey key = new Builder().withKeyCode(KEY_CODE).build();
- assertEquals(KEY_CODE, key.getKeyCode());
- assertEquals(0, key.getMetaState());
- }
-
- public void testBuildWithShiftPressed() {
- EspressoKey key = new Builder().withKeyCode(KEY_CODE).withShiftPressed(true).build();
- assertEquals(KEY_CODE, key.getKeyCode());
- assertEquals(KeyEvent.META_SHIFT_ON, key.getMetaState());
- }
-
- public void testBuildWithCtrlPressed() {
- EspressoKey key = new Builder().withKeyCode(KEY_CODE).withCtrlPressed(true).build();
- assertEquals(KEY_CODE, key.getKeyCode());
-
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
- assertEquals(KeyEvent.META_CTRL_ON, key.getMetaState());
- } else {
- assertEquals(0, key.getMetaState());
- }
- }
-
- public void testBuildWithAltPressed() {
- EspressoKey key = new Builder().withKeyCode(KEY_CODE).withAltPressed(true).build();
- assertEquals(KEY_CODE, key.getKeyCode());
- assertEquals(KeyEvent.META_ALT_ON, key.getMetaState());
- }
-
- public void testBuildWithAllMetaKeysPressed() {
- EspressoKey key = new Builder().withKeyCode(KEY_CODE)
- .withShiftPressed(true)
- .withCtrlPressed(true)
- .withAltPressed(true)
- .build();
-
- assertEquals(KEY_CODE, key.getKeyCode());
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
- assertEquals(KeyEvent.META_SHIFT_ON | KeyEvent.META_CTRL_ON | KeyEvent.META_ALT_ON,
- key.getMetaState());
- } else {
- assertEquals(KeyEvent.META_SHIFT_ON | KeyEvent.META_ALT_ON, key.getMetaState());
- }
- }
-} \ No newline at end of file
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EventActionIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EventActionIntegrationTest.java
deleted file mode 100644
index fbf55ef..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/EventActionIntegrationTest.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.doubleClick;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.longClick;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isAssignableFrom;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
-
-import com.google.android.apps.common.testing.testrunner.annotations.SdkSuppress;
-import com.google.android.apps.common.testing.ui.espresso.UiController;
-import com.google.android.apps.common.testing.ui.espresso.ViewAction;
-import com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers;
-import com.google.android.apps.common.testing.ui.testapp.GestureActivity;
-import com.google.android.apps.common.testing.ui.testapp.R;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.view.View;
-
-import org.hamcrest.Matcher;
-
-/**
- * UI tests for ClickAction, LongClickAction and DoubleClickAction.
- */
-@LargeTest
-public class EventActionIntegrationTest extends ActivityInstrumentationTestCase2<GestureActivity> {
-
- @SuppressWarnings("deprecation")
- public EventActionIntegrationTest() {
- // Keep froyo happy.
- super("com.google.android.apps.common.testing.ui.testapp", GestureActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- public void testClick() {
- onView(withText(is(getActivity().getString(R.string.text_click))))
- .check(matches(not(isDisplayed())));
- onView(withId(is(R.id.gesture_area))).perform(click());
- onView(withId(is(R.id.text_click))).check(matches(isDisplayed()));
- onView(withText(is(getActivity().getString(R.string.text_click))))
- .check(matches(isDisplayed()));
- }
-
- public void testBadClick() {
- onView(withText(is(getActivity().getString(R.string.text_click))))
- .check(matches(not(isDisplayed())));
- getActivity().setTouchDelay(700);
-
- onView(withId(is(R.id.gesture_area))).perform(click(
- new ViewAction() {
- @Override
- public String getDescription() {
- return "Handle tap->longclick.";
- }
- @Override
- public Matcher<View> getConstraints() {
- return isAssignableFrom(View.class);
- }
- @Override
- public void perform(UiController uiController, View view) {
- getActivity().setTouchDelay(0);
- }
- }));
-
-
- onView(withId(is(R.id.text_click))).check(matches(isDisplayed()));
- onView(withText(is(getActivity().getString(R.string.text_click))))
- .check(matches(isDisplayed()));
- }
-
- @SdkSuppress(bugId = -1, versions = {7, 8, 13})
- public void testLongClick() {
- onView(withText(is(getActivity().getString(R.string.text_long_click))))
- .check(matches(not(isDisplayed())));
- onView(withId(is(R.id.gesture_area))).perform(longClick());
- onView(withId(is(R.id.text_long_click))).check(matches(isDisplayed()));
- onView(withText(is(getActivity().getString(R.string.text_long_click))))
- .check(matches(isDisplayed()));
- }
-
- @SdkSuppress(bugId = -1, versions = {7, 8, 13})
- public void testDoubleClick() {
- onView(withText(is(getActivity().getString(R.string.text_double_click))))
- .check(matches(not(ViewMatchers.isDisplayed())));
- onView(withId(is(R.id.gesture_area))).perform(doubleClick());
- onView(withId(is(R.id.text_double_click))).check(matches(isDisplayed()));
- onView(withText(is("Double Click"))).check(matches(isDisplayed()));
- onView(withText(is(getActivity().getString(R.string.text_double_click))))
- .check(matches(isDisplayed()));
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/GeneralLocationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/GeneralLocationTest.java
deleted file mode 100644
index 944e660..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/GeneralLocationTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-import android.view.View;
-
-import junit.framework.TestCase;
-
-import org.mockito.Spy;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-
-/**
- * Unit tests for {@link GeneralLocation}.
- */
-public class GeneralLocationTest extends TestCase {
-
- private static final int VIEW_POSITION_X = 100;
- private static final int VIEW_POSITION_Y = 50;
- private static final int VIEW_WIDTH = 150;
- private static final int VIEW_HEIGHT = 300;
-
- private static final int AXIS_X = 0;
- private static final int AXIS_Y = 1;
-
- @Spy
- private View mockView;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- initMocks(this);
-
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- int[] array = (int[]) invocation.getArguments()[0];
- array[AXIS_X] = VIEW_POSITION_X;
- array[AXIS_Y] = VIEW_POSITION_Y;
- return null;
- }
- }).when(mockView).getLocationOnScreen(any(int[].class));
-
- mockView.layout(
- VIEW_POSITION_X,
- VIEW_POSITION_Y,
- VIEW_POSITION_X + VIEW_WIDTH,
- VIEW_POSITION_Y + VIEW_HEIGHT);
- }
-
- public void testLeftLocationsX() {
- assertPositionEquals(VIEW_POSITION_X, GeneralLocation.TOP_LEFT, AXIS_X);
- assertPositionEquals(VIEW_POSITION_X, GeneralLocation.CENTER_LEFT, AXIS_X);
- assertPositionEquals(VIEW_POSITION_X, GeneralLocation.BOTTOM_LEFT, AXIS_X);
- }
-
- public void testRightLocationsX() {
- assertPositionEquals(VIEW_POSITION_X + VIEW_WIDTH, GeneralLocation.TOP_RIGHT, AXIS_X);
- assertPositionEquals(VIEW_POSITION_X + VIEW_WIDTH, GeneralLocation.CENTER_RIGHT, AXIS_X);
- assertPositionEquals(VIEW_POSITION_X + VIEW_WIDTH, GeneralLocation.BOTTOM_RIGHT, AXIS_X);
- }
-
- public void testTopLocationsY() {
- assertPositionEquals(VIEW_POSITION_Y, GeneralLocation.TOP_LEFT, AXIS_Y);
- assertPositionEquals(VIEW_POSITION_Y, GeneralLocation.TOP_CENTER, AXIS_Y);
- assertPositionEquals(VIEW_POSITION_Y, GeneralLocation.TOP_RIGHT, AXIS_Y);
- }
-
- public void testBottomLocationsY() {
- assertPositionEquals(VIEW_POSITION_Y + VIEW_HEIGHT, GeneralLocation.BOTTOM_LEFT, AXIS_Y);
- assertPositionEquals(VIEW_POSITION_Y + VIEW_HEIGHT, GeneralLocation.BOTTOM_CENTER, AXIS_Y);
- assertPositionEquals(VIEW_POSITION_Y + VIEW_HEIGHT, GeneralLocation.BOTTOM_RIGHT, AXIS_Y);
- }
-
- public void testCenterLocationsX() {
- assertPositionEquals(VIEW_POSITION_X + VIEW_WIDTH / 2, GeneralLocation.CENTER, AXIS_X);
- assertPositionEquals(VIEW_POSITION_X + VIEW_WIDTH / 2, GeneralLocation.TOP_CENTER, AXIS_X);
- assertPositionEquals(VIEW_POSITION_X + VIEW_WIDTH / 2, GeneralLocation.BOTTOM_CENTER, AXIS_X);
- }
-
- public void testCenterLocationsY() {
- assertPositionEquals(VIEW_POSITION_Y + VIEW_HEIGHT / 2, GeneralLocation.CENTER, AXIS_Y);
- assertPositionEquals(VIEW_POSITION_Y + VIEW_HEIGHT / 2, GeneralLocation.CENTER_LEFT, AXIS_Y);
- assertPositionEquals(VIEW_POSITION_Y + VIEW_HEIGHT / 2, GeneralLocation.CENTER_RIGHT, AXIS_Y);
- }
-
- private void assertPositionEquals(int expected, GeneralLocation location, int axis) {
- assertEquals(expected, location.calculateCoordinates(mockView)[axis], 0.1f);
- }
-
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/KeyEventActionIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/KeyEventActionIntegrationTest.java
deleted file mode 100644
index c75c3fb..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/KeyEventActionIntegrationTest.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onData;
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.pressBack;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isAssignableFrom;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isRoot;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withParent;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.hasValue;
-import static org.hamcrest.Matchers.instanceOf;
-
-import com.google.android.apps.common.testing.testrunner.annotations.SdkSuppress;
-import com.google.android.apps.common.testing.ui.espresso.NoActivityResumedException;
-import com.google.android.apps.common.testing.ui.testapp.MainActivity;
-import com.google.android.apps.common.testing.ui.testapp.R;
-
-import android.content.Intent;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.FlakyTest;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.view.KeyEvent;
-import android.widget.TextView;
-
-import java.util.Map;
-
-
-/**
- * Integration tests for {@link KeyEventAction}.
- */
-@LargeTest
-public class KeyEventActionIntegrationTest extends ActivityInstrumentationTestCase2<MainActivity> {
- @SuppressWarnings("deprecation")
- public KeyEventActionIntegrationTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", MainActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- }
-
- public void testClickBackOnRootAction() {
- getActivity();
- try {
- pressBack();
- fail("Should have thrown NoActivityResumedException");
- } catch (NoActivityResumedException expected) {
- }
- }
-
- @SuppressWarnings("unchecked")
- public void testClickBackOnNonRootActivityLatte() {
- getActivity();
- onData(allOf(instanceOf(Map.class), hasValue("SendActivity"))).perform(click());
- pressBack();
-
- // Make sure we are back.
- onData(allOf(instanceOf(Map.class), hasValue("SendActivity"))).check(matches(isDisplayed()));
- }
-
- @SuppressWarnings("unchecked")
- public void testClickBackOnNonRootActionNoLatte() {
- getActivity();
- onData(allOf(instanceOf(Map.class), hasValue("SendActivity"))).perform(click());
- onView(isRoot()).perform(ViewActions.pressBack());
-
- // Make sure we are back.
- onData(allOf(instanceOf(Map.class), hasValue("SendActivity"))).check(matches(isDisplayed()));
- }
-
- @SuppressWarnings("unchecked")
- @SdkSuppress(versions = {7, 8, 10}, bugId = -1) // uses native fragments.
- @FlakyTest
- public void testClickOnBackFromFragment() {
- Intent fragmentStack = new Intent().setClassName(getInstrumentation().getTargetContext(),
- "com.google.android.apps.common.testing.ui.testapp.FragmentStack");
- fragmentStack.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- getInstrumentation().startActivitySync(fragmentStack);
- onView(allOf(withParent(withId(R.id.simple_fragment)), isAssignableFrom(TextView.class)))
- .check(matches(withText(containsString("#1"))));
- try {
- pressBack();
- fail("Should have thrown NoActivityResumedException");
- } catch (NoActivityResumedException expected) {
- }
- getInstrumentation().startActivitySync(fragmentStack);
-
- onView(withId(R.id.new_fragment)).perform(click()).perform(click()).perform(click());
-
- onView(allOf(withParent(withId(R.id.simple_fragment)), isAssignableFrom(TextView.class)))
- .check(matches(withText(containsString("#4"))));
-
- pressBack();
-
- onView(allOf(withParent(withId(R.id.simple_fragment)), isAssignableFrom(TextView.class)))
- .check(matches(withText(containsString("#3"))));
-
- pressBack();
-
- onView(allOf(withParent(withId(R.id.simple_fragment)), isAssignableFrom(TextView.class)))
- .check(matches(withText(containsString("#2"))));
-
- pressBack();
-
- onView(allOf(withParent(withId(R.id.simple_fragment)), isAssignableFrom(TextView.class)))
- .check(matches(withText(containsString("#1"))));
-
- try {
- pressBack();
- fail("Should have thrown NoActivityResumedException");
- } catch (NoActivityResumedException expected) {
- }
- }
-
- @SuppressWarnings("unchecked")
- public void testPressKeyWithKeyCode() {
- getActivity();
- onData(allOf(instanceOf(Map.class), hasValue("SendActivity"))).perform(click());
- onView(withId(R.id.enter_data_edit_text)).perform(click());
- onView(withId(R.id.enter_data_edit_text)).perform(ViewActions.pressKey(KeyEvent.KEYCODE_X));
- onView(withId(R.id.enter_data_edit_text)).perform(ViewActions.pressKey(KeyEvent.KEYCODE_Y));
- onView(withId(R.id.enter_data_edit_text)).perform(ViewActions.pressKey(KeyEvent.KEYCODE_Z));
- onView(withId(R.id.enter_data_edit_text)).perform(ViewActions.pressKey(KeyEvent.KEYCODE_ENTER));
- onView(allOf(withId(R.id.enter_data_response_text), withText("xyz")))
- .check(matches(isDisplayed()));
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/ScrollToActionIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/ScrollToActionIntegrationTest.java
deleted file mode 100644
index 60ca48b..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/ScrollToActionIntegrationTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.scrollTo;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
-
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.ScrollActivity;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-
-/**
- * Tests for ScrollToAction.
- */
-@LargeTest
-public class ScrollToActionIntegrationTest extends ActivityInstrumentationTestCase2<ScrollActivity>
-{
- @SuppressWarnings("deprecation")
- public ScrollToActionIntegrationTest() {
- // Keep froyo happy.
- super("com.google.android.apps.common.testing.ui.testapp", ScrollActivity.class);
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- public void testScrollDown() {
- onView(withId(is(R.id.bottom_left)))
- .check(matches(not(isDisplayed())))
- .perform(scrollTo())
- .check(matches(isDisplayed()))
- .perform(scrollTo()); // Should be a noop.
- }
-
- public void testScrollVerticalAndHorizontal() {
- onView(withId(is(R.id.bottom_right)))
- .check(matches(not(isDisplayed())))
- .perform(scrollTo())
- .check(matches(isDisplayed()));
- onView(withId(is(R.id.top_left)))
- .check(matches(not(isDisplayed())))
- .perform(scrollTo())
- .check(matches(isDisplayed()));
- }
-
- public void testScrollWithinScroll() {
- onView(withId(is(R.id.double_scroll)))
- .check(matches(not(isDisplayed())))
- .perform(scrollTo())
- .check(matches(isDisplayed()));
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/SwipeActionIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/SwipeActionIntegrationTest.java
deleted file mode 100644
index 90257bc..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/SwipeActionIntegrationTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.swipeLeft;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.swipeRight;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.hasDescendant;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.allOf;
-
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SwipeActivity;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-
-/**
- * Integration tests for swiping actions.
- */
-@LargeTest
-public class SwipeActionIntegrationTest extends ActivityInstrumentationTestCase2<SwipeActivity> {
-
- @SuppressWarnings("deprecation")
- public SwipeActionIntegrationTest() {
- // Keep froyo happy.
- super("com.google.android.apps.common.testing.ui.testapp", SwipeActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- /** Tests that a small view can be swiped in both directions. */
- public void testSwipeOverSmallView() {
- onView(withId(R.id.small_pager))
- .check(matches(hasDescendant(withText("Position #0"))))
- .perform(swipeLeft())
- .check(matches(hasDescendant(withText("Position #1"))))
- .perform(swipeLeft())
- .check(matches(hasDescendant(withText("Position #2"))))
- .perform(swipeRight())
- .check(matches(hasDescendant(withText("Position #1"))))
- .perform(swipeRight())
- .check(matches(hasDescendant(withText("Position #0"))));
- }
-
- /** Tests that trying to swipe beyond the start of a view pager has no effect. */
- public void testSwipingRightHasNoEffectWhenAtStart() {
- onView(withId(R.id.small_pager))
- .check(matches(hasDescendant(withText("Position #0"))))
- .perform(swipeRight())
- .check(matches(hasDescendant(withText("Position #0"))))
- .perform(swipeRight())
- .check(matches(hasDescendant(withText("Position #0"))));
- }
-
- /** Tests that trying to swipe beyond the end of a view pager has no effect. */
- public void testSwipingLeftHasNoEffectWhenAtEnd() {
- onView(withId(R.id.small_pager))
- .perform(swipeLeft())
- .perform(swipeLeft())
- .check(matches(hasDescendant(withText("Position #2"))))
- .perform(swipeLeft())
- .check(matches(hasDescendant(withText("Position #2"))))
- .perform(swipeLeft())
- .check(matches(hasDescendant(withText("Position #2"))));
- }
-
- /** Tests that swiping across a partially overlapped view works correctly. */
- public void testSwipeOverPartiallyOverlappedView() {
- onView(withId(R.id.overlapped_pager))
- .check(matches(hasDescendant(withText("Position #0"))))
- .perform(swipeLeft())
- .check(matches(hasDescendant(withText("Position #1"))))
- .perform(swipeRight())
- .check(matches(hasDescendant(withText("Position #0"))));
- }
-
- /** Tests that trying to swipe a view that doesn't respond to swipes has no effect. */
- @SuppressWarnings("unchecked")
- public void testSwipeOverUnswipableView() {
- onView(withId(R.id.text_simple))
- .check(matches(allOf(isDisplayed(), withText(R.string.text_simple))))
- .perform(swipeLeft())
- .check(matches(allOf(isDisplayed(), withText(R.string.text_simple))))
- .perform(swipeRight())
- .check(matches(allOf(isDisplayed(), withText(R.string.text_simple))));
- }
-
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/TypeTextActionIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/TypeTextActionIntegrationTest.java
deleted file mode 100644
index b1130f1..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/TypeTextActionIntegrationTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.pressImeActionButton;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.scrollTo;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.typeText;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.typeTextIntoFocusedView;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withParent;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.is;
-
-import com.google.android.apps.common.testing.ui.espresso.PerformException;
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SendActivity;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-
-/**
- * {@link TypeTextAction} integration tests.
- */
-@LargeTest
-public class TypeTextActionIntegrationTest extends ActivityInstrumentationTestCase2<SendActivity> {
- @SuppressWarnings("deprecation")
- public TypeTextActionIntegrationTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", SendActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- public void testTypeTextActionPerform() {
- onView(withId(is(R.id.send_data_to_call_edit_text))).perform(typeText("Hello!"));
- }
-
- @SuppressWarnings("unchecked")
- public void testTypeTextActionPerformWithEnter() {
- onView(withId(R.id.enter_data_edit_text)).perform(typeText("Hello World!\n"));
- onView(allOf(withId(R.id.enter_data_response_text), withText("Hello World!")))
- .check(matches(isDisplayed()));
- }
-
- public void testTypeTextInFocusedView() {
- onView(withId(is(R.id.send_data_to_call_edit_text))).perform(typeText(
- "Hello World How Are You Today? I have alot of text to type."));
- onView(withId(is(R.id.send_data_to_call_edit_text))).perform(typeTextIntoFocusedView(
- "Jolly good!"));
- onView(withId(is(R.id.send_data_to_call_edit_text))).check(matches(withText(
- "Hello World How Are You Today? I have alot of text to type.Jolly good!")));
- }
-
- public void testTypeTextInFocusedView_constraintBreakage() {
- onView(withId(is(R.id.send_data_to_call_edit_text))).perform(typeText(
- "Hello World How Are You Today? I have alot of text to type."));
- try {
- onView(withId(is(R.id.edit_text_message)))
- .perform(scrollTo(), typeTextIntoFocusedView("Jolly good!"));
- fail("Should not have been able to type into focused view.");
- } catch (PerformException expected) {
- }
- }
-
- @SuppressWarnings("unchecked")
- public void testTypeTextInDelegatedEditText() {
- String toType = "honeybadger doesn't care";
- onView(allOf(withParent(withId(R.id.delegating_edit_text)), withId(R.id.delegate_edit_text)))
- .perform(scrollTo(), typeText(toType), pressImeActionButton());
- onView(withId(R.id.edit_text_message))
- .perform(scrollTo())
- .check(matches(withText(containsString(toType))));
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/TypeTextActionTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/TypeTextActionTest.java
deleted file mode 100644
index acddc06..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/TypeTextActionTest.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static org.mockito.Matchers.isA;
-import static org.mockito.Mockito.when;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-import com.google.android.apps.common.testing.ui.espresso.InjectEventSecurityException;
-import com.google.android.apps.common.testing.ui.espresso.PerformException;
-import com.google.android.apps.common.testing.ui.espresso.UiController;
-
-import android.view.MotionEvent;
-import android.view.View;
-
-import junit.framework.TestCase;
-
-import org.mockito.Mock;
-
-/**
- * Unit tests for {@link TypeTextAction}.
- */
-public class TypeTextActionTest extends TestCase {
- @Mock
- private UiController mockUiController;
-
- @Mock
- private View mockView;
-
- private TypeTextAction typeTextAction;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- initMocks(this);
- }
-
- public void testTypeTextActionPerform() throws InjectEventSecurityException {
- String stringToBeTyped = "Hello!";
- typeTextAction = new TypeTextAction(stringToBeTyped);
- when(mockUiController.injectMotionEvent(isA(MotionEvent.class))).thenReturn(true);
- when(mockUiController.injectString(stringToBeTyped)).thenReturn(true);
- typeTextAction.perform(mockUiController, mockView);
- }
-
- public void testTypeTextActionPerformFailed() throws InjectEventSecurityException {
- String stringToBeTyped = "Hello!";
- typeTextAction = new TypeTextAction(stringToBeTyped);
- when(mockUiController.injectMotionEvent(isA(MotionEvent.class))).thenReturn(true);
- when(mockUiController.injectString(stringToBeTyped)).thenReturn(false);
-
- try {
- typeTextAction.perform(mockUiController, mockView);
- fail("Should have thrown PerformException");
- } catch (PerformException e) {
- if (e.getCause() instanceof InjectEventSecurityException) {
- fail("Exception cause should NOT be of type InjectEventSecurityException");
- }
- }
- }
-
- public void testTypeTextActionPerformInjectEventSecurityException()
- throws InjectEventSecurityException {
- String stringToBeTyped = "Hello!";
- typeTextAction = new TypeTextAction(stringToBeTyped);
- when(mockUiController.injectMotionEvent(isA(MotionEvent.class))).thenReturn(true);
- when(mockUiController.injectString(stringToBeTyped))
- .thenThrow(new InjectEventSecurityException(""));
-
- try {
- typeTextAction.perform(mockUiController, mockView);
- fail("Should have thrown PerformException");
- } catch (PerformException e) {
- if (!(e.getCause() instanceof InjectEventSecurityException)) {
- fail("Exception cause should be of type InjectEventSecurityException");
- }
- }
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/WindowOrderingIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/WindowOrderingIntegrationTest.java
deleted file mode 100644
index d50e409..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/WindowOrderingIntegrationTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.action;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.scrollTo;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.doesNotExist;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SendActivity;
-
-import android.os.Build;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-
-/**
- * Ensures view root ordering works properly.
- */
-@LargeTest
-public class WindowOrderingIntegrationTest extends ActivityInstrumentationTestCase2<SendActivity> {
- @SuppressWarnings("deprecation")
- public WindowOrderingIntegrationTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", SendActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- public void testPopupMenu() {
- if (Build.VERSION.SDK_INT < 11) {
- // popup menus are post honeycomb.
- return;
- }
- onView(withText(R.string.item_1_text))
- .check(doesNotExist());
- onView(withId(R.id.make_popup_menu_button))
- .perform(scrollTo(), click());
- onView(withText(R.string.item_1_text))
- .check(matches(isDisplayed()))
- .perform(click());
- onView(withText(R.string.item_1_text))
- .check(doesNotExist());
- }
-
- public void testPopupWindow() {
- getActivity();
- onView(withId(R.id.popup_title))
- .check(doesNotExist());
- onView(withId(R.id.make_popup_view_button))
- .perform(scrollTo(), click());
- onView(withId(R.id.popup_title))
- .check(matches(withText(R.string.popup_title)))
- .perform(click());
- onView(withId(R.id.popup_title))
- .check(doesNotExist());
- }
-
- public void testDialog() {
- onView(withText(R.string.dialog_title))
- .check(doesNotExist());
- onView(withId(R.id.make_alert_dialog))
- .perform(scrollTo(), click());
- onView(withText(R.string.dialog_title))
- .check(matches(isDisplayed()));
-
- onView(withText("Fine"))
- .perform(click());
-
- onView(withText(R.string.dialog_title))
- .check(doesNotExist());
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/assertion/ViewAssertionsTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/assertion/ViewAssertionsTest.java
deleted file mode 100644
index b49a822..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/assertion/ViewAssertionsTest.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.assertion;
-
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.selectedDescendantsMatch;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.hasContentDescription;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isAssignableFrom;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
-import static org.hamcrest.Matchers.nullValue;
-
-import com.google.android.apps.common.testing.ui.espresso.NoMatchingViewException;
-
-import android.test.InstrumentationTestCase;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.RelativeLayout;
-import android.widget.ScrollView;
-import android.widget.TextView;
-
-import junit.framework.AssertionFailedError;
-
-import org.hamcrest.Matcher;
-
-/**
- * Unit tests for {@link ViewAssertions}.
- */
-public class ViewAssertionsTest extends InstrumentationTestCase {
-
- private View presentView;
- private View absentView;
- private NoMatchingViewException absentException;
- private NoMatchingViewException presentException;
- private Matcher<View> alwaysAccepts;
- private Matcher<View> alwaysFails;
- private Matcher<View> nullViewMatcher;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- presentView = new View(getInstrumentation().getTargetContext());
- absentView = null;
- absentException = null;
- alwaysAccepts = is(presentView);
- alwaysFails = not(is(presentView));
- nullViewMatcher = nullValue();
-
- presentException = new NoMatchingViewException.Builder()
- .withViewMatcher(alwaysFails)
- .withRootView(new View(getInstrumentation().getTargetContext()))
- .build();
- }
-
- public void testViewPresent_MatcherFail() {
- try {
- matches(alwaysFails).check(presentView, absentException);
- } catch (AssertionFailedError expected) {
- return;
- }
- // cannot place inside try block, would be caught.
- fail("Should not accept.");
- }
-
- public void testViewPresent_MatcherPass() {
- try {
- matches(alwaysAccepts).check(presentView, absentException);
- } catch (AssertionError error) {
- throw new RuntimeException("Should not die!!!", error);
- }
- }
-
- public void testViewAbsent_Unexpectedly() {
- try {
- matches(alwaysAccepts).check(absentView, presentException);
- } catch (NoMatchingViewException expected) {
- return;
- }
-
- fail("should not accept, view not present.");
- }
-
- public void testViewAbsent_AndThatsWhatIWant() {
- try {
- matches(nullViewMatcher).check(absentView, presentException);
- } catch (NoMatchingViewException expected) {
- return;
- }
-
- fail("should not accept, view not present.");
- }
-
- public void testSelectedDescendantsMatch_ThereAreNone() {
- View grany = setUpViewHierarchy();
-
- try {
- selectedDescendantsMatch(withText("welfjkw"), hasContentDescription())
- .check(grany, absentException);
- } catch (AssertionError error) {
- throw new RuntimeException("Should not die!!!", error);
- }
- }
-
- public void testSelectedDescendantsMatch_SelectedDescendantsMatch() {
- View grany = setUpViewHierarchy();
-
- try {
- selectedDescendantsMatch(withText("has content description"), hasContentDescription())
- .check(grany, absentException);
- } catch (AssertionError error) {
- throw new RuntimeException("Should not die!!!", error);
- }
- }
-
- public void testSelectedDescendantsMatch_SelectedDescendantsDoNotMatch() {
- View grany = setUpViewHierarchy();
-
- try {
- selectedDescendantsMatch(withText("no content description"), hasContentDescription())
- .check(grany, absentException);
- } catch (AssertionFailedError expected) {
- return;
- }
-
- fail("should fail because descendants do not match.");
- }
-
- public void testSelectedDescendantsMatch_SelectedDescendantsMatchAndDoNotMatch() {
- View grany = setUpViewHierarchy();
-
- try {
- selectedDescendantsMatch(isAssignableFrom(TextView.class), hasContentDescription())
- .check(grany, absentException);
- } catch (AssertionFailedError expected) {
- return;
- }
-
- fail("should fail because not all descendants match.");
- }
-
- private View setUpViewHierarchy() {
- TextView v1 = new TextView(getInstrumentation().getTargetContext());
- v1.setText("no content description");
- TextView v2 = new TextView(getInstrumentation().getTargetContext());
- v2.setText("has content description");
- v2.setContentDescription("content description");
- ViewGroup parent = new RelativeLayout(getInstrumentation().getTargetContext());
- View grany = new ScrollView(getInstrumentation().getTargetContext());
- ((ViewGroup) grany).addView(parent);
- parent.addView(v1);
- parent.addView(v2);
-
- return grany;
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/AsyncTaskPoolMonitorTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/AsyncTaskPoolMonitorTest.java
deleted file mode 100644
index f400cf0..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/AsyncTaskPoolMonitorTest.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.base;
-
-import junit.framework.TestCase;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Unit test for {@link AsyncTaskPoolMonitor}
- */
-public class AsyncTaskPoolMonitorTest extends TestCase {
-
- private final ThreadPoolExecutor testThreadPool = new ThreadPoolExecutor(
- 4, 4, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
-
- private AsyncTaskPoolMonitor monitor = new AsyncTaskPoolMonitor(testThreadPool);
-
- @Override
- public void tearDown() throws Exception {
- testThreadPool.shutdownNow();
- super.tearDown();
- }
-
- public void testIsIdle_onEmptyPool() throws Exception {
- assertTrue(monitor.isIdleNow());
- final AtomicBoolean isIdle = new AtomicBoolean(false);
- // since we're already idle, this should be ran immedately on our thread.
- monitor.notifyWhenIdle(new Runnable() {
- @Override
- public void run() {
- isIdle.set(true);
- }
- });
- assertTrue(isIdle.get());
- }
-
- public void testIsIdle_withRunningTask() throws Exception {
- final CountDownLatch runLatch = new CountDownLatch(1);
- testThreadPool.submit(new Runnable() {
- @Override
- public void run() {
- runLatch.countDown();
- try {
- Thread.sleep(50000);
- } catch (InterruptedException ie) {
- throw new RuntimeException(ie);
- }
- }
- });
- assertTrue(runLatch.await(1, TimeUnit.SECONDS));
- assertFalse(monitor.isIdleNow());
-
- final AtomicBoolean isIdle = new AtomicBoolean(false);
- monitor.notifyWhenIdle(new Runnable() {
- @Override
- public void run() {
- isIdle.set(true);
- }
- });
- // runnable shouldn't be run ever..
- assertFalse(isIdle.get());
- }
-
-
- public void testIdleNotificationAndRestart() throws Exception {
-
- FutureTask<Thread> workerThreadFetchTask = new FutureTask<Thread>(new Callable<Thread>() {
- @Override
- public Thread call() {
- return Thread.currentThread();
- }
- });
- testThreadPool.submit(workerThreadFetchTask);
-
- Thread workerThread = workerThreadFetchTask.get();
-
- final CountDownLatch runLatch = new CountDownLatch(1);
- final CountDownLatch exitLatch = new CountDownLatch(1);
-
- testThreadPool.submit(new Runnable() {
- @Override
- public void run() {
- runLatch.countDown();
- try {
- exitLatch.await();
- } catch (InterruptedException ie) {
- throw new RuntimeException(ie);
- }
- }
- });
-
- assertTrue(runLatch.await(1, TimeUnit.SECONDS));
- final CountDownLatch notificationLatch = new CountDownLatch(1);
- monitor.notifyWhenIdle(new Runnable() {
- @Override
- public void run() {
- notificationLatch.countDown();
- }
- });
- // give some time for the idle detection threads to spin up.
- Thread.sleep(2000);
- // interrupt one of them
- workerThread.interrupt();
- Thread.sleep(1000);
- // unblock the dummy work item.
- exitLatch.countDown();
- assertTrue(notificationLatch.await(1, TimeUnit.SECONDS));
- assertTrue(monitor.isIdleNow());
- }
-
- public void testIdleNotification_extraWork() throws Exception {
- final CountDownLatch firstRunLatch = new CountDownLatch(1);
- final CountDownLatch firstExitLatch = new CountDownLatch(1);
-
- testThreadPool.submit(new Runnable() {
- @Override
- public void run() {
- firstRunLatch.countDown();
- try {
- firstExitLatch.await();
- } catch (InterruptedException ie) {
- throw new RuntimeException(ie);
- }
- }
- });
-
- assertTrue(firstRunLatch.await(1, TimeUnit.SECONDS));
-
- final CountDownLatch notificationLatch = new CountDownLatch(1);
- monitor.notifyWhenIdle(new Runnable() {
- @Override
- public void run() {
- notificationLatch.countDown();
- }
- });
-
- final CountDownLatch secondRunLatch = new CountDownLatch(1);
- final CountDownLatch secondExitLatch = new CountDownLatch(1);
- testThreadPool.submit(new Runnable() {
- @Override
- public void run() {
- secondRunLatch.countDown();
- try {
- secondExitLatch.await();
- } catch (InterruptedException ie) {
- throw new RuntimeException(ie);
- }
- }
- });
-
- assertFalse(notificationLatch.await(10, TimeUnit.MILLISECONDS));
- firstExitLatch.countDown();
- assertFalse(notificationLatch.await(500, TimeUnit.MILLISECONDS));
- secondExitLatch.countDown();
- assertTrue(notificationLatch.await(1, TimeUnit.SECONDS));
- assertTrue(monitor.isIdleNow());
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/DefaultFailureHandlerTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/DefaultFailureHandlerTest.java
deleted file mode 100644
index b84584c..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/DefaultFailureHandlerTest.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.base;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isRoot;
-import static com.google.common.base.Throwables.getStackTraceAsString;
-import static org.hamcrest.Matchers.not;
-
-import com.google.android.apps.common.testing.ui.espresso.AmbiguousViewMatcherException;
-import com.google.android.apps.common.testing.ui.espresso.NoMatchingViewException;
-import com.google.android.apps.common.testing.ui.espresso.ViewAssertion;
-import com.google.android.apps.common.testing.ui.testapp.MainActivity;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.view.View;
-
-import junit.framework.AssertionFailedError;
-
-import org.hamcrest.BaseMatcher;
-import org.hamcrest.Description;
-import org.hamcrest.Matcher;
-
-/**
- * Tests Espresso's default failure handling.
- */
-public class DefaultFailureHandlerTest extends ActivityInstrumentationTestCase2<MainActivity> {
-
- @SuppressWarnings("deprecation")
- public DefaultFailureHandlerTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", MainActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- getActivity();
- }
-
- public void testMismatchInCheck() {
- try {
- onView(isRoot()).check(matches(not(isDisplayed())));
- fail("Previous call expected to fail");
- } catch (AssertionFailedError e) {
- assertFailureStackContainsThisClass(e);
- }
- }
-
- public void testCustomAssertionError() {
- try {
- onView(isRoot()).check(new ViewAssertion() {
- @Override
- public void check(View view, NoMatchingViewException noViewFoundException) {
- assertFalse(true);
- }
- });
- fail("Previous call expected to fail");
- } catch (AssertionFailedError e) {
- assertFailureStackContainsThisClass(e);
- }
- }
-
- public void testNoMatchingViewException() {
- try {
- onView(withMatchesThatReturns(false)).check(matches(not(isDisplayed())));
- fail("Previous call expected to fail");
- } catch (NoMatchingViewException e) {
- assertFailureStackContainsThisClass(e);
- }
- }
-
- public void testAmbiguousViewMatcherException() {
- try {
- onView(withMatchesThatReturns(true)).check(matches(isDisplayed()));
- } catch (RuntimeException e) {
- assertTrue(e instanceof AmbiguousViewMatcherException);
- assertFailureStackContainsThisClass(e);
- }
- }
-
- private void assertFailureStackContainsThisClass(Throwable e) {
- assertTrue(getStackTraceAsString(e).contains(getClass().getSimpleName().toString()));
- }
-
- private static Matcher<View> withMatchesThatReturns(final boolean returnValue) {
- return new BaseMatcher<View>() {
- @Override
- public void describeTo(Description description) {
- description.appendText("matches=" + returnValue);
- }
-
- @Override
- public boolean matches(Object item) {
- return returnValue;
- }
- };
- }
-
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/EventInjectorTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/EventInjectorTest.java
deleted file mode 100644
index bbc367a..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/EventInjectorTest.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.base;
-
-import com.google.android.apps.common.testing.testrunner.ActivityLifecycleCallback;
-import com.google.android.apps.common.testing.testrunner.ActivityLifecycleMonitorRegistry;
-import com.google.android.apps.common.testing.testrunner.Stage;
-import com.google.android.apps.common.testing.ui.espresso.InjectEventSecurityException;
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SendActivity;
-
-import android.app.Activity;
-import android.os.Build;
-import android.os.SystemClock;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.util.Log;
-import android.view.KeyCharacterMap;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-import android.view.View;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Tests for {@link EventInjector}.
- */
-public class EventInjectorTest extends ActivityInstrumentationTestCase2<SendActivity> {
- private static final String TAG = EventInjectorTest.class.getSimpleName();
- private Activity sendActivity;
- private EventInjector injector;
- final AtomicBoolean injectEventWorked = new AtomicBoolean(false);
- final AtomicBoolean injectEventThrewSecurityException = new AtomicBoolean(false);
- final CountDownLatch latch = new CountDownLatch(1);
-
- @SuppressWarnings("deprecation")
- public EventInjectorTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", SendActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- if (Build.VERSION.SDK_INT > 15) {
- InputManagerEventInjectionStrategy strat = new InputManagerEventInjectionStrategy();
- strat.initialize();
- injector = new EventInjector(strat);
- } else {
- WindowManagerEventInjectionStrategy strat = new WindowManagerEventInjectionStrategy();
- strat.initialize();
- injector = new EventInjector(strat);
- }
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @LargeTest
- public void testInjectKeyEventUpWithNoDown() throws Exception {
- sendActivity = getActivity();
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- View view = sendActivity.findViewById(R.id.send_data_edit_text);
- assertTrue(view.requestFocus());
- latch.countDown();
- }
- });
-
- assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
- KeyCharacterMap keyCharacterMap = UiControllerImpl.getKeyCharacterMap();
- KeyEvent[] events = keyCharacterMap.getEvents("a".toCharArray());
- assertTrue(injector.injectKeyEvent(events[1]));
- }
-
- @LargeTest
- public void testInjectStaleKeyEvent() throws Exception {
- sendActivity = getActivity();
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- View view = sendActivity.findViewById(R.id.send_data_edit_text);
- assertTrue(view.requestFocus());
- latch.countDown();
- }
- });
-
- assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
- assertFalse("SecurityException exception was thrown.", injectEventThrewSecurityException.get());
-
- KeyCharacterMap keyCharacterMap = UiControllerImpl.getKeyCharacterMap();
- KeyEvent[] events = keyCharacterMap.getEvents("a".toCharArray());
- KeyEvent event = KeyEvent.changeTimeRepeat(events[0], 1, 0);
-
- // Stale event does not fail for API < 13.
- if (Build.VERSION.SDK_INT < 13) {
- assertTrue(injector.injectKeyEvent(event));
- } else {
- assertFalse(injector.injectKeyEvent(event));
- }
- }
-
- @LargeTest
- public void testInjectKeyEvent_securityException() {
- KeyCharacterMap keyCharacterMap = UiControllerImpl.getKeyCharacterMap();
- KeyEvent[] events = keyCharacterMap.getEvents("a".toCharArray());
- try {
- injector.injectKeyEvent(events[0]);
- fail("Should have thrown a security exception!");
- } catch (InjectEventSecurityException expected) { }
- }
-
- @LargeTest
- public void testInjectMotionEvent_securityException() throws Exception {
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- MotionEvent down = MotionEvent.obtain(SystemClock.uptimeMillis(),
- SystemClock.uptimeMillis(),
- MotionEvent.ACTION_DOWN,
- 0,
- 0,
- 0);
- try {
- injector.injectMotionEvent(down);
- } catch (InjectEventSecurityException expected) {
- injectEventThrewSecurityException.set(true);
- }
- latch.countDown();
- }
- });
-
- latch.await(10, TimeUnit.SECONDS);
- assertTrue(injectEventThrewSecurityException.get());
- }
-
- @LargeTest
- public void testInjectMotionEvent_upEventFailure() throws InterruptedException {
- final CountDownLatch activityStarted = new CountDownLatch(1);
- ActivityLifecycleCallback callback = new ActivityLifecycleCallback() {
- @Override
- public void onActivityLifecycleChanged(Activity activity, Stage stage) {
- if (Stage.RESUMED == stage && activity instanceof SendActivity) {
- activityStarted.countDown();
- }
- }
- };
- ActivityLifecycleMonitorRegistry
- .getInstance()
- .addLifecycleCallback(callback);
- try {
- getActivity();
- assertTrue(activityStarted.await(20, TimeUnit.SECONDS));
- final int[] xy = UiControllerImplIntegrationTest.getCoordinatesInMiddleOfSendButton(
- getActivity(), getInstrumentation());
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- MotionEvent up = MotionEvent.obtain(SystemClock.uptimeMillis(),
- SystemClock.uptimeMillis(),
- MotionEvent.ACTION_UP,
- xy[0],
- xy[1],
- 0);
-
- try {
- injectEventWorked.set(injector.injectMotionEvent(up));
- } catch (InjectEventSecurityException e) {
- Log.e(TAG, "injectEvent threw a SecurityException");
- }
- up.recycle();
- latch.countDown();
- }
- });
-
- latch.await(10, TimeUnit.SECONDS);
- assertFalse(injectEventWorked.get());
- } finally {
- ActivityLifecycleMonitorRegistry
- .getInstance()
- .removeLifecycleCallback(callback);
- }
-
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/IdlingResourceIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/IdlingResourceIntegrationTest.java
deleted file mode 100644
index 98633f7..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/IdlingResourceIntegrationTest.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.base;
-
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.pressBack;
-import static com.google.android.apps.common.testing.ui.espresso.Espresso.registerIdlingResources;
-import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
-import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.equalToIgnoringCase;
-import static org.hamcrest.Matchers.is;
-
-import com.google.android.apps.common.testing.ui.espresso.IdlingResource;
-import com.google.android.apps.common.testing.ui.testapp.SendActivity;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Integration test with IdlingResources.
- */
-@LargeTest
-public class IdlingResourceIntegrationTest extends ActivityInstrumentationTestCase2<SendActivity> {
-
- private ResettingIdlingResource r1;
- private ResettingIdlingResource r2;
-
- @SuppressWarnings("deprecation")
- public IdlingResourceIntegrationTest() {
- super("com.google.android.apps.common.testing.ui.testapp", SendActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- r1 = new ResettingIdlingResource("SlowResource", 6000);
- r2 = new ResettingIdlingResource("FastResource", 500);
- registerIdlingResources(r1, r2);
- getActivity();
- }
-
- public void testClickWithCustomIdlingResources() {
- onView(withText(equalToIgnoringCase("send"))).perform(click());
- r1.reset();
- r2.reset();
- onView(withText(is("Data from sender"))).check(matches(isDisplayed()));
- r1.reset();
- r2.reset();
- pressBack();
- r1.reset();
- r2.reset();
- onView(withText(equalToIgnoringCase("send"))).perform(click());
- r1.reset();
- r2.reset();
- pressBack();
- r1.reset();
- r2.reset();
- onView(withText(equalToIgnoringCase("send"))).perform(click());
- }
-
- private class ResettingIdlingResource implements IdlingResource {
- private final String name;
- private final long delay;
- private final AtomicBoolean isIdle = new AtomicBoolean(false);
- private final ScheduledExecutorService pool;
-
- private ResourceCallback callback;
-
- public ResettingIdlingResource(String name, long delay) {
- this.name = name;
- this.delay = delay;
- this.pool = Executors.newScheduledThreadPool(1);
- }
-
- @Override
- public void registerIdleTransitionCallback(final ResourceCallback callback) {
- this.callback = callback;
- scheduleDelayedCallback();
- }
-
- private void scheduleDelayedCallback() {
- pool.schedule(new Runnable() {
- @Override
- public void run() {
- callback.onTransitionToIdle();
- isIdle.set(true);
- }
- }, delay, TimeUnit.MILLISECONDS);
- }
-
- @Override
- public boolean isIdleNow() {
- return isIdle.get();
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- public void reset() {
- isIdle.set(false);
- scheduleDelayedCallback();
- }
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/IdlingResourceRegistryTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/IdlingResourceRegistryTest.java
deleted file mode 100644
index aee49a8..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/IdlingResourceRegistryTest.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.base;
-
-import com.google.android.apps.common.testing.ui.espresso.IdlingResource;
-import com.google.android.apps.common.testing.ui.espresso.base.IdlingResourceRegistry.IdleNotificationCallback;
-
-import android.os.Handler;
-import android.os.Looper;
-import android.test.InstrumentationTestCase;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.util.Log;
-
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * Unit tests for {@link IdlingResourceRegistry}.
- */
-public class IdlingResourceRegistryTest extends InstrumentationTestCase {
-
- private IdlingResourceRegistry registry;
- private Handler handler;
-
- @Override
- public void setUp() throws Exception {
- Looper looper = Looper.getMainLooper();
- handler = new Handler(looper);
- registry = new IdlingResourceRegistry(looper);
- }
-
- public void testRegisterDuplicates() {
- IdlingResource r1 = new OnDemandIdlingResource("r1");
- IdlingResource r1dup = new OnDemandIdlingResource("r1");
- registry.register(r1);
- registry.register(r1);
- registry.register(r1dup);
- }
-
- public void testAllResourcesAreIdle() throws InterruptedException {
- OnDemandIdlingResource r1 = new OnDemandIdlingResource("r1");
- OnDemandIdlingResource r2 = new OnDemandIdlingResource("r2");
- IdlingResource r3 = new OnDemandIdlingResource("r3");
- r1.forceIdleNow();
- r2.forceIdleNow();
- registry.register(r1);
- registry.register(r2);
- final AtomicBoolean resourcesIdle = new AtomicBoolean(false);
- final CountDownLatch latch = new CountDownLatch(1);
- handler.post(new Runnable() {
- @Override
- public void run() {
- resourcesIdle.set(registry.allResourcesAreIdle());
- latch.countDown();
- }
- });
- latch.await();
- assertTrue(resourcesIdle.get());
-
- final CountDownLatch latch2 = new CountDownLatch(1);
- registry.register(r3);
- handler.post(new Runnable() {
- @Override
- public void run() {
- resourcesIdle.set(registry.allResourcesAreIdle());
- latch2.countDown();
- }
- });
- latch2.await();
- assertFalse(resourcesIdle.get());
- }
-
- @LargeTest
- public void testAllResourcesAreIdle_RepeatingToIdleTransitions() throws InterruptedException {
- OnDemandIdlingResource r1 = new OnDemandIdlingResource("r1");
- registry.register(r1);
- final AtomicBoolean resourcesIdle = new AtomicBoolean(false);
- for (int i = 1; i <= 3; i++) {
- final CountDownLatch latch = new CountDownLatch(1);
- handler.post(new Runnable() {
- @Override
- public void run() {
- resourcesIdle.set(registry.allResourcesAreIdle());
- latch.countDown();
- }
- });
- latch.await();
- assertFalse("Busy test " + i, resourcesIdle.get());
-
- r1.forceIdleNow();
- final CountDownLatch latch2 = new CountDownLatch(1);
- handler.post(new Runnable() {
- @Override
- public void run() {
- resourcesIdle.set(registry.allResourcesAreIdle());
- latch2.countDown();
- }
- });
- latch2.await();
- assertTrue("Idle transition test " + i, resourcesIdle.get());
-
- r1.reset();
- }
- }
-
- @LargeTest
- public void testNotifyWhenAllResourcesAreIdle_success() throws InterruptedException {
- final CountDownLatch busyWarningLatch = new CountDownLatch(4);
- final CountDownLatch timeoutLatch = new CountDownLatch(1);
- final CountDownLatch allResourcesIdleLatch = new CountDownLatch(1);
- final AtomicReference<List<String>> busysFromWarning = new AtomicReference<List<String>>();
-
- OnDemandIdlingResource r1 = new OnDemandIdlingResource("r1");
- OnDemandIdlingResource r2 = new OnDemandIdlingResource("r2");
- OnDemandIdlingResource r3 = new OnDemandIdlingResource("r3");
- registry.register(r1);
- registry.register(r2);
- registry.register(r3);
-
- handler.post(new Runnable() {
-
- @Override
- public void run() {
- registry.notifyWhenAllResourcesAreIdle(new IdleNotificationCallback() {
- private static final String TAG = "IdleNotificationCallback";
- @Override
- public void resourcesStillBusyWarning(List<String> busyResourceNames) {
- Log.w(TAG, "Timeout warning: " + busyResourceNames);
- busysFromWarning.set(busyResourceNames);
- busyWarningLatch.countDown();
- }
-
- @Override
- public void resourcesHaveTimedOut(List<String> busyResourceNames) {
- Log.w(TAG, "Timeout error: " + busyResourceNames);
- timeoutLatch.countDown();
- }
-
- @Override
- public void allResourcesIdle() {
- allResourcesIdleLatch.countDown();
- }
- });
- }
- });
-
- assertFalse("Expected to timeout", busyWarningLatch.await(6, TimeUnit.SECONDS));
- assertEquals(3, busysFromWarning.get().size());
-
- r3.forceIdleNow();
- assertFalse("Expected to timeout", busyWarningLatch.await(6, TimeUnit.SECONDS));
- assertEquals(2, busysFromWarning.get().size());
-
- r2.forceIdleNow();
- assertFalse("Expected to timeout", busyWarningLatch.await(6, TimeUnit.SECONDS));
- assertEquals(1, busysFromWarning.get().size());
-
- r1.forceIdleNow();
- assertTrue(allResourcesIdleLatch.await(200, TimeUnit.MILLISECONDS));
- assertEquals(1, busyWarningLatch.getCount());
- assertEquals(1, timeoutLatch.getCount());
- }
-
- @LargeTest
- public void testNotifyWhenAllResourcesAreIdle_timeout() throws InterruptedException {
- final CountDownLatch busyWarningLatch = new CountDownLatch(5);
- final CountDownLatch timeoutLatch = new CountDownLatch(1);
- final CountDownLatch allResourcesIdleLatch = new CountDownLatch(1);
- final AtomicReference<List<String>> busysFromWarning = new AtomicReference<List<String>>();
-
- OnDemandIdlingResource r1 = new OnDemandIdlingResource("r1");
- OnDemandIdlingResource r2 = new OnDemandIdlingResource("r2");
- OnDemandIdlingResource r3 = new OnDemandIdlingResource("r3");
- registry.register(r1);
- registry.register(r2);
- registry.register(r3);
-
- handler.post(new Runnable() {
- @Override
- public void run() {
- registry.notifyWhenAllResourcesAreIdle(new IdleNotificationCallback() {
- private static final String TAG = "IdleNotificationCallback";
- @Override
- public void resourcesStillBusyWarning(List<String> busyResourceNames) {
- Log.w(TAG, "Timeout warning: " + busyResourceNames);
- busysFromWarning.set(busyResourceNames);
- busyWarningLatch.countDown();
- }
-
- @Override
- public void resourcesHaveTimedOut(List<String> busyResourceNames) {
- Log.w(TAG, "Timeout error: " + busyResourceNames);
- timeoutLatch.countDown();
- }
-
- @Override
- public void allResourcesIdle() {
- allResourcesIdleLatch.countDown();
- }
- });
- }
- });
-
- assertFalse("Expected to timeout", busyWarningLatch.await(6, TimeUnit.SECONDS));
- assertEquals(3, busysFromWarning.get().size());
-
- r1.forceIdleNow();
- assertFalse("Expected to timeout", busyWarningLatch.await(6, TimeUnit.SECONDS));
- assertEquals(2, busysFromWarning.get().size());
-
- r2.forceIdleNow();
- assertFalse("Expected to timeout", busyWarningLatch.await(6, TimeUnit.SECONDS));
- assertEquals(1, busysFromWarning.get().size());
-
- assertTrue("Expected to finish count down", busyWarningLatch.await(8, TimeUnit.SECONDS));
- assertTrue("Should have timed out", timeoutLatch.await(2, TimeUnit.SECONDS));
- assertEquals(1, busysFromWarning.get().size());
- assertEquals(1, allResourcesIdleLatch.getCount());
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/OnDemandIdlingResource.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/OnDemandIdlingResource.java
deleted file mode 100644
index ac0a5a7..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/OnDemandIdlingResource.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.base;
-
-import com.google.android.apps.common.testing.ui.espresso.IdlingResource;
-
-/**
- * An {@link IdlingResource} for testing that becomes idle on demand.
- */
-public class OnDemandIdlingResource implements IdlingResource {
- private final String name;
-
- private boolean isIdle = false;
- private ResourceCallback callback;
-
- public OnDemandIdlingResource(String name) {
- this.name = name;
- }
-
- @Override
- public void registerIdleTransitionCallback(ResourceCallback callback) {
- this.callback = callback;
- }
-
- @Override
- public boolean isIdleNow() {
- return isIdle;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- public void forceIdleNow() {
- isIdle = true;
- if (callback != null) {
- callback.onTransitionToIdle();
- }
- }
-
- public void reset() {
- isIdle = false;
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/UiControllerImplIntegrationTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/UiControllerImplIntegrationTest.java
deleted file mode 100644
index 02a3fda..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/UiControllerImplIntegrationTest.java
+++ /dev/null
@@ -1,295 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.base;
-
-import com.google.android.apps.common.testing.ui.espresso.InjectEventSecurityException;
-import com.google.android.apps.common.testing.ui.espresso.UiController;
-import com.google.android.apps.common.testing.ui.espresso.util.HumanReadables;
-import com.google.android.apps.common.testing.ui.testapp.R;
-import com.google.android.apps.common.testing.ui.testapp.SendActivity;
-import com.google.common.base.Optional;
-
-import android.app.Activity;
-import android.app.Instrumentation;
-import android.os.Build;
-import android.os.Looper;
-import android.os.SystemClock;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.util.Log;
-import android.view.KeyCharacterMap;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-import android.view.View;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Test for {@link UiControllerImpl}.
- */
-public class UiControllerImplIntegrationTest
- extends ActivityInstrumentationTestCase2<SendActivity> {
- private Activity sendActivity;
- private final AtomicBoolean injectEventWorked = new AtomicBoolean(false);
- private final AtomicBoolean injectEventThrewSecurityException = new AtomicBoolean(false);
- private final CountDownLatch focusLatch = new CountDownLatch(1);
- private final CountDownLatch latch = new CountDownLatch(1);
- private UiController uiController;
-
- @SuppressWarnings("deprecation")
- public UiControllerImplIntegrationTest() {
- // Supporting froyo.
- super("com.google.android.apps.common.testing.ui.testapp", SendActivity.class);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- EventInjector injector = null;
- if (Build.VERSION.SDK_INT > 15) {
- InputManagerEventInjectionStrategy strat = new InputManagerEventInjectionStrategy();
- strat.initialize();
- injector = new EventInjector(strat);
- } else {
- WindowManagerEventInjectionStrategy strat = new WindowManagerEventInjectionStrategy();
- strat.initialize();
- injector = new EventInjector(strat);
- }
- uiController = new UiControllerImpl(
- injector,
- new AsyncTaskPoolMonitor(new ThreadPoolExecutorExtractor(
- Looper.getMainLooper()).getAsyncTaskThreadPool()),
- Optional.<AsyncTaskPoolMonitor>absent(),
- new IdlingResourceRegistry(Looper.getMainLooper()),
- Looper.getMainLooper());
- }
-
-
- @Override
- public SendActivity getActivity() {
- SendActivity a = super.getActivity();
-
- while (!a.hasWindowFocus()) {
- getInstrumentation().waitForIdleSync();
- }
-
- return a;
- }
-
- @LargeTest
- public void testInjectKeyEvent() throws InterruptedException {
- sendActivity = getActivity();
- getInstrumentation().waitForIdleSync();
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- try {
- KeyCharacterMap keyCharacterMap = UiControllerImpl.getKeyCharacterMap();
- KeyEvent[] events = keyCharacterMap.getEvents("a".toCharArray());
- injectEventWorked.set(uiController.injectKeyEvent(events[0]));
- latch.countDown();
- } catch (InjectEventSecurityException e) {
- injectEventThrewSecurityException.set(true);
- }
- }
- });
-
- assertFalse("injectEvent threw a SecurityException", injectEventThrewSecurityException.get());
- assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
- assertTrue(injectEventWorked.get());
- }
-
- @LargeTest
- public void testInjectString() throws InterruptedException {
- sendActivity = getActivity();
- getInstrumentation().waitForIdleSync();
- final AtomicBoolean requestFocusSucceded = new AtomicBoolean(false);
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- final View view = sendActivity.findViewById(R.id.send_data_to_call_edit_text);
- Log.i("TEST", HumanReadables.describe(view));
- requestFocusSucceded.set(view.requestFocus() && view.hasWindowFocus());
- Log.i("TEST-post", HumanReadables.describe(view));
- focusLatch.countDown();
- }
- });
-
- getInstrumentation().waitForIdleSync();
- assertTrue("requestFocus timed out!", focusLatch.await(2, TimeUnit.SECONDS));
- assertTrue("requestFocus failed.", requestFocusSucceded.get());
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- try {
- injectEventWorked.set(uiController.injectString("Hello! \n&*$$$"));
- latch.countDown();
- } catch (InjectEventSecurityException e) {
- injectEventThrewSecurityException.set(true);
- }
- }
- });
-
- assertFalse("SecurityException exception was thrown.", injectEventThrewSecurityException.get());
- assertTrue("Timed out!", latch.await(20, TimeUnit.SECONDS));
- assertTrue(injectEventWorked.get());
- }
-
- @LargeTest
- public void testInjectLargeString() throws InterruptedException {
- sendActivity = getActivity();
- getInstrumentation().waitForIdleSync();
- final AtomicBoolean requestFocusSucceded = new AtomicBoolean(false);
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- final View view = sendActivity.findViewById(R.id.send_data_to_call_edit_text);
- Log.i("TEST", HumanReadables.describe(view));
- requestFocusSucceded.set(view.requestFocus());
- Log.i("TEST-post", HumanReadables.describe(view));
-
- focusLatch.countDown();
- }
- });
-
- assertTrue("requestFocus timed out!", focusLatch.await(2, TimeUnit.SECONDS));
- assertTrue("requestFocus failed.", requestFocusSucceded.get());
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- try {
- injectEventWorked.set(uiController.injectString("This is a string with 32 chars!!"));
- latch.countDown();
- } catch (InjectEventSecurityException e) {
- injectEventThrewSecurityException.set(true);
- }
- }
- });
-
- assertFalse("SecurityException exception was thrown.", injectEventThrewSecurityException.get());
- assertTrue("Timed out!", latch.await(20, TimeUnit.SECONDS));
- assertTrue(injectEventWorked.get());
- }
-
- @LargeTest
- public void testInjectEmptyString() throws InterruptedException {
- sendActivity = getActivity();
- getInstrumentation().waitForIdleSync();
- final AtomicBoolean requestFocusSucceded = new AtomicBoolean(false);
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- final View view = sendActivity.findViewById(R.id.send_data_to_call_edit_text);
- requestFocusSucceded.set(view.requestFocus());
- focusLatch.countDown();
- }
- });
-
- assertTrue("requestFocus timed out!", focusLatch.await(2, TimeUnit.SECONDS));
- assertTrue("requestFocus failed.", requestFocusSucceded.get());
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- try {
- injectEventWorked.set(uiController.injectString(""));
- latch.countDown();
- } catch (InjectEventSecurityException e) {
- injectEventThrewSecurityException.set(true);
- }
- }
- });
-
- assertFalse("SecurityException exception was thrown.", injectEventThrewSecurityException.get());
- assertTrue("Timed out!", latch.await(20, TimeUnit.SECONDS));
- assertTrue(injectEventWorked.get());
- }
-
- @LargeTest
- public void testInjectStringSecurityException() throws InterruptedException {
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- try {
- injectEventWorked.set(uiController.injectString("Hello! \n&*$$$"));
- latch.countDown();
- } catch (InjectEventSecurityException e) {
- injectEventThrewSecurityException.set(true);
- }
- }
- });
-
- assertTrue("SecurityException exception was thrown.", injectEventThrewSecurityException.get());
- assertFalse("Did NOT time out!", latch.await(3, TimeUnit.SECONDS));
- assertFalse(injectEventWorked.get());
- }
-
- @LargeTest
- public void testInjectMotionEvent() throws InterruptedException {
- sendActivity = getActivity();
- final int xy[] = getCoordinatesInMiddleOfSendButton(sendActivity, getInstrumentation());
-
- getInstrumentation().runOnMainSync(new Runnable() {
- @Override
- public void run() {
- long downTime = SystemClock.uptimeMillis();
- try {
- MotionEvent event = MotionEvent.obtain(downTime,
- SystemClock.uptimeMillis(),
- MotionEvent.ACTION_DOWN,
- xy[0],
- xy[1],
- 0);
-
- injectEventWorked.set(uiController.injectMotionEvent(event));
- event.recycle();
- latch.countDown();
- } catch (InjectEventSecurityException e) {
- injectEventThrewSecurityException.set(true);
- }
- }
- });
-
- assertFalse("SecurityException exception was thrown.", injectEventThrewSecurityException.get());
- assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
- assertTrue(injectEventWorked.get());
- }
-
- static int[] getCoordinatesInMiddleOfSendButton(
- Activity activity, Instrumentation instrumentation) {
- final View sendButton = activity.findViewById(R.id.send_button);
- final int[] xy = new int[2];
- instrumentation.runOnMainSync(new Runnable() {
- @Override
- public void run() {
- sendButton.getLocationOnScreen(xy);
- }
- });
- int x = xy[0] + (sendButton.getWidth() / 2);
- int y = xy[1] + (sendButton.getHeight() / 2);
- int[] xyMiddle = {x, y};
- return xyMiddle;
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/UiControllerImplTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/UiControllerImplTest.java
deleted file mode 100644
index 2b95fc8..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/UiControllerImplTest.java
+++ /dev/null
@@ -1,390 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.base;
-
-import com.google.android.apps.common.testing.ui.espresso.IdlingResourceTimeoutException;
-import com.google.common.base.Optional;
-
-import android.os.Build;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.util.Log;
-
-import junit.framework.TestCase;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * Unit test for {@link UiControllerImpl}.
- */
-public class UiControllerImplTest extends TestCase {
-
- private static final String TAG = UiControllerImplTest.class.getSimpleName();
-
- private LooperThread testThread;
- private AtomicReference<UiControllerImpl> uiController = new AtomicReference<UiControllerImpl>();
- private ThreadPoolExecutor asyncPool;
- private IdlingResourceRegistry idlingResourceRegistry;
-
- private static class LooperThread extends Thread {
- private final CountDownLatch init = new CountDownLatch(1);
- private Handler handler;
- private Looper looper;
-
- @Override
- public void run() {
- Looper.prepare();
- handler = new Handler();
- looper = Looper.myLooper();
- init.countDown();
- Looper.loop();
- }
-
- public void quitLooper() {
- looper.quit();
- }
-
- public Looper getLooper() {
- try {
- init.await();
- } catch (InterruptedException ie) {
- Thread.currentThread().interrupt();
- }
- return looper;
- }
-
- public Handler getHandler() {
- try {
- init.await();
- } catch (InterruptedException ie) {
- Thread.currentThread().interrupt();
- }
- return handler;
- }
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- testThread = new LooperThread();
- testThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
- @Override
- public void uncaughtException(Thread thread, Throwable ex) {
- Log.e(TAG, "Looper died: ", ex);
- }
- });
- testThread.start();
- idlingResourceRegistry = new IdlingResourceRegistry(testThread.getLooper());
- asyncPool = new ThreadPoolExecutor(3, 3, 1, TimeUnit.SECONDS,
- new LinkedBlockingQueue<Runnable>());
- EventInjector injector = null;
- if (Build.VERSION.SDK_INT > 15) {
- InputManagerEventInjectionStrategy strat = new InputManagerEventInjectionStrategy();
- strat.initialize();
- injector = new EventInjector(strat);
- } else {
- WindowManagerEventInjectionStrategy strat = new WindowManagerEventInjectionStrategy();
- strat.initialize();
- injector = new EventInjector(strat);
- }
- uiController.set(new UiControllerImpl(
- injector,
- new AsyncTaskPoolMonitor(asyncPool),
- Optional.<AsyncTaskPoolMonitor>absent(),
- idlingResourceRegistry,
- testThread.getLooper()
- ));
-
-
- }
-
- @Override
- public void tearDown() throws Exception {
- testThread.quitLooper();
- asyncPool.shutdown();
- super.tearDown();
- }
-
- public void testLoopMainThreadTillIdle_sendsMessageToRightHandler() {
- final CountDownLatch latch = new CountDownLatch(3);
- testThread.getHandler(); // blocks till initialized;
- final Handler firstHandler = new Handler(
- testThread.looper,
- new Handler.Callback() {
- private boolean counted = false;
- @Override
- public boolean handleMessage(Message me) {
- if (counted) {
- fail("Called 2x!!!!");
- }
- counted = true;
- latch.countDown();
- return true;
- }
- });
-
- final Handler secondHandler = new Handler(
- testThread.looper,
- new Handler.Callback() {
- private boolean counted = false;
- @Override
- public boolean handleMessage(Message me) {
- if (counted) {
- fail("Called 2x!!!!");
- }
- counted = true;
- latch.countDown();
- return true;
- }
- });
-
- assertTrue(testThread.getHandler().post(new Runnable() {
- @Override
- public void run() {
- firstHandler.sendEmptyMessage(1);
- secondHandler.sendEmptyMessage(1);
- uiController.get().loopMainThreadUntilIdle();
-
- latch.countDown();
- }
- }));
-
- try {
- assertTrue(
- "Timed out waiting for looper to process all events", latch.await(10, TimeUnit.SECONDS));
- } catch (InterruptedException e) {
- fail("Failed with exception " + e);
- }
- }
-
- public void testLoopForAtLeast() throws Exception {
- final CountDownLatch latch = new CountDownLatch(2);
- assertTrue(testThread.getHandler().post(new Runnable() {
- @Override
- public void run() {
- testThread.getHandler().post(new Runnable() {
- @Override
- public void run() {
- latch.countDown();
- }
-
- });
- uiController.get().loopMainThreadForAtLeast(1000);
- latch.countDown();
- }
- }));
- assertTrue("Never returned from UiControllerImpl.loopMainThreadForAtLeast();",
- latch.await(10, TimeUnit.SECONDS));
- }
-
- public void testLoopMainThreadUntilIdle_fullQueue() {
- final CountDownLatch latch = new CountDownLatch(3);
- assertTrue(testThread.getHandler().post(new Runnable() {
- @Override
- public void run() {
- Log.i(TAG, "On main thread");
- Handler handler = new Handler();
- Log.i(TAG, "Equeueing test runnable 1");
- handler.post(new Runnable() {
- @Override
- public void run() {
- Log.i(TAG, "Running test runnable 1");
- latch.countDown();
- }
- });
- Log.i(TAG, "Equeueing test runnable 2");
- handler.post(new Runnable() {
- @Override
- public void run() {
- Log.i(TAG, "Running test runnable 2");
- latch.countDown();
- }
- });
- Log.i(TAG, "Hijacking thread and looping it.");
- uiController.get().loopMainThreadUntilIdle();
- latch.countDown();
- }
- }));
-
- try {
- assertTrue(
- "Timed out waiting for looper to process all events", latch.await(10, TimeUnit.SECONDS));
- } catch (InterruptedException e) {
- fail("Failed with exception " + e);
- }
- }
-
- public void testLoopMainThreadUntilIdle_fullQueueAndAsyncTasks() throws Exception {
- final CountDownLatch latch = new CountDownLatch(3);
- final CountDownLatch asyncTaskStarted = new CountDownLatch(1);
- final CountDownLatch asyncTaskShouldComplete = new CountDownLatch(1);
- asyncPool.execute(new Runnable() {
- @Override
- public void run() {
- asyncTaskStarted.countDown();
- while (true) {
- try {
- asyncTaskShouldComplete.await();
- return;
- } catch (InterruptedException ie) {
- // cant interrupt me. ignore.
- }
- }
- }
- });
- assertTrue("async task is not starting!", asyncTaskStarted.await(2, TimeUnit.SECONDS));
-
- assertTrue(testThread.getHandler().post(new Runnable() {
- @Override
- public void run() {
- Log.i(TAG, "On main thread");
- Handler handler = new Handler();
- Log.i(TAG, "Equeueing test runnable 1");
- handler.post(new Runnable() {
- @Override
- public void run() {
- Log.i(TAG, "Running test runnable 1");
- latch.countDown();
- }
- });
- Log.i(TAG, "Equeueing test runnable 2");
- handler.post(new Runnable() {
- @Override
- public void run() {
- Log.i(TAG, "Running test runnable 2");
- latch.countDown();
- }
- });
- Log.i(TAG, "Hijacking thread and looping it.");
- uiController.get().loopMainThreadUntilIdle();
- latch.countDown();
- }
- }));
- assertFalse(
- "Should not have stopped looping the main thread yet!", latch.await(2, TimeUnit.SECONDS));
- assertEquals("Not all main thread tasks have checked in", 1L, latch.getCount());
- asyncTaskShouldComplete.countDown();
- assertTrue("App should be idle.", latch.await(5, TimeUnit.SECONDS));
- }
-
-
- public void testLoopMainThreadUntilIdle_emptyQueue() {
- final CountDownLatch latch = new CountDownLatch(1);
- assertTrue(testThread.getHandler().post(new Runnable() {
- @Override
- public void run() {
- uiController.get().loopMainThreadUntilIdle();
- latch.countDown();
- }
- }));
- try {
- assertTrue("Never returned from UiControllerImpl.loopMainThreadUntilIdle();",
- latch.await(10, TimeUnit.SECONDS));
- } catch (InterruptedException e) {
- fail("Failed with exception " + e);
- }
- }
-
- public void testLoopMainThreadUntilIdle_oneIdlingResource() throws InterruptedException {
- OnDemandIdlingResource fakeResource = new OnDemandIdlingResource("FakeResource");
- idlingResourceRegistry.register(fakeResource);
- final CountDownLatch latch = new CountDownLatch(1);
- assertTrue(testThread.getHandler().post(new Runnable() {
- @Override
- public void run() {
- Log.i(TAG, "Hijacking thread and looping it.");
- uiController.get().loopMainThreadUntilIdle();
- latch.countDown();
- }
- }));
- assertFalse(
- "Should not have stopped looping the main thread yet!", latch.await(2, TimeUnit.SECONDS));
- fakeResource.forceIdleNow();
- assertTrue("App should be idle.", latch.await(5, TimeUnit.SECONDS));
- }
-
- public void testLoopMainThreadUntilIdle_multipleIdlingResources() throws InterruptedException {
- OnDemandIdlingResource fakeResource1 = new OnDemandIdlingResource("FakeResource1");
- OnDemandIdlingResource fakeResource2 = new OnDemandIdlingResource("FakeResource2");
- OnDemandIdlingResource fakeResource3 = new OnDemandIdlingResource("FakeResource3");
- // Register the first two right away and one later (once the wait for the first two begins).
- idlingResourceRegistry.register(fakeResource1);
- idlingResourceRegistry.register(fakeResource2);
- final CountDownLatch latch = new CountDownLatch(1);
- assertTrue(testThread.getHandler().post(new Runnable() {
- @Override
- public void run() {
- Log.i(TAG, "Hijacking thread and looping it.");
- uiController.get().loopMainThreadUntilIdle();
- latch.countDown();
- }
- }));
- assertFalse(
- "Should not have stopped looping the main thread yet!", latch.await(1, TimeUnit.SECONDS));
- fakeResource1.forceIdleNow();
- assertFalse(
- "Should not have stopped looping the main thread yet!", latch.await(1, TimeUnit.SECONDS));
- idlingResourceRegistry.register(fakeResource3);
- assertFalse(
- "Should not have stopped looping the main thread yet!", latch.await(1, TimeUnit.SECONDS));
- fakeResource2.forceIdleNow();
- assertFalse(
- "Should not have stopped looping the main thread yet!", latch.await(1, TimeUnit.SECONDS));
- fakeResource3.forceIdleNow();
- assertTrue("App should be idle.", latch.await(5, TimeUnit.SECONDS));
- }
-
- @LargeTest
- public void testLoopMainThreadUntilIdle_timeout() throws InterruptedException {
- OnDemandIdlingResource goodResource =
- new OnDemandIdlingResource("GoodResource");
- OnDemandIdlingResource kindaCrappyResource =
- new OnDemandIdlingResource("KindaCrappyResource");
- OnDemandIdlingResource badResource =
- new OnDemandIdlingResource("VeryBadResource");
- idlingResourceRegistry.register(goodResource);
- idlingResourceRegistry.register(kindaCrappyResource);
- idlingResourceRegistry.register(badResource);
- final CountDownLatch latch = new CountDownLatch(1);
- assertTrue(testThread.getHandler().post(new Runnable() {
- @Override
- public void run() {
- Log.i(TAG, "Hijacking thread and looping it.");
- try {
- uiController.get().loopMainThreadUntilIdle();
- } catch (IdlingResourceTimeoutException e) {
- latch.countDown();
- }
- }
- }));
- assertFalse(
- "Should not have stopped looping the main thread yet!", latch.await(4, TimeUnit.SECONDS));
- goodResource.forceIdleNow();
- assertFalse(
- "Should not have stopped looping the main thread yet!", latch.await(12, TimeUnit.SECONDS));
- kindaCrappyResource.forceIdleNow();
- assertTrue(
- "Should have caught IdlingResourceTimeoutException", latch.await(11, TimeUnit.SECONDS));
- }
-
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/ViewFinderImplTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/ViewFinderImplTest.java
deleted file mode 100644
index 7810a83..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/base/ViewFinderImplTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.base;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.sameInstance;
-
-import com.google.android.apps.common.testing.ui.espresso.AmbiguousViewMatcherException;
-import com.google.android.apps.common.testing.ui.espresso.NoMatchingViewException;
-import com.google.android.apps.common.testing.ui.espresso.ViewFinder;
-
-import android.test.InstrumentationTestCase;
-import android.test.UiThreadTest;
-import android.view.View;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-
-import org.hamcrest.Matchers;
-
-import javax.inject.Provider;
-
-/** Unit tests for {@link ViewFinderImpl}. */
-public class ViewFinderImplTest extends InstrumentationTestCase {
- private Provider<View> testViewProvider;
- private RelativeLayout testView;
- private View child1;
- private View child2;
- private View child3;
- private View child4;
- private View nestedChild;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- testView = new RelativeLayout(getInstrumentation().getTargetContext());
- child1 = new TextView(getInstrumentation().getTargetContext());
- child1.setId(1);
- child2 = new TextView(getInstrumentation().getTargetContext());
- child2.setId(2);
- child3 = new TextView(getInstrumentation().getTargetContext());
- child3.setId(3);
- child4 = new TextView(getInstrumentation().getTargetContext());
- child4.setId(4);
- nestedChild = new TextView(getInstrumentation().getTargetContext());
- nestedChild.setId(5);
- RelativeLayout nestingLayout = new RelativeLayout(getInstrumentation().getTargetContext());
- nestingLayout.addView(nestedChild);
- testView.addView(child1);
- testView.addView(child2);
- testView.addView(nestingLayout);
- testView.addView(child3);
- testView.addView(child4);
- testViewProvider = new Provider<View>() {
- @Override
- public View get() {
- return testView;
- }
-
- @Override
- public String toString() {
- return "of(" + testView + ")";
- }
- };
- }
-
- @UiThreadTest
- public void testGetView_present() {
- ViewFinder finder = new ViewFinderImpl(sameInstance(nestedChild), testViewProvider);
- assertThat(finder.getView(), sameInstance(nestedChild));
- }
-
- @UiThreadTest
- public void testGetView_missing() {
- ViewFinder finder = new ViewFinderImpl(Matchers.<View>nullValue(), testViewProvider);
- try {
- finder.getView();
- fail("No children should pass that matcher!");
- } catch (NoMatchingViewException expected) {}
- }
-
- @UiThreadTest
- public void testGetView_multiple() {
- ViewFinder finder = new ViewFinderImpl(Matchers.<View>notNullValue(), testViewProvider);
- try {
- finder.getView();
- fail("All nodes hit that matcher!");
- } catch (AmbiguousViewMatcherException expected) {}
- }
-
- public void testFind_offUiThread() {
- ViewFinder finder = new ViewFinderImpl(sameInstance(nestedChild), testViewProvider);
- try {
- finder.getView();
- fail("not on main thread, should die.");
- } catch (IllegalStateException expected) {}
- }
-
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/contrib/CountingIdlingResourceTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/contrib/CountingIdlingResourceTest.java
deleted file mode 100644
index 8bd2d11..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/contrib/CountingIdlingResourceTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.contrib;
-
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-import com.google.android.apps.common.testing.ui.espresso.IdlingResource.ResourceCallback;
-
-import android.test.InstrumentationTestCase;
-
-import org.mockito.Mock;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.FutureTask;
-
-/** Unit tests for {@link CountingIdlingResource}. */
-public class CountingIdlingResourceTest extends InstrumentationTestCase {
-
- private static final String RESOURCE_NAME = "test_resource";
- private CountingIdlingResource resource;
-
- @Mock
- private ResourceCallback mockCallback;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- initMocks(this);
- resource = new CountingIdlingResource(RESOURCE_NAME, true);
- }
-
- public void testResourceName() {
- assertEquals(RESOURCE_NAME, resource.getName());
- }
-
- public void testInvalidStateDetected() throws Exception {
- resource.increment();
- resource.decrement();
- try {
- resource.decrement();
- fail("Should throw illegal state exception!");
- } catch (IllegalStateException expected) { }
- }
-
- public void testIsIdle() throws Exception {
- assertTrue(callIsIdle());
- resource.increment();
- assertFalse(callIsIdle());
- resource.decrement();
- assertTrue(callIsIdle());
- }
-
- public void testIdleNotification() throws Exception {
- registerIdleCallback();
- assertTrue(callIsIdle());
- verify(mockCallback, never()).onTransitionToIdle();
-
- resource.increment();
- verify(mockCallback, never()).onTransitionToIdle();
- assertFalse(callIsIdle());
-
- resource.decrement();
- verify(mockCallback).onTransitionToIdle();
- assertTrue(callIsIdle());
- }
-
- private void registerIdleCallback() throws Exception {
- FutureTask<Void> registerTask = new FutureTask<Void>(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- resource.registerIdleTransitionCallback(mockCallback);
- return null;
- }
-
- });
- getInstrumentation().runOnMainSync(registerTask);
- try {
- registerTask.get();
- } catch (ExecutionException ee) {
- throw new RuntimeException(ee.getCause());
- }
-
- }
-
- private boolean callIsIdle() throws Exception {
- FutureTask<Boolean> isIdleTask = new FutureTask<Boolean>(new IsIdleCallable());
- getInstrumentation().runOnMainSync(isIdleTask);
- try {
- return isIdleTask.get();
- } catch (ExecutionException ee) {
- throw new RuntimeException(ee.getCause());
- }
- }
-
-
- private class IsIdleCallable implements Callable<Boolean> {
- @Override
- public Boolean call() throws Exception {
- return resource.isIdleNow();
- }
- }
-
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/matcher/PreferenceMatchersTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/matcher/PreferenceMatchersTest.java
deleted file mode 100644
index 1501184..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/matcher/PreferenceMatchersTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.matcher;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-
-
-import static com.google.android.apps.common.testing.ui.espresso.matcher.PreferenceMatchers.withKey;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.PreferenceMatchers.withSummary;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.PreferenceMatchers.withSummaryText;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.PreferenceMatchers.withTitle;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.PreferenceMatchers.withTitleText;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.PreferenceMatchers.isEnabled;
-import static org.hamcrest.Matchers.not;
-
-import com.google.android.apps.common.testing.ui.testapp.test.R;
-
-import android.test.InstrumentationTestCase;
-import android.preference.CheckBoxPreference;
-import android.preference.EditTextPreference;
-
-/**
- * Unit tests for preference matchers.
- */
-public class PreferenceMatchersTest extends InstrumentationTestCase {
-
-
- public void testWithSummary() {
- CheckBoxPreference pref = new CheckBoxPreference(getInstrumentation().getContext());
- pref.setSummary(R.string.something);
- assertThat(pref, withSummary(R.string.something));
- assertThat(pref, not(withSummary(R.string.other_string)));
- assertThat(pref, withSummaryText("Hello World"));
- assertThat(pref, not(withSummaryText(("Hello Mars"))));
- assertThat(pref, withSummaryText(is("Hello World")));
- }
-
- public void testWithTitle() {
- CheckBoxPreference pref = new CheckBoxPreference(getInstrumentation().getContext());
- pref.setTitle(R.string.other_string);
- assertThat(pref, withTitle(R.string.other_string));
- assertThat(pref, not(withTitle(R.string.something)));
- assertThat(pref, withTitleText("Goodbye!!"));
- assertThat(pref, not(withTitleText(("Hello Mars"))));
- assertThat(pref, withTitleText(is("Goodbye!!")));
- }
-
-
- public void testIsEnabled() {
- CheckBoxPreference pref = new CheckBoxPreference(getInstrumentation().getContext());
- pref.setEnabled(true);
- assertThat(pref, isEnabled());
- pref.setEnabled(false);
- assertThat(pref, not(isEnabled()));
- EditTextPreference pref2 = new EditTextPreference(getInstrumentation().getContext());
- pref2.setEnabled(true);
- assertThat(pref2, isEnabled());
- pref2.setEnabled(false);
- assertThat(pref2, not(isEnabled()));
- }
-
- public void testWithKey() {
- CheckBoxPreference pref = new CheckBoxPreference(getInstrumentation().getContext());
- pref.setKey("foo");
- assertThat(pref, withKey("foo"));
- assertThat(pref, not(withKey("bar")));
- assertThat(pref, withKey(is("foo")));
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/matcher/ViewMatchersTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/matcher/ViewMatchersTest.java
deleted file mode 100644
index 5000e46..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/matcher/ViewMatchersTest.java
+++ /dev/null
@@ -1,456 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.matcher;
-
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.hasContentDescription;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.hasDescendant;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.hasImeAction;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.hasSibling;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isAssignableFrom;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isChecked;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isClickable;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDescendantOfA;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isEnabled;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isFocusable;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isNotChecked;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isRoot;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.supportsInputMethods;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withChild;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withContentDescription;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withEffectiveVisibility;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withParent;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withTagKey;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withTagValue;
-import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;
-import static org.hamcrest.Matchers.is;
-
-import com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.Visibility;
-import com.google.android.apps.common.testing.ui.testapp.test.R;
-
-import android.test.InstrumentationTestCase;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.inputmethod.EditorInfo;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.Checkable;
-import android.widget.CheckedTextView;
-import android.widget.EditText;
-import android.widget.LinearLayout;
-import android.widget.RadioButton;
-import android.widget.RelativeLayout;
-import android.widget.ScrollView;
-import android.widget.Spinner;
-import android.widget.TextView;
-
-import org.hamcrest.Matcher;
-import org.hamcrest.Matchers;
-
-/**
- * Unit tests for {@link ViewMatchers}.
- */
-public class ViewMatchersTest extends InstrumentationTestCase {
- public void testIsAssignableFrom_notAnInstance() {
- View v = new View(getInstrumentation().getTargetContext());
- assertFalse(isAssignableFrom(Spinner.class).matches(v));
- }
-
- public void testIsAssignableFrom_plainView() {
- View v = new View(getInstrumentation().getTargetContext());
- assertTrue(isAssignableFrom(View.class).matches(v));
- }
-
- public void testIsAssignableFrom_superclass() {
- View v = new RadioButton(getInstrumentation().getTargetContext());
- assertTrue(isAssignableFrom(Button.class).matches(v));
- }
-
- @SuppressWarnings("cast")
- public void testWithContentDescriptionCharSequence() {
- View view = new View(getInstrumentation().getTargetContext());
- view.setContentDescription(null);
- assertTrue(withContentDescription(Matchers.<CharSequence>nullValue()).matches(view));
- CharSequence testText = "test text!";
- view.setContentDescription(testText);
- assertTrue(withContentDescription(is(testText)).matches(view));
- assertFalse(withContentDescription(is((CharSequence) "blah")).matches(view));
- assertFalse(withContentDescription(is((CharSequence) "")).matches(view));
- }
-
- public void testWithContentDescriptionNull() {
- try {
- withContentDescription((Matcher<CharSequence>) null);
- fail("Should of thrown NPE");
- } catch (NullPointerException e) {
- // Good, this is expected.
- }
- }
-
- public void testHasContentDescription() {
- View view = new View(getInstrumentation().getTargetContext());
- view.setContentDescription(null);
- assertFalse(hasContentDescription().matches(view));
- CharSequence testText = "test text!";
- view.setContentDescription(testText);
- assertTrue(hasContentDescription().matches(view));
- }
-
- public void testWithContentDescriptionString() {
- View view = new View(getInstrumentation().getTargetContext());
- view.setContentDescription(null);
- assertTrue(withContentDescription(Matchers.<String>nullValue()).matches(view));
- String testText = "test text!";
- view.setContentDescription(testText);
- assertTrue(withContentDescription(is(testText)).matches(view));
- assertFalse(withContentDescription(is("blah")).matches(view));
- assertFalse(withContentDescription(is("")).matches(view));
- }
-
- public void testWithId() {
- View view = new View(getInstrumentation().getTargetContext());
- view.setId(R.id.testId1);
- assertTrue(withId(is(R.id.testId1)).matches(view));
- assertFalse(withId(is(R.id.testId2)).matches(view));
- assertFalse(withId(is(1234)).matches(view));
- }
-
- public void testWithTagNull() {
- try {
- withTagKey(0, null);
- fail("Should of thrown NPE");
- } catch (NullPointerException e) {
- // Good, this is expected.
- }
-
- try {
- withTagValue(null);
- fail("Should of thrown NPE");
- } catch (NullPointerException e) {
- // Good, this is expected.
- }
- }
-
- public void testWithTagObject() {
- View view = new View(getInstrumentation().getTargetContext());
- view.setTag(null);
- assertTrue(withTagValue(Matchers.<Object>nullValue()).matches(view));
- String testObjectText = "test text!";
- view.setTag(testObjectText);
- assertFalse(withTagKey(R.id.testId1).matches(view));
- assertTrue(withTagValue(is((Object) testObjectText)).matches(view));
- assertFalse(withTagValue(is((Object) "blah")).matches(view));
- assertFalse(withTagValue(is((Object) "")).matches(view));
- }
-
- public void testWithTagKey() {
- View view = new View(getInstrumentation().getTargetContext());
- assertFalse(withTagKey(R.id.testId1).matches(view));
- view.setTag(R.id.testId1, "blah");
- assertFalse(withTagValue(is((Object) "blah")).matches(view));
- assertTrue(withTagKey(R.id.testId1).matches(view));
- assertFalse(withTagKey(R.id.testId2).matches(view));
- assertFalse(withTagKey(R.id.testId3).matches(view));
- assertFalse(withTagKey(65535).matches(view));
-
- view.setTag(R.id.testId2, "blah2");
- assertTrue(withTagKey(R.id.testId1).matches(view));
- assertTrue(withTagKey(R.id.testId2).matches(view));
- assertFalse(withTagKey(R.id.testId3).matches(view));
- assertFalse(withTagKey(65535).matches(view));
- assertFalse(withTagValue(is((Object) "blah")).matches(view));
- }
-
- public void testWithTagKeyObject() {
- View view = new View(getInstrumentation().getTargetContext());
- String testObjectText1 = "test text1!";
- String testObjectText2 = "test text2!";
- assertFalse(withTagKey(R.id.testId1, is((Object) testObjectText1)).matches(view));
- view.setTag(R.id.testId1, testObjectText1);
- assertTrue(withTagKey(R.id.testId1, is((Object) testObjectText1)).matches(view));
- assertFalse(withTagKey(R.id.testId1, is((Object) testObjectText2)).matches(view));
- assertFalse(withTagKey(R.id.testId2, is((Object) testObjectText1)).matches(view));
- assertFalse(withTagKey(R.id.testId3, is((Object) testObjectText1)).matches(view));
- assertFalse(withTagKey(65535, is((Object) testObjectText1)).matches(view));
- assertFalse(withTagValue(is((Object) "blah")).matches(view));
-
- view.setTag(R.id.testId2, testObjectText2);
- assertTrue(withTagKey(R.id.testId1, is((Object) testObjectText1)).matches(view));
- assertFalse(withTagKey(R.id.testId1, is((Object) testObjectText2)).matches(view));
- assertTrue(withTagKey(R.id.testId2, is((Object) testObjectText2)).matches(view));
- assertFalse(withTagKey(R.id.testId2, is((Object) testObjectText1)).matches(view));
- assertFalse(withTagKey(R.id.testId3, is((Object) testObjectText1)).matches(view));
- assertFalse(withTagKey(65535, is((Object) testObjectText1)).matches(view));
- assertFalse(withTagValue(is((Object) "blah")).matches(view));
- }
-
- public void testWithTextNull() {
- try {
- withText((Matcher<String>) null);
- fail("Should of thrown NPE");
- } catch (NullPointerException e) {
- // Good, this is expected.
- }
- }
-
- public void testCheckBoxMatchers() {
- assertFalse(isChecked().matches(new Spinner(getInstrumentation().getTargetContext())));
- assertFalse(isNotChecked().matches(new Spinner(getInstrumentation().getTargetContext())));
-
- CheckBox checkBox = new CheckBox(getInstrumentation().getTargetContext());
- checkBox.setChecked(true);
- assertTrue(isChecked().matches(checkBox));
- assertFalse(isNotChecked().matches(checkBox));
-
- checkBox.setChecked(false);
- assertFalse(isChecked().matches(checkBox));
- assertTrue(isNotChecked().matches(checkBox));
-
- RadioButton radioButton = new RadioButton(getInstrumentation().getTargetContext());
- radioButton.setChecked(false);
- assertFalse(isChecked().matches(radioButton));
- assertTrue(isNotChecked().matches(radioButton));
-
- radioButton.setChecked(true);
- assertTrue(isChecked().matches(radioButton));
- assertFalse(isNotChecked().matches(radioButton));
-
- CheckedTextView checkedText = new CheckedTextView(getInstrumentation().getTargetContext());
- checkedText.setChecked(false);
- assertFalse(isChecked().matches(checkedText));
- assertTrue(isNotChecked().matches(checkedText));
-
- checkedText.setChecked(true);
- assertTrue(isChecked().matches(checkedText));
- assertFalse(isNotChecked().matches(checkedText));
-
- Checkable checkable = new Checkable() {
- @Override
- public boolean isChecked() { return true; }
- @Override
- public void setChecked(boolean ignored) {}
- @Override
- public void toggle() {}
- };
-
- assertFalse(isChecked().matches(checkable));
- assertFalse(isNotChecked().matches(checkable));
- }
-
- public void testWithTextString() {
- TextView textView = new TextView(getInstrumentation().getTargetContext());
- textView.setText(null);
- assertTrue(withText(is("")).matches(textView));
- String testText = "test text!";
- textView.setText(testText);
- assertTrue(withText(is(testText)).matches(textView));
- assertFalse(withText(is("blah")).matches(textView));
- assertFalse(withText(is("")).matches(textView));
- }
-
- public void testHasDescendant() {
- View v = new TextView(getInstrumentation().getTargetContext());
- ViewGroup parent = new RelativeLayout(getInstrumentation().getTargetContext());
- ViewGroup grany = new ScrollView(getInstrumentation().getTargetContext());
- grany.addView(parent);
- parent.addView(v);
- assertTrue(hasDescendant(isAssignableFrom(TextView.class)).matches(grany));
- assertTrue(hasDescendant(isAssignableFrom(TextView.class)).matches(parent));
- assertFalse(hasDescendant(isAssignableFrom(ScrollView.class)).matches(parent));
- assertFalse(hasDescendant(isAssignableFrom(TextView.class)).matches(v));
- }
-
- public void testIsDescendantOfA() {
- View v = new TextView(getInstrumentation().getTargetContext());
- ViewGroup parent = new RelativeLayout(getInstrumentation().getTargetContext());
- ViewGroup grany = new ScrollView(getInstrumentation().getTargetContext());
- grany.addView(parent);
- parent.addView(v);
- assertTrue(isDescendantOfA(isAssignableFrom(RelativeLayout.class)).matches(v));
- assertTrue(isDescendantOfA(isAssignableFrom(ScrollView.class)).matches(v));
- assertFalse(isDescendantOfA(isAssignableFrom(LinearLayout.class)).matches(v));
- }
-
- public void testIsVisible() {
- View visible = new View(getInstrumentation().getTargetContext());
- visible.setVisibility(View.VISIBLE);
- View invisible = new View(getInstrumentation().getTargetContext());
- invisible.setVisibility(View.INVISIBLE);
- assertTrue(withEffectiveVisibility(Visibility.VISIBLE).matches(visible));
- assertFalse(withEffectiveVisibility(Visibility.VISIBLE).matches(invisible));
-
- // Make the visible view invisible by giving it an invisible parent.
- ViewGroup parent = new RelativeLayout(getInstrumentation().getTargetContext());
- parent.addView(visible);
- parent.setVisibility(View.INVISIBLE);
- assertFalse(withEffectiveVisibility(Visibility.VISIBLE).matches(visible));
- }
-
- public void testIsInvisible() {
- View visible = new View(getInstrumentation().getTargetContext());
- visible.setVisibility(View.VISIBLE);
- View invisible = new View(getInstrumentation().getTargetContext());
- invisible.setVisibility(View.INVISIBLE);
- assertFalse(withEffectiveVisibility(Visibility.INVISIBLE).matches(visible));
- assertTrue(withEffectiveVisibility(Visibility.INVISIBLE).matches(invisible));
-
- // Make the visible view invisible by giving it an invisible parent.
- ViewGroup parent = new RelativeLayout(getInstrumentation().getTargetContext());
- parent.addView(visible);
- parent.setVisibility(View.INVISIBLE);
- assertTrue(withEffectiveVisibility(Visibility.INVISIBLE).matches(visible));
- }
-
- public void testIsGone() {
- View gone = new View(getInstrumentation().getTargetContext());
- gone.setVisibility(View.GONE);
- View visible = new View(getInstrumentation().getTargetContext());
- visible.setVisibility(View.VISIBLE);
- assertFalse(withEffectiveVisibility(Visibility.GONE).matches(visible));
- assertTrue(withEffectiveVisibility(Visibility.GONE).matches(gone));
-
- // Make the gone view gone by giving it a gone parent.
- ViewGroup parent = new RelativeLayout(getInstrumentation().getTargetContext());
- parent.addView(visible);
- parent.setVisibility(View.GONE);
- assertTrue(withEffectiveVisibility(Visibility.GONE).matches(visible));
- }
-
- public void testIsClickable() {
- View clickable = new View(getInstrumentation().getTargetContext());
- clickable.setClickable(true);
- View notClickable = new View(getInstrumentation().getTargetContext());
- notClickable.setClickable(false);
- assertTrue(isClickable().matches(clickable));
- assertFalse(isClickable().matches(notClickable));
- }
-
- public void testIsEnabled() {
- View enabled = new View(getInstrumentation().getTargetContext());
- enabled.setEnabled(true);
- View notEnabled = new View(getInstrumentation().getTargetContext());
- notEnabled.setEnabled(false);
- assertTrue(isEnabled().matches(enabled));
- assertFalse(isEnabled().matches(notEnabled));
- }
-
- public void testIsFocusable() {
- View focusable = new View(getInstrumentation().getTargetContext());
- focusable.setFocusable(true);
- View notFocusable = new View(getInstrumentation().getTargetContext());
- notFocusable.setFocusable(false);
- assertTrue(isFocusable().matches(focusable));
- assertFalse(isFocusable().matches(notFocusable));
- }
-
- public void testWithTextResourceId() {
- TextView textView = new TextView(getInstrumentation().getTargetContext());
- textView.setText(R.string.something);
- assertTrue(withText(R.string.something).matches(textView));
- assertFalse(withText(R.string.other_string).matches(textView));
- }
-
- public void testWithParent() {
- View view1 = new TextView(getInstrumentation().getTargetContext());
- View view2 = new TextView(getInstrumentation().getTargetContext());
- View view3 = new TextView(getInstrumentation().getTargetContext());
- ViewGroup tiptop = new RelativeLayout(getInstrumentation().getTargetContext());
- ViewGroup secondLevel = new RelativeLayout(getInstrumentation().getTargetContext());
- secondLevel.addView(view2);
- secondLevel.addView(view3);
- tiptop.addView(secondLevel);
- tiptop.addView(view1);
- assertTrue(withParent(is((View) tiptop)).matches(view1));
- assertTrue(withParent(is((View) tiptop)).matches(secondLevel));
- assertFalse(withParent(is((View) tiptop)).matches(view2));
- assertFalse(withParent(is((View) tiptop)).matches(view3));
- assertFalse(withParent(is((View) secondLevel)).matches(view1));
-
- assertTrue(withParent(is((View) secondLevel)).matches(view2));
- assertTrue(withParent(is((View) secondLevel)).matches(view3));
-
- assertFalse(withParent(is(view3)).matches(view3));
- }
-
- public void testWithChild() {
- View view1 = new TextView(getInstrumentation().getTargetContext());
- View view2 = new TextView(getInstrumentation().getTargetContext());
- View view3 = new TextView(getInstrumentation().getTargetContext());
- ViewGroup tiptop = new RelativeLayout(getInstrumentation().getTargetContext());
- ViewGroup secondLevel = new RelativeLayout(getInstrumentation().getTargetContext());
- secondLevel.addView(view2);
- secondLevel.addView(view3);
- tiptop.addView(secondLevel);
- tiptop.addView(view1);
- assertTrue(withChild(is(view1)).matches(tiptop));
- assertTrue(withChild(is((View) secondLevel)).matches(tiptop));
- assertFalse(withChild(is((View) tiptop)).matches(view1));
- assertFalse(withChild(is(view2)).matches(tiptop));
- assertFalse(withChild(is(view1)).matches(secondLevel));
-
- assertTrue(withChild(is(view2)).matches(secondLevel));
-
- assertFalse(withChild(is(view3)).matches(view3));
- }
-
- public void testIsRootView() {
- ViewGroup rootView = new ViewGroup(getInstrumentation().getTargetContext()) {
- @Override
- protected void onLayout(boolean changed, int l, int t, int r, int b) {
- }
- };
-
- View view = new View(getInstrumentation().getTargetContext());
- rootView.addView(view);
-
- assertTrue(isRoot().matches(rootView));
- assertFalse(isRoot().matches(view));
- }
-
- public void testHasSibling() {
- TextView v1 = new TextView(getInstrumentation().getTargetContext());
- v1.setText("Bill Odama");
- Button v2 = new Button(getInstrumentation().getTargetContext());
- View v3 = new View(getInstrumentation().getTargetContext());
- ViewGroup parent = new LinearLayout(getInstrumentation().getTargetContext());
- parent.addView(v1);
- parent.addView(v2);
- parent.addView(v3);
- assertTrue(hasSibling(withText("Bill Odama")).matches(v2));
- assertFalse(hasSibling(is(v3)).matches(parent));
- }
-
- public void testHasImeAction() {
- EditText editText = new EditText(getInstrumentation().getTargetContext());
- assertFalse(hasImeAction(EditorInfo.IME_ACTION_GO).matches(editText));
- editText.setImeOptions(EditorInfo.IME_ACTION_NEXT);
- assertFalse(hasImeAction(EditorInfo.IME_ACTION_GO).matches(editText));
- assertTrue(hasImeAction(EditorInfo.IME_ACTION_NEXT).matches(editText));
- }
-
- public void testHasImeActionNoInputConnection() {
- Button button = new Button(getInstrumentation().getTargetContext());
- assertFalse(hasImeAction(0).matches(button));
- }
-
- public void testSupportsInputMethods() {
- Button button = new Button(getInstrumentation().getTargetContext());
- EditText editText = new EditText(getInstrumentation().getTargetContext());
- assertFalse(supportsInputMethods().matches(button));
- assertTrue(supportsInputMethods().matches(editText));
- }
-}
diff --git a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/util/TreeIterablesTest.java b/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/util/TreeIterablesTest.java
deleted file mode 100644
index 9b2bdcc..0000000
--- a/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/util/TreeIterablesTest.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.apps.common.testing.ui.espresso.util;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.hasEntry;
-import static org.hamcrest.Matchers.is;
-
-import com.google.android.apps.common.testing.ui.espresso.util.TreeIterables.DistanceRecordingTreeViewer;
-import com.google.android.apps.common.testing.ui.espresso.util.TreeIterables.TreeViewer;
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
-import junit.framework.TestCase;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/** Unit tests for {@link TreeIterables}. */
-public class TreeIterablesTest extends TestCase {
-
- private static class TestElement {
- private final String data;
- private final ImmutableList<TestElement> children;
- public TestElement(String data, TestElement ... children) {
- this.data = checkNotNull(data);
- this.children = ImmutableList.copyOf(children);
- }
- }
-
- private static class TestElementTreeViewer implements TreeViewer<TestElement> {
- @Override
- public Collection<TestElement> children(TestElement element) {
- return element.children;
- }
- }
-
- private static class TestElementStringConvertor implements Function<TestElement, String> {
- @Override
- public String apply(TestElement e) {
- return e.data;
- }
- }
-
-
- private static final TestElement trivialTree =
- new TestElement("a", new TestElement("b", new TestElement("c", new TestElement("d"))));
-
- private static final TestElement complexTree =
- new TestElement("a",
- new TestElement("b",
- new TestElement("c",
- new TestElement("d"),
- new TestElement("e",
- new TestElement("f"))),
- new TestElement("g"),
- new TestElement("h",
- new TestElement("i",
- new TestElement("j",
- new TestElement("k"))))),
- new TestElement("l"),
- new TestElement("m"),
- new TestElement("n",
- new TestElement("o",
- new TestElement("p"),
- new TestElement("q"))));
-
- public void testDistanceRecorder_unknownItemThrowsException() {
- final DistanceRecordingTreeViewer<TestElement> distanceRecorder =
- new DistanceRecordingTreeViewer<TestElement>(complexTree, new TestElementTreeViewer());
- try {
- distanceRecorder.getDistance(new TestElement("hello"));
- fail("node should be unknown");
- } catch (RuntimeException expected) { }
- }
-
- public void testDistanceRecorder_unprocessedChildThrowsException() {
- final DistanceRecordingTreeViewer<TestElement> distanceRecorder =
- new DistanceRecordingTreeViewer<TestElement>(complexTree, new TestElementTreeViewer());
-
- try {
- distanceRecorder.getDistance(complexTree.children.iterator().next());
- fail("distance recorder hasnt processed this child yet, cannot know distance");
- } catch (RuntimeException expected) { }
- }
-
- public void testDistanceRecorder_distanceKnownAfterChildrenCall() {
- final DistanceRecordingTreeViewer<TestElement> distanceRecorder =
- new DistanceRecordingTreeViewer<TestElement>(complexTree, new TestElementTreeViewer());
-
- @SuppressWarnings("unused")
- List<TestElement> createdForSideEffect = Lists.newArrayList(
- distanceRecorder.children(complexTree));
-
- assertThat(distanceRecorder.getDistance(complexTree), is(0));
- assertThat(distanceRecorder.getDistance(complexTree.children.iterator().next()), is(1));
- }
-
- @SuppressWarnings("unchecked")
- public void testComplexTree_Distances() {
- final DistanceRecordingTreeViewer<TestElement> distanceRecorder =
- new DistanceRecordingTreeViewer<TestElement>(complexTree, new TestElementTreeViewer());
- Iterable<TestElement> complexIterable = TreeIterables.depthFirstTraversal(complexTree,
- distanceRecorder);
- Set<TestElement> complexSet = Sets.newHashSet(complexIterable);
- Map<String, Integer> distancesByData = Maps.newHashMap();
- for (TestElement e : complexSet) {
- distancesByData.put(e.data, distanceRecorder.getDistance(e));
- }
-
- assertThat(distancesByData, allOf(
- hasEntry("a", 0),
- hasEntry("b", 1),
- hasEntry("c", 2),
- hasEntry("d", 3),
- hasEntry("e", 3),
- hasEntry("f", 4),
- hasEntry("g", 2),
- hasEntry("h", 2),
- hasEntry("i", 3),
- hasEntry("j", 4),
- hasEntry("k", 5),
- hasEntry("l", 1),
- hasEntry("m", 1),
- hasEntry("n", 1),
- hasEntry("o", 2),
- hasEntry("p", 3),
- hasEntry("q", 3)));
- assertThat(distancesByData.size(), is(17));
-
- List<String> traversalOrder = Lists.newArrayList(Iterables.transform(
- complexIterable,
- new TestElementStringConvertor()));
-
- // should be depth first if forwarding correctly.
- assertThat(traversalOrder,
- is((List<String>) Lists.newArrayList(
- "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q")));
- }
-
- public void testComplexTraversal_depthFirst() {
- List<String> breadthFirst = Lists.newArrayList(Iterables.transform(
- TreeIterables.depthFirstTraversal(complexTree, new TestElementTreeViewer()),
- new TestElementStringConvertor()));
- assertThat(breadthFirst,
- is((Iterable<String>) Lists.newArrayList(
- "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q")));
- }
-
- public void testComplexTraversal_breadthFirst() {
- List<String> breadthFirst = Lists.newArrayList(Iterables.transform(
- TreeIterables.breadthFirstTraversal(complexTree, new TestElementTreeViewer()),
- new TestElementStringConvertor()));
- assertThat(breadthFirst,
- is((List<String>) Lists.newArrayList(
- "a", //root
- "b", "l", "m", "n", //L1
- "c", "g", "h", "o", //L2
- "d", "e", "i", "p", "q", //L3
- "f", "j", // L4
- "k"))); //L5
- }
-
- public void testTrivialTraversal_breadthFirst() {
- // essentially the same as depth first.
- List<String> breadthFirst = Lists.newArrayList(Iterables.transform(
- TreeIterables.breadthFirstTraversal(trivialTree, new TestElementTreeViewer()),
- new TestElementStringConvertor()));
- assertThat(breadthFirst, is((List<String>) Lists.newArrayList("a", "b", "c", "d")));
- }
-
- public void testTrivialTraversal_depthFirst() {
- List<String> depthFirst = Lists.newArrayList(Iterables.transform(
- TreeIterables.depthFirstTraversal(trivialTree, new TestElementTreeViewer()),
- new TestElementStringConvertor()));
- assertThat(depthFirst, is((List<String>) Lists.newArrayList("a", "b", "c", "d")));
- }
-
- @SuppressWarnings("unchecked")
- public void testTrivial_distance() {
- final DistanceRecordingTreeViewer<TestElement> distanceRecorder =
- new DistanceRecordingTreeViewer<TestElement>(trivialTree, new TestElementTreeViewer());
-
- Iterable<TestElement> trivialIterable = TreeIterables.depthFirstTraversal(trivialTree,
- distanceRecorder);
- Set<TestElement> trivialSet = Sets.newHashSet(trivialIterable);
- Map<String, Integer> distancesByData = Maps.newHashMap();
- for (TestElement e : trivialSet) {
- distancesByData.put(e.data, distanceRecorder.getDistance(e));
- }
-
- assertThat(distancesByData, allOf(
- hasEntry("a", 0),
- hasEntry("b", 1),
- hasEntry("c", 2),
- hasEntry("d", 3)));
- assertThat(distancesByData.size(), is(4));
- }
-}