Commit 157ea6e1 authored by Yoland Yan's avatar Yoland Yan Committed by Commit Bot

Convert misc instrumentation tests to JUnit4

This CL converts misc instrumentation tests to JUnit4. For more on
JUnit4 migration, please check src/testing/android/docs/junit4.md

Bug: 640116
Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel
Change-Id: I8ea44992b48709550855459b9ff4f20bb3eec15a
Reviewed-on: https://chromium-review.googlesource.com/627672
Commit-Queue: Yoland Yan <yolandyan@chromium.org>
Reviewed-by: default avatarTed Choc <tedchoc@chromium.org>
Reviewed-by: default avatarAndrei Kapishnikov <kapishnikov@chromium.org>
Reviewed-by: default avatarTheresa <twellington@chromium.org>
Cr-Commit-Position: refs/heads/master@{#501470}
parent 3548b822
...@@ -13,14 +13,25 @@ import android.content.Intent; ...@@ -13,14 +13,25 @@ import android.content.Intent;
import android.net.Uri; import android.net.Uri;
import android.os.Parcel; import android.os.Parcel;
import android.os.Parcelable; import android.os.Parcelable;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationState;
import org.chromium.base.ApplicationStatus; import org.chromium.base.ApplicationStatus;
import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.RetryOnFailure; import org.chromium.base.test.util.RetryOnFailure;
import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.test.ChromeActivityTestCaseBase; import org.chromium.chrome.test.ChromeActivityTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content.browser.test.util.CriteriaHelper;
...@@ -33,22 +44,27 @@ import java.util.concurrent.atomic.AtomicReference; ...@@ -33,22 +44,27 @@ import java.util.concurrent.atomic.AtomicReference;
/** /**
* Tests for launching Chrome. * Tests for launching Chrome.
*/ */
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({
ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE,
ChromeActivityTestRule.DISABLE_NETWORK_PREDICTION_FLAG,
})
@RetryOnFailure @RetryOnFailure
public class LauncherActivityTest extends ChromeActivityTestCaseBase<ChromeActivity> { public class LauncherActivityTest {
@SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
@Rule
public ChromeActivityTestRule<ChromeActivity> mActivityTestRule =
new ChromeActivityTestRule<>(ChromeActivity.class);
private Context mContext; private Context mContext;
private static final long DEVICE_STARTUP_TIMEOUT_MS = scaleTimeout(15000); private static final long DEVICE_STARTUP_TIMEOUT_MS = scaleTimeout(15000);
public LauncherActivityTest() { @Before
super(ChromeActivity.class);
}
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setUp(); mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
mContext = getInstrumentation().getTargetContext();
} }
@Test
@SmallTest @SmallTest
public void testLaunchWithUrlNoScheme() { public void testLaunchWithUrlNoScheme() {
// Prepare intent // Prepare intent
...@@ -59,9 +75,10 @@ public class LauncherActivityTest extends ChromeActivityTestCaseBase<ChromeActiv ...@@ -59,9 +75,10 @@ public class LauncherActivityTest extends ChromeActivityTestCaseBase<ChromeActiv
final Activity startedActivity = tryLaunchingChrome(intent); final Activity startedActivity = tryLaunchingChrome(intent);
final Intent activityIntent = startedActivity.getIntent(); final Intent activityIntent = startedActivity.getIntent();
assertEquals(intentUrl, activityIntent.getDataString()); Assert.assertEquals(intentUrl, activityIntent.getDataString());
} }
@Test
@SmallTest @SmallTest
public void testDoesNotCrashWithBadParcel() { public void testDoesNotCrashWithBadParcel() {
// Prepare bad intent // Prepare bad intent
...@@ -78,10 +95,12 @@ public class LauncherActivityTest extends ChromeActivityTestCaseBase<ChromeActiv ...@@ -78,10 +95,12 @@ public class LauncherActivityTest extends ChromeActivityTestCaseBase<ChromeActiv
final Activity startedActivity = tryLaunchingChrome(intent); final Activity startedActivity = tryLaunchingChrome(intent);
final Intent activityIntent = startedActivity.getIntent(); final Intent activityIntent = startedActivity.getIntent();
assertEquals("Data was not preserved", intent.getData(), activityIntent.getData()); Assert.assertEquals("Data was not preserved", intent.getData(), activityIntent.getData());
assertEquals("Action was not preserved", intent.getAction(), activityIntent.getAction()); Assert.assertEquals(
"Action was not preserved", intent.getAction(), activityIntent.getAction());
} }
@Test
@SmallTest @SmallTest
public void testDoesNotCrashWithNoUriInViewIntent() { public void testDoesNotCrashWithNoUriInViewIntent() {
// Prepare intent // Prepare intent
...@@ -128,10 +147,6 @@ public class LauncherActivityTest extends ChromeActivityTestCaseBase<ChromeActiv ...@@ -128,10 +147,6 @@ public class LauncherActivityTest extends ChromeActivityTestCaseBase<ChromeActiv
return launchedActivity.get(); return launchedActivity.get();
} }
@Override
public void startMainActivity() throws InterruptedException {
}
/** /**
* This Parcelable does not adhere to the form standards of a well formed Parcelable and will * This Parcelable does not adhere to the form standards of a well formed Parcelable and will
* thus cause a BadParcelableException. The lint suppression is needed since it detects that * thus cause a BadParcelableException. The lint suppression is needed since it detects that
......
...@@ -6,22 +6,27 @@ package org.chromium.chrome.browser.gcore; ...@@ -6,22 +6,27 @@ package org.chromium.chrome.browser.gcore;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import junit.framework.TestCase; import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.Feature;
import org.chromium.chrome.test.gcore.MockChromeGoogleApiClient; import org.chromium.chrome.test.gcore.MockChromeGoogleApiClient;
/** Tests for {@link ConnectedTask} */ /** Tests for {@link ConnectedTask} */
public class MockConnectedTaskTest extends TestCase { @RunWith(BaseJUnit4ClassRunner.class)
public class MockConnectedTaskTest {
private MockChromeGoogleApiClient mClient; private MockChromeGoogleApiClient mClient;
private MockConnectedTask<MockChromeGoogleApiClient> mTask; private MockConnectedTask<MockChromeGoogleApiClient> mTask;
@Override @Before
protected void setUp() throws Exception { public void setUp() throws Exception {
mClient = new MockChromeGoogleApiClient(); mClient = new MockChromeGoogleApiClient();
mTask = new MockConnectedTask<>(mClient); mTask = new MockConnectedTask<>(mClient);
} }
@Test
@SmallTest @SmallTest
@Feature({"GCore"}) @Feature({"GCore"})
public void testConnectionSuccess() { public void testConnectionSuccess() {
...@@ -38,6 +43,7 @@ public class MockConnectedTaskTest extends TestCase { ...@@ -38,6 +43,7 @@ public class MockConnectedTaskTest extends TestCase {
mClient.assertNoOtherMethodsCalled(); mClient.assertNoOtherMethodsCalled();
} }
@Test
@SmallTest @SmallTest
@Feature({"GCore"}) @Feature({"GCore"})
public void testConnectionFailureWithGooglePlayServicesAvailable() { public void testConnectionFailureWithGooglePlayServicesAvailable() {
...@@ -54,6 +60,7 @@ public class MockConnectedTaskTest extends TestCase { ...@@ -54,6 +60,7 @@ public class MockConnectedTaskTest extends TestCase {
mClient.assertNoOtherMethodsCalled(); mClient.assertNoOtherMethodsCalled();
} }
@Test
@SmallTest @SmallTest
@Feature({"GCore"}) @Feature({"GCore"})
public void testConnectionFailureWithGooglePlayServicesUnavailable() { public void testConnectionFailureWithGooglePlayServicesUnavailable() {
...@@ -70,6 +77,7 @@ public class MockConnectedTaskTest extends TestCase { ...@@ -70,6 +77,7 @@ public class MockConnectedTaskTest extends TestCase {
mClient.assertNoOtherMethodsCalled(); mClient.assertNoOtherMethodsCalled();
} }
@Test
@SmallTest @SmallTest
@Feature({"GCore"}) @Feature({"GCore"})
public void testRetryLimit() { public void testRetryLimit() {
......
...@@ -8,10 +8,17 @@ import android.support.test.filters.LargeTest; ...@@ -8,10 +8,17 @@ import android.support.test.filters.LargeTest;
import android.view.View; import android.view.View;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.RetryOnFailure; import org.chromium.base.test.util.RetryOnFailure;
import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.test.ChromeActivityTestCaseBase; import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.test.ChromeActivityTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.content.R; import org.chromium.content.R;
import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.ContentViewCore;
import org.chromium.content.browser.input.SuggestionsPopupWindow; import org.chromium.content.browser.input.SuggestionsPopupWindow;
...@@ -27,24 +34,31 @@ import java.util.concurrent.TimeoutException; ...@@ -27,24 +34,31 @@ import java.util.concurrent.TimeoutException;
/** /**
* Integration tests for the text suggestion menu. * Integration tests for the text suggestion menu.
*/ */
public class TextSuggestionMenuTest extends ChromeActivityTestCaseBase<ChromeActivity> { @RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({
ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE,
ChromeActivityTestRule.DISABLE_NETWORK_PREDICTION_FLAG,
})
public class TextSuggestionMenuTest {
@Rule
public ChromeActivityTestRule<ChromeActivity> mActivityTestRule =
new ChromeActivityTestRule<>(ChromeActivity.class);
private static final String URL = private static final String URL =
"data:text/html, <div contenteditable id=\"div\">iuvwneaoanls</div>"; "data:text/html, <div contenteditable id=\"div\">iuvwneaoanls</div>";
public TextSuggestionMenuTest() { @Before
super(ChromeActivity.class); public void setUp() throws InterruptedException {
} mActivityTestRule.startMainActivityOnBlankPage();
@Override
public void startMainActivity() throws InterruptedException {
startMainActivityOnBlankPage();
} }
@Test
@LargeTest @LargeTest
@RetryOnFailure @RetryOnFailure
public void testDeleteMisspelledWord() throws InterruptedException, TimeoutException { public void testDeleteMisspelledWord() throws InterruptedException, TimeoutException {
loadUrl(URL); mActivityTestRule.loadUrl(URL);
final ContentViewCore cvc = getActivity().getActivityTab().getContentViewCore(); final ContentViewCore cvc =
mActivityTestRule.getActivity().getActivityTab().getContentViewCore();
WebContents webContents = cvc.getWebContents(); WebContents webContents = cvc.getWebContents();
// The spell checker is called asynchronously, in an idle-time callback. By waiting for an // The spell checker is called asynchronously, in an idle-time callback. By waiting for an
......
...@@ -7,41 +7,57 @@ package org.chromium.chrome.browser.metrics; ...@@ -7,41 +7,57 @@ package org.chromium.chrome.browser.metrics;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.RetryOnFailure; import org.chromium.base.test.util.RetryOnFailure;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.test.ChromeTabbedActivityTestBase; import org.chromium.chrome.test.ChromeActivityTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.ChromeTabbedActivityTestRule;
import org.chromium.content.browser.test.util.JavaScriptUtils; import org.chromium.content.browser.test.util.JavaScriptUtils;
import org.chromium.ui.base.PageTransition; import org.chromium.ui.base.PageTransition;
/** /**
* Tests for UKM monitoring of incognito activity. * Tests for UKM monitoring of incognito activity.
*/ */
@CommandLineFlags.Add({"force-enable-metrics-reporting"}) @RunWith(ChromeJUnit4ClassRunner.class)
public class UkmIncognitoTest extends ChromeTabbedActivityTestBase { @CommandLineFlags.Add({
ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE,
ChromeActivityTestRule.DISABLE_NETWORK_PREDICTION_FLAG,
"force-enable-metrics-reporting"})
public class UkmIncognitoTest {
@Rule
public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule();
private static final String DEBUG_PAGE = "chrome://ukm"; private static final String DEBUG_PAGE = "chrome://ukm";
@Override @Before
public void startMainActivity() throws InterruptedException { public void setUp() throws InterruptedException {
startMainActivityOnBlankPage(); mActivityTestRule.startMainActivityOnBlankPage();
} }
public String getUkmState(Tab normalTab) throws Exception { public String getUkmState(Tab normalTab) throws Exception {
loadUrlInTab(DEBUG_PAGE, PageTransition.TYPED | PageTransition.FROM_ADDRESS_BAR, normalTab); mActivityTestRule.loadUrlInTab(
DEBUG_PAGE, PageTransition.TYPED | PageTransition.FROM_ADDRESS_BAR, normalTab);
return JavaScriptUtils.executeJavaScriptAndWaitForResult( return JavaScriptUtils.executeJavaScriptAndWaitForResult(
normalTab.getContentViewCore().getWebContents(), normalTab.getContentViewCore().getWebContents(),
"document.getElementById('state').textContent"); "document.getElementById('state').textContent");
} }
@Test
@SmallTest @SmallTest
@RetryOnFailure @RetryOnFailure
public void testUkmIncognito() throws Exception { public void testUkmIncognito() throws Exception {
Tab normalTab = getActivity().getActivityTab(); Tab normalTab = mActivityTestRule.getActivity().getActivityTab();
Assert.assertEquals("UKM State:", "\"True\"", getUkmState(normalTab)); Assert.assertEquals("UKM State:", "\"True\"", getUkmState(normalTab));
newIncognitoTabFromMenu(); mActivityTestRule.newIncognitoTabFromMenu();
Assert.assertEquals("UKM State:", "\"False\"", getUkmState(normalTab)); Assert.assertEquals("UKM State:", "\"False\"", getUkmState(normalTab));
} }
......
...@@ -6,32 +6,41 @@ package org.chromium.chrome.browser.omnibox; ...@@ -6,32 +6,41 @@ package org.chromium.chrome.browser.omnibox;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import junit.framework.TestCase; import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
public class SuggestionAnswerTest extends TestCase { import org.chromium.base.test.BaseJUnit4ClassRunner;
@RunWith(BaseJUnit4ClassRunner.class)
public class SuggestionAnswerTest {
@Test
@SmallTest @SmallTest
public void testMalformedJsonReturnsNull() { public void testMalformedJsonReturnsNull() {
String json = "} malformed json {"; String json = "} malformed json {";
SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json); SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json);
assertNull(answer); Assert.assertNull(answer);
} }
@Test
@SmallTest @SmallTest
public void testEmpyJsonReturnsNull() { public void testEmpyJsonReturnsNull() {
String json = ""; String json = "";
SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json); SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json);
assertNull(answer); Assert.assertNull(answer);
} }
@Test
@SmallTest @SmallTest
public void testOneLineReturnsNull() { public void testOneLineReturnsNull() {
String json = "{ 'l': [" String json = "{ 'l': ["
+ " { 'il': { 't': [{ 't': 'text', 'tt': 8 }] } }, " + " { 'il': { 't': [{ 't': 'text', 'tt': 8 }] } }, "
+ "] }"; + "] }";
SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json); SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json);
assertNull(answer); Assert.assertNull(answer);
} }
@Test
@SmallTest @SmallTest
public void testTwoLinesDoesntReturnNull() { public void testTwoLinesDoesntReturnNull() {
String json = "{ 'l': [" String json = "{ 'l': ["
...@@ -39,9 +48,10 @@ public class SuggestionAnswerTest extends TestCase { ...@@ -39,9 +48,10 @@ public class SuggestionAnswerTest extends TestCase {
+ " { 'il': { 't': [{ 't': 'other text', 'tt': 5 }] } }" + " { 'il': { 't': [{ 't': 'other text', 'tt': 5 }] } }"
+ "] }"; + "] }";
SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json); SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json);
assertNotNull(answer); Assert.assertNotNull(answer);
} }
@Test
@SmallTest @SmallTest
public void testThreeLinesReturnsNull() { public void testThreeLinesReturnsNull() {
String json = "{ 'l': [" String json = "{ 'l': ["
...@@ -50,9 +60,10 @@ public class SuggestionAnswerTest extends TestCase { ...@@ -50,9 +60,10 @@ public class SuggestionAnswerTest extends TestCase {
+ " { 'il': { 't': [{ 't': 'yet more text', 'tt': 13 }] } }" + " { 'il': { 't': [{ 't': 'yet more text', 'tt': 13 }] } }"
+ "] }"; + "] }";
SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json); SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json);
assertNull(answer); Assert.assertNull(answer);
} }
@Test
@SmallTest @SmallTest
public void testFiveLinesReturnsNull() { public void testFiveLinesReturnsNull() {
String json = "{ 'l': [" String json = "{ 'l': ["
...@@ -63,9 +74,10 @@ public class SuggestionAnswerTest extends TestCase { ...@@ -63,9 +74,10 @@ public class SuggestionAnswerTest extends TestCase {
+ " { 'il': { 't': [{ 't': 'line 5', 'tt': 5 }] } }" + " { 'il': { 't': [{ 't': 'line 5', 'tt': 5 }] } }"
+ "] }"; + "] }";
SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json); SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json);
assertNull(answer); Assert.assertNull(answer);
} }
@Test
@SmallTest @SmallTest
public void testPropertyPresence() { public void testPropertyPresence() {
String json = "{ 'l': [" String json = "{ 'l': ["
...@@ -78,18 +90,19 @@ public class SuggestionAnswerTest extends TestCase { ...@@ -78,18 +90,19 @@ public class SuggestionAnswerTest extends TestCase {
SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json); SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json);
SuggestionAnswer.ImageLine firstLine = answer.getFirstLine(); SuggestionAnswer.ImageLine firstLine = answer.getFirstLine();
assertEquals(2, firstLine.getTextFields().size()); Assert.assertEquals(2, firstLine.getTextFields().size());
assertFalse(firstLine.hasAdditionalText()); Assert.assertFalse(firstLine.hasAdditionalText());
assertFalse(firstLine.hasStatusText()); Assert.assertFalse(firstLine.hasStatusText());
assertTrue(firstLine.hasImage()); Assert.assertTrue(firstLine.hasImage());
SuggestionAnswer.ImageLine secondLine = answer.getSecondLine(); SuggestionAnswer.ImageLine secondLine = answer.getSecondLine();
assertEquals(1, secondLine.getTextFields().size()); Assert.assertEquals(1, secondLine.getTextFields().size());
assertTrue(secondLine.hasAdditionalText()); Assert.assertTrue(secondLine.hasAdditionalText());
assertTrue(secondLine.hasStatusText()); Assert.assertTrue(secondLine.hasStatusText());
assertFalse(secondLine.hasImage()); Assert.assertFalse(secondLine.hasImage());
} }
@Test
@SmallTest @SmallTest
public void testContents() { public void testContents() {
String json = "{ 'l': [" String json = "{ 'l': ["
...@@ -102,18 +115,18 @@ public class SuggestionAnswerTest extends TestCase { ...@@ -102,18 +115,18 @@ public class SuggestionAnswerTest extends TestCase {
SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json); SuggestionAnswer answer = SuggestionAnswer.parseAnswerContents(json);
SuggestionAnswer.ImageLine firstLine = answer.getFirstLine(); SuggestionAnswer.ImageLine firstLine = answer.getFirstLine();
assertEquals("text", firstLine.getTextFields().get(0).getText()); Assert.assertEquals("text", firstLine.getTextFields().get(0).getText());
assertEquals(8, firstLine.getTextFields().get(0).getType()); Assert.assertEquals(8, firstLine.getTextFields().get(0).getType());
assertEquals("moar", firstLine.getTextFields().get(1).getText()); Assert.assertEquals("moar", firstLine.getTextFields().get(1).getText());
assertEquals(0, firstLine.getTextFields().get(1).getType()); Assert.assertEquals(0, firstLine.getTextFields().get(1).getType());
assertEquals("hi there", firstLine.getAdditionalText().getText()); Assert.assertEquals("hi there", firstLine.getAdditionalText().getText());
assertEquals(7, firstLine.getAdditionalText().getType()); Assert.assertEquals(7, firstLine.getAdditionalText().getType());
SuggestionAnswer.ImageLine secondLine = answer.getSecondLine(); SuggestionAnswer.ImageLine secondLine = answer.getSecondLine();
assertEquals("ftw", secondLine.getTextFields().get(0).getText()); Assert.assertEquals("ftw", secondLine.getTextFields().get(0).getText());
assertEquals(6006, secondLine.getTextFields().get(0).getType()); Assert.assertEquals(6006, secondLine.getTextFields().get(0).getType());
assertEquals("shop S-Mart", secondLine.getStatusText().getText()); Assert.assertEquals("shop S-Mart", secondLine.getStatusText().getText());
assertEquals(666, secondLine.getStatusText().getType()); Assert.assertEquals(666, secondLine.getStatusText().getType());
assertEquals("Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGlj", secondLine.getImage()); Assert.assertEquals("Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGlj", secondLine.getImage());
} }
} }
...@@ -6,18 +6,28 @@ package org.chromium.chrome.browser.photo_picker; ...@@ -6,18 +6,28 @@ package org.chromium.chrome.browser.photo_picker;
import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout;
import android.support.test.filters.LargeTest;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
import android.view.View; import android.view.View;
import android.widget.Button; import android.widget.Button;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.ThreadUtils; import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.DisabledTest;
import org.chromium.chrome.R; import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.widget.selection.SelectionDelegate; import org.chromium.chrome.browser.widget.selection.SelectionDelegate;
import org.chromium.chrome.browser.widget.selection.SelectionDelegate.SelectionObserver; import org.chromium.chrome.browser.widget.selection.SelectionDelegate.SelectionObserver;
import org.chromium.chrome.test.ChromeActivityTestCaseBase; import org.chromium.chrome.test.ChromeActivityTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.util.browser.RecyclerViewTestUtils; import org.chromium.chrome.test.util.browser.RecyclerViewTestUtils;
import org.chromium.content.browser.test.util.TouchCommon; import org.chromium.content.browser.test.util.TouchCommon;
import org.chromium.ui.PhotoPickerListener; import org.chromium.ui.PhotoPickerListener;
...@@ -31,12 +41,20 @@ import java.util.concurrent.TimeUnit; ...@@ -31,12 +41,20 @@ import java.util.concurrent.TimeUnit;
/** /**
* Tests for the PhotoPickerDialog class. * Tests for the PhotoPickerDialog class.
*/ */
public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActivity> @RunWith(ChromeJUnit4ClassRunner.class)
implements PhotoPickerListener, DecoderServiceHost.ServiceReadyCallback, @CommandLineFlags.Add({
SelectionObserver<PickerBitmap> { ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE,
ChromeActivityTestRule.DISABLE_NETWORK_PREDICTION_FLAG,
})
public class PhotoPickerDialogTest implements PhotoPickerListener,
SelectionObserver<PickerBitmap>, DecoderServiceHost.ServiceReadyCallback {
// The timeout (in seconds) to wait for the decoder service to be ready. // The timeout (in seconds) to wait for the decoder service to be ready.
private static final long WAIT_TIMEOUT_SECONDS = scaleTimeout(30); private static final long WAIT_TIMEOUT_SECONDS = scaleTimeout(30);
@Rule
public ChromeActivityTestRule<ChromeActivity> mActivityTestRule =
new ChromeActivityTestRule<>(ChromeActivity.class);
// The dialog we are testing. // The dialog we are testing.
private PhotoPickerDialog mDialog; private PhotoPickerDialog mDialog;
...@@ -66,16 +84,9 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -66,16 +84,9 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
// A callback that fires when the decoder is ready. // A callback that fires when the decoder is ready.
public final CallbackHelper onDecoderReadyCallback = new CallbackHelper(); public final CallbackHelper onDecoderReadyCallback = new CallbackHelper();
public PhotoPickerDialogTest() { @Before
super(ChromeActivity.class); public void setUp() throws Exception {
} mActivityTestRule.startMainActivityOnBlankPage();
// ChromeActivityTestCaseBase:
@Override
protected void setUp() throws Exception {
super.setUp();
mTestFiles = new ArrayList<>(); mTestFiles = new ArrayList<>();
mTestFiles.add(new PickerBitmap("a", 5L, PickerBitmap.PICTURE)); mTestFiles.add(new PickerBitmap("a", 5L, PickerBitmap.PICTURE));
mTestFiles.add(new PickerBitmap("b", 4L, PickerBitmap.PICTURE)); mTestFiles.add(new PickerBitmap("b", 4L, PickerBitmap.PICTURE));
...@@ -88,11 +99,6 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -88,11 +99,6 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
DecoderServiceHost.setReadyCallback(this); DecoderServiceHost.setReadyCallback(this);
} }
@Override
public void startMainActivity() throws InterruptedException {
startMainActivityOnBlankPage();
}
// PhotoPickerDialog.PhotoPickerListener: // PhotoPickerDialog.PhotoPickerListener:
@Override @Override
...@@ -128,8 +134,9 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -128,8 +134,9 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
ThreadUtils.runOnUiThreadBlocking(new Callable<PhotoPickerDialog>() { ThreadUtils.runOnUiThreadBlocking(new Callable<PhotoPickerDialog>() {
@Override @Override
public PhotoPickerDialog call() { public PhotoPickerDialog call() {
final PhotoPickerDialog dialog = new PhotoPickerDialog( final PhotoPickerDialog dialog =
getActivity(), PhotoPickerDialogTest.this, multiselect, mimeTypes); new PhotoPickerDialog(mActivityTestRule.getActivity(),
PhotoPickerDialogTest.this, multiselect, mimeTypes);
dialog.show(); dialog.show();
return dialog; return dialog;
} }
...@@ -159,8 +166,8 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -159,8 +166,8 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
onSelectionCallback.waitForCallback(callCount, 1); onSelectionCallback.waitForCallback(callCount, 1);
// Validate the correct selection took place. // Validate the correct selection took place.
assertEquals(expectedSelectionCount, mCurrentPhotoSelection.size()); Assert.assertEquals(expectedSelectionCount, mCurrentPhotoSelection.size());
assertTrue(mSelectionDelegate.isItemSelected(mTestFiles.get(position))); Assert.assertTrue(mSelectionDelegate.isItemSelected(mTestFiles.get(position)));
} }
private void clickDone() throws Exception { private void clickDone() throws Exception {
...@@ -171,18 +178,18 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -171,18 +178,18 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
int callCount = onActionCallback.getCallCount(); int callCount = onActionCallback.getCallCount();
TouchCommon.singleClickView(done); TouchCommon.singleClickView(done);
onActionCallback.waitForCallback(callCount, 1); onActionCallback.waitForCallback(callCount, 1);
assertEquals(PhotoPickerListener.Action.PHOTOS_SELECTED, mLastActionRecorded); Assert.assertEquals(PhotoPickerListener.Action.PHOTOS_SELECTED, mLastActionRecorded);
} }
public void clickCancel() throws Exception { public void clickCancel() throws Exception {
mLastActionRecorded = null; mLastActionRecorded = null;
PickerCategoryView categoryView = mDialog.getCategoryViewForTesting(); PickerCategoryView categoryView = mDialog.getCategoryViewForTesting();
View cancel = new View(getActivity()); View cancel = new View(mActivityTestRule.getActivity());
int callCount = onActionCallback.getCallCount(); int callCount = onActionCallback.getCallCount();
categoryView.onClick(cancel); categoryView.onClick(cancel);
onActionCallback.waitForCallback(callCount, 1); onActionCallback.waitForCallback(callCount, 1);
assertEquals(PhotoPickerListener.Action.CANCEL, mLastActionRecorded); Assert.assertEquals(PhotoPickerListener.Action.CANCEL, mLastActionRecorded);
} }
private void dismissDialog() { private void dismissDialog() {
...@@ -197,22 +204,21 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -197,22 +204,21 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
/** /**
* Continues to be flaky on bots which doesn't reproduce on local devices, * Continues to be flaky on bots which doesn't reproduce on local devices,
* continuing to investigate offline. * continuing to investigate offline.
*
* https://crbug.com/761060
* @LargeTest
*/ */
@DisabledTest @Test
@DisabledTest(message = "crbug.com/761060")
@LargeTest
public void testNoSelection() throws Throwable { public void testNoSelection() throws Throwable {
createDialog(false, Arrays.asList("image/*")); // Multi-select = false. createDialog(false, Arrays.asList("image/*")); // Multi-select = false.
assertTrue(mDialog.isShowing()); Assert.assertTrue(mDialog.isShowing());
waitForDecoder(); waitForDecoder();
int expectedSelectionCount = 1; int expectedSelectionCount = 1;
clickView(0, expectedSelectionCount); clickView(0, expectedSelectionCount);
clickCancel(); clickCancel();
assertEquals(null, mLastSelectedPhotos); Assert.assertNull(mLastSelectedPhotos);
assertEquals(PhotoPickerListener.Action.CANCEL, mLastActionRecorded); Assert.assertEquals(PhotoPickerListener.Action.CANCEL, mLastActionRecorded);
dismissDialog(); dismissDialog();
} }
...@@ -220,14 +226,13 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -220,14 +226,13 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
/** /**
* Continues to be flaky on bots which doesn't reproduce on local devices, * Continues to be flaky on bots which doesn't reproduce on local devices,
* continuing to investigate offline. * continuing to investigate offline.
*
* https://crbug.com/761060
* @LargeTest
*/ */
@DisabledTest @Test
@DisabledTest(message = "crbug.com/761060")
@LargeTest
public void testSingleSelectionPhoto() throws Throwable { public void testSingleSelectionPhoto() throws Throwable {
createDialog(false, Arrays.asList("image/*")); // Multi-select = false. createDialog(false, Arrays.asList("image/*")); // Multi-select = false.
assertTrue(mDialog.isShowing()); Assert.assertTrue(mDialog.isShowing());
waitForDecoder(); waitForDecoder();
// Expected selection count is 1 because clicking on a new view unselects other. // Expected selection count is 1 because clicking on a new view unselects other.
...@@ -236,9 +241,9 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -236,9 +241,9 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
clickView(1, expectedSelectionCount); clickView(1, expectedSelectionCount);
clickDone(); clickDone();
assertEquals(1, mLastSelectedPhotos.length); Assert.assertEquals(1, mLastSelectedPhotos.length);
assertEquals(PhotoPickerListener.Action.PHOTOS_SELECTED, mLastActionRecorded); Assert.assertEquals(PhotoPickerListener.Action.PHOTOS_SELECTED, mLastActionRecorded);
assertEquals(mTestFiles.get(1).getFilePath(), mLastSelectedPhotos[0]); Assert.assertEquals(mTestFiles.get(1).getFilePath(), mLastSelectedPhotos[0]);
dismissDialog(); dismissDialog();
} }
...@@ -246,14 +251,13 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -246,14 +251,13 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
/** /**
* Continues to be flaky on bots which doesn't reproduce on local devices, * Continues to be flaky on bots which doesn't reproduce on local devices,
* continuing to investigate offline. * continuing to investigate offline.
*
* https://crbug.com/761060
* @LargeTest
*/ */
@DisabledTest @Test
@DisabledTest(message = "crbug.com/761060")
@LargeTest
public void testMultiSelectionPhoto() throws Throwable { public void testMultiSelectionPhoto() throws Throwable {
createDialog(true, Arrays.asList("image/*")); // Multi-select = true. createDialog(true, Arrays.asList("image/*")); // Multi-select = true.
assertTrue(mDialog.isShowing()); Assert.assertTrue(mDialog.isShowing());
waitForDecoder(); waitForDecoder();
// Multi-selection is enabled, so each click is counted. // Multi-selection is enabled, so each click is counted.
...@@ -263,11 +267,11 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi ...@@ -263,11 +267,11 @@ public class PhotoPickerDialogTest extends ChromeActivityTestCaseBase<ChromeActi
clickView(4, expectedSelectionCount++); clickView(4, expectedSelectionCount++);
clickDone(); clickDone();
assertEquals(3, mLastSelectedPhotos.length); Assert.assertEquals(3, mLastSelectedPhotos.length);
assertEquals(PhotoPickerListener.Action.PHOTOS_SELECTED, mLastActionRecorded); Assert.assertEquals(PhotoPickerListener.Action.PHOTOS_SELECTED, mLastActionRecorded);
assertEquals(mTestFiles.get(0).getFilePath(), mLastSelectedPhotos[0]); Assert.assertEquals(mTestFiles.get(0).getFilePath(), mLastSelectedPhotos[0]);
assertEquals(mTestFiles.get(2).getFilePath(), mLastSelectedPhotos[1]); Assert.assertEquals(mTestFiles.get(2).getFilePath(), mLastSelectedPhotos[1]);
assertEquals(mTestFiles.get(4).getFilePath(), mLastSelectedPhotos[2]); Assert.assertEquals(mTestFiles.get(4).getFilePath(), mLastSelectedPhotos[2]);
dismissDialog(); dismissDialog();
} }
......
...@@ -6,10 +6,17 @@ package org.chromium.chrome.browser.suggestions; ...@@ -6,10 +6,17 @@ package org.chromium.chrome.browser.suggestions;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.ThreadUtils; import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.UrlConstants;
import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.ntp.NewTabPage;
import org.chromium.chrome.browser.ntp.snippets.CategoryInt; import org.chromium.chrome.browser.ntp.snippets.CategoryInt;
...@@ -18,43 +25,53 @@ import org.chromium.chrome.browser.ntp.snippets.SnippetsBridge; ...@@ -18,43 +25,53 @@ import org.chromium.chrome.browser.ntp.snippets.SnippetsBridge;
import org.chromium.chrome.browser.ntp.snippets.SuggestionsSource; import org.chromium.chrome.browser.ntp.snippets.SuggestionsSource;
import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.test.ChromeActivityTestCaseBase; import org.chromium.chrome.test.ChromeActivityTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.util.NewTabPageTestUtils; import org.chromium.chrome.test.util.NewTabPageTestUtils;
/** /**
* Misc. Content Suggestions instrumentation tests. * Misc. Content Suggestions instrumentation tests.
*/ */
public class ContentSuggestionsTest extends ChromeActivityTestCaseBase<ChromeActivity> { @RunWith(ChromeJUnit4ClassRunner.class)
public ContentSuggestionsTest() { @CommandLineFlags.Add({
super(ChromeActivity.class); ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE,
} ChromeActivityTestRule.DISABLE_NETWORK_PREDICTION_FLAG,
})
public class ContentSuggestionsTest {
@Rule
public ChromeActivityTestRule<ChromeActivity> mActivityTestRule =
new ChromeActivityTestRule<>(ChromeActivity.class);
@Override @Before
public void startMainActivity() throws InterruptedException { public void setUp() throws InterruptedException {
startMainActivityOnBlankPage(); mActivityTestRule.startMainActivityOnBlankPage();
} }
@Test
@SmallTest @SmallTest
@Feature("Suggestions") @Feature("Suggestions")
@CommandLineFlags.Add("enable-features=ContentSuggestionsSettings") @CommandLineFlags.Add("enable-features=ContentSuggestionsSettings")
public void testRemoteSuggestionsEnabled() throws InterruptedException { public void testRemoteSuggestionsEnabled() throws InterruptedException {
NewTabPage ntp = loadNTPWithSearchSuggestState(true); NewTabPage ntp = loadNTPWithSearchSuggestState(true);
SuggestionsUiDelegate uiDelegate = ntp.getManagerForTesting(); SuggestionsUiDelegate uiDelegate = ntp.getManagerForTesting();
assertTrue(isCategoryEnabled(uiDelegate.getSuggestionsSource(), KnownCategories.ARTICLES)); Assert.assertTrue(
isCategoryEnabled(uiDelegate.getSuggestionsSource(), KnownCategories.ARTICLES));
} }
@Test
@SmallTest @SmallTest
@Feature("Suggestions") @Feature("Suggestions")
@CommandLineFlags.Add("enable-features=ContentSuggestionsSettings") @CommandLineFlags.Add("enable-features=ContentSuggestionsSettings")
public void testRemoteSuggestionsDisabled() throws InterruptedException { public void testRemoteSuggestionsDisabled() throws InterruptedException {
NewTabPage ntp = loadNTPWithSearchSuggestState(false); NewTabPage ntp = loadNTPWithSearchSuggestState(false);
SuggestionsUiDelegate uiDelegate = ntp.getManagerForTesting(); SuggestionsUiDelegate uiDelegate = ntp.getManagerForTesting();
assertFalse(isCategoryEnabled(uiDelegate.getSuggestionsSource(), KnownCategories.ARTICLES)); Assert.assertFalse(
isCategoryEnabled(uiDelegate.getSuggestionsSource(), KnownCategories.ARTICLES));
} }
private NewTabPage loadNTPWithSearchSuggestState(final boolean enabled) private NewTabPage loadNTPWithSearchSuggestState(final boolean enabled)
throws InterruptedException { throws InterruptedException {
Tab tab = getActivity().getActivityTab(); Tab tab = mActivityTestRule.getActivity().getActivityTab();
ThreadUtils.runOnUiThreadBlocking(new Runnable() { ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override @Override
public void run() { public void run() {
...@@ -62,10 +79,10 @@ public class ContentSuggestionsTest extends ChromeActivityTestCaseBase<ChromeAct ...@@ -62,10 +79,10 @@ public class ContentSuggestionsTest extends ChromeActivityTestCaseBase<ChromeAct
} }
}); });
loadUrl(UrlConstants.NTP_URL); mActivityTestRule.loadUrl(UrlConstants.NTP_URL);
NewTabPageTestUtils.waitForNtpLoaded(tab); NewTabPageTestUtils.waitForNtpLoaded(tab);
assertTrue(tab.getNativePage() instanceof NewTabPage); Assert.assertTrue(tab.getNativePage() instanceof NewTabPage);
return (NewTabPage) tab.getNativePage(); return (NewTabPage) tab.getNativePage();
} }
......
...@@ -278,7 +278,7 @@ public class ChromeTabUtils { ...@@ -278,7 +278,7 @@ public class ChromeTabUtils {
} }
try { try {
createdCallback.waitForCallback(0); createdCallback.waitForCallback(null, 0, 1, 10, TimeUnit.SECONDS);
} catch (TimeoutException e) { } catch (TimeoutException e) {
Assert.fail("Never received tab creation event"); Assert.fail("Never received tab creation event");
} }
......
...@@ -457,6 +457,8 @@ instrumentation_test_apk("cronet_sample_test_apk") { ...@@ -457,6 +457,8 @@ instrumentation_test_apk("cronet_sample_test_apk") {
"//base:base_java_test_support", "//base:base_java_test_support",
"//net/android:net_java_test_support", "//net/android:net_java_test_support",
"//third_party/android_support_test_runner:runner_java", "//third_party/android_support_test_runner:runner_java",
"//third_party/android_support_test_runner:rules_java",
"//third_party/junit",
] ]
additional_apks = [ "//net/android:net_test_support_apk" ] additional_apks = [ "//net/android:net_test_support_apk" ]
...@@ -560,7 +562,7 @@ android_library("cronet_test_apk_java") { ...@@ -560,7 +562,7 @@ android_library("cronet_test_apk_java") {
cronet_smoketests_platform_only_common_srcs = [ cronet_smoketests_platform_only_common_srcs = [
"test/smoketests/src/org/chromium/net/smoke/ChromiumPlatformOnlyTestSupport.java", "test/smoketests/src/org/chromium/net/smoke/ChromiumPlatformOnlyTestSupport.java",
"test/smoketests/src/org/chromium/net/smoke/CronetSmokeTestCase.java", "test/smoketests/src/org/chromium/net/smoke/CronetSmokeTestRule.java",
"test/smoketests/src/org/chromium/net/smoke/HttpTestServer.java", "test/smoketests/src/org/chromium/net/smoke/HttpTestServer.java",
"test/smoketests/src/org/chromium/net/smoke/SmokeTestRequestCallback.java", "test/smoketests/src/org/chromium/net/smoke/SmokeTestRequestCallback.java",
"test/smoketests/src/org/chromium/net/smoke/TestSupport.java", "test/smoketests/src/org/chromium/net/smoke/TestSupport.java",
...@@ -568,7 +570,7 @@ cronet_smoketests_platform_only_common_srcs = [ ...@@ -568,7 +570,7 @@ cronet_smoketests_platform_only_common_srcs = [
cronet_smoketests_native_common_srcs = cronet_smoketests_platform_only_common_srcs + [ cronet_smoketests_native_common_srcs = cronet_smoketests_platform_only_common_srcs + [
"test/smoketests/src/org/chromium/net/smoke/ChromiumNativeTestSupport.java", "test/smoketests/src/org/chromium/net/smoke/ChromiumNativeTestSupport.java",
"test/smoketests/src/org/chromium/net/smoke/NativeCronetTestCase.java", "test/smoketests/src/org/chromium/net/smoke/NativeCronetTestRule.java",
] ]
android_library("cronet_smoketests_native_java") { android_library("cronet_smoketests_native_java") {
...@@ -582,6 +584,8 @@ android_library("cronet_smoketests_native_java") { ...@@ -582,6 +584,8 @@ android_library("cronet_smoketests_native_java") {
":cronet_api_java", ":cronet_api_java",
":cronet_test_apk_java", ":cronet_test_apk_java",
"//base:base_java", "//base:base_java",
"//base:base_java_test_support",
"//third_party/junit",
"//third_party/android_support_test_runner:runner_java", "//third_party/android_support_test_runner:runner_java",
"//third_party/netty4:netty_all_java", "//third_party/netty4:netty_all_java",
] ]
...@@ -748,6 +752,8 @@ android_library("cronet_smoketests_platform_only_java") { ...@@ -748,6 +752,8 @@ android_library("cronet_smoketests_platform_only_java") {
java_files = [ "test/smoketests/src/org/chromium/net/smoke/PlatformOnlyEngineTest.java" ] + cronet_smoketests_platform_only_common_srcs java_files = [ "test/smoketests/src/org/chromium/net/smoke/PlatformOnlyEngineTest.java" ] + cronet_smoketests_platform_only_common_srcs
deps = [ deps = [
":cronet_api_java", ":cronet_api_java",
"//base:base_java_test_support",
"//third_party/junit",
"//third_party/android_support_test_runner:runner_java", "//third_party/android_support_test_runner:runner_java",
"//third_party/netty4:netty_all_java", "//third_party/netty4:netty_all_java",
] ]
...@@ -798,6 +804,8 @@ android_library("cronet_smoketests_missing_native_library_java") { ...@@ -798,6 +804,8 @@ android_library("cronet_smoketests_missing_native_library_java") {
":cronet_api_java", ":cronet_api_java",
":cronet_test_apk_java", ":cronet_test_apk_java",
"//base:base_java", "//base:base_java",
"//base:base_java_test_support",
"//third_party/junit",
"//third_party/android_support_test_runner:runner_java", "//third_party/android_support_test_runner:runner_java",
"//third_party/netty4:netty_all_java", "//third_party/netty4:netty_all_java",
] ]
......
...@@ -16,6 +16,10 @@ ...@@ -16,6 +16,10 @@
<application> <application>
<uses-library android:name="android.test.runner" /> <uses-library android:name="android.test.runner" />
</application> </application>
<instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
android:targetPackage="org.chromium.cronet_sample_apk"
android:label="Tests for org.chromium.cronet_sample_apk"
chromium-junit4="true"/>
<instrumentation android:name="android.test.InstrumentationTestRunner" <instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="org.chromium.cronet_sample_apk" android:targetPackage="org.chromium.cronet_sample_apk"
android:label="Tests for org.chromium.cronet_sample_apk"/> android:label="Tests for org.chromium.cronet_sample_apk"/>
......
...@@ -8,47 +8,56 @@ import android.content.ComponentName; ...@@ -8,47 +8,56 @@ import android.content.ComponentName;
import android.content.Intent; import android.content.Intent;
import android.net.Uri; import android.net.Uri;
import android.os.ConditionVariable; import android.os.ConditionVariable;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import android.test.ActivityInstrumentationTestCase2; import android.support.test.rule.ActivityTestRule;
import android.text.Editable; import android.text.Editable;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.widget.TextView; import android.widget.TextView;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.Feature;
import org.chromium.net.test.EmbeddedTestServer; import org.chromium.net.test.EmbeddedTestServer;
/** /**
* Base test class for all CronetSample based tests. * Base test class for all CronetSample based tests.
*/ */
public class CronetSampleTest extends @RunWith(BaseJUnit4ClassRunner.class)
ActivityInstrumentationTestCase2<CronetSampleActivity> { public class CronetSampleTest {
private EmbeddedTestServer mTestServer; private EmbeddedTestServer mTestServer;
private String mUrl; private String mUrl;
public CronetSampleTest() { @Rule
super(CronetSampleActivity.class); public ActivityTestRule<CronetSampleActivity> mActivityTestRule =
} new ActivityTestRule<>(CronetSampleActivity.class, false, false);
@Override @Before
protected void setUp() throws Exception { public void setUp() throws Exception {
super.setUp(); mTestServer = EmbeddedTestServer.createAndStartServer(
mTestServer = EmbeddedTestServer.createAndStartServer(getInstrumentation().getContext()); InstrumentationRegistry.getInstrumentation().getContext());
mUrl = mTestServer.getURL("/echo?status=200"); mUrl = mTestServer.getURL("/echo?status=200");
} }
@Override @After
protected void tearDown() throws Exception { public void tearDown() throws Exception {
mTestServer.stopAndDestroyServer(); mTestServer.stopAndDestroyServer();
super.tearDown();
} }
@Test
@SmallTest @SmallTest
@Feature({"Cronet"}) @Feature({"Cronet"})
public void testLoadUrl() throws Exception { public void testLoadUrl() throws Exception {
CronetSampleActivity activity = launchCronetSampleWithUrl(mUrl); CronetSampleActivity activity = launchCronetSampleWithUrl(mUrl);
// Make sure the activity was created as expected. // Make sure the activity was created as expected.
assertNotNull(activity); Assert.assertNotNull(activity);
// Verify successful fetch. // Verify successful fetch.
final TextView textView = (TextView) activity.findViewById(R.id.resultView); final TextView textView = (TextView) activity.findViewById(R.id.resultView);
...@@ -81,10 +90,9 @@ public class CronetSampleTest extends ...@@ -81,10 +90,9 @@ public class CronetSampleTest extends
intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse(url)); intent.setData(Uri.parse(url));
intent.setComponent(new ComponentName( intent.setComponent(
getInstrumentation().getTargetContext(), new ComponentName(InstrumentationRegistry.getInstrumentation().getTargetContext(),
CronetSampleActivity.class)); CronetSampleActivity.class));
setActivityIntent(intent); return mActivityTestRule.launchActivity(intent);
return getActivity();
} }
} }
...@@ -5,7 +5,12 @@ ...@@ -5,7 +5,12 @@
package org.chromium.net.smoke; package org.chromium.net.smoke;
import android.content.Context; import android.content.Context;
import android.test.AndroidTestCase; import android.support.test.InstrumentationRegistry;
import org.junit.Assert;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.chromium.net.CronetEngine; import org.chromium.net.CronetEngine;
import org.chromium.net.ExperimentalCronetEngine; import org.chromium.net.ExperimentalCronetEngine;
...@@ -14,33 +19,54 @@ import org.chromium.net.UrlResponseInfo; ...@@ -14,33 +19,54 @@ import org.chromium.net.UrlResponseInfo;
/** /**
* Base test class. This class should not import any classes from the org.chromium.base package. * Base test class. This class should not import any classes from the org.chromium.base package.
*/ */
public class CronetSmokeTestCase extends AndroidTestCase { public class CronetSmokeTestRule implements TestRule {
/** /**
* The key in the string resource file that specifies {@link TestSupport} that should * The key in the string resource file that specifies {@link TestSupport} that should
* be instantiated. * be instantiated.
*/ */
private static final String SUPPORT_IMPL_RES_KEY = "TestSupportImplClass"; private static final String SUPPORT_IMPL_RES_KEY = "TestSupportImplClass";
protected ExperimentalCronetEngine.Builder mCronetEngineBuilder; public ExperimentalCronetEngine.Builder mCronetEngineBuilder;
protected CronetEngine mCronetEngine; public CronetEngine mCronetEngine;
protected TestSupport mTestSupport; public TestSupport mTestSupport;
@Override @Override
protected void setUp() throws Exception { public Statement apply(final Statement base, Description desc) {
super.setUp(); return new Statement() {
mCronetEngineBuilder = new ExperimentalCronetEngine.Builder(getContext()); @Override
public void evaluate() throws Throwable {
ruleSetUp();
base.evaluate();
ruleTearDown();
}
};
}
public TestSupport getTestSupport() {
return mTestSupport;
}
public CronetEngine getCronetEngine() {
return mCronetEngine;
}
public ExperimentalCronetEngine.Builder getCronetEngineBuilder() {
return mCronetEngineBuilder;
}
private void ruleSetUp() throws Exception {
mCronetEngineBuilder =
new ExperimentalCronetEngine.Builder(InstrumentationRegistry.getTargetContext());
initTestSupport(); initTestSupport();
} }
@Override private void ruleTearDown() throws Exception {
protected void tearDown() throws Exception {
if (mCronetEngine != null) { if (mCronetEngine != null) {
mCronetEngine.shutdown(); mCronetEngine.shutdown();
} }
super.tearDown();
} }
protected void initCronetEngine() { public void initCronetEngine() {
mCronetEngine = mCronetEngineBuilder.build(); mCronetEngine = mCronetEngineBuilder.build();
} }
...@@ -50,26 +76,28 @@ public class CronetSmokeTestCase extends AndroidTestCase { ...@@ -50,26 +76,28 @@ public class CronetSmokeTestCase extends AndroidTestCase {
throw new RuntimeException( throw new RuntimeException(
"The request failed with an error", callback.getFailureError()); "The request failed with an error", callback.getFailureError());
} }
assertEquals(SmokeTestRequestCallback.State.Succeeded, callback.getFinalState()); Assert.assertEquals(SmokeTestRequestCallback.State.Succeeded, callback.getFinalState());
// Check the response info // Check the response info
UrlResponseInfo responseInfo = callback.getResponseInfo(); UrlResponseInfo responseInfo = callback.getResponseInfo();
assertNotNull(responseInfo); Assert.assertNotNull(responseInfo);
assertFalse(responseInfo.wasCached()); Assert.assertFalse(responseInfo.wasCached());
assertEquals(url, responseInfo.getUrl()); Assert.assertEquals(url, responseInfo.getUrl());
assertEquals(url, responseInfo.getUrlChain().get(responseInfo.getUrlChain().size() - 1)); Assert.assertEquals(
assertEquals(200, responseInfo.getHttpStatusCode()); url, responseInfo.getUrlChain().get(responseInfo.getUrlChain().size() - 1));
assertTrue(responseInfo.toString().length() > 0); Assert.assertEquals(200, responseInfo.getHttpStatusCode());
Assert.assertTrue(responseInfo.toString().length() > 0);
} }
static void assertJavaEngine(CronetEngine engine) { static void assertJavaEngine(CronetEngine engine) {
assertNotNull(engine); Assert.assertNotNull(engine);
assertEquals("org.chromium.net.impl.JavaCronetEngine", engine.getClass().getName()); Assert.assertEquals("org.chromium.net.impl.JavaCronetEngine", engine.getClass().getName());
} }
static void assertNativeEngine(CronetEngine engine) { static void assertNativeEngine(CronetEngine engine) {
assertNotNull(engine); Assert.assertNotNull(engine);
assertEquals("org.chromium.net.impl.CronetUrlRequestContext", engine.getClass().getName()); Assert.assertEquals(
"org.chromium.net.impl.CronetUrlRequestContext", engine.getClass().getName());
} }
/** /**
...@@ -80,7 +108,7 @@ public class CronetSmokeTestCase extends AndroidTestCase { ...@@ -80,7 +108,7 @@ public class CronetSmokeTestCase extends AndroidTestCase {
* @throws Exception if the class cannot be instantiated. * @throws Exception if the class cannot be instantiated.
*/ */
private void initTestSupport() throws Exception { private void initTestSupport() throws Exception {
Context ctx = getContext(); Context ctx = InstrumentationRegistry.getTargetContext();
String packageName = ctx.getPackageName(); String packageName = ctx.getPackageName();
int resId = ctx.getResources().getIdentifier(SUPPORT_IMPL_RES_KEY, "string", packageName); int resId = ctx.getResources().getIdentifier(SUPPORT_IMPL_RES_KEY, "string", packageName);
String className = ctx.getResources().getString(resId); String className = ctx.getResources().getString(resId);
......
...@@ -4,41 +4,54 @@ ...@@ -4,41 +4,54 @@
package org.chromium.net.smoke; package org.chromium.net.smoke;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.net.UrlRequest; import org.chromium.net.UrlRequest;
/** /**
* HTTP2 Tests. * HTTP2 Tests.
*/ */
public class Http2Test extends NativeCronetTestCase { @RunWith(BaseJUnit4ClassRunner.class)
public class Http2Test {
private TestSupport.TestServer mServer; private TestSupport.TestServer mServer;
@Override @Rule
protected void setUp() throws Exception { public NativeCronetTestRule mRule = new NativeCronetTestRule();
super.setUp();
mServer = mTestSupport.createTestServer(getContext(), TestSupport.Protocol.HTTP2); @Before
public void setUp() throws Exception {
mServer = mRule.getTestSupport().createTestServer(
InstrumentationRegistry.getTargetContext(), TestSupport.Protocol.HTTP2);
} }
@Override @After
protected void tearDown() throws Exception { public void tearDown() throws Exception {
mServer.shutdown(); mServer.shutdown();
super.tearDown();
} }
// Test that HTTP/2 is enabled by default but QUIC is not. // Test that HTTP/2 is enabled by default but QUIC is not.
@Test
@SmallTest @SmallTest
public void testHttp2() throws Exception { public void testHttp2() throws Exception {
mTestSupport.installMockCertVerifierForTesting(mCronetEngineBuilder); mRule.getTestSupport().installMockCertVerifierForTesting(mRule.getCronetEngineBuilder());
initCronetEngine(); mRule.initCronetEngine();
assertTrue(mServer.start()); Assert.assertTrue(mServer.start());
SmokeTestRequestCallback callback = new SmokeTestRequestCallback(); SmokeTestRequestCallback callback = new SmokeTestRequestCallback();
UrlRequest.Builder requestBuilder = mCronetEngine.newUrlRequestBuilder( UrlRequest.Builder requestBuilder = mRule.getCronetEngine().newUrlRequestBuilder(
mServer.getSuccessURL(), callback, callback.getExecutor()); mServer.getSuccessURL(), callback, callback.getExecutor());
requestBuilder.build().start(); requestBuilder.build().start();
callback.blockForDone(); callback.blockForDone();
assertSuccessfulNonEmptyResponse(callback, mServer.getSuccessURL()); CronetSmokeTestRule.assertSuccessfulNonEmptyResponse(callback, mServer.getSuccessURL());
assertEquals("h2", callback.getResponseInfo().getNegotiatedProtocol()); Assert.assertEquals("h2", callback.getResponseInfo().getNegotiatedProtocol());
} }
} }
...@@ -4,8 +4,17 @@ ...@@ -4,8 +4,17 @@
package org.chromium.net.smoke; package org.chromium.net.smoke;
import static org.chromium.net.smoke.CronetSmokeTestRule.assertJavaEngine;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.net.CronetEngine; import org.chromium.net.CronetEngine;
import org.chromium.net.CronetProvider; import org.chromium.net.CronetProvider;
import org.chromium.net.ExperimentalCronetEngine; import org.chromium.net.ExperimentalCronetEngine;
...@@ -16,23 +25,28 @@ import java.util.List; ...@@ -16,23 +25,28 @@ import java.util.List;
* Tests scenarios when the native shared library file is missing in the APK or was built for a * Tests scenarios when the native shared library file is missing in the APK or was built for a
* wrong architecture. * wrong architecture.
*/ */
public class MissingNativeLibraryTest extends CronetSmokeTestCase { @RunWith(BaseJUnit4ClassRunner.class)
public class MissingNativeLibraryTest {
@Rule
public CronetSmokeTestRule mRule = new CronetSmokeTestRule();
/** /**
* If the ".so" file is missing, instantiating the Cronet engine should throw an exception. * If the ".so" file is missing, instantiating the Cronet engine should throw an exception.
*/ */
@Test
@SmallTest @SmallTest
public void testExceptionWhenSoFileIsAbsent() throws Exception { public void testExceptionWhenSoFileIsAbsent() throws Exception {
ExperimentalCronetEngine.Builder builder = ExperimentalCronetEngine.Builder builder =
new ExperimentalCronetEngine.Builder(getContext()); new ExperimentalCronetEngine.Builder(InstrumentationRegistry.getTargetContext());
try { try {
builder.build(); builder.build();
fail("Expected exception since the shared library '.so' file is absent"); Assert.fail("Expected exception since the shared library '.so' file is absent");
} catch (Throwable t) { } catch (Throwable t) {
// Find the root cause. // Find the root cause.
while (t.getCause() != null) { while (t.getCause() != null) {
t = t.getCause(); t = t.getCause();
} }
assertEquals(UnsatisfiedLinkError.class, t.getClass()); Assert.assertEquals(UnsatisfiedLinkError.class, t.getClass());
} }
} }
...@@ -40,13 +54,15 @@ public class MissingNativeLibraryTest extends CronetSmokeTestCase { ...@@ -40,13 +54,15 @@ public class MissingNativeLibraryTest extends CronetSmokeTestCase {
* Tests the embedder ability to select Java (platform) based implementation when * Tests the embedder ability to select Java (platform) based implementation when
* the native library is missing or doesn't load for some reason, * the native library is missing or doesn't load for some reason,
*/ */
@Test
@SmallTest @SmallTest
public void testForceChoiceOfJavaEngine() throws Exception { public void testForceChoiceOfJavaEngine() throws Exception {
List<CronetProvider> availableProviders = CronetProvider.getAllProviders(getContext()); List<CronetProvider> availableProviders =
CronetProvider.getAllProviders(InstrumentationRegistry.getTargetContext());
boolean foundNativeProvider = false; boolean foundNativeProvider = false;
CronetProvider platformProvider = null; CronetProvider platformProvider = null;
for (CronetProvider provider : availableProviders) { for (CronetProvider provider : availableProviders) {
assertTrue(provider.isEnabled()); Assert.assertTrue(provider.isEnabled());
if (provider.getName().equals(CronetProvider.PROVIDER_NAME_APP_PACKAGED)) { if (provider.getName().equals(CronetProvider.PROVIDER_NAME_APP_PACKAGED)) {
foundNativeProvider = true; foundNativeProvider = true;
} else if (provider.getName().equals(CronetProvider.PROVIDER_NAME_FALLBACK)) { } else if (provider.getName().equals(CronetProvider.PROVIDER_NAME_FALLBACK)) {
...@@ -54,18 +70,18 @@ public class MissingNativeLibraryTest extends CronetSmokeTestCase { ...@@ -54,18 +70,18 @@ public class MissingNativeLibraryTest extends CronetSmokeTestCase {
} }
} }
assertTrue("Unable to find the native cronet provider", foundNativeProvider); Assert.assertTrue("Unable to find the native cronet provider", foundNativeProvider);
assertNotNull("Unable to find the platform cronet provider", platformProvider); Assert.assertNotNull("Unable to find the platform cronet provider", platformProvider);
CronetEngine.Builder builder = platformProvider.createBuilder(); CronetEngine.Builder builder = platformProvider.createBuilder();
CronetEngine engine = builder.build(); CronetEngine engine = builder.build();
assertJavaEngine(engine); assertJavaEngine(engine);
assertTrue("It should be always possible to cast the created builder to" Assert.assertTrue("It should be always possible to cast the created builder to"
+ " ExperimentalCronetEngine.Builder", + " ExperimentalCronetEngine.Builder",
builder instanceof ExperimentalCronetEngine.Builder); builder instanceof ExperimentalCronetEngine.Builder);
assertTrue("It should be always possible to cast the created engine to" Assert.assertTrue("It should be always possible to cast the created engine to"
+ " ExperimentalCronetEngine.Builder", + " ExperimentalCronetEngine.Builder",
engine instanceof ExperimentalCronetEngine); engine instanceof ExperimentalCronetEngine);
} }
......
...@@ -4,6 +4,11 @@ ...@@ -4,6 +4,11 @@
package org.chromium.net.smoke; package org.chromium.net.smoke;
import android.support.test.InstrumentationRegistry;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.chromium.base.ContextUtils; import org.chromium.base.ContextUtils;
import org.chromium.base.PathUtils; import org.chromium.base.PathUtils;
...@@ -13,31 +18,40 @@ import java.io.File; ...@@ -13,31 +18,40 @@ import java.io.File;
* Test base class for testing native Engine implementation. This class can import classes from the * Test base class for testing native Engine implementation. This class can import classes from the
* org.chromium.base package. * org.chromium.base package.
*/ */
public class NativeCronetTestCase extends CronetSmokeTestCase { public class NativeCronetTestRule extends CronetSmokeTestRule {
private static final String PRIVATE_DATA_DIRECTORY_SUFFIX = "cronet_test"; private static final String PRIVATE_DATA_DIRECTORY_SUFFIX = "cronet_test";
private static final String LOGFILE_NAME = "cronet-netlog.json"; private static final String LOGFILE_NAME = "cronet-netlog.json";
@Override @Override
protected void setUp() throws Exception { public Statement apply(final Statement base, Description desc) {
super.setUp(); return super.apply(new Statement() {
ContextUtils.initApplicationContext(getContext().getApplicationContext()); @Override
PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX); public void evaluate() throws Throwable {
mTestSupport.loadTestNativeLibrary(); ruleSetUp();
} base.evaluate();
ruleTearDown();
@Override }
protected void tearDown() throws Exception { }, desc);
stopAndSaveNetLog();
super.tearDown();
} }
@Override @Override
protected void initCronetEngine() { public void initCronetEngine() {
super.initCronetEngine(); super.initCronetEngine();
assertNativeEngine(mCronetEngine); assertNativeEngine(mCronetEngine);
startNetLog(); startNetLog();
} }
private void ruleSetUp() throws Exception {
ContextUtils.initApplicationContext(
InstrumentationRegistry.getTargetContext().getApplicationContext());
PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX);
mTestSupport.loadTestNativeLibrary();
}
private void ruleTearDown() throws Exception {
stopAndSaveNetLog();
}
private void startNetLog() { private void startNetLog() {
if (mCronetEngine != null) { if (mCronetEngine != null) {
mCronetEngine.startNetLogToFile( mCronetEngine.startNetLogToFile(
...@@ -50,6 +64,6 @@ public class NativeCronetTestCase extends CronetSmokeTestCase { ...@@ -50,6 +64,6 @@ public class NativeCronetTestCase extends CronetSmokeTestCase {
mCronetEngine.stopNetLog(); mCronetEngine.stopNetLog();
File netLogFile = new File(PathUtils.getDataDirectory(), LOGFILE_NAME); File netLogFile = new File(PathUtils.getDataDirectory(), LOGFILE_NAME);
if (!netLogFile.exists()) return; if (!netLogFile.exists()) return;
mTestSupport.processNetLog(getContext(), netLogFile); mTestSupport.processNetLog(InstrumentationRegistry.getTargetContext(), netLogFile);
} }
} }
...@@ -4,42 +4,58 @@ ...@@ -4,42 +4,58 @@
package org.chromium.net.smoke; package org.chromium.net.smoke;
import static org.chromium.net.smoke.CronetSmokeTestRule.assertJavaEngine;
import static org.chromium.net.smoke.CronetSmokeTestRule.assertSuccessfulNonEmptyResponse;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.net.UrlRequest; import org.chromium.net.UrlRequest;
/** /**
* Tests scenario when an app doesn't contain the native Cronet implementation. * Tests scenario when an app doesn't contain the native Cronet implementation.
*/ */
public class PlatformOnlyEngineTest extends CronetSmokeTestCase { @RunWith(BaseJUnit4ClassRunner.class)
public class PlatformOnlyEngineTest {
private String mURL; private String mURL;
private TestSupport.TestServer mServer; private TestSupport.TestServer mServer;
@Override @Rule
protected void setUp() throws Exception { public CronetSmokeTestRule mRule = new CronetSmokeTestRule();
super.setUp();
@Before
public void setUp() throws Exception {
// Java-only implementation of the Cronet engine only supports Http/1 protocol. // Java-only implementation of the Cronet engine only supports Http/1 protocol.
mServer = mTestSupport.createTestServer(getContext(), TestSupport.Protocol.HTTP1); mServer = mRule.getTestSupport().createTestServer(
assertTrue(mServer.start()); InstrumentationRegistry.getTargetContext(), TestSupport.Protocol.HTTP1);
Assert.assertTrue(mServer.start());
mURL = mServer.getSuccessURL(); mURL = mServer.getSuccessURL();
} }
@Override @After
protected void tearDown() throws Exception { public void tearDown() throws Exception {
mServer.shutdown(); mServer.shutdown();
super.tearDown();
} }
/** /**
* Test a successful response when a request is sent by the Java Cronet Engine. * Test a successful response when a request is sent by the Java Cronet Engine.
*/ */
@Test
@SmallTest @SmallTest
public void testSuccessfulResponse() { public void testSuccessfulResponse() {
initCronetEngine(); mRule.initCronetEngine();
assertJavaEngine(mCronetEngine); assertJavaEngine(mRule.getCronetEngine());
SmokeTestRequestCallback callback = new SmokeTestRequestCallback(); SmokeTestRequestCallback callback = new SmokeTestRequestCallback();
UrlRequest.Builder requestBuilder = UrlRequest.Builder requestBuilder = mRule.getCronetEngine().newUrlRequestBuilder(
mCronetEngine.newUrlRequestBuilder(mURL, callback, callback.getExecutor()); mURL, callback, callback.getExecutor());
requestBuilder.build().start(); requestBuilder.build().start();
callback.blockForDone(); callback.blockForDone();
assertSuccessfulNonEmptyResponse(callback, mURL); assertSuccessfulNonEmptyResponse(callback, mURL);
......
...@@ -4,12 +4,20 @@ ...@@ -4,12 +4,20 @@
package org.chromium.net.smoke; package org.chromium.net.smoke;
import static org.chromium.net.smoke.TestSupport.Protocol.QUIC;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest; import android.support.test.filters.SmallTest;
import org.json.JSONObject; import org.json.JSONObject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.chromium.net.smoke.TestSupport.Protocol.QUIC; import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.net.UrlRequest; import org.chromium.net.UrlRequest;
import java.net.URL; import java.net.URL;
...@@ -17,37 +25,41 @@ import java.net.URL; ...@@ -17,37 +25,41 @@ import java.net.URL;
/** /**
* QUIC Tests. * QUIC Tests.
*/ */
public class QuicTest extends NativeCronetTestCase { @RunWith(BaseJUnit4ClassRunner.class)
public class QuicTest {
private TestSupport.TestServer mServer; private TestSupport.TestServer mServer;
@Override @Rule
protected void setUp() throws Exception { public NativeCronetTestRule mRule = new NativeCronetTestRule();
super.setUp();
mServer = mTestSupport.createTestServer(getContext(), QUIC); @Before
public void setUp() throws Exception {
mServer = mRule.getTestSupport().createTestServer(
InstrumentationRegistry.getTargetContext(), QUIC);
} }
@Override @After
protected void tearDown() throws Exception { public void tearDown() throws Exception {
mServer.shutdown(); mServer.shutdown();
super.tearDown();
} }
@Test
@SmallTest @SmallTest
public void testQuic() throws Exception { public void testQuic() throws Exception {
assertTrue(mServer.start()); Assert.assertTrue(mServer.start());
final String urlString = mServer.getSuccessURL(); final String urlString = mServer.getSuccessURL();
final URL url = new URL(urlString); final URL url = new URL(urlString);
mCronetEngineBuilder.enableQuic(true); mRule.getCronetEngineBuilder().enableQuic(true);
mCronetEngineBuilder.addQuicHint(url.getHost(), url.getPort(), url.getPort()); mRule.getCronetEngineBuilder().addQuicHint(url.getHost(), url.getPort(), url.getPort());
mTestSupport.installMockCertVerifierForTesting(mCronetEngineBuilder); mRule.getTestSupport().installMockCertVerifierForTesting(mRule.getCronetEngineBuilder());
JSONObject quicParams = new JSONObject(); JSONObject quicParams = new JSONObject();
JSONObject experimentalOptions = new JSONObject().put("QUIC", quicParams); JSONObject experimentalOptions = new JSONObject().put("QUIC", quicParams);
mTestSupport.addHostResolverRules(experimentalOptions); mRule.getTestSupport().addHostResolverRules(experimentalOptions);
mCronetEngineBuilder.setExperimentalOptions(experimentalOptions.toString()); mRule.getCronetEngineBuilder().setExperimentalOptions(experimentalOptions.toString());
initCronetEngine(); mRule.initCronetEngine();
// QUIC is not guaranteed to win the race, so try multiple times. // QUIC is not guaranteed to win the race, so try multiple times.
boolean quicNegotiated = false; boolean quicNegotiated = false;
...@@ -55,15 +67,16 @@ public class QuicTest extends NativeCronetTestCase { ...@@ -55,15 +67,16 @@ public class QuicTest extends NativeCronetTestCase {
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
SmokeTestRequestCallback callback = new SmokeTestRequestCallback(); SmokeTestRequestCallback callback = new SmokeTestRequestCallback();
UrlRequest.Builder requestBuilder = UrlRequest.Builder requestBuilder =
mCronetEngine.newUrlRequestBuilder(urlString, callback, callback.getExecutor()); mRule.getCronetEngine().newUrlRequestBuilder(
urlString, callback, callback.getExecutor());
requestBuilder.build().start(); requestBuilder.build().start();
callback.blockForDone(); callback.blockForDone();
assertSuccessfulNonEmptyResponse(callback, urlString); NativeCronetTestRule.assertSuccessfulNonEmptyResponse(callback, urlString);
if (callback.getResponseInfo().getNegotiatedProtocol().startsWith("http/2+quic/")) { if (callback.getResponseInfo().getNegotiatedProtocol().startsWith("http/2+quic/")) {
quicNegotiated = true; quicNegotiated = true;
break; break;
} }
} }
assertTrue(quicNegotiated); Assert.assertTrue(quicNegotiated);
} }
} }
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