Commit 1c7f988e authored by Ted Choc's avatar Ted Choc Committed by Commit Bot

Add initial support for Criteria specific exception.

This does the conversion of content/public tests. As part of this
transition, Criteria.equals is being replaced in tests to allow
its removal.

BUG=1071247

Change-Id: I27f336db7e66e01834945b7fa1df073093641b18
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2255658
Commit-Queue: Ted Choc <tedchoc@chromium.org>
Reviewed-by: default avatarWei-Yin Chen (陳威尹) <wychen@chromium.org>
Reviewed-by: default avatarBo <boliu@chromium.org>
Reviewed-by: default avatarBoris Sazonov <bsazonov@chromium.org>
Reviewed-by: default avatarYaron Friedman <yfriedman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#781388}
parent 20901fef
......@@ -102,10 +102,10 @@ public class ChildProcessLauncherHelperTest {
Assert.assertTrue(context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE));
// Wait for the Helper service to connect.
CriteriaHelper.pollInstrumentationThread(
()
-> Assert.assertNotNull("Failed to get helper service Messenger",
serviceConnection.mMessenger));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat("Failed to get helper service Messenger",
serviceConnection.mMessenger, Matchers.notNullValue());
});
Assert.assertNotNull(serviceConnection.mMessenger);
......@@ -128,10 +128,10 @@ public class ChildProcessLauncherHelperTest {
msg.replyTo = new Messenger(new Handler(Looper.getMainLooper(), replyHandler));
serviceConnection.mMessenger.send(msg);
CriteriaHelper.pollInstrumentationThread(
()
-> Assert.assertNotNull(
"Failed waiting for helper service reply", replyHandler.mMessage));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat("Failed waiting for helper service reply", replyHandler.mMessage,
Matchers.notNullValue());
});
// Verify that the Helper was able to launch the sandboxed service.
Assert.assertNotNull(replyHandler.mMessage);
......@@ -178,11 +178,11 @@ public class ChildProcessLauncherHelperTest {
Assert.assertEquals(
connectionAllocator.getChildProcessConnectionAtSlotForTesting(1), retryConnection);
CriteriaHelper.pollInstrumentationThread(
()
-> Assert.assertThat("Failed waiting retry connection to get pid",
ChildProcessLauncherTestUtils.getConnectionPid(retryConnection),
Matchers.greaterThan(0)));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat("Failed waiting retry connection to get pid",
ChildProcessLauncherTestUtils.getConnectionPid(retryConnection),
Matchers.greaterThan(0));
});
Assert.assertTrue(ChildProcessLauncherTestUtils.getConnectionPid(retryConnection)
!= helperConnectionPid);
Assert.assertTrue(ChildProcessLauncherTestUtils.getConnectionService(retryConnection)
......@@ -193,10 +193,10 @@ public class ChildProcessLauncherHelperTest {
msg = Message.obtain(null, ChildProcessLauncherTestHelperService.MSG_UNBIND_SERVICE);
msg.replyTo = new Messenger(new Handler(Looper.getMainLooper(), replyHandler));
serviceConnection.mMessenger.send(msg);
CriteriaHelper.pollInstrumentationThread(
()
-> Assert.assertNotNull("Failed waiting for helper service unbind reply",
replyHandler.mMessage));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat("Failed waiting for helper service unbind reply",
replyHandler.mMessage, Matchers.notNullValue());
});
Assert.assertEquals(ChildProcessLauncherTestHelperService.MSG_UNBIND_SERVICE_REPLY,
replyHandler.mMessage.what);
......@@ -385,8 +385,9 @@ public class ChildProcessLauncherHelperTest {
private static void blockUntilConnected(final ChildProcessLauncherHelperImpl launcher) {
CriteriaHelper.pollInstrumentationThread(() -> {
Assert.assertNotNull(launcher.getChildProcessConnection());
Assert.assertTrue(launcher.getChildProcessConnection().isConnected());
Criteria.checkThat(launcher.getChildProcessConnection(), Matchers.notNullValue());
Criteria.checkThat(
launcher.getChildProcessConnection().isConnected(), Matchers.is(true));
});
}
......@@ -396,10 +397,10 @@ public class ChildProcessLauncherHelperTest {
}
private static void blockUntilSetup(final ChildProcessLauncherHelperImpl launcher) {
CriteriaHelper.pollInstrumentationThread(
()
-> Assert.assertNotEquals(
"The connection wasn't established", 0, getPid(launcher)));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(
"The connection wasn't established", getPid(launcher), Matchers.not(0));
});
}
// Returns the number of all connection currently connected.
......@@ -425,21 +426,18 @@ public class ChildProcessLauncherHelperTest {
// Blocks until the number of sandboxed connections reaches targetCount.
private static void waitForConnectedSandboxedServicesCount(int targetCount) {
CriteriaHelper.pollInstrumentationThread(
Criteria.equals(targetCount, new Callable<Integer>() {
@Override
public Integer call() {
return getConnectedSandboxedServicesCount();
}
}));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(getConnectedSandboxedServicesCount(), Matchers.is(targetCount));
});
}
private static ChildProcessConnection retrieveConnection(
final ChildProcessLauncherHelperImpl launcherHelper) {
CriteriaHelper.pollInstrumentationThread(
()
-> Assert.assertNotNull("Failed waiting for child process to connect",
ChildProcessLauncherTestUtils.getConnection(launcherHelper)));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat("Failed waiting for child process to connect",
ChildProcessLauncherTestUtils.getConnection(launcherHelper),
Matchers.notNullValue());
});
return ChildProcessLauncherTestUtils.getConnection(launcherHelper);
}
......
......@@ -486,8 +486,10 @@ public class ChildProcessLauncherTest {
private static void waitForConnectionAllocatorState(
final ChildConnectionAllocator connectionAllocator, final boolean emptyState) {
CriteriaHelper.pollInstrumentationThread(
Criteria.equals(!emptyState, connectionAllocator::anyConnectionAllocated));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(
connectionAllocator.anyConnectionAllocated(), Matchers.not(emptyState));
});
}
private static void waitForConnectionState(
......@@ -497,19 +499,19 @@ public class ChildProcessLauncherTest {
Matchers.equalTo(CONNECTION_BLOCK_UNTIL_SETUP)));
CriteriaHelper.pollInstrumentationThread(() -> {
if (connectionState == CONNECTION_BLOCK_UNTIL_CONNECTED) {
Assert.assertTrue(connection.isConnected());
Criteria.checkThat(connection.isConnected(), Matchers.is(true));
} else {
Assert.assertEquals(CONNECTION_BLOCK_UNTIL_SETUP, connectionState);
Assert.assertNotEquals(0, getConnectionPid(connection));
Criteria.checkThat(connectionState, Matchers.is(CONNECTION_BLOCK_UNTIL_SETUP));
Criteria.checkThat(getConnectionPid(connection), Matchers.not(0));
}
});
}
private static void waitUntilLauncherSetup(final ChildProcessLauncher launcher) {
CriteriaHelper.pollInstrumentationThread(
()
-> Assert.assertNotNull(
"Failed wait for launcher to connect.", launcher.getConnection()));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat("Failed wait for launcher to connect.", launcher.getConnection(),
Matchers.notNullValue());
});
waitForConnectionState(launcher.getConnection(), CONNECTION_BLOCK_UNTIL_SETUP);
}
......
......@@ -14,6 +14,7 @@ import android.os.SystemClock;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
......@@ -414,9 +415,12 @@ public class ContentTextSelectionTest {
DOMUtils.clickNode(mWebContents, "smart_selection");
CriteriaHelper.pollUiThread(Criteria.equals(
0, () -> mSelectionPopupController.getClassificationResult().startAdjust));
Assert.assertEquals("Amphitheatre", mSelectionPopupController.getSelectedText());
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(mSelectionPopupController.getClassificationResult().startAdjust,
Matchers.is(0));
Criteria.checkThat(
mSelectionPopupController.getSelectedText(), Matchers.is("Amphitheatre"));
});
}
@Test
......@@ -681,13 +685,9 @@ public class ContentTextSelectionTest {
Assert.assertEquals(mSelectionPopupController.getSelectedText(), "SampleTextArea");
hideSelectActionMode();
waitForSelectActionBarVisible(false);
CriteriaHelper.pollInstrumentationThread(
Criteria.equals("SampleTextArea", new Callable<CharSequence>() {
@Override
public CharSequence call() {
return getTextBeforeCursor(50, 0);
}
}));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(getTextBeforeCursor(50, 0), Matchers.is("SampleTextArea"));
});
}
@Test
......@@ -833,19 +833,17 @@ public class ContentTextSelectionTest {
ClipboardManager clipboardManager =
(ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = clipboardManager.getPrimaryClip();
Assert.assertNotNull(clip);
Assert.assertEquals(1, clip.getItemCount());
Assert.assertEquals(expectedContents, clip.getItemAt(0).getText());
Criteria.checkThat(clip, Matchers.notNullValue());
Criteria.checkThat(clip.getItemCount(), Matchers.is(1));
Criteria.checkThat(clip.getItemAt(0).getText(), Matchers.is(expectedContents));
});
}
private void waitForSelectActionBarVisible(final boolean visible) {
CriteriaHelper.pollUiThread(Criteria.equals(visible, new Callable<Boolean>() {
@Override
public Boolean call() {
return mSelectionPopupController.isSelectActionBarShowing();
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(
mSelectionPopupController.isSelectActionBarShowing(), Matchers.is(visible));
});
}
private void setVisibileOnUiThread(final boolean show) {
......@@ -907,20 +905,15 @@ public class ContentTextSelectionTest {
}
private void waitForPastePopupStatus(final boolean show) {
CriteriaHelper.pollUiThread(Criteria.equals(show, new Callable<Boolean>() {
@Override
public Boolean call() {
return mSelectionPopupController.isPastePopupShowing();
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(mSelectionPopupController.isPastePopupShowing(), Matchers.is(show));
});
}
private void waitForInsertion(final boolean show) {
CriteriaHelper.pollUiThread(Criteria.equals(show, new Callable<Boolean>() {
@Override
public Boolean call() {
return mSelectionPopupController.isInsertionForTesting();
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(
mSelectionPopupController.isInsertionForTesting(), Matchers.is(show));
});
}
}
......@@ -21,14 +21,13 @@ import org.chromium.base.test.util.Feature;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.CriteriaNotSatisfiedException;
import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer;
import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer.OnEvaluateJavaScriptResultHelper;
import org.chromium.content_shell_apk.ContentShellActivityTestRule;
import org.chromium.device.geolocation.LocationProviderOverrider;
import org.chromium.device.geolocation.MockLocationProvider;
import java.util.concurrent.Callable;
/**
* Test suite for ensureing that Geolocation interacts as expected
* with ContentView APIs - e.g. that it's started and stopped as the
......@@ -73,10 +72,10 @@ public class ContentViewLocationTest {
try {
mJavascriptHelper.waitUntilHasValue();
} catch (Exception e) {
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
int result = Integer.parseInt(mJavascriptHelper.getJsonResultAndClear());
Assert.assertThat(result, Matchers.greaterThan(0));
Criteria.checkThat(result, Matchers.greaterThan(0));
});
}
......@@ -87,12 +86,9 @@ public class ContentViewLocationTest {
}
private void ensureGeolocationRunning(final boolean running) {
CriteriaHelper.pollInstrumentationThread(Criteria.equals(running, new Callable<Boolean>() {
@Override
public Boolean call() {
return mMockLocationProvider.isRunning();
}
}));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(mMockLocationProvider.isRunning(), Matchers.is(running));
});
}
@Before
......
......@@ -24,6 +24,7 @@ import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.content_public.browser.ViewEventSink.InternalAccessDelegate;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.WebContentsUtils;
import org.chromium.content_shell_apk.ContentShellActivityTestRule;
......@@ -93,16 +94,18 @@ public class ContentViewScrollingTest {
final int minThreshold = 5;
final int maxThreshold = 100;
if (hugLeft) {
Assert.assertThat(mCoordinates.getScrollXPixInt(), Matchers.lessThan(minThreshold));
Criteria.checkThat(
mCoordinates.getScrollXPixInt(), Matchers.lessThan(minThreshold));
} else {
Assert.assertThat(
Criteria.checkThat(
mCoordinates.getScrollXPixInt(), Matchers.greaterThan(maxThreshold));
}
if (hugTop) {
Assert.assertThat(mCoordinates.getScrollYPixInt(), Matchers.lessThan(minThreshold));
Criteria.checkThat(
mCoordinates.getScrollYPixInt(), Matchers.lessThan(minThreshold));
} else {
Assert.assertThat(
Criteria.checkThat(
mCoordinates.getScrollYPixInt(), Matchers.greaterThan(maxThreshold));
}
});
......@@ -113,18 +116,19 @@ public class ContentViewScrollingTest {
// Scrolling and flinging don't result in exact coordinates.
final int threshold = 5;
Assert.assertThat(mCoordinates.getScrollXPixInt(),
Criteria.checkThat(mCoordinates.getScrollXPixInt(),
Matchers.allOf(
Matchers.lessThan(x + threshold), Matchers.greaterThan(x - threshold)));
Assert.assertThat(mCoordinates.getScrollYPixInt(),
Criteria.checkThat(mCoordinates.getScrollYPixInt(),
Matchers.allOf(
Matchers.lessThan(y + threshold), Matchers.greaterThan(y - threshold)));
});
}
private void waitForViewportInitialization() {
CriteriaHelper.pollInstrumentationThread(
() -> Assert.assertNotEquals(0, mCoordinates.getLastFrameViewportWidthPixInt()));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(mCoordinates.getLastFrameViewportWidthPixInt(), Matchers.not(0));
});
}
private void fling(final int vx, final int vy) {
......
......@@ -8,7 +8,7 @@ import android.support.test.InstrumentationRegistry;
import androidx.test.filters.LargeTest;
import org.junit.Assert;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
......@@ -18,7 +18,9 @@ import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.CriteriaNotSatisfiedException;
import org.chromium.content_public.browser.test.util.DOMUtils;
import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer;
import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer.OnPageFinishedHelper;
......@@ -65,9 +67,9 @@ public class GestureDetectorResetTest {
try {
contents = DOMUtils.getNodeContents(mWebContents, mNodeId);
} catch (Throwable e) {
Assert.fail("Failed to retrieve node contents: " + e);
throw new CriteriaNotSatisfiedException(e);
}
Assert.assertEquals(mFailureReason, mExpectedContents, contents);
Criteria.checkThat(mFailureReason, contents, Matchers.is(mExpectedContents));
}
}
......
......@@ -10,6 +10,7 @@ import android.media.AudioManager;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
......@@ -32,7 +33,6 @@ import org.chromium.content_shell_apk.ContentShellActivityTestRule;
import org.chromium.media.MediaSwitches;
import java.util.ArrayList;
import java.util.concurrent.Callable;
/**
* Tests for MediaSession.
......@@ -92,12 +92,7 @@ public class MediaSessionTest {
public void waitForFocusStateChange(int focusType) {
CriteriaHelper.pollInstrumentationThread(
Criteria.equals(focusType, new Callable<Integer>() {
@Override
public Integer call() {
return getAudioFocusState();
}
}));
() -> Criteria.checkThat(getAudioFocusState(), Matchers.is(focusType)));
}
}
......
......@@ -11,6 +11,7 @@ import android.support.test.InstrumentationRegistry;
import androidx.test.filters.MediumTest;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
......@@ -23,6 +24,7 @@ import org.chromium.base.test.util.Restriction;
import org.chromium.content_public.browser.test.ContentJUnit4ClassRunner;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.CriteriaNotSatisfiedException;
import org.chromium.content_public.browser.test.util.DOMUtils;
import org.chromium.content_public.browser.test.util.JavaScriptUtils;
import org.chromium.content_public.browser.test.util.UiUtils;
......@@ -30,7 +32,6 @@ import org.chromium.content_shell_apk.ContentShellActivityTestRule;
import org.chromium.media.MediaSwitches;
import org.chromium.ui.test.util.UiRestriction;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
/**
......@@ -47,13 +48,14 @@ public class VideoFullscreenOrientationLockTest {
private static final String VIDEO_ID = "video";
private void waitForContentsFullscreenState(boolean fullscreenValue) {
CriteriaHelper.pollInstrumentationThread(
Criteria.equals(fullscreenValue, new Callable<Boolean>() {
@Override
public Boolean call() throws TimeoutException {
return DOMUtils.isFullscreen(mActivityTestRule.getWebContents());
}
}));
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Criteria.checkThat(DOMUtils.isFullscreen(mActivityTestRule.getWebContents()),
Matchers.is(fullscreenValue));
} catch (TimeoutException ex) {
throw new CriteriaNotSatisfiedException(ex);
}
});
}
private boolean isScreenOrientationLocked() {
......@@ -76,17 +78,17 @@ public class VideoFullscreenOrientationLockTest {
private void waitUntilLockedToLandscape() {
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertTrue(isScreenOrientationLocked());
Assert.assertTrue(isScreenOrientationLandscape());
Criteria.checkThat(isScreenOrientationLocked(), Matchers.is(true));
Criteria.checkThat(isScreenOrientationLandscape(), Matchers.is(true));
} catch (TimeoutException e) {
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
}
private void waitUntilUnlocked() {
CriteriaHelper.pollInstrumentationThread(
Criteria.equals(false, this::isScreenOrientationLocked));
() -> Criteria.checkThat(isScreenOrientationLocked(), Matchers.is(false)));
}
// TODO(mlamouri): move these constants and bounds methods to a dedicated helper file for
......
......@@ -9,6 +9,7 @@ import android.provider.Settings;
import androidx.test.filters.MediumTest;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
......@@ -23,6 +24,7 @@ import org.chromium.base.test.util.Restriction;
import org.chromium.content_public.browser.test.ContentJUnit4ClassRunner;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.CriteriaNotSatisfiedException;
import org.chromium.content_public.browser.test.util.DOMUtils;
import org.chromium.content_public.browser.test.util.JavaScriptUtils;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
......@@ -30,7 +32,6 @@ import org.chromium.content_shell_apk.ContentShellActivityTestRule;
import org.chromium.media.MediaSwitches;
import org.chromium.ui.test.util.UiRestriction;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
/**
......@@ -47,23 +48,24 @@ public class VideoRotateToFullscreenTest {
private static final String VIDEO_ID = "video";
private void waitForContentsFullscreenState(boolean fullscreenValue) {
CriteriaHelper.pollInstrumentationThread(
Criteria.equals(fullscreenValue, new Callable<Boolean>() {
@Override
public Boolean call() throws TimeoutException {
return DOMUtils.isFullscreen(mRule.getWebContents());
}
}));
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Criteria.checkThat(DOMUtils.isFullscreen(mRule.getWebContents()),
Matchers.is(fullscreenValue));
} catch (TimeoutException ex) {
throw new CriteriaNotSatisfiedException(ex);
}
});
}
private void waitForScreenOrientation(String orientationValue) {
CriteriaHelper.pollInstrumentationThread(
Criteria.equals(orientationValue, new Callable<String>() {
@Override
public String call() throws TimeoutException {
return screenOrientation();
}
}));
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Criteria.checkThat(screenOrientation(), Matchers.is(orientationValue));
} catch (TimeoutException ex) {
throw new CriteriaNotSatisfiedException(ex);
}
});
}
private String screenOrientation() throws TimeoutException {
......
......@@ -35,6 +35,7 @@ import org.junit.runner.RunWith;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.MinAndroidSdkLevel;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.content_shell_apk.ContentShellActivityTestRule;
......@@ -85,8 +86,9 @@ public class WebContentsAccessibilityTest {
wcax.setState(true);
wcax.setAccessibilityEnabledForTesting();
CriteriaHelper.pollUiThread(
() -> Assert.assertNotNull(wcax.getAccessibilityNodeProvider()));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(wcax.getAccessibilityNodeProvider(), Matchers.notNullValue());
});
return wcax.getAccessibilityNodeProvider();
}
......@@ -142,10 +144,10 @@ public class WebContentsAccessibilityTest {
*/
private int waitForNodeMatching(
AccessibilityNodeProvider provider, AccessibilityNodeInfoMatcher matcher) {
CriteriaHelper.pollUiThread(
()
-> Assert.assertNotEquals(
View.NO_ID, findNodeMatching(provider, View.NO_ID, matcher)));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(
findNodeMatching(provider, View.NO_ID, matcher), Matchers.not(View.NO_ID));
});
int virtualViewId = TestThreadUtils.runOnUiThreadBlockingNoException(
() -> findNodeMatching(provider, View.NO_ID, matcher));
......@@ -1009,8 +1011,8 @@ public class WebContentsAccessibilityTest {
Bundle textNodeExtras = textNode.getExtras();
RectF[] textNodeResults = (RectF[]) textNodeExtras.getParcelableArray(
EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY);
Assert.assertThat(textNodeResults, Matchers.arrayWithSize(4));
Assert.assertNotEquals(textNodeResults[0], textNodeResults[1]);
Criteria.checkThat(textNodeResults, Matchers.arrayWithSize(4));
Criteria.checkThat(textNodeResults[0], Matchers.not(textNodeResults[1]));
});
// The final result should be the separate bounding box of all four characters.
......
......@@ -27,6 +27,7 @@ import org.chromium.content.browser.webcontents.WebContentsImpl;
import org.chromium.content_public.browser.ImeAdapter;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.CriteriaNotSatisfiedException;
import org.chromium.content_public.browser.test.util.DOMUtils;
import org.chromium.content_public.browser.test.util.JavaScriptUtils;
import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer;
......@@ -168,23 +169,25 @@ class ImeActivityTestRule extends ContentShellActivityTestRule {
void waitForEventLogState(String expectedLogs) {
final String code = "getEventLogs()";
final String sanitizedExpectedLogs = "\"" + expectedLogs + "\"";
CriteriaHelper.pollInstrumentationThread(
Criteria.equals(sanitizedExpectedLogs, new Callable<String>() {
@Override
public String call() throws Exception {
return JavaScriptUtils.executeJavaScriptAndWaitForResult(
getWebContents(), code);
}
}));
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Criteria.checkThat(
JavaScriptUtils.executeJavaScriptAndWaitForResult(getWebContents(), code),
Matchers.is(sanitizedExpectedLogs));
} catch (TimeoutException ex) {
throw new CriteriaNotSatisfiedException(ex);
}
});
}
void waitForFocusedElement(String id) {
CriteriaHelper.pollInstrumentationThread(Criteria.equals(id, new Callable<String>() {
@Override
public String call() throws Exception {
return DOMUtils.getFocusedNode(getWebContents());
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Criteria.checkThat(DOMUtils.getFocusedNode(getWebContents()), Matchers.is(id));
} catch (TimeoutException ex) {
throw new CriteriaNotSatisfiedException(ex);
}
}));
});
}
void assertTextsAroundCursor(CharSequence before, CharSequence selected, CharSequence after)
......@@ -197,36 +200,27 @@ class ImeActivityTestRule extends ContentShellActivityTestRule {
void waitForKeyboardStates(int show, int hide, int restart, Integer[] textInputTypeHistory) {
final String expected =
stringifyKeyboardStates(show, hide, restart, textInputTypeHistory, null, null);
CriteriaHelper.pollUiThread(Criteria.equals(expected, new Callable<String>() {
@Override
public String call() {
return getKeyboardStates(false, false);
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(getKeyboardStates(false, false), Matchers.is(expected));
});
}
void waitForKeyboardStates(int show, int hide, int restart, Integer[] textInputTypeHistory,
Integer[] textInputModeHistory) {
final String expected = stringifyKeyboardStates(
show, hide, restart, textInputTypeHistory, textInputModeHistory, null);
CriteriaHelper.pollUiThread(Criteria.equals(expected, new Callable<String>() {
@Override
public String call() {
return getKeyboardStates(true, false);
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(getKeyboardStates(true, false), Matchers.is(expected));
});
}
void waitForKeyboardInputActionStates(int show, int hide, int restart,
Integer[] textInputTypeHistory, Integer[] textInputActionHistory) {
final String expected = stringifyKeyboardStates(
show, hide, restart, textInputTypeHistory, null, textInputActionHistory);
CriteriaHelper.pollUiThread(Criteria.equals(expected, new Callable<String>() {
@Override
public String call() {
return getKeyboardStates(false, true);
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(getKeyboardStates(false, true), Matchers.is(expected));
});
}
void resetAllStates() {
......@@ -258,15 +252,13 @@ class ImeActivityTestRule extends ContentShellActivityTestRule {
}
void waitForEditorAction(final int expectedAction) {
CriteriaHelper.pollUiThread(Criteria.equals(expectedAction, new Callable<Integer>() {
@Override
public Integer call() {
EditorInfo editorInfo = mConnectionFactory.getOutAttrs();
return editorInfo.actionId != 0
? editorInfo.actionId
: editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION;
}
}));
CriteriaHelper.pollUiThread(() -> {
EditorInfo editorInfo = mConnectionFactory.getOutAttrs();
int actualAction = editorInfo.actionId != 0
? editorInfo.actionId
: editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION;
Criteria.checkThat(actualAction, Matchers.is(expectedAction));
});
}
void performEditorAction(final int action) {
......@@ -300,26 +292,25 @@ class ImeActivityTestRule extends ContentShellActivityTestRule {
void assertWaitForKeyboardStatus(final boolean show) {
CriteriaHelper.pollUiThread(() -> {
if (show) {
Assert.assertNotNull(getInputConnection());
Criteria.checkThat(getInputConnection(), Matchers.notNullValue());
}
Assert.assertEquals(show, mInputMethodManagerWrapper.isShowWithoutHideOutstanding());
Criteria.checkThat(
mInputMethodManagerWrapper.isShowWithoutHideOutstanding(), Matchers.is(show));
});
}
void assertWaitForSelectActionBarStatus(final boolean show) {
CriteriaHelper.pollUiThread(Criteria.equals(show, new Callable<Boolean>() {
@Override
public Boolean call() {
return mSelectionPopupController.isSelectActionBarShowing();
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(
mSelectionPopupController.isSelectActionBarShowing(), Matchers.is(show));
});
}
void waitAndVerifyUpdateSelection(final int index, final int selectionStart,
final int selectionEnd, final int compositionStart, final int compositionEnd) {
final List<Pair<Range, Range>> states = mInputMethodManagerWrapper.getUpdateSelectionList();
CriteriaHelper.pollUiThread(
() -> Assert.assertThat(states.size(), Matchers.greaterThan(index)));
() -> Criteria.checkThat(states.size(), Matchers.greaterThan(index)));
Pair<Range, Range> selection = states.get(index);
Assert.assertEquals("Mismatched selection start", selectionStart, selection.first.start());
Assert.assertEquals("Mismatched selection end", selectionEnd, selection.first.end());
......@@ -337,9 +328,9 @@ class ImeActivityTestRule extends ContentShellActivityTestRule {
ClipboardManager clipboardManager =
(ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = clipboardManager.getPrimaryClip();
Assert.assertNotNull(clip);
Assert.assertEquals(1, clip.getItemCount());
Assert.assertEquals(expectedContents, clip.getItemAt(0).getText());
Criteria.checkThat(clip, Matchers.notNullValue());
Criteria.checkThat(clip.getItemCount(), Matchers.is(1));
Criteria.checkThat(clip.getItemAt(0).getText(), Matchers.is(expectedContents));
});
}
......
......@@ -11,6 +11,7 @@ import android.view.inputmethod.InputConnection;
import androidx.test.filters.MediumTest;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
......@@ -20,6 +21,7 @@ import org.junit.runner.RunWith;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.MinAndroidSdkLevel;
import org.chromium.content_public.browser.test.ContentJUnit4ClassRunner;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
......@@ -94,11 +96,11 @@ public class ImeLollipopTest {
CriteriaHelper.pollUiThread(() -> {
CursorAnchorInfo info = mRule.getInputMethodManagerWrapper().getLastCursorAnchorInfo();
if (info != null) {
Assert.assertNotNull(info.getComposingText());
Criteria.checkThat(info.getComposingText(), Matchers.notNullValue());
}
String actual = (info == null ? "" : info.getComposingText().toString());
Assert.assertEquals(expected, actual);
Criteria.checkThat(actual, Matchers.is(expected));
});
}
}
......@@ -21,6 +21,7 @@ import android.view.inputmethod.EditorInfo;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
......@@ -35,6 +36,7 @@ import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.test.ContentJUnit4ClassRunner;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.CriteriaNotSatisfiedException;
import org.chromium.content_public.browser.test.util.DOMUtils;
import org.chromium.content_public.browser.test.util.JavaScriptUtils;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
......@@ -511,7 +513,8 @@ public class ImeTest {
// When input connection is null, we still need to set flags to prevent InputMethodService
// from entering fullscreen mode and from opening custom UI.
CriteriaHelper.pollUiThread(Criteria.equals(null, mRule::getInputConnection));
CriteriaHelper.pollUiThread(
() -> Criteria.checkThat(mRule.getInputConnection(), Matchers.nullValue()));
Assert.assertTrue(
(mRule.getConnectionFactory().getOutAttrs().imeOptions
& (EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_FLAG_NO_EXTRACT_UI))
......@@ -666,12 +669,10 @@ public class ImeTest {
// hide status of IME, so we will just check whether showIme() has been triggered.
DOMUtils.longPressNode(mRule.getWebContents(), "input_text");
final int newCount = showCount + 2;
CriteriaHelper.pollUiThread(Criteria.equals(newCount, new Callable<Integer>() {
@Override
public Integer call() {
return mRule.getInputMethodManagerWrapper().getShowSoftInputCounter();
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(mRule.getInputMethodManagerWrapper().getShowSoftInputCounter(),
Matchers.is(newCount));
});
}
private void reloadPage() throws Exception {
......@@ -1228,33 +1229,27 @@ public class ImeTest {
mRule.focusElement("textarea");
// focusElement() calls showSoftInput().
CriteriaHelper.pollUiThread(Criteria.equals(showCount + 1, new Callable<Integer>() {
@Override
public Integer call() {
return mRule.getInputMethodManagerWrapper().getShowSoftInputCounter();
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(mRule.getInputMethodManagerWrapper().getShowSoftInputCounter(),
Matchers.is(showCount + 1));
});
// DPAD_CENTER should cause keyboard to appear on keyup.
mRule.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER));
// Should not have called showSoftInput() on keydown.
CriteriaHelper.pollUiThread(Criteria.equals(showCount + 1, new Callable<Integer>() {
@Override
public Integer call() {
return mRule.getInputMethodManagerWrapper().getShowSoftInputCounter();
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(mRule.getInputMethodManagerWrapper().getShowSoftInputCounter(),
Matchers.is(showCount + 1));
});
mRule.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER));
// Should have called showSoftInput() on keyup.
CriteriaHelper.pollUiThread(Criteria.equals(showCount + 2, new Callable<Integer>() {
@Override
public Integer call() {
return mRule.getInputMethodManagerWrapper().getShowSoftInputCounter();
}
}));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(mRule.getInputMethodManagerWrapper().getShowSoftInputCounter(),
Matchers.is(showCount + 2));
});
}
@Test
......@@ -1289,13 +1284,17 @@ public class ImeTest {
DOMUtils.longPressNode(mRule.getWebContents(), "input_text");
CriteriaHelper.pollUiThread(() -> {
Assert.assertTrue(mRule.getSelectionPopupController().isPastePopupShowing());
Assert.assertTrue(mRule.getSelectionPopupController().isInsertionForTesting());
Criteria.checkThat(
mRule.getSelectionPopupController().isPastePopupShowing(), Matchers.is(true));
Criteria.checkThat(
mRule.getSelectionPopupController().isInsertionForTesting(), Matchers.is(true));
});
mRule.setComposingText("h", 1);
CriteriaHelper.pollUiThread(Criteria.equals(
false, () -> mRule.getSelectionPopupController().isPastePopupShowing()));
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(
mRule.getSelectionPopupController().isPastePopupShowing(), Matchers.is(false));
});
Assert.assertFalse(mRule.getSelectionPopupController().isInsertionForTesting());
}
......@@ -1621,9 +1620,10 @@ public class ImeTest {
// necessarily have been committed yet.
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertEquals("hello world", DOMUtils.getNodeContents(webContents, "div"));
Criteria.checkThat(
DOMUtils.getNodeContents(webContents, "div"), Matchers.is("hello world"));
} catch (TimeoutException e) {
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
......
......@@ -8,7 +8,7 @@ import android.support.test.InstrumentationRegistry;
import androidx.test.filters.LargeTest;
import org.junit.Assert;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
......@@ -18,6 +18,7 @@ import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.DOMUtils;
import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer;
......@@ -53,7 +54,8 @@ public class SelectPopupTest {
private void verifyPopupShownState(boolean shown) {
CriteriaHelper.pollUiThread(() -> {
Assert.assertEquals(shown, mActivityTestRule.getSelectPopup().isVisibleForTesting());
Criteria.checkThat(
mActivityTestRule.getSelectPopup().isVisibleForTesting(), Matchers.is(shown));
});
}
......
......@@ -13,6 +13,7 @@ import android.widget.TextView;
import androidx.test.filters.LargeTest;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
......@@ -23,7 +24,9 @@ import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.content.R;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.test.ContentJUnit4ClassRunner;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.CriteriaNotSatisfiedException;
import org.chromium.content_public.browser.test.util.DOMUtils;
import org.chromium.content_public.browser.test.util.JavaScriptUtils;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
......@@ -70,9 +73,10 @@ public class TextSuggestionMenuTest {
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertEquals("", DOMUtils.getNodeContents(webContents, "div"));
Criteria.checkThat(
DOMUtils.getNodeContents(webContents, "div"), Matchers.isEmptyString());
} catch (TimeoutException e) {
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
......@@ -96,9 +100,10 @@ public class TextSuggestionMenuTest {
// necessarily have been committed yet.
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertEquals("hello", DOMUtils.getNodeContents(webContents, "div"));
Criteria.checkThat(
DOMUtils.getNodeContents(webContents, "div"), Matchers.is("hello"));
} catch (TimeoutException e) {
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
......@@ -118,9 +123,10 @@ public class TextSuggestionMenuTest {
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertEquals("", DOMUtils.getNodeContents(mRule.getWebContents(), "div"));
Criteria.checkThat(DOMUtils.getNodeContents(mRule.getWebContents(), "div"),
Matchers.isEmptyString());
} catch (TimeoutException e) {
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
......@@ -164,9 +170,10 @@ public class TextSuggestionMenuTest {
// Wait for renderer to acknowledge commitText().
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertEquals("hello world", DOMUtils.getNodeContents(webContents, "div"));
Criteria.checkThat(
DOMUtils.getNodeContents(webContents, "div"), Matchers.is("hello world"));
} catch (TimeoutException e) {
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
......@@ -189,10 +196,10 @@ public class TextSuggestionMenuTest {
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertEquals(
"suggestion3", DOMUtils.getNodeContents(mRule.getWebContents(), "div"));
Criteria.checkThat(DOMUtils.getNodeContents(mRule.getWebContents(), "div"),
Matchers.is("suggestion3"));
} catch (TimeoutException e) {
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
......@@ -229,10 +236,10 @@ public class TextSuggestionMenuTest {
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertEquals(
"replacement", DOMUtils.getNodeContents(mRule.getWebContents(), "div"));
Criteria.checkThat(DOMUtils.getNodeContents(mRule.getWebContents(), "div"),
Matchers.is("replacement"));
} catch (TimeoutException e) {
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
......@@ -396,12 +403,13 @@ public class TextSuggestionMenuTest {
private void waitForMenuToShow(WebContents webContents) {
CriteriaHelper.pollUiThread(() -> {
View deleteButton = getDeleteButton(webContents);
Assert.assertNotNull(deleteButton);
Criteria.checkThat(deleteButton, Matchers.notNullValue());
// suggestionsPopupWindow.isShowing() returns true, the delete button hasn't been
// measured yet and getWidth()/getHeight() return 0. This causes the menu button
// click to instead fall on the "Add to dictionary" button. So we have to check that
// this isn't happening.
Assert.assertNotEquals(0, deleteButton.getWidth());
Criteria.checkThat(deleteButton.getWidth(), Matchers.not(0));
});
}
......@@ -409,11 +417,11 @@ public class TextSuggestionMenuTest {
CriteriaHelper.pollUiThread(() -> {
SuggestionsPopupWindow suggestionsPopupWindow =
getTextSuggestionHost(webContents).getTextSuggestionsPopupWindowForTesting();
Assert.assertNull(suggestionsPopupWindow);
Criteria.checkThat(suggestionsPopupWindow, Matchers.nullValue());
SuggestionsPopupWindow spellCheckPopupWindow =
getTextSuggestionHost(webContents).getSpellCheckPopupWindowForTesting();
Assert.assertNull(spellCheckPopupWindow);
Criteria.checkThat(spellCheckPopupWindow, Matchers.nullValue());
});
}
......
......@@ -25,6 +25,7 @@ import org.chromium.base.task.PostTask;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.CriteriaNotSatisfiedException;
import java.io.PrintWriter;
import java.io.StringWriter;
......@@ -245,7 +246,7 @@ public class CriteriaHelperTest {
}, 0, DEFAULT_POLLING_INTERVAL);
}
private String getStackTrace(AssertionError e) {
private String getStackTrace(Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
return sw.toString();
......@@ -255,7 +256,9 @@ public class CriteriaHelperTest {
@MediumTest
public void testStack_Runnable_UiThread() {
try {
CriteriaHelper.pollUiThread((Runnable) Assert::fail, 0, DEFAULT_POLLING_INTERVAL);
CriteriaHelper.pollUiThread(() -> {
throw new CriteriaNotSatisfiedException("test");
}, 0, DEFAULT_POLLING_INTERVAL);
} catch (AssertionError e) {
assertThat(getStackTrace(e),
containsString("CriteriaHelperTest.testStack_Runnable_UiThread("));
......@@ -268,8 +271,9 @@ public class CriteriaHelperTest {
@MediumTest
public void testStack_Runnable_InstrumentationThread() {
try {
CriteriaHelper.pollInstrumentationThread(
(Runnable) Assert::fail, 0, DEFAULT_POLLING_INTERVAL);
CriteriaHelper.pollInstrumentationThread(() -> {
throw new CriteriaNotSatisfiedException("test");
}, 0, DEFAULT_POLLING_INTERVAL);
} catch (AssertionError e) {
assertThat(getStackTrace(e),
containsString("CriteriaHelperTest.testStack_Runnable_InstrumentationThread("));
......
......@@ -40,6 +40,7 @@ android_library("content_java_test_support") {
"javatests/src/org/chromium/content_public/browser/test/util/Coordinates.java",
"javatests/src/org/chromium/content_public/browser/test/util/Criteria.java",
"javatests/src/org/chromium/content_public/browser/test/util/CriteriaHelper.java",
"javatests/src/org/chromium/content_public/browser/test/util/CriteriaNotSatisfiedException.java",
"javatests/src/org/chromium/content_public/browser/test/util/DOMUtils.java",
"javatests/src/org/chromium/content_public/browser/test/util/DomAutomationController.java",
"javatests/src/org/chromium/content_public/browser/test/util/HistoryUtils.java",
......
......@@ -4,7 +4,12 @@
package org.chromium.content_public.browser.test.util;
import android.text.TextUtils;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.StringDescription;
import java.util.concurrent.Callable;
......@@ -56,25 +61,45 @@ public abstract class Criteria {
}
/**
* Constructs a Criteria that will determine the equality of two items.
*
* <p>
* <pre>
* Sample Usage:
* <code>
* public void waitForTabTitle(final Tab tab, String title) {
* CriteriaHelper.pollUiThread(Criteria.equals(title, () -> tab.getTitle()));
* }
* </code>
* </pre>
*
* @param <T> The type of value whose equality will be tested.
* @param expectedValue The value that is expected to determine the success of the criteria.
* @param actualValueCallable A {@link Callable} that provides a way of getting the current
* actual value.
* @return A Criteria that will check the equality of the passed in data.
* Do not use. Use checkThat(...) instead. This will be removed as soon as all clients
* are migrated.
*/
public static <T> Criteria equals(T expectedValue, Callable<T> actualValueCallable) {
return new MatcherCriteria<>(actualValueCallable, Matchers.equalTo(expectedValue));
}
/**
* Validates that a expected condition has been met, and throws an
* {@link CriteriaNotSatisfiedException} if not.
*
* @param <T> The type of value whose being tested.
* @param actual The actual value being tested.
* @param matcher Determines if the current value matches the desired expectation.
*/
public static <T> void checkThat(T actual, Matcher<T> matcher) {
checkThat("", actual, matcher);
}
/**
* Validates that a expected condition has been met, and throws an
* {@link CriteriaNotSatisfiedException} if not.
*
* @param <T> The type of value whose being tested.
* @param reason Additional reason description for the failure.
* @param actual The actual value being tested.
* @param matcher Determines if the current value matches the desired expectation.
*/
public static <T> void checkThat(String reason, T actual, Matcher<T> matcher) {
if (matcher.matches(actual)) return;
Description description = new StringDescription();
if (!TextUtils.isEmpty(reason)) {
description.appendText(reason).appendText(System.lineSeparator());
}
description.appendText("Expected: ")
.appendDescriptionOf(matcher)
.appendText(System.lineSeparator())
.appendText(" but: ");
matcher.describeMismatch(actual, description);
throw new CriteriaNotSatisfiedException(description.toString());
}
}
......@@ -4,7 +4,7 @@
package org.chromium.content_public.browser.test.util;
import org.junit.Assert;
import org.hamcrest.Matchers;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.TimeoutTimer;
......@@ -29,9 +29,10 @@ import java.util.concurrent.atomic.AtomicReference;
* <code>
* private void verifyMenuShown() {
* CriteriaHelper.pollUiThread(() -> {
* Assert.assertNotNull("App menu was null", getActivity().getAppMenuHandler());
* Assert.assertTrue("App menu was not shown",
* getActivity().getAppMenuHandler().isAppMenuShowing());
* Criteria.checkThat("App menu was null", getActivity().getAppMenuHandler(),
* Matchers.notNullValue());
* Criteria.checkThat("App menu was not shown",
* getActivity().getAppMenuHandler().isAppMenuShowing(), Matchers.is(true));
* });
* }
* </code>
......@@ -75,12 +76,16 @@ public class CriteriaHelper {
*/
public static void pollInstrumentationThread(
Runnable criteria, long maxTimeoutMs, long checkIntervalMs) {
AssertionError assertionError;
Throwable throwable;
try {
criteria.run();
return;
} catch (CriteriaNotSatisfiedException cnse) {
throwable = cnse;
} catch (AssertionError ae) {
assertionError = ae;
// TODO(tedchoc): Remove support for this once all clients move over to
// CriteriaNotSatisfiedException.
throwable = ae;
}
TimeoutTimer timer = new TimeoutTimer(maxTimeoutMs);
while (!timer.isTimedOut()) {
......@@ -93,11 +98,21 @@ public class CriteriaHelper {
try {
criteria.run();
return;
} catch (CriteriaNotSatisfiedException cnse) {
throwable = cnse;
} catch (AssertionError ae) {
assertionError = ae;
// TODO(tedchoc): Remove support for this once all clients move over to
// CriteriaNotSatisfiedException.
throwable = ae;
}
}
throw assertionError;
if (throwable instanceof CriteriaNotSatisfiedException) {
throw new AssertionError(throwable);
} else if (throwable instanceof AssertionError) {
throw(AssertionError) throwable;
}
assert false : "Invalid throwable";
throw new RuntimeException(throwable);
}
/**
......@@ -120,7 +135,7 @@ public class CriteriaHelper {
*/
public static void pollInstrumentationThread(
Criteria criteria, long maxTimeoutMs, long checkIntervalMs) {
pollInstrumentationThread(toAssertionRunnable(criteria), maxTimeoutMs, checkIntervalMs);
pollInstrumentationThread(toNotSatisfiedRunnable(criteria), maxTimeoutMs, checkIntervalMs);
}
/**
......@@ -147,7 +162,7 @@ public class CriteriaHelper {
public static void pollInstrumentationThread(final Callable<Boolean> criteria,
String failureReason, long maxTimeoutMs, long checkIntervalMs) {
pollInstrumentationThread(
toAssertionRunnable(criteria, failureReason), maxTimeoutMs, checkIntervalMs);
toNotSatisfiedRunnable(criteria, failureReason), maxTimeoutMs, checkIntervalMs);
}
/**
......@@ -221,8 +236,12 @@ public class CriteriaHelper {
});
Throwable throwable = throwableRef.get();
if (throwable != null) {
if (throwable instanceof AssertionError) {
throw new AssertionError(throwable);
if (throwable instanceof CriteriaNotSatisfiedException) {
throw new CriteriaNotSatisfiedException(throwable);
} else if (throwable instanceof AssertionError) {
// TODO(tedchoc): Remove support for this once all clients move over to
// CriteriaNotSatisfiedException.
throw new CriteriaNotSatisfiedException(throwable);
} else if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
} else {
......@@ -248,7 +267,7 @@ public class CriteriaHelper {
*/
public static void pollUiThread(
final Criteria criteria, long maxTimeoutMs, long checkIntervalMs) {
pollUiThread(toAssertionRunnable(criteria), maxTimeoutMs, checkIntervalMs);
pollUiThread(toNotSatisfiedRunnable(criteria), maxTimeoutMs, checkIntervalMs);
}
/**
......@@ -272,7 +291,8 @@ public class CriteriaHelper {
*/
public static void pollUiThread(final Callable<Boolean> criteria, String failureReason,
long maxTimeoutMs, long checkIntervalMs) {
pollUiThread(toAssertionRunnable(criteria, failureReason), maxTimeoutMs, checkIntervalMs);
pollUiThread(
toNotSatisfiedRunnable(criteria, failureReason), maxTimeoutMs, checkIntervalMs);
}
/**
......@@ -314,7 +334,8 @@ public class CriteriaHelper {
pollUiThread(criteria, null);
}
private static Runnable toAssertionRunnable(Callable<Boolean> criteria, String failureReason) {
private static Runnable toNotSatisfiedRunnable(
Callable<Boolean> criteria, String failureReason) {
return () -> {
boolean isSatisfied;
try {
......@@ -324,14 +345,14 @@ public class CriteriaHelper {
} catch (Exception e) {
throw new RuntimeException(e);
}
Assert.assertTrue(failureReason, isSatisfied);
Criteria.checkThat(failureReason, isSatisfied, Matchers.is(true));
};
}
private static Runnable toAssertionRunnable(Criteria criteria) {
private static Runnable toNotSatisfiedRunnable(Criteria criteria) {
return () -> {
boolean satisfied = criteria.isSatisfied();
Assert.assertTrue(criteria.getFailureReason(), satisfied);
Criteria.checkThat(criteria.getFailureReason(), satisfied, Matchers.is(true));
};
}
}
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content_public.browser.test.util;
/**
* Exception indicating that a Criteria did not match expectations.
*/
public class CriteriaNotSatisfiedException extends AssertionError {
/**
* @param msg The reason the criteria was not met.
*/
public CriteriaNotSatisfiedException(String msg) {
super(msg);
}
/**
* @param cause The underlying exception that prevented the Criteria.
*/
public CriteriaNotSatisfiedException(Throwable cause) {
super(cause);
}
}
......@@ -106,12 +106,12 @@ public class DOMUtils {
CriteriaHelper.pollInstrumentationThread(() -> {
try {
// Playback can't be reliably detected until current time moves forward.
Assert.assertFalse(DOMUtils.isMediaPaused(webContents, id));
Assert.assertThat(
Criteria.checkThat(DOMUtils.isMediaPaused(webContents, id), Matchers.is(false));
Criteria.checkThat(
DOMUtils.getCurrentTime(webContents, id), Matchers.greaterThan(0d));
} catch (TimeoutException e) {
// Intentionally do nothing
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
}, MEDIA_TIMEOUT_MILLISECONDS, CriteriaHelper.DEFAULT_POLLING_INTERVAL);
}
......@@ -124,11 +124,11 @@ public class DOMUtils {
public static void waitForMediaPauseBeforeEnd(final WebContents webContents, final String id) {
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertTrue(DOMUtils.isMediaPaused(webContents, id));
Assert.assertFalse(DOMUtils.isMediaEnded(webContents, id));
Criteria.checkThat(DOMUtils.isMediaPaused(webContents, id), Matchers.is(true));
Criteria.checkThat(DOMUtils.isMediaEnded(webContents, id), Matchers.is(false));
} catch (TimeoutException e) {
// Intentionally do nothing
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
}
......@@ -462,10 +462,11 @@ public class DOMUtils {
final WebContents webContents, final String nodeId) {
CriteriaHelper.pollInstrumentationThread(() -> {
try {
Assert.assertFalse(DOMUtils.getNodeBounds(webContents, nodeId).isEmpty());
Criteria.checkThat(
DOMUtils.getNodeBounds(webContents, nodeId).isEmpty(), Matchers.is(false));
} catch (TimeoutException e) {
// Intentionally do nothing
Assert.fail(e.toString());
throw new CriteriaNotSatisfiedException(e);
}
});
}
......
......@@ -246,9 +246,9 @@ public class ContentShellActivityTestRule extends ActivityTestRule<ContentShellA
// Wait for the Content Shell to be initialized.
CriteriaHelper.pollUiThread(() -> {
Shell shell = getActivity().getActiveShell();
Assert.assertNotNull("Shell is null.", shell);
Assert.assertFalse("Shell is still loading.", shell.isLoading());
Assert.assertThat("Shell's URL is empty or null.",
Criteria.checkThat("Shell is null.", shell, Matchers.notNullValue());
Criteria.checkThat("Shell is still loading.", shell.isLoading(), Matchers.is(false));
Criteria.checkThat("Shell's URL is empty or null.",
shell.getWebContents().getLastCommittedUrl(),
Matchers.not(Matchers.isEmptyOrNullString()));
}, WAIT_FOR_ACTIVE_SHELL_LOADING_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL);
......@@ -317,13 +317,9 @@ public class ContentShellActivityTestRule extends ActivityTestRule<ContentShellA
*/
public void assertWaitForPageScaleFactorMatch(float expectedScale) {
final RenderCoordinatesImpl coord = getRenderCoordinates();
CriteriaHelper.pollInstrumentationThread(
Criteria.equals(expectedScale, new Callable<Float>() {
@Override
public Float call() {
return coord.getPageScaleFactor();
}
}));
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(coord.getPageScaleFactor(), Matchers.is(expectedScale));
});
}
/**
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment