public class FakeRequestQueue extends RequestQueue { public FakeRequestQueue(Context context) { super(new NoCache(), new BasicNetwork(new FakeHttpStack(context))); } }
addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); responseContents = entityToBytes(httpResponse.getEntity()); } else { logSlowRequests(requestLifetime, request, responseContents, statusLine); SystemClock.elapsedRealtime() - requestStart); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else {
fakeResponse.setEntity(new StringEntity("foobar")); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = new Request<String>(Request.Method.GET, "http://foo", null) { httpNetwork.performRequest(request); assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader")); assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody()));
@Test public void parseCaseInsensitive() { long now = System.currentTimeMillis(); Header[] headersArray = new Header[5]; headersArray[0] = new BasicHeader("eTAG", "Yow!"); headersArray[1] = new BasicHeader("DATE", rfc1123Date(now)); headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS)); headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400"); headersArray[4] = new BasicHeader("content-type", "text/plain"); Map<String, String> headers = BasicNetwork.convertHeaders(headersArray); NetworkResponse response = new NetworkResponse(0, null, headers, false); Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response); assertNotNull(entry); assertEquals("Yow!", entry.etag); assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS); assertEquals(entry.softTtl, entry.ttl); assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers)); } }
fakeResponse.setEntity(new StringEntity("foobar")); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = new Request<String>(Request.Method.GET, "http://foo", null) { httpNetwork.performRequest(request); assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader")); assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody()));
@Test public void parseCaseInsensitive() { long now = System.currentTimeMillis(); Header[] headersArray = new Header[5]; headersArray[0] = new BasicHeader("eTAG", "Yow!"); headersArray[1] = new BasicHeader("DATE", rfc1123Date(now)); headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS)); headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400"); headersArray[4] = new BasicHeader("content-type", "text/plain"); Map<String, String> headers = BasicNetwork.convertHeaders(headersArray); NetworkResponse response = new NetworkResponse(0, null, headers, false); Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response); assertNotNull(entry); assertEquals("Yow!", entry.etag); assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS); assertEquals(entry.softTtl, entry.ttl); assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers)); } }
addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); responseContents = entityToBytes(httpResponse.getEntity()); } else { logSlowRequests(requestLifetime, request, responseContents, statusLine); SystemClock.elapsedRealtime() - requestStart); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else {
public static RequestQueue newRequestQueueForTest(final Context context, final OkHttpClient okHttpClient) { final File cacheDir = new File(context.getCacheDir(), "volley"); final Network network = new BasicNetwork(new OkHttpStack(okHttpClient)); final ResponseDelivery responseDelivery = new ExecutorDelivery(Executors.newSingleThreadExecutor()); final RequestQueue queue = new RequestQueue( new DiskBasedCache(cacheDir), network, 4, responseDelivery); queue.start(); return queue; }
@Test public void noConnection() throws Exception { MockHttpStack mockHttpStack = new MockHttpStack(); mockHttpStack.setExceptionToThrow(new IOException()); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should not retry when there is no connection verify(mMockRetryPolicy, never()).retry(any(VolleyError.class)); }
@Test public void parseCaseInsensitive() { long now = System.currentTimeMillis(); Header[] headersArray = new Header[5]; headersArray[0] = new BasicHeader("eTAG", "Yow!"); headersArray[1] = new BasicHeader("DATE", rfc1123Date(now)); headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS)); headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400"); headersArray[4] = new BasicHeader("content-type", "text/plain"); Map<String, String> headers = BasicNetwork.convertHeaders(headersArray); NetworkResponse response = new NetworkResponse(0, null, headers, false); Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response); assertNotNull(entry); assertEquals("Yow!", entry.etag); assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS); assertEquals(entry.softTtl, entry.ttl); assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers)); } }
addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); responseContents = entityToBytes(httpResponse.getEntity()); } else { logSlowRequests(requestLifetime, request, responseContents, statusLine); SystemClock.elapsedRealtime() - requestStart); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { attemptRetryOnException("redirect", request, new RedirectError(networkResponse)); } else {
/** * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. * * @param context A {@link android.content.Context} to use for creating the cache dir. * @param stack An {@link HttpStack} to use for the network, or null for default. * @return A started {@link RequestQueue} instance. */ public static RequestQueue newRequestQueue(Context context, HttpStack stack) { File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); String userAgent = "volley/0"; try { String packageName = context.getPackageName(); PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); userAgent = packageName + "/" + info.versionCode; } catch (NameNotFoundException e) { } if (stack == null) { if (Build.VERSION.SDK_INT >= 9) { stack = new HurlStack(); } else { // Prior to Gingerbread, HttpUrlConnection was unreliable. // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); } } Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); queue.start(); return queue; }
@Test public void socketTimeout() throws Exception { MockHttpStack mockHttpStack = new MockHttpStack(); mockHttpStack.setExceptionToThrow(new SocketTimeoutException()); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should retry socket timeouts verify(mMockRetryPolicy).retry(any(TimeoutError.class)); }
@Test public void parseCaseInsensitive() { long now = System.currentTimeMillis(); Header[] headersArray = new Header[5]; headersArray[0] = new BasicHeader("eTAG", "Yow!"); headersArray[1] = new BasicHeader("DATE", rfc1123Date(now)); headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS)); headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400"); headersArray[4] = new BasicHeader("content-type", "text/plain"); Map<String, String> headers = BasicNetwork.convertHeaders(headersArray); NetworkResponse response = new NetworkResponse(0, null, headers, false); Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response); assertNotNull(entry); assertEquals("Yow!", entry.etag); assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS); assertEquals(entry.softTtl, entry.ttl); assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers)); } }
addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); responseContents = entityToBytes(httpResponse.getEntity()); } else { logSlowRequests(requestLifetime, request, responseContents, statusLine); SystemClock.elapsedRealtime() - requestStart); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { attemptRetryOnException("redirect", request, new RedirectError(networkResponse)); } else {
/** * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. * * @param context A {@link Context} to use for creating the cache dir. * @param stack An {@link HttpStack} to use for the network, or null for default. * @return A started {@link RequestQueue} instance. */ public static RequestQueue newRequestQueue(Context context, HttpStack stack) { File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); String userAgent = "volley/0"; try { String packageName = context.getPackageName(); PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); userAgent = packageName + "/" + info.versionCode; } catch (NameNotFoundException e) { } if (stack == null) { if (Build.VERSION.SDK_INT >= 9) { stack = new HurlStack(); } else { // Prior to Gingerbread, HttpUrlConnection was unreliable. // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); } } Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); queue.start(); return queue; }
@Test public void connectTimeout() throws Exception { MockHttpStack mockHttpStack = new MockHttpStack(); mockHttpStack.setExceptionToThrow(new ConnectTimeoutException()); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should retry connection timeouts verify(mMockRetryPolicy).retry(any(TimeoutError.class)); }
@Test public void parseCaseInsensitive() { long now = System.currentTimeMillis(); Header[] headersArray = new Header[5]; headersArray[0] = new BasicHeader("eTAG", "Yow!"); headersArray[1] = new BasicHeader("DATE", rfc1123Date(now)); headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS)); headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400"); headersArray[4] = new BasicHeader("content-type", "text/plain"); Map<String, String> headers = BasicNetwork.convertHeaders(headersArray); NetworkResponse response = new NetworkResponse(0, null, headers, false); Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response); assertNotNull(entry); assertEquals("Yow!", entry.etag); assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS); assertEquals(entry.softTtl, entry.ttl); assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers)); } }
addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); responseContents = entityToBytes(httpResponse.getEntity()); } else { logSlowRequests(requestLifetime, request, responseContents, statusLine); attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { attemptRetryOnException("redirect", request, new AuthFailureError(networkResponse)); } else {
Network network = new BasicNetwork(stack);