diff --git a/pom.xml b/pom.xml
index d7ef8a995..7b7ecba85 100644
--- a/pom.xml
+++ b/pom.xml
@@ -42,7 +42,7 @@
1.47
- 3.8.2
+ 4.10
diff --git a/src/main/java/com/squareup/okhttp/internal/net/http/HttpAuthenticator.java b/src/main/java/com/squareup/okhttp/internal/net/http/HttpAuthenticator.java
index eed1a78c9..4345f2d93 100644
--- a/src/main/java/com/squareup/okhttp/internal/net/http/HttpAuthenticator.java
+++ b/src/main/java/com/squareup/okhttp/internal/net/http/HttpAuthenticator.java
@@ -42,7 +42,7 @@ public final class HttpAuthenticator {
* @return true if credentials have been added to successorRequestHeaders
* and another request should be attempted.
*/
- public static boolean processAuthHeader(int responseCode, RawHeaders responeHeaders,
+ public static boolean processAuthHeader(int responseCode, RawHeaders responseHeaders,
RawHeaders successorRequestHeaders, Proxy proxy, URL url) throws IOException {
if (responseCode != HTTP_PROXY_AUTH && responseCode != HTTP_UNAUTHORIZED) {
throw new IllegalArgumentException();
@@ -52,7 +52,7 @@ public final class HttpAuthenticator {
String challengeHeader = responseCode == HTTP_PROXY_AUTH
? "Proxy-Authenticate"
: "WWW-Authenticate";
- String credentials = getCredentials(responeHeaders, challengeHeader, proxy, url);
+ String credentials = getCredentials(responseHeaders, challengeHeader, proxy, url);
if (credentials == null) {
return false; // Could not find credentials so end the request cycle.
}
diff --git a/src/main/java/com/squareup/okhttp/internal/net/http/HttpDate.java b/src/main/java/com/squareup/okhttp/internal/net/http/HttpDate.java
index d8f218b2b..60f1f3559 100644
--- a/src/main/java/com/squareup/okhttp/internal/net/http/HttpDate.java
+++ b/src/main/java/com/squareup/okhttp/internal/net/http/HttpDate.java
@@ -26,7 +26,7 @@ import java.util.TimeZone;
/**
* Best-effort parser for HTTP dates.
*/
-public final class HttpDate {
+final class HttpDate {
/**
* Most websites serve cookies in the blessed format. Eagerly create the parser to ensure such
diff --git a/src/main/java/com/squareup/okhttp/internal/net/http/HttpEngine.java b/src/main/java/com/squareup/okhttp/internal/net/http/HttpEngine.java
index a58ea2313..abb9fa648 100644
--- a/src/main/java/com/squareup/okhttp/internal/net/http/HttpEngine.java
+++ b/src/main/java/com/squareup/okhttp/internal/net/http/HttpEngine.java
@@ -596,7 +596,7 @@ public class HttpEngine {
return null;
}
- public static final String getDefaultUserAgent() {
+ public static String getDefaultUserAgent() {
String agent = System.getProperty("http.agent");
return agent != null ? agent : ("Java" + System.getProperty("java.version"));
}
diff --git a/src/main/java/com/squareup/okhttp/internal/net/http/HttpsURLConnectionImpl.java b/src/main/java/com/squareup/okhttp/internal/net/http/HttpsURLConnectionImpl.java
index 85602ab95..dbf56986e 100644
--- a/src/main/java/com/squareup/okhttp/internal/net/http/HttpsURLConnectionImpl.java
+++ b/src/main/java/com/squareup/okhttp/internal/net/http/HttpsURLConnectionImpl.java
@@ -261,8 +261,8 @@ public final class HttpsURLConnectionImpl extends HttpsURLConnection {
}
@Override
- public String getHeaderFieldKey(int posn) {
- return delegate.getHeaderFieldKey(posn);
+ public String getHeaderFieldKey(int position) {
+ return delegate.getHeaderFieldKey(position);
}
@Override
diff --git a/src/main/java/com/squareup/okhttp/internal/net/http/RequestHeaders.java b/src/main/java/com/squareup/okhttp/internal/net/http/RequestHeaders.java
index ca872c2e1..b53fc8106 100644
--- a/src/main/java/com/squareup/okhttp/internal/net/http/RequestHeaders.java
+++ b/src/main/java/com/squareup/okhttp/internal/net/http/RequestHeaders.java
@@ -24,7 +24,7 @@ import java.util.Map;
/**
* Parsed HTTP request headers.
*/
-public final class RequestHeaders {
+final class RequestHeaders {
private final URI uri;
private final RawHeaders headers;
diff --git a/src/main/java/com/squareup/okhttp/internal/net/http/ResponseHeaders.java b/src/main/java/com/squareup/okhttp/internal/net/http/ResponseHeaders.java
index 2061960d7..5e6962d10 100644
--- a/src/main/java/com/squareup/okhttp/internal/net/http/ResponseHeaders.java
+++ b/src/main/java/com/squareup/okhttp/internal/net/http/ResponseHeaders.java
@@ -32,7 +32,7 @@ import java.util.concurrent.TimeUnit;
/**
* Parsed HTTP response headers.
*/
-public final class ResponseHeaders {
+final class ResponseHeaders {
/** HTTP header name for the local time when the request was sent. */
private static final String SENT_MILLIS = "X-Android-Sent-Millis";
diff --git a/src/main/java/com/squareup/okhttp/internal/net/http/RouteSelector.java b/src/main/java/com/squareup/okhttp/internal/net/http/RouteSelector.java
index 1d6571c5c..81ddf96fd 100644
--- a/src/main/java/com/squareup/okhttp/internal/net/http/RouteSelector.java
+++ b/src/main/java/com/squareup/okhttp/internal/net/http/RouteSelector.java
@@ -37,7 +37,7 @@ import java.util.NoSuchElementException;
* choice of proxy server, IP address, and TLS mode. Connections may also be
* recycled.
*/
-public final class RouteSelector {
+final class RouteSelector {
/**
* A TLS connection with useful extensions enabled. This mode supports more
* features, but is less likely to be compatible with older HTTP servers.
diff --git a/src/test/java/com/squareup/okhttp/internal/io/DiskLruCacheTest.java b/src/test/java/com/squareup/okhttp/internal/io/DiskLruCacheTest.java
index 7375be0f6..c77cdd9a3 100644
--- a/src/test/java/com/squareup/okhttp/internal/io/DiskLruCacheTest.java
+++ b/src/test/java/com/squareup/okhttp/internal/io/DiskLruCacheTest.java
@@ -30,18 +30,24 @@ import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import junit.framework.TestCase;
+import org.junit.After;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import org.junit.Before;
+import org.junit.Test;
-public final class DiskLruCacheTest extends TestCase {
+public final class DiskLruCacheTest {
private final int appVersion = 100;
private String javaTmpDir;
private File cacheDir;
private File journalFile;
private DiskLruCache cache;
-// private final MockOs mockOs = new MockOs();
- @Override public void setUp() throws Exception {
- super.setUp();
+ @Before public void setUp() throws Exception {
javaTmpDir = System.getProperty("java.io.tmpdir");
cacheDir = new File(javaTmpDir, "DiskLruCacheTest");
cacheDir.mkdir();
@@ -50,21 +56,18 @@ public final class DiskLruCacheTest extends TestCase {
file.delete();
}
cache = DiskLruCache.open(cacheDir, appVersion, 2, Integer.MAX_VALUE);
-// mockOs.install();
}
- @Override protected void tearDown() throws Exception {
-// mockOs.uninstall();
+ @After public void tearDown() throws Exception {
cache.close();
- super.tearDown();
}
- public void testEmptyCache() throws Exception {
+ @Test public void emptyCache() throws Exception {
cache.close();
assertJournalEquals();
}
- public void testWriteAndReadEntry() throws Exception {
+ @Test public void writeAndReadEntry() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1");
creator.set(0, "ABC");
creator.set(1, "DE");
@@ -79,7 +82,7 @@ public final class DiskLruCacheTest extends TestCase {
assertEquals("DE", snapshot.getString(1));
}
- public void testReadAndWriteEntryAcrossCacheOpenAndClose() throws Exception {
+ @Test public void readAndWriteEntryAcrossCacheOpenAndClose() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1");
creator.set(0, "A");
creator.set(1, "B");
@@ -93,7 +96,7 @@ public final class DiskLruCacheTest extends TestCase {
snapshot.close();
}
- public void testJournalWithEditAndPublish() throws Exception {
+ @Test public void journalWithEditAndPublish() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1");
assertJournalEquals("DIRTY k1"); // DIRTY must always be flushed
creator.set(0, "AB");
@@ -103,7 +106,7 @@ public final class DiskLruCacheTest extends TestCase {
assertJournalEquals("DIRTY k1", "CLEAN k1 2 1");
}
- public void testRevertedNewFileIsRemoveInJournal() throws Exception {
+ @Test public void revertedNewFileIsRemoveInJournal() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1");
assertJournalEquals("DIRTY k1"); // DIRTY must always be flushed
creator.set(0, "AB");
@@ -113,13 +116,13 @@ public final class DiskLruCacheTest extends TestCase {
assertJournalEquals("DIRTY k1", "REMOVE k1");
}
- public void testUnterminatedEditIsRevertedOnClose() throws Exception {
+ @Test public void unterminatedEditIsRevertedOnClose() throws Exception {
cache.edit("k1");
cache.close();
assertJournalEquals("DIRTY k1", "REMOVE k1");
}
- public void testJournalDoesNotIncludeReadOfYetUnpublishedValue() throws Exception {
+ @Test public void journalDoesNotIncludeReadOfYetUnpublishedValue() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1");
assertNull(cache.get("k1"));
creator.set(0, "A");
@@ -129,7 +132,7 @@ public final class DiskLruCacheTest extends TestCase {
assertJournalEquals("DIRTY k1", "CLEAN k1 1 2");
}
- public void testJournalWithEditAndPublishAndRead() throws Exception {
+ @Test public void journalWithEditAndPublishAndRead() throws Exception {
DiskLruCache.Editor k1Creator = cache.edit("k1");
k1Creator.set(0, "AB");
k1Creator.set(1, "C");
@@ -146,7 +149,7 @@ public final class DiskLruCacheTest extends TestCase {
"READ k1");
}
- public void testCannotOperateOnEditAfterPublish() throws Exception {
+ @Test public void cannotOperateOnEditAfterPublish() throws Exception {
DiskLruCache.Editor editor = cache.edit("k1");
editor.set(0, "A");
editor.set(1, "B");
@@ -154,7 +157,7 @@ public final class DiskLruCacheTest extends TestCase {
assertInoperable(editor);
}
- public void testCannotOperateOnEditAfterRevert() throws Exception {
+ @Test public void cannotOperateOnEditAfterRevert() throws Exception {
DiskLruCache.Editor editor = cache.edit("k1");
editor.set(0, "A");
editor.set(1, "B");
@@ -162,7 +165,7 @@ public final class DiskLruCacheTest extends TestCase {
assertInoperable(editor);
}
- public void testExplicitRemoveAppliedToDiskImmediately() throws Exception {
+ @Test public void explicitRemoveAppliedToDiskImmediately() throws Exception {
DiskLruCache.Editor editor = cache.edit("k1");
editor.set(0, "ABC");
editor.set(1, "B");
@@ -177,7 +180,7 @@ public final class DiskLruCacheTest extends TestCase {
* Each read sees a snapshot of the file at the time read was called.
* This means that two reads of the same key can see different data.
*/
- public void testReadAndWriteOverlapsMaintainConsistency() throws Exception {
+ @Test public void readAndWriteOverlapsMaintainConsistency() throws Exception {
DiskLruCache.Editor v1Creator = cache.edit("k1");
v1Creator.set(0, "AAaa");
v1Creator.set(1, "BBbb");
@@ -204,7 +207,7 @@ public final class DiskLruCacheTest extends TestCase {
snapshot1.close();
}
- public void testOpenWithDirtyKeyDeletesAllFilesForThatKey() throws Exception {
+ @Test public void openWithDirtyKeyDeletesAllFilesForThatKey() throws Exception {
cache.close();
File cleanFile0 = getCleanFile("k1", 0);
File cleanFile1 = getCleanFile("k1", 1);
@@ -223,7 +226,7 @@ public final class DiskLruCacheTest extends TestCase {
assertNull(cache.get("k1"));
}
- public void testOpenWithInvalidVersionClearsDirectory() throws Exception {
+ @Test public void openWithInvalidVersionClearsDirectory() throws Exception {
cache.close();
generateSomeGarbageFiles();
createJournalWithHeader(MAGIC, "0", "100", "2", "");
@@ -231,7 +234,7 @@ public final class DiskLruCacheTest extends TestCase {
assertGarbageFilesAllDeleted();
}
- public void testOpenWithInvalidAppVersionClearsDirectory() throws Exception {
+ @Test public void openWithInvalidAppVersionClearsDirectory() throws Exception {
cache.close();
generateSomeGarbageFiles();
createJournalWithHeader(MAGIC, "1", "101", "2", "");
@@ -239,7 +242,7 @@ public final class DiskLruCacheTest extends TestCase {
assertGarbageFilesAllDeleted();
}
- public void testOpenWithInvalidValueCountClearsDirectory() throws Exception {
+ @Test public void openWithInvalidValueCountClearsDirectory() throws Exception {
cache.close();
generateSomeGarbageFiles();
createJournalWithHeader(MAGIC, "1", "100", "1", "");
@@ -247,7 +250,7 @@ public final class DiskLruCacheTest extends TestCase {
assertGarbageFilesAllDeleted();
}
- public void testOpenWithInvalidBlankLineClearsDirectory() throws Exception {
+ @Test public void openWithInvalidBlankLineClearsDirectory() throws Exception {
cache.close();
generateSomeGarbageFiles();
createJournalWithHeader(MAGIC, "1", "100", "2", "x");
@@ -255,7 +258,7 @@ public final class DiskLruCacheTest extends TestCase {
assertGarbageFilesAllDeleted();
}
- public void testOpenWithInvalidJournalLineClearsDirectory() throws Exception {
+ @Test public void openWithInvalidJournalLineClearsDirectory() throws Exception {
cache.close();
generateSomeGarbageFiles();
createJournal("CLEAN k1 1 1", "BOGUS");
@@ -264,7 +267,7 @@ public final class DiskLruCacheTest extends TestCase {
assertNull(cache.get("k1"));
}
- public void testOpenWithInvalidFileSizeClearsDirectory() throws Exception {
+ @Test public void openWithInvalidFileSizeClearsDirectory() throws Exception {
cache.close();
generateSomeGarbageFiles();
createJournal("CLEAN k1 0000x001 1");
@@ -273,7 +276,7 @@ public final class DiskLruCacheTest extends TestCase {
assertNull(cache.get("k1"));
}
- public void testOpenWithTruncatedLineDiscardsThatLine() throws Exception {
+ @Test public void openWithTruncatedLineDiscardsThatLine() throws Exception {
cache.close();
writeFile(getCleanFile("k1", 0), "A");
writeFile(getCleanFile("k1", 1), "B");
@@ -284,7 +287,7 @@ public final class DiskLruCacheTest extends TestCase {
assertNull(cache.get("k1"));
}
- public void testOpenWithTooManyFileSizesClearsDirectory() throws Exception {
+ @Test public void openWithTooManyFileSizesClearsDirectory() throws Exception {
cache.close();
generateSomeGarbageFiles();
createJournal("CLEAN k1 1 1 1");
@@ -293,7 +296,7 @@ public final class DiskLruCacheTest extends TestCase {
assertNull(cache.get("k1"));
}
- public void testKeyWithSpaceNotPermitted() throws Exception {
+ @Test public void keyWithSpaceNotPermitted() throws Exception {
try {
cache.edit("my key");
fail();
@@ -301,7 +304,7 @@ public final class DiskLruCacheTest extends TestCase {
}
}
- public void testKeyWithNewlineNotPermitted() throws Exception {
+ @Test public void keyWithNewlineNotPermitted() throws Exception {
try {
cache.edit("my\nkey");
fail();
@@ -309,7 +312,7 @@ public final class DiskLruCacheTest extends TestCase {
}
}
- public void testKeyWithCarriageReturnNotPermitted() throws Exception {
+ @Test public void keyWithCarriageReturnNotPermitted() throws Exception {
try {
cache.edit("my\rkey");
fail();
@@ -317,7 +320,7 @@ public final class DiskLruCacheTest extends TestCase {
}
}
- public void testNullKeyThrows() throws Exception {
+ @Test public void nullKeyThrows() throws Exception {
try {
cache.edit(null);
fail();
@@ -325,7 +328,7 @@ public final class DiskLruCacheTest extends TestCase {
}
}
- public void testCreateNewEntryWithTooFewValuesFails() throws Exception {
+ @Test public void createNewEntryWithTooFewValuesFails() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1");
creator.set(1, "A");
try {
@@ -346,7 +349,7 @@ public final class DiskLruCacheTest extends TestCase {
creator2.commit();
}
- public void testCreateNewEntryWithMissingFileAborts() throws Exception {
+ @Test public void createNewEntryWithMissingFileAborts() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1");
creator.set(0, "A");
creator.set(1, "A");
@@ -368,7 +371,7 @@ public final class DiskLruCacheTest extends TestCase {
creator2.commit();
}
- public void testRevertWithTooFewValues() throws Exception {
+ @Test public void revertWithTooFewValues() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1");
creator.set(1, "A");
creator.abort();
@@ -379,7 +382,7 @@ public final class DiskLruCacheTest extends TestCase {
assertNull(cache.get("k1"));
}
- public void testUpdateExistingEntryWithTooFewValuesReusesPreviousValues() throws Exception {
+ @Test public void updateExistingEntryWithTooFewValuesReusesPreviousValues() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1");
creator.set(0, "A");
creator.set(1, "B");
@@ -395,7 +398,7 @@ public final class DiskLruCacheTest extends TestCase {
snapshot.close();
}
- public void testEvictOnInsert() throws Exception {
+ @Test public void evictOnInsert() throws Exception {
cache.close();
cache = DiskLruCache.open(cacheDir, appVersion, 2, 10);
@@ -431,7 +434,7 @@ public final class DiskLruCacheTest extends TestCase {
assertValue("E", "eeee", "eeee");
}
- public void testEvictOnUpdate() throws Exception {
+ @Test public void evictOnUpdate() throws Exception {
cache.close();
cache = DiskLruCache.open(cacheDir, appVersion, 2, 10);
@@ -449,7 +452,7 @@ public final class DiskLruCacheTest extends TestCase {
assertValue("C", "c", "cc");
}
- public void testEvictionHonorsLruFromCurrentSession() throws Exception {
+ @Test public void evictionHonorsLruFromCurrentSession() throws Exception {
cache.close();
cache = DiskLruCache.open(cacheDir, appVersion, 2, 10);
set("A", "a", "a");
@@ -473,7 +476,7 @@ public final class DiskLruCacheTest extends TestCase {
assertValue("F", "f", "f");
}
- public void testEvictionHonorsLruFromPreviousSession() throws Exception {
+ @Test public void evictionHonorsLruFromPreviousSession() throws Exception {
set("A", "a", "a");
set("B", "b", "b");
set("C", "c", "c");
@@ -497,7 +500,7 @@ public final class DiskLruCacheTest extends TestCase {
assertValue("G", "g", "g");
}
- public void testCacheSingleEntryOfSizeGreaterThanMaxSize() throws Exception {
+ @Test public void cacheSingleEntryOfSizeGreaterThanMaxSize() throws Exception {
cache.close();
cache = DiskLruCache.open(cacheDir, appVersion, 2, 10);
set("A", "aaaaa", "aaaaaa"); // size=11
@@ -505,7 +508,7 @@ public final class DiskLruCacheTest extends TestCase {
assertAbsent("A");
}
- public void testCacheSingleValueOfSizeGreaterThanMaxSize() throws Exception {
+ @Test public void cacheSingleValueOfSizeGreaterThanMaxSize() throws Exception {
cache.close();
cache = DiskLruCache.open(cacheDir, appVersion, 2, 10);
set("A", "aaaaaaaaaaa", "a"); // size=12
@@ -513,7 +516,7 @@ public final class DiskLruCacheTest extends TestCase {
assertAbsent("A");
}
- public void testConstructorDoesNotAllowZeroCacheSize() throws Exception {
+ @Test public void constructorDoesNotAllowZeroCacheSize() throws Exception {
try {
DiskLruCache.open(cacheDir, appVersion, 2, 0);
fail();
@@ -521,7 +524,7 @@ public final class DiskLruCacheTest extends TestCase {
}
}
- public void testConstructorDoesNotAllowZeroValuesPerEntry() throws Exception {
+ @Test public void constructorDoesNotAllowZeroValuesPerEntry() throws Exception {
try {
DiskLruCache.open(cacheDir, appVersion, 0, 10);
fail();
@@ -529,18 +532,18 @@ public final class DiskLruCacheTest extends TestCase {
}
}
- public void testRemoveAbsentElement() throws Exception {
+ @Test public void removeAbsentElement() throws Exception {
cache.remove("A");
}
- public void testReadingTheSameStreamMultipleTimes() throws Exception {
+ @Test public void readingTheSameStreamMultipleTimes() throws Exception {
set("A", "a", "b");
DiskLruCache.Snapshot snapshot = cache.get("A");
assertSame(snapshot.getInputStream(0), snapshot.getInputStream(0));
snapshot.close();
}
- public void testRebuildJournalOnRepeatedReads() throws Exception {
+ @Test public void rebuildJournalOnRepeatedReads() throws Exception {
set("A", "a", "a");
set("B", "b", "b");
long lastJournalLength = 0;
@@ -557,7 +560,7 @@ public final class DiskLruCacheTest extends TestCase {
}
}
- public void testRebuildJournalOnRepeatedEdits() throws Exception {
+ @Test public void rebuildJournalOnRepeatedEdits() throws Exception {
long lastJournalLength = 0;
while (true) {
long journalLength = journalFile.length();
@@ -576,7 +579,7 @@ public final class DiskLruCacheTest extends TestCase {
assertValue("B", "b", "b");
}
- public void testOpenCreatesDirectoryIfNecessary() throws Exception {
+ @Test public void openCreatesDirectoryIfNecessary() throws Exception {
cache.close();
File dir = new File(javaTmpDir, "testOpenCreatesDirectoryIfNecessary");
cache = DiskLruCache.open(dir, appVersion, 2, Integer.MAX_VALUE);
@@ -586,42 +589,13 @@ public final class DiskLruCacheTest extends TestCase {
assertTrue(new File(dir, "journal").exists());
}
- public void testFileDeletedExternally() throws Exception {
+ @Test public void fileDeletedExternally() throws Exception {
set("A", "a", "a");
getCleanFile("A", 1).delete();
assertNull(cache.get("A"));
}
-// public void testFileBecomesInaccessibleDuringReadResultsInIoException() throws Exception {
-// set("A", "aaaaa", "a");
-// DiskLruCache.Snapshot snapshot = cache.get("A");
-// InputStream in = snapshot.getInputStream(0);
-// assertEquals('a', in.read());
-// mockOs.enqueueFault("read");
-// try {
-// in.read();
-// fail();
-// } catch (IOException expected) {
-// }
-// snapshot.close();
-// }
-
-// public void testFileBecomesInaccessibleDuringWriteIsSilentlyDiscarded() throws Exception {
-// set("A", "a", "a");
-// DiskLruCache.Editor editor = cache.edit("A");
-// OutputStream out0 = editor.newOutputStream(0);
-// out0.write('b');
-// out0.close();
-// OutputStream out1 = editor.newOutputStream(1);
-// out1.write('c');
-// mockOs.enqueueFault("write");
-// out1.write('c'); // this doesn't throw...
-// out1.close();
-// editor.commit(); // ... but this will abort
-// assertAbsent("A");
-// }
-
- public void testEditSameVersion() throws Exception {
+ @Test public void editSameVersion() throws Exception {
set("A", "a", "a");
DiskLruCache.Snapshot snapshot = cache.get("A");
DiskLruCache.Editor editor = snapshot.edit();
@@ -630,7 +604,7 @@ public final class DiskLruCacheTest extends TestCase {
assertValue("A", "a", "a2");
}
- public void testEditSnapshotAfterChangeAborted() throws Exception {
+ @Test public void editSnapshotAfterChangeAborted() throws Exception {
set("A", "a", "a");
DiskLruCache.Snapshot snapshot = cache.get("A");
DiskLruCache.Editor toAbort = snapshot.edit();
@@ -642,7 +616,7 @@ public final class DiskLruCacheTest extends TestCase {
assertValue("A", "a", "a2");
}
- public void testEditSnapshotAfterChangeCommitted() throws Exception {
+ @Test public void editSnapshotAfterChangeCommitted() throws Exception {
set("A", "a", "a");
DiskLruCache.Snapshot snapshot = cache.get("A");
DiskLruCache.Editor toAbort = snapshot.edit();
@@ -651,7 +625,7 @@ public final class DiskLruCacheTest extends TestCase {
assertNull(snapshot.edit());
}
- public void testEditSinceEvicted() throws Exception {
+ @Test public void editSinceEvicted() throws Exception {
cache.close();
cache = DiskLruCache.open(cacheDir, appVersion, 2, 10);
set("A", "aa", "aaa"); // size 5
@@ -662,7 +636,7 @@ public final class DiskLruCacheTest extends TestCase {
assertNull(snapshot.edit());
}
- public void testEditSinceEvictedAndRecreated() throws Exception {
+ @Test public void editSinceEvictedAndRecreated() throws Exception {
cache.close();
cache = DiskLruCache.open(cacheDir, appVersion, 2, 10);
set("A", "aa", "aaa"); // size 5
diff --git a/src/test/java/com/squareup/okhttp/internal/io/StrictLineReaderTest.java b/src/test/java/com/squareup/okhttp/internal/io/StrictLineReaderTest.java
index 2241d1ae1..dc52e9e49 100644
--- a/src/test/java/com/squareup/okhttp/internal/io/StrictLineReaderTest.java
+++ b/src/test/java/com/squareup/okhttp/internal/io/StrictLineReaderTest.java
@@ -19,44 +19,38 @@ package com.squareup.okhttp.internal.io;
import static com.squareup.okhttp.internal.Util.US_ASCII;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
-import java.io.IOException;
import java.io.InputStream;
-import junit.framework.TestCase;
+import static org.junit.Assert.fail;
+import org.junit.Test;
-public class StrictLineReaderTest extends TestCase {
-
- public void testLineReaderConsistencyWithReadAsciiLine () {
- try {
- // Testing with LineReader buffer capacity 32 to check some corner cases.
- StrictLineReader lineReader = new StrictLineReader(createTestInputStream(), 32,
- US_ASCII);
- InputStream refStream = createTestInputStream();
- while (true) {
+public final class StrictLineReaderTest {
+ @Test public void lineReaderConsistencyWithReadAsciiLine() throws Exception {
+ // Testing with LineReader buffer capacity 32 to check some corner cases.
+ StrictLineReader lineReader = new StrictLineReader(createTestInputStream(), 32, US_ASCII);
+ InputStream refStream = createTestInputStream();
+ while (true) {
+ try {
+ String refLine = Streams.readAsciiLine(refStream);
try {
- String refLine = Streams.readAsciiLine(refStream);
- try {
- String line = lineReader.readLine();
- if (!refLine.equals(line)) {
- fail("line (\""+line+"\") differs from expected (\""+refLine+"\").");
- }
- } catch (EOFException eof) {
- fail("line reader threw EOFException too early.");
- }
- } catch (EOFException refEof) {
- try {
- lineReader.readLine();
- fail("line reader didn't throw the expected EOFException.");
- } catch (EOFException eof) {
- // OK
- break;
+ String line = lineReader.readLine();
+ if (!refLine.equals(line)) {
+ fail("line (\""+line+"\") differs from expected (\""+refLine+"\").");
}
+ } catch (EOFException eof) {
+ fail("line reader threw EOFException too early.");
+ }
+ } catch (EOFException refEof) {
+ try {
+ lineReader.readLine();
+ fail("line reader didn't throw the expected EOFException.");
+ } catch (EOFException eof) {
+ // OK
+ break;
}
}
- refStream.close();
- lineReader.close();
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
}
+ refStream.close();
+ lineReader.close();
}
private InputStream createTestInputStream() {
@@ -79,4 +73,3 @@ public class StrictLineReaderTest extends TestCase {
).getBytes());
}
}
-
diff --git a/src/test/java/com/squareup/okhttp/internal/net/http/HttpResponseCacheTest.java b/src/test/java/com/squareup/okhttp/internal/net/http/HttpResponseCacheTest.java
index ad54daf8e..dfc0f8173 100644
--- a/src/test/java/com/squareup/okhttp/internal/net/http/HttpResponseCacheTest.java
+++ b/src/test/java/com/squareup/okhttp/internal/net/http/HttpResponseCacheTest.java
@@ -67,12 +67,20 @@ import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
-import junit.framework.TestCase;
+import org.junit.After;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import org.junit.Before;
+import org.junit.Test;
/**
* Android's HttpResponseCacheTest.
*/
-public final class HttpResponseCacheTest extends TestCase {
+public final class HttpResponseCacheTest {
private static final HostnameVerifier NULL_HOSTNAME_VERIFIER = new HostnameVerifier() {
@Override public boolean verify(String s, SSLSession sslSession) {
return true;
@@ -94,8 +102,7 @@ public final class HttpResponseCacheTest extends TestCase {
}
}
- @Override protected void setUp() throws Exception {
- super.setUp();
+ @Before public void setUp() throws Exception {
String tmp = System.getProperty("java.io.tmpdir");
File cacheDir = new File(tmp, "HttpCache-" + UUID.randomUUID());
cache = new HttpResponseCache(cacheDir, Integer.MAX_VALUE);
@@ -103,12 +110,11 @@ public final class HttpResponseCacheTest extends TestCase {
CookieHandler.setDefault(cookieManager);
}
- @Override protected void tearDown() throws Exception {
+ @After public void tearDown() throws Exception {
server.shutdown();
ResponseCache.setDefault(null);
cache.getCache().delete();
CookieHandler.setDefault(null);
- super.tearDown();
}
private HttpURLConnection openConnection(URL url) {
@@ -119,7 +125,7 @@ public final class HttpResponseCacheTest extends TestCase {
* Test that response caching is consistent with the RI and the spec.
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
*/
- public void testResponseCachingByResponseCode() throws Exception {
+ @Test public void responseCachingByResponseCode() throws Exception {
// Test each documented HTTP/1.1 code, plus the first unused value in each range.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
@@ -159,7 +165,7 @@ public final class HttpResponseCacheTest extends TestCase {
* Response code 407 should only come from proxy servers. Android's client
* throws if it is sent by an origin server.
*/
- public void testOriginServerSends407() throws Exception {
+ @Test public void originServerSends407() throws Exception {
server.enqueue(new MockResponse().setResponseCode(407));
server.play();
@@ -172,7 +178,7 @@ public final class HttpResponseCacheTest extends TestCase {
}
}
- public void test_responseCaching_410() throws Exception {
+ @Test public void responseCaching_410() throws Exception {
// the HTTP spec permits caching 410s, but the RI doesn't.
assertCached(true, 410);
}
@@ -215,7 +221,7 @@ public final class HttpResponseCacheTest extends TestCase {
* Test that we can interrogate the response when the cache is being
* populated. http://code.google.com/p/android/issues/detail?id=7787
*/
- public void testResponseCacheCallbackApis() throws Exception {
+ @Test public void responseCacheCallbackApis() throws Exception {
final String body = "ABCDE";
final AtomicInteger cacheCount = new AtomicInteger();
@@ -266,15 +272,15 @@ public final class HttpResponseCacheTest extends TestCase {
}
- public void testResponseCachingAndInputStreamSkipWithFixedLength() throws IOException {
+ @Test public void responseCachingAndInputStreamSkipWithFixedLength() throws IOException {
testResponseCaching(TransferKind.FIXED_LENGTH);
}
- public void testResponseCachingAndInputStreamSkipWithChunkedEncoding() throws IOException {
+ @Test public void responseCachingAndInputStreamSkipWithChunkedEncoding() throws IOException {
testResponseCaching(TransferKind.CHUNKED);
}
- public void testResponseCachingAndInputStreamSkipWithNoLengthHeaders() throws IOException {
+ @Test public void responseCachingAndInputStreamSkipWithNoLengthHeaders() throws IOException {
testResponseCaching(TransferKind.END_OF_STREAM);
}
@@ -317,7 +323,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(1, cache.getHitCount());
}
- public void testSecureResponseCaching() throws IOException {
+ @Test public void secureResponseCaching() throws IOException {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
@@ -353,7 +359,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(localPrincipal, connection.getLocalPrincipal());
}
- public void testCacheReturnsInsecureResponseForSecureRequest() throws IOException {
+ @Test public void cacheReturnsInsecureResponseForSecureRequest() throws IOException {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse().setBody("ABC"));
server.enqueue(new MockResponse().setBody("DEF"));
@@ -373,7 +379,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("DEF", readAscii(connection2));
}
- public void testResponseCachingAndRedirects() throws Exception {
+ @Test public void responseCachingAndRedirects() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
@@ -397,7 +403,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(2, cache.getHitCount());
}
- public void testRedirectToCachedResult() throws Exception {
+ @Test public void redirectToCachedResult() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.setBody("ABC"));
@@ -424,7 +430,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(2, request3.getSequenceNumber());
}
- public void testSecureResponseCachingAndRedirects() throws IOException {
+ @Test public void secureResponseCachingAndRedirects() throws IOException {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
@@ -453,7 +459,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(2, cache.getHitCount());
}
- public void testResponseCacheRequestHeaders() throws IOException, URISyntaxException {
+ @Test public void responseCacheRequestHeaders() throws IOException, URISyntaxException {
server.enqueue(new MockResponse().setBody("ABC"));
server.play();
@@ -478,15 +484,15 @@ public final class HttpResponseCacheTest extends TestCase {
}
- public void testServerDisconnectsPrematurelyWithContentLengthHeader() throws IOException {
+ @Test public void serverDisconnectsPrematurelyWithContentLengthHeader() throws IOException {
testServerPrematureDisconnect(TransferKind.FIXED_LENGTH);
}
- public void testServerDisconnectsPrematurelyWithChunkedEncoding() throws IOException {
+ @Test public void serverDisconnectsPrematurelyWithChunkedEncoding() throws IOException {
testServerPrematureDisconnect(TransferKind.CHUNKED);
}
- public void testServerDisconnectsPrematurelyWithNoLengthHeaders() throws IOException {
+ @Test public void serverDisconnectsPrematurelyWithNoLengthHeaders() throws IOException {
/*
* Intentionally empty. This case doesn't make sense because there's no
* such thing as a premature disconnect when the disconnect itself
@@ -520,15 +526,15 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(1, cache.getWriteSuccessCount());
}
- public void testClientPrematureDisconnectWithContentLengthHeader() throws IOException {
+ @Test public void clientPrematureDisconnectWithContentLengthHeader() throws IOException {
testClientPrematureDisconnect(TransferKind.FIXED_LENGTH);
}
- public void testClientPrematureDisconnectWithChunkedEncoding() throws IOException {
+ @Test public void clientPrematureDisconnectWithChunkedEncoding() throws IOException {
testClientPrematureDisconnect(TransferKind.CHUNKED);
}
- public void testClientPrematureDisconnectWithNoLengthHeaders() throws IOException {
+ @Test public void clientPrematureDisconnectWithNoLengthHeaders() throws IOException {
testClientPrematureDisconnect(TransferKind.END_OF_STREAM);
}
@@ -558,7 +564,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(1, cache.getWriteSuccessCount());
}
- public void testDefaultExpirationDateFullyCachedForLessThan24Hours() throws Exception {
+ @Test public void defaultExpirationDateFullyCachedForLessThan24Hours() throws Exception {
// last modified: 105 seconds ago
// served: 5 seconds ago
// default lifetime: (105 - 5) / 10 = 10 seconds
@@ -576,7 +582,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertNull(connection.getHeaderField("Warning"));
}
- public void testDefaultExpirationDateConditionallyCached() throws Exception {
+ @Test public void defaultExpirationDateConditionallyCached() throws Exception {
// last modified: 115 seconds ago
// served: 15 seconds ago
// default lifetime: (115 - 15) / 10 = 10 seconds
@@ -589,7 +595,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertTrue(headers.contains("If-Modified-Since: " + lastModifiedDate));
}
- public void testDefaultExpirationDateFullyCachedForMoreThan24Hours() throws Exception {
+ @Test public void defaultExpirationDateFullyCachedForMoreThan24Hours() throws Exception {
// last modified: 105 days ago
// served: 5 days ago
// default lifetime: (105 - 5) / 10 = 10 days
@@ -607,7 +613,7 @@ public final class HttpResponseCacheTest extends TestCase {
connection.getHeaderField("Warning"));
}
- public void testNoDefaultExpirationForUrlsWithQueryString() throws Exception {
+ @Test public void noDefaultExpirationForUrlsWithQueryString() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-105, TimeUnit.SECONDS))
.addHeader("Date: " + formatDate(-5, TimeUnit.SECONDS))
@@ -620,7 +626,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(openConnection(url)));
}
- public void testExpirationDateInThePastWithLastModifiedHeader() throws Exception {
+ @Test public void expirationDateInThePastWithLastModifiedHeader() throws Exception {
String lastModifiedDate = formatDate(-2, TimeUnit.HOURS);
RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse()
.addHeader("Last-Modified: " + lastModifiedDate)
@@ -629,24 +635,24 @@ public final class HttpResponseCacheTest extends TestCase {
assertTrue(headers.contains("If-Modified-Since: " + lastModifiedDate));
}
- public void testExpirationDateInThePastWithNoLastModifiedHeader() throws Exception {
+ @Test public void expirationDateInThePastWithNoLastModifiedHeader() throws Exception {
assertNotCached(new MockResponse()
.addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS)));
}
- public void testExpirationDateInTheFuture() throws Exception {
+ @Test public void expirationDateInTheFuture() throws Exception {
assertFullyCached(new MockResponse()
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)));
}
- public void testMaxAgePreferredWithMaxAgeAndExpires() throws Exception {
+ @Test public void maxAgePreferredWithMaxAgeAndExpires() throws Exception {
assertFullyCached(new MockResponse()
.addHeader("Date: " + formatDate(0, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Cache-Control: max-age=60"));
}
- public void testMaxAgeInThePastWithDateAndLastModifiedHeaders() throws Exception {
+ @Test public void maxAgeInThePastWithDateAndLastModifiedHeaders() throws Exception {
String lastModifiedDate = formatDate(-2, TimeUnit.HOURS);
RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse()
.addHeader("Date: " + formatDate(-120, TimeUnit.SECONDS))
@@ -656,7 +662,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertTrue(headers.contains("If-Modified-Since: " + lastModifiedDate));
}
- public void testMaxAgeInThePastWithDateHeaderButNoLastModifiedHeader() throws Exception {
+ @Test public void maxAgeInThePastWithDateHeaderButNoLastModifiedHeader() throws Exception {
/*
* Chrome interprets max-age relative to the local clock. Both our cache
* and Firefox both use the earlier of the local and server's clock.
@@ -666,71 +672,71 @@ public final class HttpResponseCacheTest extends TestCase {
.addHeader("Cache-Control: max-age=60"));
}
- public void testMaxAgeInTheFutureWithDateHeader() throws Exception {
+ @Test public void maxAgeInTheFutureWithDateHeader() throws Exception {
assertFullyCached(new MockResponse()
.addHeader("Date: " + formatDate(0, TimeUnit.HOURS))
.addHeader("Cache-Control: max-age=60"));
}
- public void testMaxAgeInTheFutureWithNoDateHeader() throws Exception {
+ @Test public void maxAgeInTheFutureWithNoDateHeader() throws Exception {
assertFullyCached(new MockResponse()
.addHeader("Cache-Control: max-age=60"));
}
- public void testMaxAgeWithLastModifiedButNoServedDate() throws Exception {
+ @Test public void maxAgeWithLastModifiedButNoServedDate() throws Exception {
assertFullyCached(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS))
.addHeader("Cache-Control: max-age=60"));
}
- public void testMaxAgeInTheFutureWithDateAndLastModifiedHeaders() throws Exception {
+ @Test public void maxAgeInTheFutureWithDateAndLastModifiedHeaders() throws Exception {
assertFullyCached(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS))
.addHeader("Date: " + formatDate(0, TimeUnit.SECONDS))
.addHeader("Cache-Control: max-age=60"));
}
- public void testMaxAgePreferredOverLowerSharedMaxAge() throws Exception {
+ @Test public void maxAgePreferredOverLowerSharedMaxAge() throws Exception {
assertFullyCached(new MockResponse()
.addHeader("Date: " + formatDate(-2, TimeUnit.MINUTES))
.addHeader("Cache-Control: s-maxage=60")
.addHeader("Cache-Control: max-age=180"));
}
- public void testMaxAgePreferredOverHigherMaxAge() throws Exception {
+ @Test public void maxAgePreferredOverHigherMaxAge() throws Exception {
assertNotCached(new MockResponse()
.addHeader("Date: " + formatDate(-2, TimeUnit.MINUTES))
.addHeader("Cache-Control: s-maxage=180")
.addHeader("Cache-Control: max-age=60"));
}
- public void testRequestMethodOptionsIsNotCached() throws Exception {
+ @Test public void requestMethodOptionsIsNotCached() throws Exception {
testRequestMethod("OPTIONS", false);
}
- public void testRequestMethodGetIsCached() throws Exception {
+ @Test public void requestMethodGetIsCached() throws Exception {
testRequestMethod("GET", true);
}
- public void testRequestMethodHeadIsNotCached() throws Exception {
+ @Test public void requestMethodHeadIsNotCached() throws Exception {
// We could support this but choose not to for implementation simplicity
testRequestMethod("HEAD", false);
}
- public void testRequestMethodPostIsNotCached() throws Exception {
+ @Test public void requestMethodPostIsNotCached() throws Exception {
// We could support this but choose not to for implementation simplicity
testRequestMethod("POST", false);
}
- public void testRequestMethodPutIsNotCached() throws Exception {
+ @Test public void requestMethodPutIsNotCached() throws Exception {
testRequestMethod("PUT", false);
}
- public void testRequestMethodDeleteIsNotCached() throws Exception {
+ @Test public void requestMethodDeleteIsNotCached() throws Exception {
testRequestMethod("DELETE", false);
}
- public void testRequestMethodTraceIsNotCached() throws Exception {
+ @Test public void requestMethodTraceIsNotCached() throws Exception {
testRequestMethod("TRACE", false);
}
@@ -748,7 +754,7 @@ public final class HttpResponseCacheTest extends TestCase {
URL url = server.getUrl("/");
- HttpURLConnection request1 = (HttpURLConnection) openConnection(url);
+ HttpURLConnection request1 = openConnection(url);
request1.setRequestMethod(requestMethod);
addRequestBodyIfNecessary(requestMethod, request1);
assertEquals("1", request1.getHeaderField("X-Response-ID"));
@@ -761,15 +767,15 @@ public final class HttpResponseCacheTest extends TestCase {
}
}
- public void testPostInvalidatesCache() throws Exception {
+ @Test public void postInvalidatesCache() throws Exception {
testMethodInvalidates("POST");
}
- public void testPutInvalidatesCache() throws Exception {
+ @Test public void putInvalidatesCache() throws Exception {
testMethodInvalidates("PUT");
}
- public void testDeleteMethodInvalidatesCache() throws Exception {
+ @Test public void deleteMethodInvalidatesCache() throws Exception {
testMethodInvalidates("DELETE");
}
@@ -797,13 +803,13 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("C", readAscii(openConnection(url)));
}
- public void testEtag() throws Exception {
+ @Test public void etag() throws Exception {
RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse()
.addHeader("ETag: v1"));
assertTrue(conditionalRequest.getHeaders().contains("If-None-Match: v1"));
}
- public void testEtagAndExpirationDateInThePast() throws Exception {
+ @Test public void etagAndExpirationDateInThePast() throws Exception {
String lastModifiedDate = formatDate(-2, TimeUnit.HOURS);
RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse()
.addHeader("ETag: v1")
@@ -814,18 +820,18 @@ public final class HttpResponseCacheTest extends TestCase {
assertTrue(headers.contains("If-Modified-Since: " + lastModifiedDate));
}
- public void testEtagAndExpirationDateInTheFuture() throws Exception {
+ @Test public void etagAndExpirationDateInTheFuture() throws Exception {
assertFullyCached(new MockResponse()
.addHeader("ETag: v1")
.addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)));
}
- public void testCacheControlNoCache() throws Exception {
+ @Test public void cacheControlNoCache() throws Exception {
assertNotCached(new MockResponse().addHeader("Cache-Control: no-cache"));
}
- public void testCacheControlNoCacheAndExpirationDateInTheFuture() throws Exception {
+ @Test public void cacheControlNoCacheAndExpirationDateInTheFuture() throws Exception {
String lastModifiedDate = formatDate(-2, TimeUnit.HOURS);
RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse()
.addHeader("Last-Modified: " + lastModifiedDate)
@@ -835,11 +841,11 @@ public final class HttpResponseCacheTest extends TestCase {
assertTrue(headers.contains("If-Modified-Since: " + lastModifiedDate));
}
- public void testPragmaNoCache() throws Exception {
+ @Test public void pragmaNoCache() throws Exception {
assertNotCached(new MockResponse().addHeader("Pragma: no-cache"));
}
- public void testPragmaNoCacheAndExpirationDateInTheFuture() throws Exception {
+ @Test public void pragmaNoCacheAndExpirationDateInTheFuture() throws Exception {
String lastModifiedDate = formatDate(-2, TimeUnit.HOURS);
RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse()
.addHeader("Last-Modified: " + lastModifiedDate)
@@ -849,18 +855,18 @@ public final class HttpResponseCacheTest extends TestCase {
assertTrue(headers.contains("If-Modified-Since: " + lastModifiedDate));
}
- public void testCacheControlNoStore() throws Exception {
+ @Test public void cacheControlNoStore() throws Exception {
assertNotCached(new MockResponse().addHeader("Cache-Control: no-store"));
}
- public void testCacheControlNoStoreAndExpirationDateInTheFuture() throws Exception {
+ @Test public void cacheControlNoStoreAndExpirationDateInTheFuture() throws Exception {
assertNotCached(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.addHeader("Cache-Control: no-store"));
}
- public void testPartialRangeResponsesDoNotCorruptCache() throws Exception {
+ @Test public void partialRangeResponsesDoNotCorruptCache() throws Exception {
/*
* 1. request a range
* 2. request a full document, expecting a cache miss
@@ -881,7 +887,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("BB", readAscii(openConnection(url)));
}
- public void testServerReturnsDocumentOlderThanCache() throws Exception {
+ @Test public void serverReturnsDocumentOlderThanCache() throws Exception {
server.enqueue(new MockResponse().setBody("A")
.addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS)));
@@ -895,13 +901,13 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(openConnection(url)));
}
- public void testNonIdentityEncodingAndConditionalCache() throws Exception {
+ @Test public void nonIdentityEncodingAndConditionalCache() throws Exception {
assertNonIdentityEncodingCached(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS)));
}
- public void testNonIdentityEncodingAndFullCache() throws Exception {
+ @Test public void nonIdentityEncodingAndFullCache() throws Exception {
assertNonIdentityEncodingCached(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)));
@@ -918,13 +924,13 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("ABCABCABC", readAscii(openConnection(server.getUrl("/"))));
}
- public void testExpiresDateBeforeModifiedDate() throws Exception {
+ @Test public void expiresDateBeforeModifiedDate() throws Exception {
assertConditionallyCached(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(-2, TimeUnit.HOURS)));
}
- public void testRequestMaxAge() throws IOException {
+ @Test public void requestMaxAge() throws IOException {
server.enqueue(new MockResponse().setBody("A")
.addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS))
.addHeader("Date: " + formatDate(-1, TimeUnit.MINUTES))
@@ -939,7 +945,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(connection));
}
- public void testRequestMinFresh() throws IOException {
+ @Test public void requestMinFresh() throws IOException {
server.enqueue(new MockResponse().setBody("A")
.addHeader("Cache-Control: max-age=60")
.addHeader("Date: " + formatDate(0, TimeUnit.MINUTES)));
@@ -953,7 +959,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(connection));
}
- public void testRequestMaxStale() throws IOException {
+ @Test public void requestMaxStale() throws IOException {
server.enqueue(new MockResponse().setBody("A")
.addHeader("Cache-Control: max-age=120")
.addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES)));
@@ -969,7 +975,7 @@ public final class HttpResponseCacheTest extends TestCase {
connection.getHeaderField("Warning"));
}
- public void testRequestMaxStaleNotHonoredWithMustRevalidate() throws IOException {
+ @Test public void requestMaxStaleNotHonoredWithMustRevalidate() throws IOException {
server.enqueue(new MockResponse().setBody("A")
.addHeader("Cache-Control: max-age=120, must-revalidate")
.addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES)));
@@ -983,7 +989,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(connection));
}
- public void testRequestOnlyIfCachedWithNoResponseCached() throws IOException {
+ @Test public void requestOnlyIfCachedWithNoResponseCached() throws IOException {
// (no responses enqueued)
server.play();
@@ -992,7 +998,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertGatewayTimeout(connection);
}
- public void testRequestOnlyIfCachedWithFullResponseCached() throws IOException {
+ @Test public void requestOnlyIfCachedWithFullResponseCached() throws IOException {
server.enqueue(new MockResponse().setBody("A")
.addHeader("Cache-Control: max-age=30")
.addHeader("Date: " + formatDate(0, TimeUnit.MINUTES)));
@@ -1004,7 +1010,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(openConnection(server.getUrl("/"))));
}
- public void testRequestOnlyIfCachedWithConditionalResponseCached() throws IOException {
+ @Test public void requestOnlyIfCachedWithConditionalResponseCached() throws IOException {
server.enqueue(new MockResponse().setBody("A")
.addHeader("Cache-Control: max-age=30")
.addHeader("Date: " + formatDate(-1, TimeUnit.MINUTES)));
@@ -1016,7 +1022,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertGatewayTimeout(connection);
}
- public void testRequestOnlyIfCachedWithUnhelpfulResponseCached() throws IOException {
+ @Test public void requestOnlyIfCachedWithUnhelpfulResponseCached() throws IOException {
server.enqueue(new MockResponse().setBody("A"));
server.play();
@@ -1026,7 +1032,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertGatewayTimeout(connection);
}
- public void testRequestCacheControlNoCache() throws Exception {
+ @Test public void requestCacheControlNoCache() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS))
.addHeader("Date: " + formatDate(0, TimeUnit.SECONDS))
@@ -1042,7 +1048,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(connection));
}
- public void testRequestPragmaNoCache() throws Exception {
+ @Test public void requestPragmaNoCache() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS))
.addHeader("Date: " + formatDate(0, TimeUnit.SECONDS))
@@ -1058,7 +1064,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(connection));
}
- public void testClientSuppliedIfModifiedSinceWithCachedResult() throws Exception {
+ @Test public void clientSuppliedIfModifiedSinceWithCachedResult() throws Exception {
MockResponse response = new MockResponse()
.addHeader("ETag: v3")
.addHeader("Cache-Control: max-age=0");
@@ -1070,7 +1076,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertFalse(headers.contains("If-None-Match: v3"));
}
- public void testClientSuppliedIfNoneMatchSinceWithCachedResult() throws Exception {
+ @Test public void clientSuppliedIfNoneMatchSinceWithCachedResult() throws Exception {
String lastModifiedDate = formatDate(-3, TimeUnit.MINUTES);
MockResponse response = new MockResponse()
.addHeader("Last-Modified: " + lastModifiedDate)
@@ -1101,7 +1107,7 @@ public final class HttpResponseCacheTest extends TestCase {
return server.takeRequest();
}
- public void testSetIfModifiedSince() throws Exception {
+ @Test public void setIfModifiedSince() throws Exception {
Date since = new Date();
server.enqueue(new MockResponse().setBody("A"));
server.play();
@@ -1114,7 +1120,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertTrue(request.getHeaders().contains("If-Modified-Since: " + formatDate(since)));
}
- public void testClientSuppliedConditionWithoutCachedResult() throws Exception {
+ @Test public void clientSuppliedConditionWithoutCachedResult() throws Exception {
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
server.play();
@@ -1126,7 +1132,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("", readAscii(connection));
}
- public void testAuthorizationRequestHeaderPreventsCaching() throws Exception {
+ @Test public void authorizationRequestHeaderPreventsCaching() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-2, TimeUnit.MINUTES))
.addHeader("Cache-Control: max-age=60")
@@ -1141,17 +1147,17 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(openConnection(url)));
}
- public void testAuthorizationResponseCachedWithSMaxAge() throws Exception {
+ @Test public void authorizationResponseCachedWithSMaxAge() throws Exception {
assertAuthorizationRequestFullyCached(new MockResponse()
.addHeader("Cache-Control: s-maxage=60"));
}
- public void testAuthorizationResponseCachedWithPublic() throws Exception {
+ @Test public void authorizationResponseCachedWithPublic() throws Exception {
assertAuthorizationRequestFullyCached(new MockResponse()
.addHeader("Cache-Control: public"));
}
- public void testAuthorizationResponseCachedWithMustRevalidate() throws Exception {
+ @Test public void authorizationResponseCachedWithMustRevalidate() throws Exception {
assertAuthorizationRequestFullyCached(new MockResponse()
.addHeader("Cache-Control: must-revalidate"));
}
@@ -1170,7 +1176,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(openConnection(url)));
}
- public void testContentLocationDoesNotPopulateCache() throws Exception {
+ @Test public void contentLocationDoesNotPopulateCache() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Content-Location: /bar")
@@ -1182,7 +1188,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(openConnection(server.getUrl("/bar"))));
}
- public void testUseCachesFalseDoesNotWriteToCache() throws Exception {
+ @Test public void useCachesFalseDoesNotWriteToCache() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.setBody("A").setBody("A"));
@@ -1195,7 +1201,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(openConnection(server.getUrl("/"))));
}
- public void testUseCachesFalseDoesNotReadFromCache() throws Exception {
+ @Test public void useCachesFalseDoesNotReadFromCache() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.setBody("A").setBody("A"));
@@ -1208,7 +1214,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(connection));
}
- public void testDefaultUseCachesSetsInitialValueOnly() throws Exception {
+ @Test public void defaultUseCachesSetsInitialValueOnly() throws Exception {
URL url = new URL("http://localhost/");
URLConnection c1 = openConnection(url);
URLConnection c2 = openConnection(url);
@@ -1224,7 +1230,7 @@ public final class HttpResponseCacheTest extends TestCase {
}
}
- public void testConnectionIsReturnedToPoolAfterConditionalSuccess() throws Exception {
+ @Test public void connectionIsReturnedToPoolAfterConditionalSuccess() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Cache-Control: max-age=0")
@@ -1242,7 +1248,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(2, server.takeRequest().getSequenceNumber());
}
- public void testStatisticsConditionalCacheMiss() throws Exception {
+ @Test public void statisticsConditionalCacheMiss() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Cache-Control: max-age=0")
@@ -1262,7 +1268,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(0, cache.getHitCount());
}
- public void testStatisticsConditionalCacheHit() throws Exception {
+ @Test public void statisticsConditionalCacheHit() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Cache-Control: max-age=0")
@@ -1282,7 +1288,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(2, cache.getHitCount());
}
- public void testStatisticsFullCacheHit() throws Exception {
+ @Test public void statisticsFullCacheHit() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.setBody("A"));
@@ -1299,7 +1305,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(2, cache.getHitCount());
}
- public void testVaryMatchesChangedRequestHeaderField() throws Exception {
+ @Test public void varyMatchesChangedRequestHeaderField() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language")
@@ -1317,7 +1323,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(enConnection));
}
- public void testVaryMatchesUnchangedRequestHeaderField() throws Exception {
+ @Test public void varyMatchesUnchangedRequestHeaderField() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language")
@@ -1334,7 +1340,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(connection2));
}
- public void testVaryMatchesAbsentRequestHeaderField() throws Exception {
+ @Test public void varyMatchesAbsentRequestHeaderField() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Foo")
@@ -1346,7 +1352,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(openConnection(server.getUrl("/"))));
}
- public void testVaryMatchesAddedRequestHeaderField() throws Exception {
+ @Test public void varyMatchesAddedRequestHeaderField() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Foo")
@@ -1360,7 +1366,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(fooConnection));
}
- public void testVaryMatchesRemovedRequestHeaderField() throws Exception {
+ @Test public void varyMatchesRemovedRequestHeaderField() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Foo")
@@ -1374,7 +1380,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(openConnection(server.getUrl("/"))));
}
- public void testVaryFieldsAreCaseInsensitive() throws Exception {
+ @Test public void varyFieldsAreCaseInsensitive() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: ACCEPT-LANGUAGE")
@@ -1391,7 +1397,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(connection2));
}
- public void testVaryMultipleFieldsWithMatch() throws Exception {
+ @Test public void varyMultipleFieldsWithMatch() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language, Accept-Charset")
@@ -1413,7 +1419,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(connection2));
}
- public void testVaryMultipleFieldsWithNoMatch() throws Exception {
+ @Test public void varyMultipleFieldsWithNoMatch() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language, Accept-Charset")
@@ -1435,7 +1441,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(enConnection));
}
- public void testVaryMultipleFieldValuesWithMatch() throws Exception {
+ @Test public void varyMultipleFieldValuesWithMatch() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language")
@@ -1455,7 +1461,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(connection2));
}
- public void testVaryMultipleFieldValuesWithNoMatch() throws Exception {
+ @Test public void varyMultipleFieldValuesWithNoMatch() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language")
@@ -1475,7 +1481,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(connection2));
}
- public void testVaryAsterisk() throws Exception {
+ @Test public void varyAsterisk() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("Vary: *")
@@ -1487,7 +1493,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(openConnection(server.getUrl("/"))));
}
- public void testVaryAndHttps() throws Exception {
+ @Test public void varyAndHttps() throws Exception {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
@@ -1510,35 +1516,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(connection2));
}
-// public void testDiskWriteFailureCacheDegradation() throws Exception {
-// Deque writeHandlers = mockOs.getHandlers("write");
-// int i = 0;
-// boolean hasMoreScenarios = true;
-// while (hasMoreScenarios) {
-// mockOs.enqueueNormal("write", i++);
-// mockOs.enqueueFault("write");
-// exercisePossiblyFaultyCache(false);
-// hasMoreScenarios = writeHandlers.isEmpty();
-// writeHandlers.clear();
-// }
-// System.out.println("Exercising the cache performs " + (i - 1) + " writes.");
-// }
-//
-// public void testDiskReadFailureCacheDegradation() throws Exception {
-// Deque readHandlers = mockOs.getHandlers("read");
-// int i = 0;
-// boolean hasMoreScenarios = true;
-// while (hasMoreScenarios) {
-// mockOs.enqueueNormal("read", i++);
-// mockOs.enqueueFault("read");
-// exercisePossiblyFaultyCache(true);
-// hasMoreScenarios = readHandlers.isEmpty();
-// readHandlers.clear();
-// }
-// System.out.println("Exercising the cache performs " + (i - 1) + " reads.");
-// }
-
- public void testCachePlusCookies() throws Exception {
+ @Test public void cachePlusCookies() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Set-Cookie: a=FIRST; domain=" + server.getCookieDomain() + ";")
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
@@ -1556,7 +1534,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertCookies(url, "a=SECOND");
}
- public void testGetHeadersReturnsNetworkEndToEndHeaders() throws Exception {
+ @Test public void getHeadersReturnsNetworkEndToEndHeaders() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Allow: GET, HEAD")
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
@@ -1576,7 +1554,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("GET, HEAD, PUT", connection2.getHeaderField("Allow"));
}
- public void testGetHeadersReturnsCachedHopByHopHeaders() throws Exception {
+ @Test public void getHeadersReturnsCachedHopByHopHeaders() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Transfer-Encoding: identity")
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
@@ -1596,7 +1574,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("identity", connection2.getHeaderField("Transfer-Encoding"));
}
- public void testGetHeadersDeletesCached100LevelWarnings() throws Exception {
+ @Test public void getHeadersDeletesCached100LevelWarnings() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Warning: 199 test danger")
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
@@ -1615,7 +1593,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(null, connection2.getHeaderField("Warning"));
}
- public void testGetHeadersRetainsCached200LevelWarnings() throws Exception {
+ @Test public void getHeadersRetainsCached200LevelWarnings() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Warning: 299 test danger")
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
@@ -1642,7 +1620,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals(Arrays.asList(expectedCookies), actualCookies);
}
- public void testCachePlusRange() throws Exception {
+ @Test public void cachePlusRange() throws Exception {
assertNotCached(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_PARTIAL)
.addHeader("Date: " + formatDate(0, TimeUnit.HOURS))
@@ -1650,7 +1628,7 @@ public final class HttpResponseCacheTest extends TestCase {
.addHeader("Cache-Control: max-age=60"));
}
- public void testConditionalHitUpdatesCache() throws Exception {
+ @Test public void conditionalHitUpdatesCache() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(0, TimeUnit.SECONDS))
.addHeader("Cache-Control: max-age=0")
@@ -1716,31 +1694,6 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("B", readAscii(openConnection(url)));
}
- private void exercisePossiblyFaultyCache(boolean permitReadBodyFailures) throws Exception {
- server.shutdown();
- server = new MockWebServer();
- server.enqueue(new MockResponse()
- .addHeader("Cache-Control: max-age=60")
- .setBody("A"));
- server.enqueue(new MockResponse().setBody("B"));
- server.play();
-
- URL url = server.getUrl("/" + UUID.randomUUID());
- assertEquals("A", readAscii(openConnection(url)));
-
- URLConnection connection = openConnection(url);
- InputStream in = connection.getInputStream();
- try {
- int bodyChar = in.read();
- assertTrue(bodyChar == 'A' || bodyChar == 'B');
- assertEquals(-1, in.read());
- } catch (IOException e) {
- if (!permitReadBodyFailures) {
- throw e;
- }
- }
- }
-
/**
* @return the request with the conditional get headers.
*/
diff --git a/src/test/java/com/squareup/okhttp/internal/net/http/NewURLConnectionTest.java b/src/test/java/com/squareup/okhttp/internal/net/http/NewURLConnectionTest.java
deleted file mode 100644
index 183d15d56..000000000
--- a/src/test/java/com/squareup/okhttp/internal/net/http/NewURLConnectionTest.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.squareup.okhttp.internal.net.http;
-
-import junit.framework.TestCase;
-
-public final class NewURLConnectionTest extends TestCase {
-
- public void testUrlConnection() {
- }
-
- // TODO: write a test that shows pooled connections detect HTTP/1.0 (vs. HTTP/1.1)
-
- // TODO: write a test that shows POST bodies are retained on AUTH problems (or prove it unnecessary)
-
- // TODO: cookies + trailers. Do cookie headers get processed too many times?
-
- // TODO: crash on header names or values containing the '\0' character
-
- // TODO: crash on empty names and empty values
-
- // TODO: deflate compression
-
- // TODO: read the outgoing status line and incoming status line?
-
-}
diff --git a/src/test/java/com/squareup/okhttp/internal/net/http/RawHeadersTest.java b/src/test/java/com/squareup/okhttp/internal/net/http/RawHeadersTest.java
index 285476773..ccee0a04e 100644
--- a/src/test/java/com/squareup/okhttp/internal/net/http/RawHeadersTest.java
+++ b/src/test/java/com/squareup/okhttp/internal/net/http/RawHeadersTest.java
@@ -17,10 +17,11 @@ package com.squareup.okhttp.internal.net.http;
import java.util.Arrays;
import java.util.List;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
-public final class RawHeadersTest extends TestCase {
- public void testParseNameValueBlock() {
+public final class RawHeadersTest {
+ @Test public void parseNameValueBlock() {
List nameValueBlock = Arrays.asList(
"cache-control",
"no-cache, no-store",
@@ -42,7 +43,7 @@ public final class RawHeadersTest extends TestCase {
assertEquals("200 OK", rawHeaders.getValue(3));
}
- public void testToNameValueBlock() {
+ @Test public void toNameValueBlock() {
RawHeaders rawHeaders = new RawHeaders();
rawHeaders.add("cache-control", "no-cache, no-store");
rawHeaders.add("set-cookie", "Cookie1");
diff --git a/src/test/java/com/squareup/okhttp/internal/net/http/RouteSelectorTest.java b/src/test/java/com/squareup/okhttp/internal/net/http/RouteSelectorTest.java
index 559abf431..dd75bc8f1 100644
--- a/src/test/java/com/squareup/okhttp/internal/net/http/RouteSelectorTest.java
+++ b/src/test/java/com/squareup/okhttp/internal/net/http/RouteSelectorTest.java
@@ -36,9 +36,13 @@ import java.util.NoSuchElementException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import org.junit.Test;
-public final class RouteSelectorTest extends TestCase {
+public final class RouteSelectorTest {
private static final int proxyAPort = 1001;
private static final String proxyAHost = "proxyA";
private static final Proxy proxyA
@@ -70,7 +74,7 @@ public final class RouteSelectorTest extends TestCase {
private final FakeDns dns = new FakeDns();
private final FakeProxySelector proxySelector = new FakeProxySelector();
- public void testSingleRoute() throws Exception {
+ @Test public void singleRoute() throws Exception {
Address address = new Address(uriHost, uriPort, null, null, null);
RouteSelector routeSelector = new RouteSelector(address, uri, proxySelector, pool, dns);
@@ -88,7 +92,7 @@ public final class RouteSelectorTest extends TestCase {
}
}
- public void testExplicitProxyTriesThatProxiesAddressesOnly() throws Exception {
+ @Test public void explicitProxyTriesThatProxiesAddressesOnly() throws Exception {
Address address = new Address(uriHost, uriPort, null, null, proxyA);
RouteSelector routeSelector = new RouteSelector(address, uri, proxySelector, pool, dns);
@@ -104,7 +108,7 @@ public final class RouteSelectorTest extends TestCase {
proxySelector.assertRequests(); // No proxy selector requests!
}
- public void testExplicitDirectProxy() throws Exception {
+ @Test public void explicitDirectProxy() throws Exception {
Address address = new Address(uriHost, uriPort, null, null, NO_PROXY);
RouteSelector routeSelector = new RouteSelector(address, uri, proxySelector, pool, dns);
@@ -120,7 +124,7 @@ public final class RouteSelectorTest extends TestCase {
proxySelector.assertRequests(); // No proxy selector requests!
}
- public void testProxySelectorReturnsNull() throws Exception {
+ @Test public void proxySelectorReturnsNull() throws Exception {
Address address = new Address(uriHost, uriPort, null, null, null);
proxySelector.proxies = null;
@@ -136,7 +140,7 @@ public final class RouteSelectorTest extends TestCase {
assertFalse(routeSelector.hasNext());
}
- public void testProxySelectorReturnsNoProxies() throws Exception {
+ @Test public void proxySelectorReturnsNoProxies() throws Exception {
Address address = new Address(uriHost, uriPort, null, null, null);
RouteSelector routeSelector = new RouteSelector(address, uri, proxySelector, pool, dns);
@@ -152,7 +156,7 @@ public final class RouteSelectorTest extends TestCase {
proxySelector.assertRequests(uri);
}
- public void testProxySelectorReturnsMultipleProxies() throws Exception {
+ @Test public void proxySelectorReturnsMultipleProxies() throws Exception {
Address address = new Address(uriHost, uriPort, null, null, null);
proxySelector.proxies.add(proxyA);
@@ -186,7 +190,7 @@ public final class RouteSelectorTest extends TestCase {
assertFalse(routeSelector.hasNext());
}
- public void testProxySelectorDirectConnectionsAreSkipped() throws Exception {
+ @Test public void proxySelectorDirectConnectionsAreSkipped() throws Exception {
Address address = new Address(uriHost, uriPort, null, null, null);
proxySelector.proxies.add(NO_PROXY);
@@ -203,7 +207,7 @@ public final class RouteSelectorTest extends TestCase {
assertFalse(routeSelector.hasNext());
}
- public void testProxyDnsFailureContinuesToNextProxy() throws Exception {
+ @Test public void proxyDnsFailureContinuesToNextProxy() throws Exception {
Address address = new Address(uriHost, uriPort, null, null, null);
proxySelector.proxies.add(proxyA);
@@ -242,7 +246,7 @@ public final class RouteSelectorTest extends TestCase {
assertFalse(routeSelector.hasNext());
}
- public void testMultipleTlsModes() throws Exception {
+ @Test public void multipleTlsModes() throws Exception {
Address address = new Address(
uriHost, uriPort, socketFactory, hostnameVerifier, Proxy.NO_PROXY);
RouteSelector routeSelector = new RouteSelector(address, uri, proxySelector, pool, dns);
@@ -261,7 +265,7 @@ public final class RouteSelectorTest extends TestCase {
assertFalse(routeSelector.hasNext());
}
- public void testMultipleProxiesMultipleInetAddressesMultipleTlsModes() throws Exception {
+ @Test public void multipleProxiesMultipleInetAddressesMultipleTlsModes() throws Exception {
Address address = new Address(
uriHost, uriPort, socketFactory, hostnameVerifier, null);
proxySelector.proxies.add(proxyA);
diff --git a/src/test/java/com/squareup/okhttp/internal/net/http/URLConnectionTest.java b/src/test/java/com/squareup/okhttp/internal/net/http/URLConnectionTest.java
index 52beed0c7..b94eb62b8 100644
--- a/src/test/java/com/squareup/okhttp/internal/net/http/URLConnectionTest.java
+++ b/src/test/java/com/squareup/okhttp/internal/net/http/URLConnectionTest.java
@@ -46,7 +46,6 @@ import java.net.ResponseCache;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.URI;
-import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
@@ -63,22 +62,30 @@ import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
-import junit.framework.TestCase;
+import org.junit.After;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
/**
* Android's URLConnectionTest.
*/
-public final class URLConnectionTest extends TestCase {
+public final class URLConnectionTest {
/** base64("username:password") */
private static final String BASE_64_CREDENTIALS = "dXNlcm5hbWU6cGFzc3dvcmQ=";
@@ -100,12 +107,11 @@ public final class URLConnectionTest extends TestCase {
}
}
- @Override protected void setUp() throws Exception {
- super.setUp();
+ @Before public void setUp() throws Exception {
hostName = server.getHostName();
}
- @Override protected void tearDown() throws Exception {
+ @After public void tearDown() throws Exception {
System.clearProperty("proxyHost");
System.clearProperty("proxyPort");
System.clearProperty("http.proxyHost");
@@ -117,13 +123,9 @@ public final class URLConnectionTest extends TestCase {
if (cache != null) {
cache.getCache().delete();
}
- super.tearDown();
}
- // TODO: test that request bodies are retransmitted on IP address failures
- // TODO: pooled proxy failures are not reported to the proxy selector
-
- public void testRequestHeaders() throws IOException, InterruptedException {
+ @Test public void requestHeaders() throws IOException, InterruptedException {
server.enqueue(new MockResponse());
server.play();
@@ -186,7 +188,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testGetRequestPropertyReturnsLastValue() throws Exception {
+ @Test public void getRequestPropertyReturnsLastValue() throws Exception {
server.play();
HttpURLConnection urlConnection = client.open(server.getUrl("/"));
urlConnection.addRequestProperty("A", "value1");
@@ -194,7 +196,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals("value2", urlConnection.getRequestProperty("A"));
}
- public void testResponseHeaders() throws IOException, InterruptedException {
+ @Test public void responseHeaders() throws IOException, InterruptedException {
server.enqueue(new MockResponse()
.setStatus("HTTP/1.0 200 Fantastic")
.addHeader("A: c")
@@ -229,7 +231,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals("e", urlConnection.getHeaderField(2));
}
- public void testServerSendsInvalidResponseHeaders() throws Exception {
+ @Test public void serverSendsInvalidResponseHeaders() throws Exception {
server.enqueue(new MockResponse().setStatus("HTP/1.1 200 OK"));
server.play();
@@ -241,7 +243,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testServerSendsInvalidCodeTooLarge() throws Exception {
+ @Test public void serverSendsInvalidCodeTooLarge() throws Exception {
server.enqueue(new MockResponse().setStatus("HTTP/1.1 2147483648 OK"));
server.play();
@@ -253,7 +255,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testServerSendsInvalidCodeNotANumber() throws Exception {
+ @Test public void serverSendsInvalidCodeNotANumber() throws Exception {
server.enqueue(new MockResponse().setStatus("HTTP/1.1 00a OK"));
server.play();
@@ -265,7 +267,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testServerSendsUnnecessaryWhitespace() throws Exception {
+ @Test public void serverSendsUnnecessaryWhitespace() throws Exception {
server.enqueue(new MockResponse().setStatus(" HTTP/1.1 2147483648 OK"));
server.play();
@@ -277,7 +279,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testConnectRetriesUntilConnectedOrFailed() throws Exception {
+ @Test public void connectRetriesUntilConnectedOrFailed() throws Exception {
server.play();
URL url = server.getUrl("/foo");
server.shutdown();
@@ -290,15 +292,15 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testRequestBodySurvivesRetriesWithFixedLength() throws Exception {
+ @Test public void requestBodySurvivesRetriesWithFixedLength() throws Exception {
testRequestBodySurvivesRetries(TransferKind.FIXED_LENGTH);
}
- public void testRequestBodySurvivesRetriesWithChunkedStreaming() throws Exception {
+ @Test public void requestBodySurvivesRetriesWithChunkedStreaming() throws Exception {
testRequestBodySurvivesRetries(TransferKind.CHUNKED);
}
- public void testRequestBodySurvivesRetriesWithBufferedBody() throws Exception {
+ @Test public void requestBodySurvivesRetriesWithBufferedBody() throws Exception {
testRequestBodySurvivesRetries(TransferKind.END_OF_STREAM);
}
@@ -322,14 +324,14 @@ public final class URLConnectionTest extends TestCase {
assertEquals("body", server.takeRequest().getUtf8Body());
}
- public void testGetErrorStreamOnSuccessfulRequest() throws Exception {
+ @Test public void getErrorStreamOnSuccessfulRequest() throws Exception {
server.enqueue(new MockResponse().setBody("A"));
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
assertNull(connection.getErrorStream());
}
- public void testGetErrorStreamOnUnsuccessfulRequest() throws Exception {
+ @Test public void getErrorStreamOnUnsuccessfulRequest() throws Exception {
server.enqueue(new MockResponse().setResponseCode(404).setBody("A"));
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
@@ -339,7 +341,7 @@ public final class URLConnectionTest extends TestCase {
// Check that if we don't read to the end of a response, the next request on the
// recycled connection doesn't get the unread tail of the first request's response.
// http://code.google.com/p/android/issues/detail?id=2939
- public void test_2939() throws Exception {
+ @Test public void bug2939() throws Exception {
MockResponse response = new MockResponse().setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8);
server.enqueue(response);
@@ -352,12 +354,12 @@ public final class URLConnectionTest extends TestCase {
// Check that we recognize a few basic mime types by extension.
// http://code.google.com/p/android/issues/detail?id=10100
- public void test_10100() throws Exception {
+ @Test public void bug10100() throws Exception {
assertEquals("image/jpeg", URLConnection.guessContentTypeFromName("someFile.jpg"));
assertEquals("application/pdf", URLConnection.guessContentTypeFromName("stuff.pdf"));
}
- public void testConnectionsArePooled() throws Exception {
+ @Test public void connectionsArePooled() throws Exception {
MockResponse response = new MockResponse().setBody("ABCDEFGHIJKLMNOPQR");
server.enqueue(response);
@@ -373,7 +375,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals(2, server.takeRequest().getSequenceNumber());
}
- public void testChunkedConnectionsArePooled() throws Exception {
+ @Test public void chunkedConnectionsArePooled() throws Exception {
MockResponse response = new MockResponse().setChunkedBody("ABCDEFGHIJKLMNOPQR", 5);
server.enqueue(response);
@@ -389,15 +391,15 @@ public final class URLConnectionTest extends TestCase {
assertEquals(2, server.takeRequest().getSequenceNumber());
}
- public void testServerClosesSocket() throws Exception {
+ @Test public void serverClosesSocket() throws Exception {
testServerClosesOutput(DISCONNECT_AT_END);
}
- public void testServerShutdownInput() throws Exception {
+ @Test public void serverShutdownInput() throws Exception {
testServerClosesOutput(SHUTDOWN_INPUT_AT_END);
}
- public void SUPPRESSED_testServerShutdownOutput() throws Exception {
+ @Test public void serverShutdownOutput() throws Exception {
testServerClosesOutput(SHUTDOWN_OUTPUT_AT_END);
}
@@ -405,40 +407,52 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse()
.setBody("This connection won't pool properly")
.setSocketPolicy(socketPolicy));
- server.enqueue(new MockResponse()
- .setBody("This comes after a busted connection"));
+ MockResponse responseAfter = new MockResponse()
+ .setBody("This comes after a busted connection");
+ server.enqueue(responseAfter);
+ server.enqueue(responseAfter); // Enqueue 2x because the broken connection may be reused.
server.play();
- assertContent("This connection won't pool properly", client.open(server.getUrl("/a")));
+ HttpURLConnection connection1 = client.open(server.getUrl("/a"));
+ connection1.setReadTimeout(100);
+ assertContent("This connection won't pool properly", connection1);
assertEquals(0, server.takeRequest().getSequenceNumber());
- assertContent("This comes after a busted connection", client.open(server.getUrl("/b")));
+ HttpURLConnection connection2 = client.open(server.getUrl("/b"));
+ connection2.setReadTimeout(100);
+ assertContent("This comes after a busted connection", connection2);
+
+ // Check that a fresh connection was created, either immediately or after attempting reuse.
+ RecordedRequest requestAfter = server.takeRequest();
+ if (server.getRequestCount() == 3) {
+ requestAfter = server.takeRequest(); // The failure consumed a response.
+ }
// sequence number 0 means the HTTP socket connection was not reused
- assertEquals(0, server.takeRequest().getSequenceNumber());
+ assertEquals(0, requestAfter.getSequenceNumber());
}
enum WriteKind { BYTE_BY_BYTE, SMALL_BUFFERS, LARGE_BUFFERS }
- public void test_chunkedUpload_byteByByte() throws Exception {
+ @Test public void chunkedUpload_byteByByte() throws Exception {
doUpload(TransferKind.CHUNKED, WriteKind.BYTE_BY_BYTE);
}
- public void test_chunkedUpload_smallBuffers() throws Exception {
+ @Test public void chunkedUpload_smallBuffers() throws Exception {
doUpload(TransferKind.CHUNKED, WriteKind.SMALL_BUFFERS);
}
- public void test_chunkedUpload_largeBuffers() throws Exception {
+ @Test public void chunkedUpload_largeBuffers() throws Exception {
doUpload(TransferKind.CHUNKED, WriteKind.LARGE_BUFFERS);
}
- public void SUPPRESSED_test_fixedLengthUpload_byteByByte() throws Exception {
+ @Test public void fixedLengthUpload_byteByByte() throws Exception {
doUpload(TransferKind.FIXED_LENGTH, WriteKind.BYTE_BY_BYTE);
}
- public void test_fixedLengthUpload_smallBuffers() throws Exception {
+ @Test public void fixedLengthUpload_smallBuffers() throws Exception {
doUpload(TransferKind.FIXED_LENGTH, WriteKind.SMALL_BUFFERS);
}
- public void test_fixedLengthUpload_largeBuffers() throws Exception {
+ @Test public void fixedLengthUpload_largeBuffers() throws Exception {
doUpload(TransferKind.FIXED_LENGTH, WriteKind.LARGE_BUFFERS);
}
@@ -479,7 +493,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testGetResponseCodeNoResponseBody() throws Exception {
+ @Test public void getResponseCodeNoResponseBody() throws Exception {
server.enqueue(new MockResponse()
.addHeader("abc: def"));
server.play();
@@ -496,7 +510,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testConnectViaHttps() throws Exception {
+ @Test public void connectViaHttps() throws Exception {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
server.play();
@@ -511,7 +525,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
}
- public void testConnectViaHttpsReusingConnections() throws IOException, InterruptedException {
+ @Test public void connectViaHttpsReusingConnections() throws IOException, InterruptedException {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
server.enqueue(new MockResponse().setBody("another response via HTTPS"));
@@ -533,7 +547,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals(1, server.takeRequest().getSequenceNumber());
}
- public void testConnectViaHttpsReusingConnectionsDifferentFactories()
+ @Test public void connectViaHttpsReusingConnectionsDifferentFactories()
throws IOException, InterruptedException {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
@@ -555,7 +569,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testConnectViaHttpsWithSSLFallback() throws IOException, InterruptedException {
+ @Test public void connectViaHttpsWithSSLFallback() throws IOException, InterruptedException {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
server.enqueue(new MockResponse().setBody("this response comes via SSL"));
@@ -576,34 +590,30 @@ public final class URLConnectionTest extends TestCase {
*
* http://code.google.com/p/android/issues/detail?id=13178
*/
-// public void testConnectViaHttpsToUntrustedServer() throws IOException, InterruptedException {
-// TestSSLContext testSSLContext = TestSSLContext.create(TestKeyStore.getClientCA2(),
-// TestKeyStore.getServer());
-//
-// server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
-// server.enqueue(new MockResponse()); // unused
-// server.play();
-//
-// HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
-// connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
-// try {
-// connection.getInputStream();
-// fail();
-// } catch (SSLHandshakeException expected) {
-// assertTrue(expected.getCause() instanceof CertificateException);
-// }
-// assertEquals(0, server.getRequestCount());
-// }
+ @Test public void connectViaHttpsToUntrustedServer() throws IOException, InterruptedException {
+ server.useHttps(sslContext.getSocketFactory(), false);
+ server.enqueue(new MockResponse()); // unused
+ server.play();
- public void testConnectViaProxyUsingProxyArg() throws Exception {
+ HttpURLConnection connection = client.open(server.getUrl("/foo"));
+ try {
+ connection.getInputStream();
+ fail();
+ } catch (SSLHandshakeException expected) {
+ assertTrue(expected.getCause() instanceof CertificateException);
+ }
+ assertEquals(0, server.getRequestCount());
+ }
+
+ @Test public void connectViaProxyUsingProxyArg() throws Exception {
testConnectViaProxy(ProxyConfig.CREATE_ARG);
}
- public void testConnectViaProxyUsingProxySystemProperty() throws Exception {
+ @Test public void connectViaProxyUsingProxySystemProperty() throws Exception {
testConnectViaProxy(ProxyConfig.PROXY_SYSTEM_PROPERTY);
}
- public void testConnectViaProxyUsingHttpProxySystemProperty() throws Exception {
+ @Test public void connectViaProxyUsingHttpProxySystemProperty() throws Exception {
testConnectViaProxy(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
}
@@ -621,7 +631,7 @@ public final class URLConnectionTest extends TestCase {
assertContains(request.getHeaders(), "Host: android.com");
}
- public void testContentDisagreesWithContentLengthHeader() throws IOException {
+ @Test public void contentDisagreesWithContentLengthHeader() throws IOException {
server.enqueue(new MockResponse()
.setBody("abc\r\nYOU SHOULD NOT SEE THIS")
.clearHeaders()
@@ -631,7 +641,7 @@ public final class URLConnectionTest extends TestCase {
assertContent("abc", client.open(server.getUrl("/")));
}
- public void testContentDisagreesWithChunkedHeader() throws IOException {
+ @Test public void contentDisagreesWithChunkedHeader() throws IOException {
MockResponse mockResponse = new MockResponse();
mockResponse.setChunkedBody("abc", 3);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
@@ -647,11 +657,11 @@ public final class URLConnectionTest extends TestCase {
assertContent("abc", client.open(server.getUrl("/")));
}
- public void testConnectViaHttpProxyToHttpsUsingProxyArgWithNoProxy() throws Exception {
+ @Test public void connectViaHttpProxyToHttpsUsingProxyArgWithNoProxy() throws Exception {
testConnectViaDirectProxyToHttps(ProxyConfig.NO_PROXY);
}
- public void testConnectViaHttpProxyToHttpsUsingHttpProxySystemProperty() throws Exception {
+ @Test public void connectViaHttpProxyToHttpsUsingHttpProxySystemProperty() throws Exception {
// https should not use http proxy
testConnectViaDirectProxyToHttps(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
}
@@ -672,7 +682,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
}
- public void testConnectViaHttpProxyToHttpsUsingProxyArg() throws Exception {
+ @Test public void connectViaHttpProxyToHttpsUsingProxyArg() throws Exception {
testConnectViaHttpProxyToHttps(ProxyConfig.CREATE_ARG);
}
@@ -680,11 +690,11 @@ public final class URLConnectionTest extends TestCase {
* We weren't honoring all of the appropriate proxy system properties when
* connecting via HTTPS. http://b/3097518
*/
- public void testConnectViaHttpProxyToHttpsUsingProxySystemProperty() throws Exception {
+ @Test public void connectViaHttpProxyToHttpsUsingProxySystemProperty() throws Exception {
testConnectViaHttpProxyToHttps(ProxyConfig.PROXY_SYSTEM_PROPERTY);
}
- public void testConnectViaHttpProxyToHttpsUsingHttpsProxySystemProperty() throws Exception {
+ @Test public void connectViaHttpProxyToHttpsUsingHttpsProxySystemProperty() throws Exception {
testConnectViaHttpProxyToHttps(ProxyConfig.HTTPS_PROXY_SYSTEM_PROPERTY);
}
@@ -723,7 +733,8 @@ public final class URLConnectionTest extends TestCase {
/**
* Tolerate bad https proxy response when using HttpResponseCache. http://b/6754912
*/
- public void testConnectViaHttpProxyToHttpsUsingBadProxyAndHttpResponseCache() throws Exception {
+ @Test public void connectViaHttpProxyToHttpsUsingBadProxyAndHttpResponseCache()
+ throws Exception {
initResponseCache();
server.useHttps(sslContext.getSocketFactory(), true);
@@ -770,7 +781,7 @@ public final class URLConnectionTest extends TestCase {
/**
* Test which headers are sent unencrypted to the HTTP proxy.
*/
- public void testProxyConnectIncludesProxyHeadersOnly()
+ @Test public void proxyConnectIncludesProxyHeadersOnly()
throws IOException, InterruptedException {
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
@@ -803,7 +814,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
}
- public void testProxyAuthenticateOnConnect() throws Exception {
+ @Test public void proxyAuthenticateOnConnect() throws Exception {
Authenticator.setDefault(new RecordingAuthenticator());
server.useHttps(sslContext.getSocketFactory(), true);
server.enqueue(new MockResponse()
@@ -837,7 +848,7 @@ public final class URLConnectionTest extends TestCase {
// Don't disconnect after building a tunnel with CONNECT
// http://code.google.com/p/android/issues/detail?id=37221
- public void testProxyWithConnectionClose() throws IOException {
+ @Test public void proxyWithConnectionClose() throws IOException {
server.useHttps(sslContext.getSocketFactory(), true);
server.enqueue(new MockResponse()
.setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
@@ -855,7 +866,7 @@ public final class URLConnectionTest extends TestCase {
assertContent("this response comes via a proxy", connection);
}
- public void testProxyWithConnectionReuse() throws IOException {
+ @Test public void proxyWithConnectionReuse() throws IOException {
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
@@ -875,7 +886,7 @@ public final class URLConnectionTest extends TestCase {
assertContent("response 2", client.open(url));
}
- public void testDisconnectedConnection() throws IOException {
+ @Test public void disconnectedConnection() throws IOException {
server.enqueue(new MockResponse().setBody("ABCDEFGHIJKLMNOPQR"));
server.play();
@@ -890,7 +901,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testDisconnectBeforeConnect() throws IOException {
+ @Test public void disconnectBeforeConnect() throws IOException {
server.enqueue(new MockResponse().setBody("A"));
server.play();
@@ -901,7 +912,8 @@ public final class URLConnectionTest extends TestCase {
assertEquals(200, connection.getResponseCode());
}
- public void testDefaultRequestProperty() throws Exception {
+ @SuppressWarnings("deprecation")
+ @Test public void defaultRequestProperty() throws Exception {
URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A");
assertNull(URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty"));
}
@@ -924,15 +936,15 @@ public final class URLConnectionTest extends TestCase {
return result.toString();
}
- public void testMarkAndResetWithContentLengthHeader() throws IOException {
+ @Test public void markAndResetWithContentLengthHeader() throws IOException {
testMarkAndReset(TransferKind.FIXED_LENGTH);
}
- public void testMarkAndResetWithChunkedEncoding() throws IOException {
+ @Test public void markAndResetWithChunkedEncoding() throws IOException {
testMarkAndReset(TransferKind.CHUNKED);
}
- public void testMarkAndResetWithNoLengthHeaders() throws IOException {
+ @Test public void markAndResetWithNoLengthHeaders() throws IOException {
testMarkAndReset(TransferKind.END_OF_STREAM);
}
@@ -961,7 +973,7 @@ public final class URLConnectionTest extends TestCase {
* code 401. This causes a new HTTP request to be issued for every call into
* the URLConnection.
*/
- public void SUPPRESSED_testUnauthorizedResponseHandling() throws IOException {
+ @Test public void unauthorizedResponseHandling() throws IOException {
MockResponse response = new MockResponse()
.addHeader("WWW-Authenticate: challenge")
.setResponseCode(401) // UNAUTHORIZED
@@ -980,7 +992,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals(1, server.getRequestCount());
}
- public void testNonHexChunkSize() throws IOException {
+ @Test public void nonHexChunkSize() throws IOException {
server.enqueue(new MockResponse()
.setBody("5\r\nABCDE\r\nG\r\nFGHIJKLMNOPQRSTU\r\n0\r\n\r\n")
.clearHeaders()
@@ -995,7 +1007,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testMissingChunkBody() throws IOException {
+ @Test public void missingChunkBody() throws IOException {
server.enqueue(new MockResponse()
.setBody("5")
.clearHeaders()
@@ -1016,7 +1028,7 @@ public final class URLConnectionTest extends TestCase {
* behavior in not required by the API, so a failure of this test does not
* imply a bug in the implementation.
*/
- public void testGzipEncodingEnabledByDefault() throws IOException, InterruptedException {
+ @Test public void gzipEncodingEnabledByDefault() throws IOException, InterruptedException {
server.enqueue(new MockResponse()
.setBody(gzip("ABCABCABC".getBytes("UTF-8")))
.addHeader("Content-Encoding: gzip"));
@@ -1030,7 +1042,7 @@ public final class URLConnectionTest extends TestCase {
assertContains(request.getHeaders(), "Accept-Encoding: gzip");
}
- public void testClientConfiguredGzipContentEncoding() throws Exception {
+ @Test public void clientConfiguredGzipContentEncoding() throws Exception {
server.enqueue(new MockResponse()
.setBody(gzip("ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes("UTF-8")))
.addHeader("Content-Encoding: gzip"));
@@ -1045,23 +1057,23 @@ public final class URLConnectionTest extends TestCase {
assertContains(request.getHeaders(), "Accept-Encoding: gzip");
}
- public void testGzipAndConnectionReuseWithFixedLength() throws Exception {
+ @Test public void gzipAndConnectionReuseWithFixedLength() throws Exception {
testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.FIXED_LENGTH, false);
}
- public void testGzipAndConnectionReuseWithChunkedEncoding() throws Exception {
+ @Test public void gzipAndConnectionReuseWithChunkedEncoding() throws Exception {
testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.CHUNKED, false);
}
- public void testGzipAndConnectionReuseWithFixedLengthAndTls() throws Exception {
+ @Test public void gzipAndConnectionReuseWithFixedLengthAndTls() throws Exception {
testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.FIXED_LENGTH, true);
}
- public void testGzipAndConnectionReuseWithChunkedEncodingAndTls() throws Exception {
+ @Test public void gzipAndConnectionReuseWithChunkedEncodingAndTls() throws Exception {
testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.CHUNKED, true);
}
- public void testClientConfiguredCustomContentEncoding() throws Exception {
+ @Test public void clientConfiguredCustomContentEncoding() throws Exception {
server.enqueue(new MockResponse()
.setBody("ABCDE")
.addHeader("Content-Encoding: custom"));
@@ -1083,11 +1095,9 @@ public final class URLConnectionTest extends TestCase {
*/
private void testClientConfiguredGzipContentEncodingAndConnectionReuse(
TransferKind transferKind, boolean tls) throws Exception {
- SSLSocketFactory socketFactory = null;
- RecordingHostnameVerifier hostnameVerifier = null;
if (tls) {
- socketFactory = sslContext.getSocketFactory();
- hostnameVerifier = new RecordingHostnameVerifier();
+ SSLSocketFactory socketFactory = sslContext.getSocketFactory();
+ RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
server.useHttps(socketFactory, false);
client.setSSLSocketFactory(socketFactory);
client.setHostnameVerifier(hostnameVerifier);
@@ -1113,11 +1123,11 @@ public final class URLConnectionTest extends TestCase {
assertEquals(1, server.takeRequest().getSequenceNumber());
}
- public void testEarlyDisconnectDoesntHarmPoolingWithChunkedEncoding() throws Exception {
+ @Test public void earlyDisconnectDoesntHarmPoolingWithChunkedEncoding() throws Exception {
testEarlyDisconnectDoesntHarmPooling(TransferKind.CHUNKED);
}
- public void testEarlyDisconnectDoesntHarmPoolingWithFixedLengthEncoding() throws Exception {
+ @Test public void earlyDisconnectDoesntHarmPoolingWithFixedLengthEncoding() throws Exception {
testEarlyDisconnectDoesntHarmPooling(TransferKind.FIXED_LENGTH);
}
@@ -1152,7 +1162,7 @@ public final class URLConnectionTest extends TestCase {
* isn't specific about whether the size applies to the data or the
* complete chunk, the RI interprets it as a complete chunk.
*/
- public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
+ @Test public void setChunkedStreamingMode() throws IOException, InterruptedException {
server.enqueue(new MockResponse());
server.play();
@@ -1168,11 +1178,11 @@ public final class URLConnectionTest extends TestCase {
assertEquals(Arrays.asList(3, 3, 3, 3, 3, 2), request.getChunkSizes());
}
- public void testAuthenticateWithFixedLengthStreaming() throws Exception {
+ @Test public void authenticateWithFixedLengthStreaming() throws Exception {
testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH);
}
- public void testAuthenticateWithChunkedStreaming() throws Exception {
+ @Test public void authenticateWithChunkedStreaming() throws Exception {
testAuthenticateWithStreamingPost(StreamingMode.CHUNKED);
}
@@ -1208,12 +1218,12 @@ public final class URLConnectionTest extends TestCase {
assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
}
- public void testNonStandardAuthenticationScheme() throws Exception {
+ @Test public void nonStandardAuthenticationScheme() throws Exception {
List calls = authCallsForHeader("WWW-Authenticate: Foo");
assertEquals(Collections.emptyList(), calls);
}
- public void testNonStandardAuthenticationSchemeWithRealm() throws Exception {
+ @Test public void nonStandardAuthenticationSchemeWithRealm() throws Exception {
List calls = authCallsForHeader("WWW-Authenticate: Foo realm=\"Bar\"");
assertEquals(1, calls.size());
String call = calls.get(0);
@@ -1223,7 +1233,7 @@ public final class URLConnectionTest extends TestCase {
// Digest auth is currently unsupported. Test that digest requests should fail reasonably.
// http://code.google.com/p/android/issues/detail?id=11140
- public void testDigestAuthentication() throws Exception {
+ @Test public void digestAuthentication() throws Exception {
List calls = authCallsForHeader("WWW-Authenticate: Digest "
+ "realm=\"testrealm@host.com\", qop=\"auth,auth-int\", "
+ "nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\", "
@@ -1234,7 +1244,7 @@ public final class URLConnectionTest extends TestCase {
assertTrue(call, call.contains("prompt=testrealm@host.com"));
}
- public void testAllAttributesSetInServerAuthenticationCallbacks() throws Exception {
+ @Test public void allAttributesSetInServerAuthenticationCallbacks() throws Exception {
List calls = authCallsForHeader("WWW-Authenticate: Basic realm=\"Bar\"");
assertEquals(1, calls.size());
URL url = server.getUrl("/");
@@ -1249,7 +1259,7 @@ public final class URLConnectionTest extends TestCase {
assertTrue(call, call.toLowerCase().contains("scheme=basic")); // lowercase for the RI.
}
- public void testAllAttributesSetInProxyAuthenticationCallbacks() throws Exception {
+ @Test public void allAttributesSetInProxyAuthenticationCallbacks() throws Exception {
List calls = authCallsForHeader("Proxy-Authenticate: Basic realm=\"Bar\"");
assertEquals(1, calls.size());
URL url = server.getUrl("/");
@@ -1287,7 +1297,7 @@ public final class URLConnectionTest extends TestCase {
return authenticator.calls;
}
- public void testSetValidRequestMethod() throws Exception {
+ @Test public void setValidRequestMethod() throws Exception {
server.play();
assertValidRequestMethod("GET");
assertValidRequestMethod("DELETE");
@@ -1304,12 +1314,12 @@ public final class URLConnectionTest extends TestCase {
assertEquals(requestMethod, connection.getRequestMethod());
}
- public void testSetInvalidRequestMethodLowercase() throws Exception {
+ @Test public void setInvalidRequestMethodLowercase() throws Exception {
server.play();
assertInvalidRequestMethod("get");
}
- public void testSetInvalidRequestMethodConnect() throws Exception {
+ @Test public void setInvalidRequestMethodConnect() throws Exception {
server.play();
assertInvalidRequestMethod("CONNECT");
}
@@ -1323,7 +1333,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testCannotSetNegativeFixedLengthStreamingMode() throws Exception {
+ @Test public void cannotSetNegativeFixedLengthStreamingMode() throws Exception {
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
try {
@@ -1333,13 +1343,13 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testCanSetNegativeChunkedStreamingMode() throws Exception {
+ @Test public void canSetNegativeChunkedStreamingMode() throws Exception {
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
connection.setChunkedStreamingMode(-2);
}
- public void testCannotSetFixedLengthStreamingModeAfterConnect() throws Exception {
+ @Test public void cannotSetFixedLengthStreamingModeAfterConnect() throws Exception {
server.enqueue(new MockResponse().setBody("A"));
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
@@ -1351,7 +1361,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testCannotSetChunkedStreamingModeAfterConnect() throws Exception {
+ @Test public void cannotSetChunkedStreamingModeAfterConnect() throws Exception {
server.enqueue(new MockResponse().setBody("A"));
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
@@ -1363,7 +1373,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testCannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception {
+ @Test public void cannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception {
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
connection.setChunkedStreamingMode(1);
@@ -1374,7 +1384,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testCannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception {
+ @Test public void cannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception {
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
connection.setFixedLengthStreamingMode(1);
@@ -1385,11 +1395,11 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testSecureFixedLengthStreaming() throws Exception {
+ @Test public void secureFixedLengthStreaming() throws Exception {
testSecureStreamingPost(StreamingMode.FIXED_LENGTH);
}
- public void testSecureChunkedStreaming() throws Exception {
+ @Test public void secureChunkedStreaming() throws Exception {
testSecureStreamingPost(StreamingMode.CHUNKED);
}
@@ -1431,7 +1441,7 @@ public final class URLConnectionTest extends TestCase {
FIXED_LENGTH, CHUNKED
}
- public void testAuthenticateWithPost() throws Exception {
+ @Test public void authenticateWithPost() throws Exception {
MockResponse pleaseAuthenticate = new MockResponse()
.setResponseCode(401)
.addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
@@ -1466,7 +1476,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testAuthenticateWithGet() throws Exception {
+ @Test public void authenticateWithGet() throws Exception {
MockResponse pleaseAuthenticate = new MockResponse()
.setResponseCode(401)
.addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
@@ -1495,15 +1505,15 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testRedirectedWithChunkedEncoding() throws Exception {
+ @Test public void redirectedWithChunkedEncoding() throws Exception {
testRedirected(TransferKind.CHUNKED, true);
}
- public void testRedirectedWithContentLengthHeader() throws Exception {
+ @Test public void redirectedWithContentLengthHeader() throws Exception {
testRedirected(TransferKind.FIXED_LENGTH, true);
}
- public void testRedirectedWithNoLengthHeaders() throws Exception {
+ @Test public void redirectedWithNoLengthHeaders() throws Exception {
testRedirected(TransferKind.END_OF_STREAM, false);
}
@@ -1529,7 +1539,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testRedirectedOnHttps() throws IOException, InterruptedException {
+ @Test public void redirectedOnHttps() throws IOException, InterruptedException {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
@@ -1551,7 +1561,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
}
- public void testNotRedirectedFromHttpsToHttp() throws IOException, InterruptedException {
+ @Test public void notRedirectedFromHttpsToHttp() throws IOException, InterruptedException {
server.useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
@@ -1566,7 +1576,7 @@ public final class URLConnectionTest extends TestCase {
readAscii(connection.getInputStream(), Integer.MAX_VALUE));
}
- public void testNotRedirectedFromHttpToHttps() throws IOException, InterruptedException {
+ @Test public void notRedirectedFromHttpToHttps() throws IOException, InterruptedException {
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: https://anyhost/foo")
@@ -1578,7 +1588,7 @@ public final class URLConnectionTest extends TestCase {
readAscii(connection.getInputStream(), Integer.MAX_VALUE));
}
- public void SUPPRESSED_testRedirectToAnotherOriginServer() throws Exception {
+ @Test public void redirectToAnotherOriginServer() throws Exception {
MockWebServer server2 = new MockWebServer();
server2.enqueue(new MockResponse().setBody("This is the 2nd server!"));
server2.play();
@@ -1597,7 +1607,7 @@ public final class URLConnectionTest extends TestCase {
// make sure the first server was careful to recycle the connection
assertEquals("This is the first server again!",
- readAscii(server.getUrl("/").openStream(), Integer.MAX_VALUE));
+ readAscii(client.open(server.getUrl("/")).getInputStream(), Integer.MAX_VALUE));
RecordedRequest first = server.takeRequest();
assertContains(first.getHeaders(), "Host: " + hostName + ":" + server.getPort());
@@ -1609,20 +1619,20 @@ public final class URLConnectionTest extends TestCase {
server2.shutdown();
}
- public void testResponse300MultipleChoiceWithPost() throws Exception {
+ @Test public void response300MultipleChoiceWithPost() throws Exception {
// Chrome doesn't follow the redirect, but Firefox and the RI both do
testResponseRedirectedWithPost(HttpURLConnection.HTTP_MULT_CHOICE);
}
- public void testResponse301MovedPermanentlyWithPost() throws Exception {
+ @Test public void response301MovedPermanentlyWithPost() throws Exception {
testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_PERM);
}
- public void testResponse302MovedTemporarilyWithPost() throws Exception {
+ @Test public void response302MovedTemporarilyWithPost() throws Exception {
testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_TEMP);
}
- public void testResponse303SeeOtherWithPost() throws Exception {
+ @Test public void response303SeeOtherWithPost() throws Exception {
testResponseRedirectedWithPost(HttpURLConnection.HTTP_SEE_OTHER);
}
@@ -1651,7 +1661,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
}
- public void testResponse305UseProxy() throws Exception {
+ @Test public void response305UseProxy() throws Exception {
server.play();
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_USE_PROXY)
@@ -1669,7 +1679,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals(1, server.getRequestCount());
}
- public void testHttpsWithCustomTrustManager() throws Exception {
+ @Test public void httpsWithCustomTrustManager() throws Exception {
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
RecordingTrustManager trustManager = new RecordingTrustManager();
SSLContext sc = SSLContext.getInstance("TLS");
@@ -1693,7 +1703,7 @@ public final class URLConnectionTest extends TestCase {
trustManager.calls);
}
- public void testReadTimeouts() throws IOException {
+ @Test public void readTimeouts() throws IOException {
/*
* This relies on the fact that MockWebServer doesn't close the
* connection after a response has been sent. This causes the client to
@@ -1720,7 +1730,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testSetChunkedEncodingAsRequestProperty() throws IOException, InterruptedException {
+ @Test public void setChunkedEncodingAsRequestProperty() throws IOException, InterruptedException {
server.enqueue(new MockResponse());
server.play();
@@ -1734,7 +1744,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals("ABC", new String(request.getBody(), "UTF-8"));
}
- public void testConnectionCloseInRequest() throws IOException, InterruptedException {
+ @Test public void connectionCloseInRequest() throws IOException, InterruptedException {
server.enqueue(new MockResponse()); // server doesn't honor the connection: close header!
server.enqueue(new MockResponse());
server.play();
@@ -1751,7 +1761,7 @@ public final class URLConnectionTest extends TestCase {
0, server.takeRequest().getSequenceNumber());
}
- public void testConnectionCloseInResponse() throws IOException, InterruptedException {
+ @Test public void connectionCloseInResponse() throws IOException, InterruptedException {
server.enqueue(new MockResponse().addHeader("Connection: close"));
server.enqueue(new MockResponse());
server.play();
@@ -1767,7 +1777,7 @@ public final class URLConnectionTest extends TestCase {
0, server.takeRequest().getSequenceNumber());
}
- public void testConnectionCloseWithRedirect() throws IOException, InterruptedException {
+ @Test public void connectionCloseWithRedirect() throws IOException, InterruptedException {
MockResponse response = new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: /foo")
@@ -1785,7 +1795,7 @@ public final class URLConnectionTest extends TestCase {
0, server.takeRequest().getSequenceNumber());
}
- public void testResponseCodeDisagreesWithHeaders() throws IOException, InterruptedException {
+ @Test public void responseCodeDisagreesWithHeaders() throws IOException, InterruptedException {
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_NO_CONTENT)
.setBody("This body is not allowed!"));
@@ -1796,7 +1806,7 @@ public final class URLConnectionTest extends TestCase {
readAscii(connection.getInputStream(), Integer.MAX_VALUE));
}
- public void testSingleByteReadIsSigned() throws IOException {
+ @Test public void singleByteReadIsSigned() throws IOException {
server.enqueue(new MockResponse().setBody(new byte[] { -2, -1 }));
server.play();
@@ -1807,15 +1817,15 @@ public final class URLConnectionTest extends TestCase {
assertEquals(-1, in.read());
}
- public void testFlushAfterStreamTransmittedWithChunkedEncoding() throws IOException {
+ @Test public void flushAfterStreamTransmittedWithChunkedEncoding() throws IOException {
testFlushAfterStreamTransmitted(TransferKind.CHUNKED);
}
- public void testFlushAfterStreamTransmittedWithFixedLength() throws IOException {
+ @Test public void flushAfterStreamTransmittedWithFixedLength() throws IOException {
testFlushAfterStreamTransmitted(TransferKind.FIXED_LENGTH);
}
- public void testFlushAfterStreamTransmittedWithNoLengthHeaders() throws IOException {
+ @Test public void flushAfterStreamTransmittedWithNoLengthHeaders() throws IOException {
testFlushAfterStreamTransmitted(TransferKind.END_OF_STREAM);
}
@@ -1850,7 +1860,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testGetHeadersThrows() throws IOException {
+ @Test public void getHeadersThrows() throws IOException {
// Enqueue a response for every IP address held by localhost, because the route selector
// will try each in sequence.
// TODO: use the fake Dns implementation instead of a loop
@@ -1873,7 +1883,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testDnsFailureThrowsIOException() throws IOException {
+ @Test public void dnsFailureThrowsIOException() throws IOException {
HttpURLConnection connection = client.open(new URL("http://host.unlikelytld"));
try {
connection.connect();
@@ -1882,7 +1892,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testMalformedUrlThrowsUnknownHostException() throws IOException {
+ @Test public void malformedUrlThrowsUnknownHostException() throws IOException {
HttpURLConnection connection = client.open(new URL("http:///foo.html"));
try {
connection.connect();
@@ -1891,141 +1901,31 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void SUPPRESSED_testGetKeepAlive() throws Exception {
+ @Test public void getKeepAlive() throws Exception {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setBody("ABC"));
server.play();
// The request should work once and then fail
- URLConnection connection = client.open(server.getUrl(""));
- InputStream input = connection.getInputStream();
+ URLConnection connection1 = client.open(server.getUrl(""));
+ connection1.setReadTimeout(100);
+ InputStream input = connection1.getInputStream();
assertEquals("ABC", readAscii(input, Integer.MAX_VALUE));
input.close();
+ server.shutdown();
try {
- client.open(server.getUrl("")).getInputStream();
+ HttpURLConnection connection2 = client.open(server.getUrl(""));
+ connection2.setReadTimeout(100);
+ connection2.getInputStream();
fail();
} catch (ConnectException expected) {
}
}
- /**
- * This test goes through the exhaustive set of interesting ASCII characters
- * because most of those characters are interesting in some way according to
- * RFC 2396 and RFC 2732. http://b/1158780
- */
- public void SUPPRESSED_testLenientUrlToUri() throws Exception {
- // alphanum
- testUrlToUriMapping("abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09");
-
- // control characters
- testUrlToUriMapping("\u0001", "%01", "%01", "%01", "%01");
- testUrlToUriMapping("\u001f", "%1F", "%1F", "%1F", "%1F");
-
- // ascii characters
- testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
- testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
- testUrlToUriMapping(" ", "%20", "%20", "%20", "%20");
- testUrlToUriMapping("!", "!", "!", "!", "!");
- testUrlToUriMapping("\"", "%22", "%22", "%22", "%22");
- testUrlToUriMapping("#", null, null, null, "%23");
- testUrlToUriMapping("$", "$", "$", "$", "$");
- testUrlToUriMapping("&", "&", "&", "&", "&");
- testUrlToUriMapping("'", "'", "'", "'", "'");
- testUrlToUriMapping("(", "(", "(", "(", "(");
- testUrlToUriMapping(")", ")", ")", ")", ")");
- testUrlToUriMapping("*", "*", "*", "*", "*");
- testUrlToUriMapping("+", "+", "+", "+", "+");
- testUrlToUriMapping(",", ",", ",", ",", ",");
- testUrlToUriMapping("-", "-", "-", "-", "-");
- testUrlToUriMapping(".", ".", ".", ".", ".");
- testUrlToUriMapping("/", null, "/", "/", "/");
- testUrlToUriMapping(":", null, ":", ":", ":");
- testUrlToUriMapping(";", ";", ";", ";", ";");
- testUrlToUriMapping("<", "%3C", "%3C", "%3C", "%3C");
- testUrlToUriMapping("=", "=", "=", "=", "=");
- testUrlToUriMapping(">", "%3E", "%3E", "%3E", "%3E");
- testUrlToUriMapping("?", null, null, "?", "?");
- testUrlToUriMapping("@", "@", "@", "@", "@");
- testUrlToUriMapping("[", null, "%5B", null, "%5B");
- testUrlToUriMapping("\\", "%5C", "%5C", "%5C", "%5C");
- testUrlToUriMapping("]", null, "%5D", null, "%5D");
- testUrlToUriMapping("^", "%5E", "%5E", "%5E", "%5E");
- testUrlToUriMapping("_", "_", "_", "_", "_");
- testUrlToUriMapping("`", "%60", "%60", "%60", "%60");
- testUrlToUriMapping("{", "%7B", "%7B", "%7B", "%7B");
- testUrlToUriMapping("|", "%7C", "%7C", "%7C", "%7C");
- testUrlToUriMapping("}", "%7D", "%7D", "%7D", "%7D");
- testUrlToUriMapping("~", "~", "~", "~", "~");
- testUrlToUriMapping("~", "~", "~", "~", "~");
- testUrlToUriMapping("\u007f", "%7F", "%7F", "%7F", "%7F");
-
- // beyond ascii
- testUrlToUriMapping("\u0080", "%C2%80", "%C2%80", "%C2%80", "%C2%80");
- testUrlToUriMapping("\u20ac", "\u20ac", "\u20ac", "\u20ac", "\u20ac");
- testUrlToUriMapping("\ud842\udf9f",
- "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f");
- }
-
- public void SUPPRESSED_testLenientUrlToUriNul() throws Exception {
- testUrlToUriMapping("\u0000", "%00", "%00", "%00", "%00"); // RI fails this
- }
-
- private void testUrlToUriMapping(String string, String asAuthority, String asFile,
- String asQuery, String asFragment) throws Exception {
- if (asAuthority != null) {
- assertEquals("http://host" + asAuthority + ".tld/",
- backdoorUrlToUri(new URL("http://host" + string + ".tld/")).toString());
- }
- if (asFile != null) {
- assertEquals("http://host.tld/file" + asFile + "/",
- backdoorUrlToUri(new URL("http://host.tld/file" + string + "/")).toString());
- }
- if (asQuery != null) {
- assertEquals("http://host.tld/file?q" + asQuery + "=x",
- backdoorUrlToUri(new URL("http://host.tld/file?q" + string + "=x")).toString());
- }
- assertEquals("http://host.tld/file#" + asFragment + "-x",
- backdoorUrlToUri(new URL("http://host.tld/file#" + asFragment + "-x")).toString());
- }
-
- /**
- * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI,
- * HttpURLConnection recovers from URLs with unescaped but unsupported URI
- * characters like '{' and '|' by escaping these characters.
- */
- private URI backdoorUrlToUri(URL url) throws Exception {
- final AtomicReference uriReference = new AtomicReference();
-
- client.setResponseCache(new ResponseCache() {
- @Override
- public CacheRequest put(URI uri, URLConnection connection) throws IOException {
- return null;
- }
-
- @Override
- public CacheResponse get(URI uri, String requestMethod,
- Map> requestHeaders) throws IOException {
- uriReference.set(uri);
- throw new UnsupportedOperationException();
- }
- });
-
- try {
- HttpURLConnection connection = client.open(url);
- connection.getResponseCode();
- } catch (Exception expected) {
- if (expected.getCause() instanceof URISyntaxException) {
- expected.printStackTrace();
- }
- }
-
- return uriReference.get();
- }
-
/**
* Don't explode if the cache returns a null body. http://b/3373699
*/
- public void testResponseCacheReturnsNullOutputStream() throws Exception {
+ @Test public void responseCacheReturnsNullOutputStream() throws Exception {
final AtomicBoolean aborted = new AtomicBoolean();
client.setResponseCache(new ResponseCache() {
@Override
@@ -2063,7 +1963,7 @@ public final class URLConnectionTest extends TestCase {
/**
* http://code.google.com/p/android/issues/detail?id=14562
*/
- public void testReadAfterLastByte() throws Exception {
+ @Test public void readAfterLastByte() throws Exception {
server.enqueue(new MockResponse()
.setBody("ABC")
.clearHeaders()
@@ -2078,7 +1978,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals(-1, in.read()); // throws IOException in Gingerbread
}
- public void testGetContent() throws Exception {
+ @Test public void getContent() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Content-Type: text/plain")
.setBody("A"));
@@ -2088,7 +1988,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals("A", readAscii(in, Integer.MAX_VALUE));
}
- public void testGetContentOfType() throws Exception {
+ @Test public void getContentOfType() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Content-Type: text/plain")
.setBody("A"));
@@ -2108,7 +2008,7 @@ public final class URLConnectionTest extends TestCase {
connection.disconnect();
}
- public void testGetOutputStreamOnGetFails() throws Exception {
+ @Test public void getOutputStreamOnGetFails() throws Exception {
server.enqueue(new MockResponse());
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
@@ -2119,7 +2019,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testGetOutputAfterGetInputStreamFails() throws Exception {
+ @Test public void getOutputAfterGetInputStreamFails() throws Exception {
server.enqueue(new MockResponse());
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
@@ -2132,7 +2032,7 @@ public final class URLConnectionTest extends TestCase {
}
}
- public void testSetDoOutputOrDoInputAfterConnectFails() throws Exception {
+ @Test public void setDoOutputOrDoInputAfterConnectFails() throws Exception {
server.enqueue(new MockResponse());
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
@@ -2150,7 +2050,7 @@ public final class URLConnectionTest extends TestCase {
connection.disconnect();
}
- public void testClientSendsContentLength() throws Exception {
+ @Test public void clientSendsContentLength() throws Exception {
server.enqueue(new MockResponse().setBody("A"));
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
@@ -2163,7 +2063,7 @@ public final class URLConnectionTest extends TestCase {
assertContains(request.getHeaders(), "Content-Length: 3");
}
- public void testGetContentLengthConnects() throws Exception {
+ @Test public void getContentLengthConnects() throws Exception {
server.enqueue(new MockResponse().setBody("ABC"));
server.play();
HttpURLConnection connection = client.open(server.getUrl("/"));
@@ -2171,7 +2071,7 @@ public final class URLConnectionTest extends TestCase {
connection.disconnect();
}
- public void testGetContentTypeConnects() throws Exception {
+ @Test public void getContentTypeConnects() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Content-Type: text/plain")
.setBody("ABC"));
@@ -2181,7 +2081,7 @@ public final class URLConnectionTest extends TestCase {
connection.disconnect();
}
- public void testGetContentEncodingConnects() throws Exception {
+ @Test public void getContentEncodingConnects() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Content-Encoding: identity")
.setBody("ABC"));
@@ -2192,7 +2092,7 @@ public final class URLConnectionTest extends TestCase {
}
// http://b/4361656
- public void testUrlContainsQueryButNoPath() throws Exception {
+ @Test public void urlContainsQueryButNoPath() throws Exception {
server.enqueue(new MockResponse().setBody("A"));
server.play();
URL url = new URL("http", server.getHostName(), server.getPort(), "?query");
@@ -2202,15 +2102,15 @@ public final class URLConnectionTest extends TestCase {
}
// http://code.google.com/p/android/issues/detail?id=20442
- public void testInputStreamAvailableWithChunkedEncoding() throws Exception {
+ @Test public void inputStreamAvailableWithChunkedEncoding() throws Exception {
testInputStreamAvailable(TransferKind.CHUNKED);
}
- public void testInputStreamAvailableWithContentLengthHeader() throws Exception {
+ @Test public void inputStreamAvailableWithContentLengthHeader() throws Exception {
testInputStreamAvailable(TransferKind.FIXED_LENGTH);
}
- public void testInputStreamAvailableWithNoLengthHeaders() throws Exception {
+ @Test public void inputStreamAvailableWithNoLengthHeaders() throws Exception {
testInputStreamAvailable(TransferKind.END_OF_STREAM);
}
@@ -2230,6 +2130,52 @@ public final class URLConnectionTest extends TestCase {
assertEquals(-1, in.read());
}
+ @Test @Ignore public void testPooledConnectionsDetectHttp10() {
+ // TODO: write a test that shows pooled connections detect HTTP/1.0 (vs. HTTP/1.1)
+ fail("TODO");
+ }
+
+ @Test @Ignore public void postBodiesRetransmittedOnAuthProblems() {
+ fail("TODO");
+ }
+
+ @Test @Ignore public void cookiesAndTrailers() {
+ // Do cookie headers get processed too many times?
+ fail("TODO");
+ }
+
+ @Test @Ignore public void headerNamesContainingNullCharacter() {
+ // This is relevant for SPDY
+ fail("TODO");
+ }
+
+ @Test @Ignore public void headerValuesContainingNullCharacter() {
+ // This is relevant for SPDY
+ fail("TODO");
+ }
+
+ @Test @Ignore public void emptyHeaderName() {
+ // This is relevant for SPDY
+ fail("TODO");
+ }
+
+ @Test @Ignore public void emptyHeaderValue() {
+ // This is relevant for SPDY
+ fail("TODO");
+ }
+
+ @Test @Ignore public void deflateCompression() {
+ fail("TODO");
+ }
+
+ @Test @Ignore public void postBodiesRetransmittedOnIpAddressProblems() {
+ fail("TODO");
+ }
+
+ @Test @Ignore public void pooledConnectionProblemsNotReportedToProxySelector() {
+ fail("TODO");
+ }
+
/**
* Returns a gzipped copy of {@code bytes}.
*/
diff --git a/src/test/java/com/squareup/okhttp/internal/net/http/URLEncodingTest.java b/src/test/java/com/squareup/okhttp/internal/net/http/URLEncodingTest.java
new file mode 100644
index 000000000..ad54cb797
--- /dev/null
+++ b/src/test/java/com/squareup/okhttp/internal/net/http/URLEncodingTest.java
@@ -0,0 +1,150 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.net.http;
+
+import com.squareup.okhttp.OkHttpClient;
+import java.io.IOException;
+import java.net.CacheRequest;
+import java.net.CacheResponse;
+import java.net.HttpURLConnection;
+import java.net.ResponseCache;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+import static org.junit.Assert.assertEquals;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI,
+ * HttpURLConnection recovers from URLs with unescaped but unsupported URI
+ * characters like '{' and '|' by escaping these characters.
+ */
+public final class URLEncodingTest {
+ /**
+ * This test goes through the exhaustive set of interesting ASCII characters
+ * because most of those characters are interesting in some way according to
+ * RFC 2396 and RFC 2732. http://b/1158780
+ */
+ @Test @Ignore public void lenientUrlToUri() throws Exception {
+ // alphanum
+ testUrlToUriMapping("abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09");
+
+ // control characters
+ testUrlToUriMapping("\u0001", "%01", "%01", "%01", "%01");
+ testUrlToUriMapping("\u001f", "%1F", "%1F", "%1F", "%1F");
+
+ // ascii characters
+ testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
+ testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
+ testUrlToUriMapping(" ", "%20", "%20", "%20", "%20");
+ testUrlToUriMapping("!", "!", "!", "!", "!");
+ testUrlToUriMapping("\"", "%22", "%22", "%22", "%22");
+ testUrlToUriMapping("#", null, null, null, "%23");
+ testUrlToUriMapping("$", "$", "$", "$", "$");
+ testUrlToUriMapping("&", "&", "&", "&", "&");
+ testUrlToUriMapping("'", "'", "'", "'", "'");
+ testUrlToUriMapping("(", "(", "(", "(", "(");
+ testUrlToUriMapping(")", ")", ")", ")", ")");
+ testUrlToUriMapping("*", "*", "*", "*", "*");
+ testUrlToUriMapping("+", "+", "+", "+", "+");
+ testUrlToUriMapping(",", ",", ",", ",", ",");
+ testUrlToUriMapping("-", "-", "-", "-", "-");
+ testUrlToUriMapping(".", ".", ".", ".", ".");
+ testUrlToUriMapping("/", null, "/", "/", "/");
+ testUrlToUriMapping(":", null, ":", ":", ":");
+ testUrlToUriMapping(";", ";", ";", ";", ";");
+ testUrlToUriMapping("<", "%3C", "%3C", "%3C", "%3C");
+ testUrlToUriMapping("=", "=", "=", "=", "=");
+ testUrlToUriMapping(">", "%3E", "%3E", "%3E", "%3E");
+ testUrlToUriMapping("?", null, null, "?", "?");
+ testUrlToUriMapping("@", "@", "@", "@", "@");
+ testUrlToUriMapping("[", null, "%5B", null, "%5B");
+ testUrlToUriMapping("\\", "%5C", "%5C", "%5C", "%5C");
+ testUrlToUriMapping("]", null, "%5D", null, "%5D");
+ testUrlToUriMapping("^", "%5E", "%5E", "%5E", "%5E");
+ testUrlToUriMapping("_", "_", "_", "_", "_");
+ testUrlToUriMapping("`", "%60", "%60", "%60", "%60");
+ testUrlToUriMapping("{", "%7B", "%7B", "%7B", "%7B");
+ testUrlToUriMapping("|", "%7C", "%7C", "%7C", "%7C");
+ testUrlToUriMapping("}", "%7D", "%7D", "%7D", "%7D");
+ testUrlToUriMapping("~", "~", "~", "~", "~");
+ testUrlToUriMapping("~", "~", "~", "~", "~");
+ testUrlToUriMapping("\u007f", "%7F", "%7F", "%7F", "%7F");
+
+ // beyond ascii
+ testUrlToUriMapping("\u0080", "%C2%80", "%C2%80", "%C2%80", "%C2%80");
+ testUrlToUriMapping("\u20ac", "\u20ac", "\u20ac", "\u20ac", "\u20ac");
+ testUrlToUriMapping("\ud842\udf9f",
+ "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f");
+ }
+
+ @Test @Ignore public void lenientUrlToUriNul() throws Exception {
+ testUrlToUriMapping("\u0000", "%00", "%00", "%00", "%00"); // RI fails this
+ }
+
+ private void testUrlToUriMapping(String string, String asAuthority, String asFile,
+ String asQuery, String asFragment) throws Exception {
+ if (asAuthority != null) {
+ assertEquals("http://host" + asAuthority + ".tld/",
+ backdoorUrlToUri(new URL("http://host" + string + ".tld/")).toString());
+ }
+ if (asFile != null) {
+ assertEquals("http://host.tld/file" + asFile + "/",
+ backdoorUrlToUri(new URL("http://host.tld/file" + string + "/")).toString());
+ }
+ if (asQuery != null) {
+ assertEquals("http://host.tld/file?q" + asQuery + "=x",
+ backdoorUrlToUri(new URL("http://host.tld/file?q" + string + "=x")).toString());
+ }
+ assertEquals("http://host.tld/file#" + asFragment + "-x",
+ backdoorUrlToUri(new URL("http://host.tld/file#" + asFragment + "-x")).toString());
+ }
+
+ private URI backdoorUrlToUri(URL url) throws Exception {
+ final AtomicReference uriReference = new AtomicReference();
+
+ OkHttpClient client = new OkHttpClient();
+ client.setResponseCache(new ResponseCache() {
+ @Override public CacheRequest put(URI uri, URLConnection connection)
+ throws IOException {
+ return null;
+ }
+
+ @Override public CacheResponse get(URI uri, String requestMethod,
+ Map> requestHeaders) throws IOException {
+ uriReference.set(uri);
+ throw new UnsupportedOperationException();
+ }
+ });
+
+ try {
+ HttpURLConnection connection = client.open(url);
+ connection.getResponseCode();
+ } catch (Exception expected) {
+ if (expected.getCause() instanceof URISyntaxException) {
+ expected.printStackTrace();
+ }
+ }
+
+ return uriReference.get();
+ }
+}
diff --git a/src/test/java/com/squareup/okhttp/internal/net/spdy/SettingsTest.java b/src/test/java/com/squareup/okhttp/internal/net/spdy/SettingsTest.java
index f0c83a741..bc276862c 100644
--- a/src/test/java/com/squareup/okhttp/internal/net/spdy/SettingsTest.java
+++ b/src/test/java/com/squareup/okhttp/internal/net/spdy/SettingsTest.java
@@ -21,15 +21,18 @@ import static com.squareup.okhttp.internal.net.spdy.Settings.MAX_CONCURRENT_STRE
import static com.squareup.okhttp.internal.net.spdy.Settings.PERSISTED;
import static com.squareup.okhttp.internal.net.spdy.Settings.PERSIST_VALUE;
import static com.squareup.okhttp.internal.net.spdy.Settings.UPLOAD_BANDWIDTH;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import org.junit.Test;
-public final class SettingsTest extends TestCase {
- public void testUnsetField() {
+public final class SettingsTest {
+ @Test public void unsetField() {
Settings settings = new Settings();
assertEquals(-3, settings.getUploadBandwidth(-3));
}
- public void testSetFields() {
+ @Test public void setFields() {
Settings settings = new Settings();
assertEquals(-3, settings.getUploadBandwidth(-3));
@@ -61,7 +64,7 @@ public final class SettingsTest extends TestCase {
assertEquals(108, settings.getInitialWindowSize(-3));
}
- public void testIsPersisted() {
+ @Test public void isPersisted() {
Settings settings = new Settings();
// Initially false.
@@ -92,7 +95,7 @@ public final class SettingsTest extends TestCase {
assertFalse(settings.isPersisted(Settings.ROUND_TRIP_TIME));
}
- public void testPersistValue() {
+ @Test public void persistValue() {
Settings settings = new Settings();
// Initially false.
@@ -123,7 +126,7 @@ public final class SettingsTest extends TestCase {
assertFalse(settings.persistValue(Settings.ROUND_TRIP_TIME));
}
- public void testMerge() {
+ @Test public void merge() {
Settings a = new Settings();
a.set(UPLOAD_BANDWIDTH, PERSIST_VALUE, 100);
a.set(DOWNLOAD_BANDWIDTH, PERSIST_VALUE, 200);
diff --git a/src/test/java/com/squareup/okhttp/internal/net/spdy/SpdyConnectionTest.java b/src/test/java/com/squareup/okhttp/internal/net/spdy/SpdyConnectionTest.java
index 4c609b906..11e7724c3 100644
--- a/src/test/java/com/squareup/okhttp/internal/net/spdy/SpdyConnectionTest.java
+++ b/src/test/java/com/squareup/okhttp/internal/net/spdy/SpdyConnectionTest.java
@@ -33,9 +33,12 @@ import java.io.OutputStream;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import org.junit.Test;
-public final class SpdyConnectionTest extends TestCase {
+public final class SpdyConnectionTest {
private static final IncomingStreamHandler REJECT_INCOMING_STREAMS
= new IncomingStreamHandler() {
@Override public void receive(SpdyStream stream) throws IOException {
@@ -44,7 +47,7 @@ public final class SpdyConnectionTest extends TestCase {
};
private final MockSpdyPeer peer = new MockSpdyPeer();
- public void testClientCreatesStreamAndServerReplies() throws Exception {
+ @Test public void clientCreatesStreamAndServerReplies() throws Exception {
// write the mocking script
peer.acceptFrame();
peer.sendFrame().synReply(0, 1, Arrays.asList("a", "android"));
@@ -70,7 +73,7 @@ public final class SpdyConnectionTest extends TestCase {
assertTrue(Arrays.equals("c3po".getBytes("UTF-8"), requestData.data));
}
- public void testServerCreatesStreamAndClientReplies() throws Exception {
+ @Test public void serverCreatesStreamAndClientReplies() throws Exception {
// write the mocking script
peer.sendFrame().synStream(0, 2, 0, 0, Arrays.asList("a", "android"));
peer.acceptFrame();
@@ -100,7 +103,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(1, receiveCount.get());
}
- public void testReplyWithNoData() throws Exception {
+ @Test public void replyWithNoData() throws Exception {
// write the mocking script
peer.sendFrame().synStream(0, 2, 0, 0, Arrays.asList("a", "android"));
peer.acceptFrame();
@@ -126,7 +129,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(1, receiveCount.get());
}
- public void testNoop() throws Exception {
+ @Test public void noop() throws Exception {
// write the mocking script
peer.acceptFrame();
peer.play();
@@ -143,7 +146,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(0, ping.flags);
}
- public void testServerPingsClient() throws Exception {
+ @Test public void serverPingsClient() throws Exception {
// write the mocking script
peer.sendFrame().ping(0, 2);
peer.acceptFrame();
@@ -161,7 +164,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(2, ping.streamId);
}
- public void testClientPingsServer() throws Exception {
+ @Test public void clientPingsServer() throws Exception {
// write the mocking script
peer.acceptFrame();
peer.sendFrame().ping(0, 1);
@@ -182,7 +185,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(1, pingFrame.streamId);
}
- public void testUnexpectedPingIsNotReturned() throws Exception {
+ @Test public void unexpectedPingIsNotReturned() throws Exception {
// write the mocking script
peer.sendFrame().ping(0, 2);
peer.acceptFrame();
@@ -203,7 +206,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(4, ping4.streamId);
}
- public void testServerSendsSettingsToClient() throws Exception {
+ @Test public void serverSendsSettingsToClient() throws Exception {
// write the mocking script
Settings settings = new Settings();
settings.set(Settings.MAX_CONCURRENT_STREAMS, PERSIST_VALUE, 10);
@@ -223,7 +226,7 @@ public final class SpdyConnectionTest extends TestCase {
}
}
- public void testMultipleSettingsFramesAreMerged() throws Exception {
+ @Test public void multipleSettingsFramesAreMerged() throws Exception {
// write the mocking script
Settings settings1 = new Settings();
settings1.set(Settings.UPLOAD_BANDWIDTH, PERSIST_VALUE, 100);
@@ -257,7 +260,7 @@ public final class SpdyConnectionTest extends TestCase {
}
}
- public void testBogusDataFrameDoesNotDisruptConnection() throws Exception {
+ @Test public void bogusDataFrameDoesNotDisruptConnection() throws Exception {
// write the mocking script
peer.sendFrame().data(SpdyConnection.FLAG_FIN, 42, "bogus".getBytes("UTF-8"));
peer.acceptFrame(); // RST_STREAM
@@ -280,7 +283,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(2, ping.streamId);
}
- public void testBogusReplyFrameDoesNotDisruptConnection() throws Exception {
+ @Test public void bogusReplyFrameDoesNotDisruptConnection() throws Exception {
// write the mocking script
peer.sendFrame().synReply(0, 42, Arrays.asList("a", "android"));
peer.acceptFrame(); // RST_STREAM
@@ -303,7 +306,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(2, ping.streamId);
}
- public void testClientClosesClientOutputStream() throws Exception {
+ @Test public void clientClosesClientOutputStream() throws Exception {
// write the mocking script
peer.acceptFrame(); // SYN_STREAM
peer.acceptFrame(); // TYPE_DATA
@@ -343,7 +346,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(2, ping.streamId);
}
- public void testServerClosesClientOutputStream() throws Exception {
+ @Test public void serverClosesClientOutputStream() throws Exception {
// write the mocking script
peer.acceptFrame(); // SYN_STREAM
peer.sendFrame().synReset(1, SpdyStream.RST_CANCEL);
@@ -378,7 +381,7 @@ public final class SpdyConnectionTest extends TestCase {
* Test that the client sends a RST_STREAM if doing so won't disrupt the
* output stream.
*/
- public void testClientClosesClientInputStream() throws Exception {
+ @Test public void clientClosesClientInputStream() throws Exception {
// write the mocking script
peer.acceptFrame(); // SYN_STREAM
peer.acceptFrame(); // RST_STREAM
@@ -417,7 +420,7 @@ public final class SpdyConnectionTest extends TestCase {
* Test that the client doesn't send a RST_STREAM if doing so will disrupt
* the output stream.
*/
- public void testClientClosesClientInputStreamIfOutputStreamIsClosed() throws Exception {
+ @Test public void clientClosesClientInputStreamIfOutputStreamIsClosed() throws Exception {
// write the mocking script
peer.acceptFrame(); // SYN_STREAM
peer.acceptFrame(); // DATA
@@ -460,7 +463,7 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(SpdyStream.RST_CANCEL, rstStream.statusCode);
}
- public void testServerClosesClientInputStream() throws Exception {
+ @Test public void serverClosesClientInputStream() throws Exception {
// write the mocking script
peer.acceptFrame(); // SYN_STREAM
peer.sendFrame().data(FLAG_FIN, 1, "square".getBytes(UTF_8));
@@ -480,22 +483,22 @@ public final class SpdyConnectionTest extends TestCase {
assertEquals(SpdyConnection.FLAG_FIN, synStream.flags);
}
- public void testRemoteDoubleReply() {
+ @Test public void remoteDoubleReply() {
// We should get a PROTOCOL ERROR
// TODO
}
- public void testRemoteSendsDataAfterInFinished() {
+ @Test public void remoteSendsDataAfterInFinished() {
// We have a bug where we don't fastfoward the stream
// TODO
}
- public void testRemoteSendsTooMuchData() {
+ @Test public void remoteSendsTooMuchData() {
// We should send RST_FLOW_CONTROL_ERROR (and fastforward the stream)
// TODO
}
- public void testRemoteSendsRefusedStreamBeforeReplyHeaders() {
+ @Test public void remoteSendsRefusedStreamBeforeReplyHeaders() {
// Calling getResponseHeaders() should throw an IOException if the stream is refused.
// TODO
}