@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testWriteLessThanContentLength() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); // Set a content length that's 1 byte more. connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length + 1); OutputStream out = connection.getOutputStream(); out.write(TestUtil.UPLOAD_DATA); try { connection.getResponseCode(); fail(); } catch (ProtocolException e) { // Expected. } connection.disconnect(); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testFixedLengthStreamingModeWriteOneByte() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length); OutputStream out = connection.getOutputStream(); for (int i = 0; i < TestUtil.UPLOAD_DATA.length; i++) { // Write one byte at a time. out.write(TestUtil.UPLOAD_DATA[i]); } assertEquals(200, connection.getResponseCode()); assertEquals("OK", connection.getResponseMessage()); assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection)); connection.disconnect(); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testPostOneMassiveWriteWriteOneByte() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setChunkedStreamingMode(0); OutputStream out = connection.getOutputStream(); byte[] largeData = TestUtil.getLargeData(); for (int i = 0; i < largeData.length; i++) { out.write(largeData[i]); } assertEquals(200, connection.getResponseCode()); assertEquals("OK", connection.getResponseMessage()); TestUtil.checkLargeData(TestUtil.getResponseAsString(connection)); connection.disconnect(); }
@SmallTest @Feature({"Cronet"}) public void testInitTwoEnginesInSequence() throws Exception { final CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit(); ConditionVariable runBlocker = new ConditionVariable(true); RequestThread thread1 = new RequestThread(testFramework, mUrl, runBlocker); RequestThread thread2 = new RequestThread(testFramework, mUrl404, runBlocker); thread1.start(); thread1.join(); thread2.start(); thread2.join(); assertEquals(200, thread1.mCallback.mResponseInfo.getHttpStatusCode()); assertEquals(404, thread2.mCallback.mResponseInfo.getHttpStatusCode()); }
@SmallTest @Feature({"Android-AppBase"}) public void testAddWhileIteration() { ObserverList<Observer> observerList = new ObserverList<Observer>(); Foo a = new Foo(1); Foo b = new Foo(-1); Foo c = new Foo(1); FooAdder evil = new FooAdder(observerList, c); observerList.addObserver(evil); observerList.addObserver(a); observerList.addObserver(b); for (Observer obs : observerList) obs.observe(10); assertTrue(observerList.hasObserver(c)); assertEquals(10, a.mTotal); assertEquals(-10, b.mTotal); assertEquals(0, c.mTotal); }
/** * Tests recording of boolean histograms. */ @SmallTest public void testRecordBooleanHistogram() { String histogram = "HelloWorld.BooleanMetric"; HistogramDelta falseCount = new HistogramDelta(histogram, 0); HistogramDelta trueCount = new HistogramDelta(histogram, 1); assertEquals(0, trueCount.getDelta()); assertEquals(0, falseCount.getDelta()); RecordHistogram.recordBooleanHistogram(histogram, true); assertEquals(1, trueCount.getDelta()); assertEquals(0, falseCount.getDelta()); RecordHistogram.recordBooleanHistogram(histogram, true); assertEquals(2, trueCount.getDelta()); assertEquals(0, falseCount.getDelta()); RecordHistogram.recordBooleanHistogram(histogram, false); assertEquals(2, trueCount.getDelta()); assertEquals(1, falseCount.getDelta()); }
@SmallTest public void testFinishAndRemoveTask() throws InterruptedException { MockActivity activity = new MockActivity(); ApiCompatibilityUtils.finishAndRemoveTask(activity); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { assertEquals(1, activity.mFinishAndRemoveTaskCallbackCount); assertEquals(0, activity.mFinishCallbackCount); } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) { long startTime = SystemClock.uptimeMillis(); while (activity.mFinishCallbackCount == 0 && SystemClock.uptimeMillis() - startTime < WAIT_TIMEOUT_IN_MS) { Thread.sleep(SLEEP_INTERVAL_IN_MS); } // MockActivity#finishAndRemoveTask() never sets isFinishing() to true for LOLLIPOP to // simulate an exceptional case. In that case, MockActivity#finish() should be called // after 3 tries. assertEquals(3, activity.mFinishAndRemoveTaskCallbackCount); assertEquals(1, activity.mFinishCallbackCount); } else { assertEquals(0, activity.mFinishAndRemoveTaskCallbackCount); assertEquals(1, activity.mFinishCallbackCount); } assertTrue(activity.mIsFinishing); }
@SmallTest @Feature({"Android-AppBase"}) public void testCanRecordEvent() { EarlyTraceEvent.enable(); long myThreadId = Process.myTid(); long beforeMs = SystemClock.elapsedRealtime(); EarlyTraceEvent.begin(EVENT_NAME); EarlyTraceEvent.end(EVENT_NAME); long afterMs = SystemClock.elapsedRealtime(); assertEquals(1, EarlyTraceEvent.sCompletedEvents.size()); assertTrue(EarlyTraceEvent.sPendingEvents.isEmpty()); EarlyTraceEvent.Event event = EarlyTraceEvent.sCompletedEvents.get(0); assertEquals(EVENT_NAME, event.mName); assertEquals(myThreadId, event.mThreadId); assertTrue(beforeMs <= event.mBeginTimeMs && event.mBeginTimeMs <= afterMs); assertTrue(event.mBeginTimeMs <= event.mEndTimeMs); assertTrue(beforeMs <= event.mEndTimeMs && event.mEndTimeMs <= afterMs); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testConnectBeforeWrite() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length); OutputStream out = connection.getOutputStream(); connection.connect(); out.write(TestUtil.UPLOAD_DATA); assertEquals(200, connection.getResponseCode()); assertEquals("OK", connection.getResponseMessage()); assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection)); connection.disconnect(); }
@SmallTest @Feature({"Cronet"}) public void testRedirectURLRequest() throws Exception { createRequestAndWaitForComplete( NativeTestServer.getRedirectURL(), false); // ChromiumUrlRequest does not expose the url after redirect. assertEquals(NativeTestServer.getRedirectURL(), mListener.mUrl); assertEquals(200, mListener.mHttpStatusCode); assertEquals("OK", mListener.mHttpStatusText); // Expect that the request is redirected to success.txt. assertEquals("this is a text file\n", new String(mListener.mResponseAsBytes)); // Test that ChromiumUrlRequest caches information which is available // after the native request adapter has been destroyed. assertEquals(200, mRequest.getHttpStatusCode()); assertEquals("OK", mRequest.getHttpStatusText()); assertNull(mRequest.getException()); checkAfterAdapterDestroyed(mRequest); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testGetOutputStreamAfterConnectionMade() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setChunkedStreamingMode(0); assertEquals(200, connection.getResponseCode()); try { connection.getOutputStream(); fail(); } catch (ProtocolException e) { // Expected. } }
@SmallTest @Feature({"Cronet"}) @OnlyRunNativeCronet public void testSimpleGet() throws Exception { String url = Http2TestServer.getEchoMethodUrl(); TestBidirectionalStreamCallback callback = new TestBidirectionalStreamCallback(); // Create stream. BidirectionalStream stream = new BidirectionalStream .Builder(url, callback, callback.getExecutor(), mTestFramework.mCronetEngine) .setHttpMethod("GET") .build(); stream.start(); callback.blockForDone(); assertTrue(stream.isDone()); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); // Default method is 'GET'. assertEquals("GET", callback.mResponseAsString); UrlResponseInfo urlResponseInfo = createUrlResponseInfo(new String[] {url}, "", 200, 27, ":status", "200"); assertResponseEquals(urlResponseInfo, callback.mResponseInfo); checkResponseInfo(callback.mResponseInfo, Http2TestServer.getEchoMethodUrl(), 200, ""); }
/** * Tests write after connect. Strangely, the default implementation allows * writing after being connected, so this test only runs against Cronet's * implementation. */ @SmallTest @Feature({"Cronet"}) @OnlyRunCronetHttpURLConnection public void testWriteAfterConnect() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStream out = connection.getOutputStream(); out.write(TestUtil.UPLOAD_DATA); connection.connect(); try { // Attemp to write some more. out.write(TestUtil.UPLOAD_DATA); fail(); } catch (IllegalStateException e) { assertEquals("Cannot write after being connected.", e.getMessage()); } }
/** * Tests that {@link CronetBufferedOutputStream} supports rewind in a * POST preserving redirect. * Use {@code OnlyRunCronetHttpURLConnection} as the default implementation * does not pass this test. */ @SmallTest @Feature({"Cronet"}) @OnlyRunCronetHttpURLConnection public void testRewind() throws Exception { URL url = new URL(NativeTestServer.getRedirectToEchoBody()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty( "Content-Length", Integer.toString(TestUtil.UPLOAD_DATA.length)); OutputStream out = connection.getOutputStream(); out.write(TestUtil.UPLOAD_DATA); assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection)); connection.disconnect(); }
@SmallTest @Feature({"Cronet"}) public void testBadFileDescriptorProvider() throws Exception { TestUrlRequestCallback callback = new TestUrlRequestCallback(); UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getRedirectToEchoBody(), callback, callback.getExecutor(), mTestFramework.mCronetEngine); ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe(); try { UploadDataProvider dataProvider = UploadDataProviders.create(pipe[0]); builder.setUploadDataProvider(dataProvider, callback.getExecutor()); builder.addHeader("Content-Type", "useless/string"); builder.build().start(); callback.blockForDone(); assertTrue(callback.mError.getCause() instanceof IllegalArgumentException); } finally { pipe[1].close(); } }
/** * Tests uploading from a channel in the case a redirect preserves the post * body. Since channels can't be rewound, the request fails when we try to * rewind it to send the second request. */ @SmallTest @Feature({"Cronet"}) public void testUploadChannelWithRedirect() throws Exception { TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener(); HttpUrlRequest request = createRequest( NativeTestServer.getRedirectToEchoBody(), listener); setUploadChannel(request, "text/plain", UPLOAD_CHANNEL_DATA, UPLOAD_CHANNEL_DATA.length()); request.start(); listener.blockForComplete(); assertEquals(0, listener.mHttpStatusCode); assertEquals( "System error: net::ERR_UPLOAD_STREAM_REWIND_NOT_SUPPORTED(-25)", listener.mException.getMessage()); }
@SmallTest @Feature({"Cronet"}) public void testSuccessURLRequest() throws Exception { createRequestAndWaitForComplete( NativeTestServer.getSuccessURL(), false); assertEquals(NativeTestServer.getSuccessURL(), mListener.mUrl); assertEquals(200, mListener.mHttpStatusCode); assertEquals("OK", mListener.mHttpStatusText); assertEquals("this is a text file\n", new String(mListener.mResponseAsBytes)); // Test that ChromiumUrlRequest caches information which is available // after the native request adapter has been destroyed. assertEquals(200, mRequest.getHttpStatusCode()); assertEquals("OK", mRequest.getHttpStatusText()); assertNull(mRequest.getException()); checkAfterAdapterDestroyed(mRequest); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet // Tests that redirects across the HTTP and HTTPS boundary are not followed. public void testDoNotFollowRedirectsIfSchemesDontMatch() throws Exception { URL url = new URL(NativeTestServer.getFileURL("/redirect_invalid_scheme.html")); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); assertEquals(302, connection.getResponseCode()); assertEquals("Found", connection.getResponseMessage()); // Behavior changed in Android Marshmallow to not update the URL. if (testingSystemHttpURLConnection() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Redirected port is randomized, verify everything but port. assertEquals(url.getProtocol(), connection.getURL().getProtocol()); assertEquals(url.getHost(), connection.getURL().getHost()); assertEquals(url.getFile(), connection.getURL().getFile()); } else { // Redirect is not followed, but the url is updated to the Location header. assertEquals("https://127.0.0.1:8000/success.txt", connection.getURL().toString()); } connection.disconnect(); }
@SmallTest @Feature({"Cronet"}) @OnlyRunNativeCronet // No canonical exception to assert on public void testContentLengthMismatchFailsOnce() throws Exception { String url = NativeTestServer.getFileURL( "/content_length_mismatch.html"); TestUrlRequestCallback callback = startAndWaitForComplete(url); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); // The entire response body will be read before the error is returned. // This is because the network stack returns data as it's read from the // socket, and the socket close message which triggers the error will // only be passed along after all data has been read. assertEquals("Response that lies about content length.", callback.mResponseAsString); assertNotNull(callback.mError); assertEquals("Exception in CronetUrlRequest: net::ERR_CONTENT_LENGTH_MISMATCH", callback.mError.getMessage()); // Wait for a couple round trips to make sure there are no pending // onFailed messages. This test relies on checks in // TestUrlRequestCallback catching a second onFailed call. testSimpleGet(); }
@SmallTest @Feature({"Cronet"}) public void testSetHttpMethod() throws Exception { TestUrlRequestCallback callback = new TestUrlRequestCallback(); String methodName = "HEAD"; UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getEchoMethodURL(), callback, callback.getExecutor(), mTestFramework.mCronetEngine); // Try to set 'null' method. try { builder.setHttpMethod(null); fail("Exception not thrown"); } catch (NullPointerException e) { assertEquals("Method is required.", e.getMessage()); } builder.setHttpMethod(methodName); builder.build().start(); callback.blockForDone(); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); assertEquals(0, callback.mHttpResponseDataLength); }
@SmallTest @Feature({"Cronet"}) public void testAddHeader() throws Exception { TestUrlRequestCallback callback = new TestUrlRequestCallback(); String headerName = "header-name"; String headerValue = "header-value"; UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getEchoHeaderURL(headerName), callback, callback.getExecutor(), mTestFramework.mCronetEngine); builder.addHeader(headerName, headerValue); builder.build().start(); callback.blockForDone(); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); assertEquals(headerValue, callback.mResponseAsString); }
@SmallTest @Feature({"Cronet"}) public void testMultiRequestHeaders() throws Exception { TestUrlRequestCallback callback = new TestUrlRequestCallback(); String headerName = "header-name"; String headerValue1 = "header-value1"; String headerValue2 = "header-value2"; UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getEchoAllHeadersURL(), callback, callback.getExecutor(), mTestFramework.mCronetEngine); builder.addHeader(headerName, headerValue1); builder.addHeader(headerName, headerValue2); builder.build().start(); callback.blockForDone(); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); String headers = callback.mResponseAsString; Pattern pattern = Pattern.compile(headerName + ":\\s(.*)\\r\\n"); Matcher matcher = pattern.matcher(headers); List<String> actualValues = new ArrayList<String>(); while (matcher.find()) { actualValues.add(matcher.group(1)); } assertEquals(1, actualValues.size()); assertEquals("header-value2", actualValues.get(0)); }
@SmallTest @Feature({"Cronet"}) public void testDefaultUserAgent() throws Exception { TestUrlRequestCallback callback = new TestUrlRequestCallback(); String headerName = "User-Agent"; UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getEchoHeaderURL(headerName), callback, callback.getExecutor(), mTestFramework.mCronetEngine); builder.build().start(); callback.blockForDone(); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); assertTrue("Default User-Agent should contain Cronet/n.n.n.n but is " + callback.mResponseAsString, Pattern.matches( ".+Cronet/\\d+\\.\\d+\\.\\d+\\.\\d+.+", callback.mResponseAsString)); }
@SmallTest @Feature({"Cronet"}) public void testFailedURLRequest() throws Exception { // -2 is the net error code for FAILED. See net_error_list.h. int errorFailed = -2; String failedUrl = MockUrlRequestJobFactory.getMockUrlWithFailure( FailurePhase.START, errorFailed); createRequestAndWaitForComplete(failedUrl, false); assertEquals(failedUrl, mListener.mUrl); assertEquals("", mListener.mHttpStatusText); assertEquals(0, mListener.mHttpStatusCode); // Test that ChromiumUrlRequest caches information which is available // after the native request adapter has been destroyed. assertEquals(0, mRequest.getHttpStatusCode()); assertEquals("", mRequest.getHttpStatusText()); assertEquals("System error: net::ERR_FAILED(-2)", mRequest.getException().getMessage()); checkAfterAdapterDestroyed(mRequest); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testFixedLengthStreamingMode() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length); OutputStream out = connection.getOutputStream(); out.write(TestUtil.UPLOAD_DATA); assertEquals(200, connection.getResponseCode()); assertEquals("OK", connection.getResponseMessage()); assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection)); connection.disconnect(); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testPostWithoutContentLengthWriteOneByte() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStream out = connection.getOutputStream(); byte[] largeData = TestUtil.getLargeData(); for (int i = 0; i < largeData.length; i++) { out.write(largeData[i]); } assertEquals(200, connection.getResponseCode()); assertEquals("OK", connection.getResponseMessage()); TestUtil.checkLargeData(TestUtil.getResponseAsString(connection)); connection.disconnect(); }
@SmallTest @Feature({"Cronet"}) @OnlyRunNativeCronet // Java impl doesn't support MockUrlRequestJobFactory public void testMockReadDataSyncError() throws Exception { final int arbitraryNetError = -4; TestUrlRequestCallback callback = startAndWaitForComplete(MockUrlRequestJobFactory.getMockUrlWithFailure( FailurePhase.READ_SYNC, arbitraryNetError)); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); assertEquals(0, callback.mResponseInfo.getReceivedBytesCount()); assertNotNull(callback.mError); assertEquals(arbitraryNetError, callback.mError.getCronetInternalErrorCode()); assertEquals(0, callback.mRedirectCount); assertTrue(callback.mOnErrorCalled); assertEquals(callback.mResponseStep, ResponseStep.ON_RESPONSE_STARTED); }
@SmallTest @Feature({"Cronet"}) @SuppressWarnings("deprecation") public void testConfigUserAgent() throws Exception { String userAgentName = "User-Agent"; String userAgentValue = "User-Agent-Value"; CronetEngine.Builder cronetEngineBuilder = new CronetEngine.Builder(getContext()); if (testingJavaImpl()) { cronetEngineBuilder.enableLegacyMode(true); } cronetEngineBuilder.setUserAgent(userAgentValue); cronetEngineBuilder.setLibraryName("cronet_tests"); mTestFramework = startCronetTestFrameworkWithUrlAndCronetEngineBuilder(mUrl, cronetEngineBuilder); NativeTestServer.shutdownNativeTestServer(); // startNativeTestServer returns false if it's // already running assertTrue(NativeTestServer.startNativeTestServer(getContext())); TestUrlRequestCallback callback = new TestUrlRequestCallback(); UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(NativeTestServer.getEchoHeaderURL(userAgentName), callback, callback.getExecutor(), mTestFramework.mCronetEngine); urlRequestBuilder.build().start(); callback.blockForDone(); assertEquals(userAgentValue, callback.mResponseAsString); }
@SmallTest @Feature({"Cronet"}) public void testShutdownAfterCancel() throws Exception { mTestFramework = startCronetTestFramework(); TestUrlRequestCallback callback = new TestUrlRequestCallback(); // Block callback when response starts to verify that shutdown fails // if there are active requests. callback.setAutoAdvance(false); UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder( mUrl, callback, callback.getExecutor(), mTestFramework.mCronetEngine); UrlRequest urlRequest = urlRequestBuilder.build(); urlRequest.start(); try { mTestFramework.mCronetEngine.shutdown(); fail("Should throw an exception"); } catch (Exception e) { assertEquals("Cannot shutdown with active requests.", e.getMessage()); } callback.waitForNextStep(); assertEquals(ResponseStep.ON_RESPONSE_STARTED, callback.mResponseStep); urlRequest.cancel(); mTestFramework.mCronetEngine.shutdown(); }
@SmallTest @Feature({"Cronet"}) public void testCronetEngineBuilderConfig() throws Exception { // This is to prompt load of native library. startCronetTestFramework(); // Verify CronetEngine.Builder config is passed down accurately to native code. CronetEngine.Builder builder = new CronetEngine.Builder(getContext()); builder.enableHttp2(false); builder.enableQuic(true); builder.enableSDCH(true); builder.addQuicHint("example.com", 12, 34); builder.setCertVerifierData("test_cert_verifier_data"); builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_IN_MEMORY, 54321); builder.enableDataReductionProxy("abcd"); builder.setUserAgent("efgh"); builder.setExperimentalOptions("ijkl"); builder.setDataReductionProxyOptions("mnop", "qrst", "uvwx"); builder.setStoragePath(CronetTestFramework.getTestStorage(getContext())); builder.enablePublicKeyPinningBypassForLocalTrustAnchors(false); nativeVerifyUrlRequestContextConfig( CronetUrlRequestContext.createNativeUrlRequestContextConfig(getContext(), builder), CronetTestFramework.getTestStorage(getContext())); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testWriteAfterReadingResponse() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStream out = connection.getOutputStream(); assertEquals(200, connection.getResponseCode()); try { out.write(TestUtil.UPLOAD_DATA); fail(); } catch (Exception e) { // Default implementation gives an IOException and says that the // stream is closed. Cronet gives an IllegalStateException and // complains about write after connected. } }
@SmallTest @Feature({"Cronet"}) public void testUploadRedirectSync() throws Exception { TestUrlRequestCallback callback = new TestUrlRequestCallback(); UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getRedirectToEchoBody(), callback, callback.getExecutor(), mTestFramework.mCronetEngine); TestUploadDataProvider dataProvider = new TestUploadDataProvider( TestUploadDataProvider.SuccessCallbackMode.SYNC, callback.getExecutor()); dataProvider.addRead("test".getBytes()); builder.setUploadDataProvider(dataProvider, callback.getExecutor()); builder.addHeader("Content-Type", "useless/string"); builder.build().start(); callback.blockForDone(); dataProvider.assertClosed(); // 1 read call before the rewind, 1 after. assertEquals(2, dataProvider.getNumReadCalls()); assertEquals(1, dataProvider.getNumRewindCalls()); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); assertEquals("test", callback.mResponseAsString); }
@SmallTest @Feature({"Cronet"}) @OnlyRunNativeCronet public void testSimpleHead() throws Exception { String url = Http2TestServer.getEchoMethodUrl(); TestBidirectionalStreamCallback callback = new TestBidirectionalStreamCallback(); // Create stream. BidirectionalStream stream = new BidirectionalStream .Builder(url, callback, callback.getExecutor(), mTestFramework.mCronetEngine) .setHttpMethod("HEAD") .build(); stream.start(); callback.blockForDone(); assertTrue(stream.isDone()); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); assertEquals("HEAD", callback.mResponseAsString); UrlResponseInfo urlResponseInfo = createUrlResponseInfo(new String[] {url}, "", 200, 28, ":status", "200"); assertResponseEquals(urlResponseInfo, callback.mResponseInfo); checkResponseInfo(callback.mResponseInfo, Http2TestServer.getEchoMethodUrl(), 200, ""); }
@SmallTest @Feature({"Cronet"}) @OnlyRunNativeCronet public void testDictionaryNotFound() throws Exception { setUp(Sdch.ENABLED, Api.ASYNC); // Make a request to /sdch/index which advertises a bad dictionary that // does not exist. TestUrlRequestCallback callback1 = startAndWaitForComplete(mTestFramework.mCronetEngine, NativeTestServer.getSdchURL() + "/sdch/index?q=NotFound"); assertEquals(200, callback1.mResponseInfo.getHttpStatusCode()); assertEquals("This is an index page.\n", callback1.mResponseAsString); assertEquals(Arrays.asList("/sdch/dict/NotFound"), callback1.mResponseInfo.getAllHeaders().get("Get-Dictionary")); // Make a request to fetch /sdch/test, and make sure Sdch encoding is not used. TestUrlRequestCallback callback2 = startAndWaitForComplete( mTestFramework.mCronetEngine, NativeTestServer.getSdchURL() + "/sdch/test"); assertEquals(200, callback2.mResponseInfo.getHttpStatusCode()); assertEquals("Sdch is not used.\n", callback2.mResponseAsString); }
@SmallTest @Feature({"Cronet"}) public void testUploadReadFailSync() throws Exception { TestUrlRequestCallback callback = new TestUrlRequestCallback(); UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getEchoBodyURL(), callback, callback.getExecutor(), mTestFramework.mCronetEngine); TestUploadDataProvider dataProvider = new TestUploadDataProvider( TestUploadDataProvider.SuccessCallbackMode.SYNC, callback.getExecutor()); dataProvider.setReadFailure(0, TestUploadDataProvider.FailMode.CALLBACK_SYNC); // This will never be read, but if the length is 0, read may never be // called. dataProvider.addRead("test".getBytes()); builder.setUploadDataProvider(dataProvider, callback.getExecutor()); builder.addHeader("Content-Type", "useless/string"); builder.build().start(); callback.blockForDone(); dataProvider.assertClosed(); assertEquals(1, dataProvider.getNumReadCalls()); assertEquals(0, dataProvider.getNumRewindCalls()); assertEquals("Exception received from UploadDataProvider", callback.mError.getMessage()); assertEquals("Sync read failure", callback.mError.getCause().getMessage()); assertEquals(null, callback.mResponseInfo); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testGetOutputStreamAfterConnectionMade() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); assertEquals(200, connection.getResponseCode()); try { connection.getOutputStream(); fail(); } catch (java.net.ProtocolException e) { // Expected. } }
@SmallTest @Feature({"Cronet"}) public void testUploadRewindFailSync() throws Exception { TestUrlRequestCallback callback = new TestUrlRequestCallback(); UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getRedirectToEchoBody(), callback, callback.getExecutor(), mTestFramework.mCronetEngine); TestUploadDataProvider dataProvider = new TestUploadDataProvider( TestUploadDataProvider.SuccessCallbackMode.SYNC, callback.getExecutor()); dataProvider.setRewindFailure(TestUploadDataProvider.FailMode.CALLBACK_SYNC); dataProvider.addRead("test".getBytes()); builder.setUploadDataProvider(dataProvider, callback.getExecutor()); builder.addHeader("Content-Type", "useless/string"); builder.build().start(); callback.blockForDone(); dataProvider.assertClosed(); assertEquals(1, dataProvider.getNumReadCalls()); assertEquals(1, dataProvider.getNumRewindCalls()); assertEquals("Exception received from UploadDataProvider", callback.mError.getMessage()); assertEquals("Sync rewind failure", callback.mError.getCause().getMessage()); assertEquals(null, callback.mResponseInfo); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testInitOutputStreamInConnect() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); String dataString = "some very important data"; byte[] data = dataString.getBytes(); connection.setFixedLengthStreamingMode(data.length); connection.connect(); OutputStream out = connection.getOutputStream(); out.write(data); assertEquals(200, connection.getResponseCode()); assertEquals("OK", connection.getResponseMessage()); assertEquals(dataString, TestUtil.getResponseAsString(connection)); connection.disconnect(); }
@SmallTest @Feature({"Cronet"}) public void testInitEngineStartTwoRequests() throws Exception { CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit(); // Make two requests after initializing the context. CronetEngine cronetEngine = testFramework.initCronetEngine(); int[] statusCodes = {0, 0}; String[] urls = {mUrl, mUrl404}; for (int i = 0; i < 2; i++) { TestUrlRequestCallback callback = new TestUrlRequestCallback(); UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(urls[i], callback, callback.getExecutor(), cronetEngine); urlRequestBuilder.build().start(); callback.blockForDone(); statusCodes[i] = callback.mResponseInfo.getHttpStatusCode(); } assertEquals(200, statusCodes[0]); assertEquals(404, statusCodes[1]); }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testPostWithoutContentLengthOneMassiveWrite() throws Exception { URL url = new URL(NativeTestServer.getEchoBodyURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStream out = connection.getOutputStream(); byte[] largeData = TestUtil.getLargeData(); out.write(largeData); assertEquals(200, connection.getResponseCode()); assertEquals("OK", connection.getResponseMessage()); TestUtil.checkLargeData(TestUtil.getResponseAsString(connection)); connection.disconnect(); }