1
0
mirror of https://github.com/square/okhttp.git synced 2025-07-31 05:04:26 +03:00

Use AssertJ in tests (#4713)

This commit is contained in:
Benoît Quenaudon
2019-03-13 21:07:33 -04:00
committed by Jesse Wilson
parent a217a390ee
commit 6c4855a7c7
92 changed files with 4937 additions and 4619 deletions

View File

@ -34,6 +34,11 @@
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -25,7 +25,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public class CustomDispatcherTest { public class CustomDispatcherTest {
private MockWebServer mockWebServer = new MockWebServer(); private MockWebServer mockWebServer = new MockWebServer();
@ -44,13 +44,13 @@ public class CustomDispatcherTest {
return new MockResponse(); return new MockResponse();
} }
}; };
assertEquals(0, requestsMade.size()); assertThat(requestsMade.size()).isEqualTo(0);
mockWebServer.setDispatcher(dispatcher); mockWebServer.setDispatcher(dispatcher);
final URL url = mockWebServer.url("/").url(); final URL url = mockWebServer.url("/").url();
final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getResponseCode(); // Force the connection to hit the "server". conn.getResponseCode(); // Force the connection to hit the "server".
// Make sure our dispatcher got the request. // Make sure our dispatcher got the request.
assertEquals(1, requestsMade.size()); assertThat(requestsMade.size()).isEqualTo(1);
} }
@Test public void outOfOrderResponses() throws Exception { @Test public void outOfOrderResponses() throws Exception {
@ -75,12 +75,16 @@ public class CustomDispatcherTest {
final Thread endsFirst = buildRequestThread(secondRequest, secondResponseCode); final Thread endsFirst = buildRequestThread(secondRequest, secondResponseCode);
endsFirst.start(); endsFirst.start();
endsFirst.join(); endsFirst.join();
assertEquals(0, firstResponseCode.get()); // First response is still waiting. // First response is still waiting.
assertEquals(200, secondResponseCode.get()); // Second response is done. assertThat(firstResponseCode.get()).isEqualTo(0);
// Second response is done.
assertThat(secondResponseCode.get()).isEqualTo(200);
latch.countDown(); latch.countDown();
startsFirst.join(); startsFirst.join();
assertEquals(200, firstResponseCode.get()); // And now it's done! // And now it's done!
assertEquals(200, secondResponseCode.get()); // (Still done). assertThat(firstResponseCode.get()).isEqualTo(200);
// (Still done).
assertThat(secondResponseCode.get()).isEqualTo(200);
} }
private Thread buildRequestThread(String path, AtomicInteger responseCode) { private Thread buildRequestThread(String path, AtomicInteger responseCode) {

View File

@ -51,11 +51,8 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotEquals; import static org.assertj.core.data.Offset.offset;
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 static org.junit.Assert.fail;
public final class MockWebServerTest { public final class MockWebServerTest {
@ -63,8 +60,8 @@ public final class MockWebServerTest {
@Test public void defaultMockResponse() { @Test public void defaultMockResponse() {
MockResponse response = new MockResponse(); MockResponse response = new MockResponse();
assertEquals(Arrays.asList("Content-Length: 0"), headersToList(response)); assertThat(headersToList(response)).containsExactly("Content-Length: 0");
assertEquals("HTTP/1.1 200 OK", response.getStatus()); assertThat(response.getStatus()).isEqualTo("HTTP/1.1 200 OK");
} }
@Test public void setResponseMockReason() { @Test public void setResponseMockReason() {
@ -80,21 +77,21 @@ public final class MockWebServerTest {
for (int i = 0; i < 600; i++) { for (int i = 0; i < 600; i++) {
MockResponse response = new MockResponse().setResponseCode(i); MockResponse response = new MockResponse().setResponseCode(i);
String expectedReason = reasons[i / 100]; String expectedReason = reasons[i / 100];
assertEquals("HTTP/1.1 " + i + " " + expectedReason, response.getStatus()); assertThat(response.getStatus()).isEqualTo(("HTTP/1.1 " + i + " " + expectedReason));
assertEquals(Arrays.asList("Content-Length: 0"), headersToList(response)); assertThat(headersToList(response)).containsExactly("Content-Length: 0");
} }
} }
@Test public void setStatusControlsWholeStatusLine() { @Test public void setStatusControlsWholeStatusLine() {
MockResponse response = new MockResponse().setStatus("HTTP/1.1 202 That'll do pig"); MockResponse response = new MockResponse().setStatus("HTTP/1.1 202 That'll do pig");
assertEquals(Arrays.asList("Content-Length: 0"), headersToList(response)); assertThat(headersToList(response)).containsExactly("Content-Length: 0");
assertEquals("HTTP/1.1 202 That'll do pig", response.getStatus()); assertThat(response.getStatus()).isEqualTo("HTTP/1.1 202 That'll do pig");
} }
@Test public void setBodyAdjustsHeaders() throws IOException { @Test public void setBodyAdjustsHeaders() throws IOException {
MockResponse response = new MockResponse().setBody("ABC"); MockResponse response = new MockResponse().setBody("ABC");
assertEquals(Arrays.asList("Content-Length: 3"), headersToList(response)); assertThat(headersToList(response)).containsExactly("Content-Length: 3");
assertEquals("ABC", response.getBody().readUtf8()); assertThat(response.getBody().readUtf8()).isEqualTo("ABC");
} }
@Test public void mockResponseAddHeader() { @Test public void mockResponseAddHeader() {
@ -102,7 +99,7 @@ public final class MockWebServerTest {
.clearHeaders() .clearHeaders()
.addHeader("Cookie: s=square") .addHeader("Cookie: s=square")
.addHeader("Cookie", "a=android"); .addHeader("Cookie", "a=android");
assertEquals(Arrays.asList("Cookie: s=square", "Cookie: a=android"), headersToList(response)); assertThat(headersToList(response)).containsExactly("Cookie: s=square", "Cookie: a=android");
} }
@Test public void mockResponseSetHeader() { @Test public void mockResponseSetHeader() {
@ -112,7 +109,7 @@ public final class MockWebServerTest {
.addHeader("Cookie: a=android") .addHeader("Cookie: a=android")
.addHeader("Cookies: delicious"); .addHeader("Cookies: delicious");
response.setHeader("cookie", "r=robot"); response.setHeader("cookie", "r=robot");
assertEquals(Arrays.asList("Cookies: delicious", "cookie: r=robot"), headersToList(response)); assertThat(headersToList(response)).containsExactly("Cookies: delicious", "cookie: r=robot");
} }
@Test public void mockResponseSetHeaders() { @Test public void mockResponseSetHeaders() {
@ -123,7 +120,7 @@ public final class MockWebServerTest {
response.setHeaders(new Headers.Builder().add("Cookie", "a=android").build()); response.setHeaders(new Headers.Builder().add("Cookie", "a=android").build());
assertEquals(Arrays.asList("Cookie: a=android"), headersToList(response)); assertThat(headersToList(response)).containsExactly("Cookie: a=android");
} }
@Test public void regularResponse() throws Exception { @Test public void regularResponse() throws Exception {
@ -134,12 +131,12 @@ public final class MockWebServerTest {
connection.setRequestProperty("Accept-Language", "en-US"); connection.setRequestProperty("Accept-Language", "en-US");
InputStream in = connection.getInputStream(); InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK);
assertEquals("hello world", reader.readLine()); assertThat(reader.readLine()).isEqualTo("hello world");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("GET / HTTP/1.1", request.getRequestLine()); assertThat(request.getRequestLine()).isEqualTo("GET / HTTP/1.1");
assertEquals("en-US", request.getHeader("Accept-Language")); assertThat(request.getHeader("Accept-Language")).isEqualTo("en-US");
} }
@Test public void redirect() throws Exception { @Test public void redirect() throws Exception {
@ -152,12 +149,12 @@ public final class MockWebServerTest {
URLConnection connection = server.url("/").url().openConnection(); URLConnection connection = server.url("/").url().openConnection();
InputStream in = connection.getInputStream(); InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals("This is the new location!", reader.readLine()); assertThat(reader.readLine()).isEqualTo("This is the new location!");
RecordedRequest first = server.takeRequest(); RecordedRequest first = server.takeRequest();
assertEquals("GET / HTTP/1.1", first.getRequestLine()); assertThat(first.getRequestLine()).isEqualTo("GET / HTTP/1.1");
RecordedRequest redirect = server.takeRequest(); RecordedRequest redirect = server.takeRequest();
assertEquals("GET /new-path HTTP/1.1", redirect.getRequestLine()); assertThat(redirect.getRequestLine()).isEqualTo("GET /new-path HTTP/1.1");
} }
/** /**
@ -176,7 +173,7 @@ public final class MockWebServerTest {
URLConnection connection = server.url("/").url().openConnection(); URLConnection connection = server.url("/").url().openConnection();
InputStream in = connection.getInputStream(); InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals("enqueued in the background", reader.readLine()); assertThat(reader.readLine()).isEqualTo("enqueued in the background");
} }
@Test public void nonHexadecimalChunkSize() throws Exception { @Test public void nonHexadecimalChunkSize() throws Exception {
@ -204,9 +201,9 @@ public final class MockWebServerTest {
URLConnection urlConnection = server.url("/").url().openConnection(); URLConnection urlConnection = server.url("/").url().openConnection();
urlConnection.setReadTimeout(1000); urlConnection.setReadTimeout(1000);
InputStream in = urlConnection.getInputStream(); InputStream in = urlConnection.getInputStream();
assertEquals('A', in.read()); assertThat(in.read()).isEqualTo('A');
assertEquals('B', in.read()); assertThat(in.read()).isEqualTo('B');
assertEquals('C', in.read()); assertThat(in.read()).isEqualTo('C');
try { try {
in.read(); // if Content-Length was accurate, this would return -1 immediately in.read(); // if Content-Length was accurate, this would return -1 immediately
fail(); fail();
@ -215,13 +212,13 @@ public final class MockWebServerTest {
URLConnection urlConnection2 = server.url("/").url().openConnection(); URLConnection urlConnection2 = server.url("/").url().openConnection();
InputStream in2 = urlConnection2.getInputStream(); InputStream in2 = urlConnection2.getInputStream();
assertEquals('D', in2.read()); assertThat(in2.read()).isEqualTo('D');
assertEquals('E', in2.read()); assertThat(in2.read()).isEqualTo('E');
assertEquals('F', in2.read()); assertThat(in2.read()).isEqualTo('F');
assertEquals(-1, in2.read()); assertThat(in2.read()).isEqualTo(-1);
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void disconnectAtStart() throws Exception { @Test public void disconnectAtStart() throws Exception {
@ -248,12 +245,14 @@ public final class MockWebServerTest {
connection.setDoOutput(true); connection.setDoOutput(true);
connection.getOutputStream().write("ABCDEF".getBytes(UTF_8)); connection.getOutputStream().write("ABCDEF".getBytes(UTF_8));
InputStream in = connection.getInputStream(); InputStream in = connection.getInputStream();
assertEquals(-1, in.read()); assertThat(in.read()).isEqualTo(-1);
long elapsedNanos = System.nanoTime() - startNanos; long elapsedNanos = System.nanoTime() - startNanos;
long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos);
assertTrue(Util.format("Request + Response: %sms", elapsedMillis), elapsedMillis >= 500); assertThat(elapsedMillis >= 500).overridingErrorMessage(
assertTrue(Util.format("Request + Response: %sms", elapsedMillis), elapsedMillis < 1000); Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
assertThat(elapsedMillis < 1000).overridingErrorMessage(
Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
} }
/** /**
@ -268,18 +267,20 @@ public final class MockWebServerTest {
long startNanos = System.nanoTime(); long startNanos = System.nanoTime();
URLConnection connection = server.url("/").url().openConnection(); URLConnection connection = server.url("/").url().openConnection();
InputStream in = connection.getInputStream(); InputStream in = connection.getInputStream();
assertEquals('A', in.read()); assertThat(in.read()).isEqualTo('A');
assertEquals('B', in.read()); assertThat(in.read()).isEqualTo('B');
assertEquals('C', in.read()); assertThat(in.read()).isEqualTo('C');
assertEquals('D', in.read()); assertThat(in.read()).isEqualTo('D');
assertEquals('E', in.read()); assertThat(in.read()).isEqualTo('E');
assertEquals('F', in.read()); assertThat(in.read()).isEqualTo('F');
assertEquals(-1, in.read()); assertThat(in.read()).isEqualTo(-1);
long elapsedNanos = System.nanoTime() - startNanos; long elapsedNanos = System.nanoTime() - startNanos;
long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos);
assertTrue(Util.format("Request + Response: %sms", elapsedMillis), elapsedMillis >= 500); assertThat(elapsedMillis >= 500).overridingErrorMessage(
assertTrue(Util.format("Request + Response: %sms", elapsedMillis), elapsedMillis < 1000); Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
assertThat(elapsedMillis < 1000).overridingErrorMessage(
Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
} }
/** Delay the response body by sleeping 1s. */ /** Delay the response body by sleeping 1s. */
@ -291,10 +292,11 @@ public final class MockWebServerTest {
long startNanos = System.nanoTime(); long startNanos = System.nanoTime();
URLConnection connection = server.url("/").url().openConnection(); URLConnection connection = server.url("/").url().openConnection();
InputStream in = connection.getInputStream(); InputStream in = connection.getInputStream();
assertEquals('A', in.read()); assertThat(in.read()).isEqualTo('A');
long elapsedNanos = System.nanoTime() - startNanos; long elapsedNanos = System.nanoTime() - startNanos;
long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos);
assertTrue(Util.format("Request + Response: %sms", elapsedMillis), elapsedMillis >= 1000); assertThat(elapsedMillis >= 1000).overridingErrorMessage(
Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
in.close(); in.close();
} }
@ -326,7 +328,8 @@ public final class MockWebServerTest {
break; break;
} }
} }
assertEquals(512f, i, 5f); // Halfway +/- 0.5% // Halfway +/- 0.5%
assertThat((float) i).isCloseTo(512f, offset(5f));
} }
@Test public void disconnectResponseHalfway() throws IOException { @Test public void disconnectResponseHalfway() throws IOException {
@ -335,13 +338,13 @@ public final class MockWebServerTest {
.setSocketPolicy(SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY)); .setSocketPolicy(SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY));
URLConnection connection = server.url("/").url().openConnection(); URLConnection connection = server.url("/").url().openConnection();
assertEquals(2, connection.getContentLength()); assertThat(connection.getContentLength()).isEqualTo(2);
InputStream in = connection.getInputStream(); InputStream in = connection.getInputStream();
assertEquals('a', in.read()); assertThat(in.read()).isEqualTo('a');
try { try {
int byteRead = in.read(); int byteRead = in.read();
// OpenJDK behavior: end of stream. // OpenJDK behavior: end of stream.
assertEquals(-1, byteRead); assertThat(byteRead).isEqualTo(-1);
} catch (ProtocolException e) { } catch (ProtocolException e) {
// On Android, HttpURLConnection is implemented by OkHttp v2. OkHttp // On Android, HttpURLConnection is implemented by OkHttp v2. OkHttp
// treats an incomplete response body as a ProtocolException. // treats an incomplete response body as a ProtocolException.
@ -379,20 +382,20 @@ public final class MockWebServerTest {
} }
@Test public void portImplicitlyStarts() throws IOException { @Test public void portImplicitlyStarts() throws IOException {
assertTrue(server.getPort() > 0); assertThat(server.getPort() > 0).isTrue();
} }
@Test public void hostnameImplicitlyStarts() throws IOException { @Test public void hostnameImplicitlyStarts() throws IOException {
assertNotNull(server.getHostName()); assertThat(server.getHostName()).isNotNull();
} }
@Test public void toProxyAddressImplicitlyStarts() throws IOException { @Test public void toProxyAddressImplicitlyStarts() throws IOException {
assertNotNull(server.toProxyAddress()); assertThat(server.toProxyAddress()).isNotNull();
} }
@Test public void differentInstancesGetDifferentPorts() throws IOException { @Test public void differentInstancesGetDifferentPorts() throws IOException {
MockWebServer other = new MockWebServer(); MockWebServer other = new MockWebServer();
assertNotEquals(server.getPort(), other.getPort()); assertThat(other.getPort()).isNotEqualTo(server.getPort());
other.shutdown(); other.shutdown();
} }
@ -407,7 +410,7 @@ public final class MockWebServerTest {
statement.evaluate(); statement.evaluate();
assertTrue(called.get()); assertThat(called.get()).isTrue();
try { try {
server.url("/").url().openConnection().connect(); server.url("/").url().openConnection().connect();
fail(); fail();
@ -436,18 +439,19 @@ public final class MockWebServerTest {
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream(); InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK);
assertEquals("hello world", reader.readLine()); assertThat(reader.readLine()).isEqualTo("hello world");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("GET /a/deep/path?key=foo%20bar HTTP/1.1", request.getRequestLine()); assertThat(request.getRequestLine()).isEqualTo(
"GET /a/deep/path?key=foo%20bar HTTP/1.1");
HttpUrl requestUrl = request.getRequestUrl(); HttpUrl requestUrl = request.getRequestUrl();
assertEquals("http", requestUrl.scheme()); assertThat(requestUrl.scheme()).isEqualTo("http");
assertEquals(server.getHostName(), requestUrl.host()); assertThat(requestUrl.host()).isEqualTo(server.getHostName());
assertEquals(server.getPort(), requestUrl.port()); assertThat(requestUrl.port()).isEqualTo(server.getPort());
assertEquals("/a/deep/path", requestUrl.encodedPath()); assertThat(requestUrl.encodedPath()).isEqualTo("/a/deep/path");
assertEquals("foo bar", requestUrl.queryParameter("key")); assertThat(requestUrl.queryParameter("key")).isEqualTo("foo bar");
} }
@Test public void shutdownServerAfterRequest() throws Exception { @Test public void shutdownServerAfterRequest() throws Exception {
@ -456,7 +460,7 @@ public final class MockWebServerTest {
URL url = server.url("/").url(); URL url = server.url("/").url();
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK);
HttpURLConnection refusedConnection = (HttpURLConnection) url.openConnection(); HttpURLConnection refusedConnection = (HttpURLConnection) url.openConnection();
@ -464,7 +468,7 @@ public final class MockWebServerTest {
refusedConnection.getResponseCode(); refusedConnection.getResponseCode();
fail("Second connection should be refused"); fail("Second connection should be refused");
} catch (ConnectException e ) { } catch (ConnectException e ) {
assertTrue(e.getMessage().contains("refused")); assertThat(e.getMessage().contains("refused")).isTrue();
} }
} }
@ -479,10 +483,10 @@ public final class MockWebServerTest {
InputStream in = connection.getInputStream(); InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals("response", reader.readLine()); assertThat(reader.readLine()).isEqualTo("response");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("request", request.getBody().readUtf8()); assertThat(request.getBody().readUtf8()).isEqualTo("request");
} }
@Test public void testH2PriorKnowledgeServerFallback() { @Test public void testH2PriorKnowledgeServerFallback() {
@ -490,8 +494,9 @@ public final class MockWebServerTest {
server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)); server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1));
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("protocols containing h2_prior_knowledge cannot use other protocols: " assertThat(expected.getMessage()).isEqualTo(
+ "[h2_prior_knowledge, http/1.1]", expected.getMessage()); ("protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, http/1.1]"));
} }
} }
@ -501,16 +506,17 @@ public final class MockWebServerTest {
server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)); server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE));
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("protocols containing h2_prior_knowledge cannot use other protocols: " assertThat(expected.getMessage()).isEqualTo(
+ "[h2_prior_knowledge, h2_prior_knowledge]", expected.getMessage()); ("protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, h2_prior_knowledge]"));
} }
} }
@Test public void testMockWebServerH2PriorKnowledgeProtocol() { @Test public void testMockWebServerH2PriorKnowledgeProtocol() {
server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)); server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE));
assertEquals(1, server.protocols().size()); assertThat(server.protocols().size()).isEqualTo(1);
assertEquals(Protocol.H2_PRIOR_KNOWLEDGE, server.protocols().get(0)); assertThat(server.protocols().get(0)).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE);
} }
@Test public void https() throws Exception { @Test public void https() throws Exception {
@ -523,19 +529,19 @@ public final class MockWebServerTest {
connection.setSSLSocketFactory(handshakeCertificates.sslSocketFactory()); connection.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier()); connection.setHostnameVerifier(new RecordingHostnameVerifier());
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
assertEquals("abc", reader.readLine()); assertThat(reader.readLine()).isEqualTo("abc");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("https", request.getRequestUrl().scheme()); assertThat(request.getRequestUrl().scheme()).isEqualTo("https");
Handshake handshake = request.getHandshake(); Handshake handshake = request.getHandshake();
assertNotNull(handshake.tlsVersion()); assertThat(handshake.tlsVersion()).isNotNull();
assertNotNull(handshake.cipherSuite()); assertThat(handshake.cipherSuite()).isNotNull();
assertNotNull(handshake.localPrincipal()); assertThat(handshake.localPrincipal()).isNotNull();
assertEquals(1, handshake.localCertificates().size()); assertThat(handshake.localCertificates().size()).isEqualTo(1);
assertNull(handshake.peerPrincipal()); assertThat(handshake.peerPrincipal()).isNull();
assertEquals(0, handshake.peerCertificates().size()); assertThat(handshake.peerCertificates().size()).isEqualTo(0);
} }
@Test public void httpsWithClientAuth() throws Exception { @Test public void httpsWithClientAuth() throws Exception {
@ -571,18 +577,18 @@ public final class MockWebServerTest {
connection.setSSLSocketFactory(clientHandshakeCertificates.sslSocketFactory()); connection.setSSLSocketFactory(clientHandshakeCertificates.sslSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier()); connection.setHostnameVerifier(new RecordingHostnameVerifier());
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
assertEquals("abc", reader.readLine()); assertThat(reader.readLine()).isEqualTo("abc");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("https", request.getRequestUrl().scheme()); assertThat(request.getRequestUrl().scheme()).isEqualTo("https");
Handshake handshake = request.getHandshake(); Handshake handshake = request.getHandshake();
assertNotNull(handshake.tlsVersion()); assertThat(handshake.tlsVersion()).isNotNull();
assertNotNull(handshake.cipherSuite()); assertThat(handshake.cipherSuite()).isNotNull();
assertNotNull(handshake.localPrincipal()); assertThat(handshake.localPrincipal()).isNotNull();
assertEquals(1, handshake.localCertificates().size()); assertThat(handshake.localCertificates().size()).isEqualTo(1);
assertNotNull(handshake.peerPrincipal()); assertThat(handshake.peerPrincipal()).isNotNull();
assertEquals(1, handshake.peerCertificates().size()); assertThat(handshake.peerCertificates().size()).isEqualTo(1);
} }
} }

View File

@ -26,7 +26,7 @@ import okhttp3.internal.Util;
import okio.Buffer; import okio.Buffer;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public class RecordedRequestTest { public class RecordedRequestTest {
Headers headers = Util.EMPTY_HEADERS; Headers headers = Util.EMPTY_HEADERS;
@ -76,7 +76,7 @@ public class RecordedRequestTest {
RecordedRequest request = new RecordedRequest("GET / HTTP/1.1", headers, RecordedRequest request = new RecordedRequest("GET / HTTP/1.1", headers,
Collections.emptyList(), 0, new Buffer(), 0, socket); Collections.emptyList(), 0, new Buffer(), 0, socket);
assertEquals("http://127.0.0.1/", request.getRequestUrl().toString()); assertThat(request.getRequestUrl().toString()).isEqualTo("http://127.0.0.1/");
} }
@Test public void testIpv6() throws UnknownHostException { @Test public void testIpv6() throws UnknownHostException {
@ -86,7 +86,7 @@ public class RecordedRequestTest {
RecordedRequest request = new RecordedRequest("GET / HTTP/1.1", headers, RecordedRequest request = new RecordedRequest("GET / HTTP/1.1", headers,
Collections.emptyList(), 0, new Buffer(), 0, socket); Collections.emptyList(), 0, new Buffer(), 0, socket);
assertEquals("http://[::1]/", request.getRequestUrl().toString()); assertThat(request.getRequestUrl().toString()).isEqualTo("http://[::1]/");
} }
@Test public void testUsesLocal() throws UnknownHostException { @Test public void testUsesLocal() throws UnknownHostException {
@ -96,6 +96,6 @@ public class RecordedRequestTest {
RecordedRequest request = new RecordedRequest("GET / HTTP/1.1", headers, RecordedRequest request = new RecordedRequest("GET / HTTP/1.1", headers,
Collections.emptyList(), 0, new Buffer(), 0, socket); Collections.emptyList(), 0, new Buffer(), 0, socket);
assertEquals("http://127.0.0.1/", request.getRequestUrl().toString()); assertThat(request.getRequestUrl().toString()).isEqualTo("http://127.0.0.1/");
} }
} }

View File

@ -43,6 +43,11 @@
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -22,72 +22,74 @@ import okio.Buffer;
import org.junit.Test; import org.junit.Test;
import static okhttp3.curl.Main.fromArgs; import static okhttp3.curl.Main.fromArgs;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
public class MainTest { public class MainTest {
@Test public void simple() { @Test public void simple() {
Request request = fromArgs("http://example.com").createRequest(); Request request = fromArgs("http://example.com").createRequest();
assertEquals("GET", request.method()); assertThat(request.method()).isEqualTo("GET");
assertEquals("http://example.com/", request.url().toString()); assertThat(request.url().toString()).isEqualTo("http://example.com/");
assertNull(request.body()); assertThat(request.body()).isNull();
} }
@Test public void put() throws IOException { @Test public void put() throws IOException {
Request request = fromArgs("-X", "PUT", "-d", "foo", "http://example.com").createRequest(); Request request = fromArgs("-X", "PUT", "-d", "foo", "http://example.com").createRequest();
assertEquals("PUT", request.method()); assertThat(request.method()).isEqualTo("PUT");
assertEquals("http://example.com/", request.url().toString()); assertThat(request.url().toString()).isEqualTo("http://example.com/");
assertEquals(3, request.body().contentLength()); assertThat(request.body().contentLength()).isEqualTo(3);
} }
@Test public void dataPost() { @Test public void dataPost() {
Request request = fromArgs("-d", "foo", "http://example.com").createRequest(); Request request = fromArgs("-d", "foo", "http://example.com").createRequest();
RequestBody body = request.body(); RequestBody body = request.body();
assertEquals("POST", request.method()); assertThat(request.method()).isEqualTo("POST");
assertEquals("http://example.com/", request.url().toString()); assertThat(request.url().toString()).isEqualTo("http://example.com/");
assertEquals("application/x-www-form-urlencoded; charset=utf-8", body.contentType().toString()); assertThat(body.contentType().toString()).isEqualTo(
assertEquals("foo", bodyAsString(body)); "application/x-www-form-urlencoded; charset=utf-8");
assertThat(bodyAsString(body)).isEqualTo("foo");
} }
@Test public void dataPut() { @Test public void dataPut() {
Request request = fromArgs("-d", "foo", "-X", "PUT", "http://example.com").createRequest(); Request request = fromArgs("-d", "foo", "-X", "PUT", "http://example.com").createRequest();
RequestBody body = request.body(); RequestBody body = request.body();
assertEquals("PUT", request.method()); assertThat(request.method()).isEqualTo("PUT");
assertEquals("http://example.com/", request.url().toString()); assertThat(request.url().toString()).isEqualTo("http://example.com/");
assertEquals("application/x-www-form-urlencoded; charset=utf-8", body.contentType().toString()); assertThat(body.contentType().toString()).isEqualTo(
assertEquals("foo", bodyAsString(body)); "application/x-www-form-urlencoded; charset=utf-8");
assertThat(bodyAsString(body)).isEqualTo("foo");
} }
@Test public void contentTypeHeader() { @Test public void contentTypeHeader() {
Request request = fromArgs("-d", "foo", "-H", "Content-Type: application/json", Request request = fromArgs("-d", "foo", "-H", "Content-Type: application/json",
"http://example.com").createRequest(); "http://example.com").createRequest();
RequestBody body = request.body(); RequestBody body = request.body();
assertEquals("POST", request.method()); assertThat(request.method()).isEqualTo("POST");
assertEquals("http://example.com/", request.url().toString()); assertThat(request.url().toString()).isEqualTo("http://example.com/");
assertEquals("application/json; charset=utf-8", body.contentType().toString()); assertThat(body.contentType().toString()).isEqualTo("application/json; charset=utf-8");
assertEquals("foo", bodyAsString(body)); assertThat(bodyAsString(body)).isEqualTo("foo");
} }
@Test public void referer() { @Test public void referer() {
Request request = fromArgs("-e", "foo", "http://example.com").createRequest(); Request request = fromArgs("-e", "foo", "http://example.com").createRequest();
assertEquals("GET", request.method()); assertThat(request.method()).isEqualTo("GET");
assertEquals("http://example.com/", request.url().toString()); assertThat(request.url().toString()).isEqualTo("http://example.com/");
assertEquals("foo", request.header("Referer")); assertThat(request.header("Referer")).isEqualTo("foo");
assertNull(request.body()); assertThat(request.body()).isNull();
} }
@Test public void userAgent() { @Test public void userAgent() {
Request request = fromArgs("-A", "foo", "http://example.com").createRequest(); Request request = fromArgs("-A", "foo", "http://example.com").createRequest();
assertEquals("GET", request.method()); assertThat(request.method()).isEqualTo("GET");
assertEquals("http://example.com/", request.url().toString()); assertThat(request.url().toString()).isEqualTo("http://example.com/");
assertEquals("foo", request.header("User-Agent")); assertThat(request.header("User-Agent")).isEqualTo("foo");
assertNull(request.body()); assertThat(request.body()).isNull();
} }
@Test public void headerSplitWithDate() { @Test public void headerSplitWithDate() {
Request request = fromArgs("-H", "If-Modified-Since: Mon, 18 Aug 2014 15:16:06 GMT", Request request = fromArgs("-H", "If-Modified-Since: Mon, 18 Aug 2014 15:16:06 GMT",
"http://example.com").createRequest(); "http://example.com").createRequest();
assertEquals("Mon, 18 Aug 2014 15:16:06 GMT", request.header("If-Modified-Since")); assertThat(request.header("If-Modified-Since")).isEqualTo(
"Mon, 18 Aug 2014 15:16:06 GMT");
} }
private static String bodyAsString(RequestBody body) { private static String bodyAsString(RequestBody body) {

View File

@ -46,6 +46,11 @@
<artifactId>conscrypt-openjdk-uber</artifactId> <artifactId>conscrypt-openjdk-uber</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -39,8 +39,7 @@ import org.junit.Test;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public class DnsOverHttpsTest { public class DnsOverHttpsTest {
@ -62,12 +61,12 @@ public class DnsOverHttpsTest {
List<InetAddress> result = dns.lookup("google.com"); List<InetAddress> result = dns.lookup("google.com");
assertEquals(singletonList(address("157.240.1.18")), result); assertThat(result).isEqualTo(singletonList(address("157.240.1.18")));
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertEquals("GET", recordedRequest.getMethod()); assertThat(recordedRequest.getMethod()).isEqualTo("GET");
assertEquals("/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ", assertThat(recordedRequest.getPath()).isEqualTo(
recordedRequest.getPath()); "/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ");
} }
@Test public void getIpv6() throws Exception { @Test public void getIpv6() throws Exception {
@ -84,20 +83,20 @@ public class DnsOverHttpsTest {
List<InetAddress> result = dns.lookup("google.com"); List<InetAddress> result = dns.lookup("google.com");
assertEquals(2, result.size()); assertThat(result.size()).isEqualTo(2);
assertTrue(result.contains(address("157.240.1.18"))); assertThat(result.contains(address("157.240.1.18"))).isTrue();
assertTrue(result.contains(address("2a03:2880:f029:11:face:b00c:0:2"))); assertThat(result.contains(address("2a03:2880:f029:11:face:b00c:0:2"))).isTrue();
RecordedRequest request1 = server.takeRequest(); RecordedRequest request1 = server.takeRequest();
assertEquals("GET", request1.getMethod()); assertThat(request1.getMethod()).isEqualTo("GET");
RecordedRequest request2 = server.takeRequest(); RecordedRequest request2 = server.takeRequest();
assertEquals("GET", request2.getMethod()); assertThat(request2.getMethod()).isEqualTo("GET");
assertEquals(new HashSet<>( assertThat(new LinkedHashSet<>(Arrays.asList(request1.getPath(), request2.getPath()))).isEqualTo(
new HashSet<>(
Arrays.asList("/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ", Arrays.asList("/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ",
"/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ")), "/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ")));
new LinkedHashSet<>(Arrays.asList(request1.getPath(), request2.getPath())));
} }
@Test public void failure() throws Exception { @Test public void failure() throws Exception {
@ -111,13 +110,13 @@ public class DnsOverHttpsTest {
fail(); fail();
} catch (UnknownHostException uhe) { } catch (UnknownHostException uhe) {
uhe.printStackTrace(); uhe.printStackTrace();
assertEquals("google.com: NXDOMAIN", uhe.getMessage()); assertThat(uhe.getMessage()).isEqualTo("google.com: NXDOMAIN");
} }
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertEquals("GET", recordedRequest.getMethod()); assertThat(recordedRequest.getMethod()).isEqualTo("GET");
assertEquals("/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ", assertThat(recordedRequest.getPath()).isEqualTo(
recordedRequest.getPath()); "/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ");
} }
@Test public void failOnExcessiveResponse() { @Test public void failOnExcessiveResponse() {
@ -129,10 +128,11 @@ public class DnsOverHttpsTest {
dns.lookup("google.com"); dns.lookup("google.com");
fail(); fail();
} catch (IOException ioe) { } catch (IOException ioe) {
assertEquals("google.com", ioe.getMessage()); assertThat(ioe.getMessage()).isEqualTo("google.com");
Throwable cause = ioe.getCause(); Throwable cause = ioe.getCause();
assertTrue(cause instanceof IOException); assertThat(cause instanceof IOException).isTrue();
assertEquals("response size exceeds limit (65536 bytes): 65537 bytes", cause.getMessage()); assertThat(cause.getMessage()).isEqualTo(
"response size exceeds limit (65536 bytes): 65537 bytes");
} }
} }
@ -143,9 +143,10 @@ public class DnsOverHttpsTest {
dns.lookup("google.com"); dns.lookup("google.com");
fail(); fail();
} catch (IOException ioe) { } catch (IOException ioe) {
assertEquals("google.com", ioe.getMessage()); assertThat(ioe.getMessage()).isEqualTo("google.com");
Throwable cause = ioe.getCause(); Throwable cause = ioe.getCause();
assertTrue(cause instanceof RuntimeException); boolean condition = cause instanceof RuntimeException;
assertThat(condition).isTrue();
} }
} }
@ -170,15 +171,15 @@ public class DnsOverHttpsTest {
List<InetAddress> result = cachedDns.lookup("google.com"); List<InetAddress> result = cachedDns.lookup("google.com");
assertEquals(singletonList(address("157.240.1.18")), result); assertThat(result).containsExactly(address("157.240.1.18"));
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertEquals("GET", recordedRequest.getMethod()); assertThat(recordedRequest.getMethod()).isEqualTo("GET");
assertEquals("/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ", assertThat(recordedRequest.getPath()).isEqualTo(
recordedRequest.getPath()); "/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ");
result = cachedDns.lookup("google.com"); result = cachedDns.lookup("google.com");
assertEquals(singletonList(address("157.240.1.18")), result); assertThat(result).isEqualTo(singletonList(address("157.240.1.18")));
} }
private MockResponse dnsResponse(String s) { private MockResponse dnsResponse(String s) {

View File

@ -17,21 +17,20 @@ package okhttp3.dnsoverhttps;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List; import java.util.List;
import okio.ByteString; import okio.ByteString;
import org.junit.Test; import org.junit.Test;
import static okhttp3.dnsoverhttps.DnsRecordCodec.TYPE_A; import static okhttp3.dnsoverhttps.DnsRecordCodec.TYPE_A;
import static okhttp3.dnsoverhttps.DnsRecordCodec.TYPE_AAAA; import static okhttp3.dnsoverhttps.DnsRecordCodec.TYPE_AAAA;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public class DnsRecordCodecTest { public class DnsRecordCodecTest {
@Test public void testGoogleDotComEncoding() { @Test public void testGoogleDotComEncoding() {
String encoded = encodeQuery("google.com", TYPE_A); String encoded = encodeQuery("google.com", TYPE_A);
assertEquals("AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ", encoded); assertThat(encoded).isEqualTo("AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ");
} }
private String encodeQuery(String host, int type) { private String encodeQuery(String host, int type) {
@ -41,30 +40,28 @@ public class DnsRecordCodecTest {
@Test public void testGoogleDotComEncodingWithIPv6() { @Test public void testGoogleDotComEncodingWithIPv6() {
String encoded = encodeQuery("google.com", TYPE_AAAA); String encoded = encodeQuery("google.com", TYPE_AAAA);
assertEquals("AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ", encoded); assertThat(encoded).isEqualTo("AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ");
} }
@Test public void testGoogleDotComDecodingFromCloudflare() throws Exception { @Test public void testGoogleDotComDecodingFromCloudflare() throws Exception {
List<InetAddress> encoded = DnsRecordCodec.decodeAnswers("test.com", ByteString.decodeHex( List<InetAddress> encoded = DnsRecordCodec.decodeAnswers("test.com", ByteString.decodeHex(
"00008180000100010000000006676f6f676c6503636f6d0000010001c00c00010001000000430004d83ad54e")); "00008180000100010000000006676f6f676c6503636f6d0000010001c00c00010001000000430004d83ad54e"));
assertEquals(Collections.singletonList(InetAddress.getByName("216.58.213.78")), encoded); assertThat(encoded).containsExactly(InetAddress.getByName("216.58.213.78"));
} }
@Test public void testGoogleDotComDecodingFromGoogle() throws Exception { @Test public void testGoogleDotComDecodingFromGoogle() throws Exception {
List<InetAddress> decoded = DnsRecordCodec.decodeAnswers("test.com", ByteString.decodeHex( List<InetAddress> decoded = DnsRecordCodec.decodeAnswers("test.com", ByteString.decodeHex(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c0005000100000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c042000100010000003b00049df00112")); "0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c0005000100000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c042000100010000003b00049df00112"));
assertEquals(Collections.singletonList(InetAddress.getByName("157.240.1.18")), decoded); assertThat(decoded).containsExactly(InetAddress.getByName("157.240.1.18"));
} }
@Test public void testGoogleDotComDecodingFromGoogleIPv6() throws Exception { @Test public void testGoogleDotComDecodingFromGoogleIPv6() throws Exception {
List<InetAddress> decoded = DnsRecordCodec.decodeAnswers("test.com", ByteString.decodeHex( List<InetAddress> decoded = DnsRecordCodec.decodeAnswers("test.com", ByteString.decodeHex(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d00001c0001c00c0005000100000a1b000603617069c012c0300005000100000b1f000c04737461720463313072c012c042001c00010000003b00102a032880f0290011faceb00c00000002")); "0000818000010003000000000567726170680866616365626f6f6b03636f6d00001c0001c00c0005000100000a1b000603617069c012c0300005000100000b1f000c04737461720463313072c012c042001c00010000003b00102a032880f0290011faceb00c00000002"));
assertEquals( assertThat(decoded).containsExactly(InetAddress.getByName("2a03:2880:f029:11:face:b00c:0:2"));
Collections.singletonList(InetAddress.getByName("2a03:2880:f029:11:face:b00c:0:2")),
decoded);
} }
@Test public void testGoogleDotComDecodingNxdomainFailure() throws Exception { @Test public void testGoogleDotComDecodingNxdomainFailure() throws Exception {
@ -73,7 +70,7 @@ public class DnsRecordCodecTest {
"0000818300010000000100000e7364666c6b686673646c6b6a64660265650000010001c01b00060001000007070038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e6574c01b5adb12c100000e10000003840012750000000e10")); "0000818300010000000100000e7364666c6b686673646c6b6a64660265650000010001c01b00060001000007070038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e6574c01b5adb12c100000e10000003840012750000000e10"));
fail(); fail();
} catch (UnknownHostException uhe) { } catch (UnknownHostException uhe) {
assertEquals("sdflkhfsdlkjdf.ee: NXDOMAIN", uhe.getMessage()); assertThat(uhe.getMessage()).isEqualTo("sdflkhfsdlkjdf.ee: NXDOMAIN");
} }
} }
} }

View File

@ -8,7 +8,7 @@
<parent> <parent>
<groupId>com.squareup.okhttp3</groupId> <groupId>com.squareup.okhttp3</groupId>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<version>3.13.0-SNAPSHOT</version> <version>3.14.0-SNAPSHOT</version>
</parent> </parent>
<artifactId>okhttp-hpacktests</artifactId> <artifactId>okhttp-hpacktests</artifactId>
@ -45,6 +45,11 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -24,7 +24,7 @@ import okhttp3.internal.http2.hpackjson.HpackJsonUtil;
import okhttp3.internal.http2.hpackjson.Story; import okhttp3.internal.http2.hpackjson.Story;
import okio.Buffer; import okio.Buffer;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
/** /**
@ -83,7 +83,8 @@ public class HpackDecodeTestBase {
*/ */
private static void assertSetEquals( private static void assertSetEquals(
String message, List<Header> expected, List<Header> observed) { String message, List<Header> expected, List<Header> observed) {
assertEquals(message, new LinkedHashSet<>(expected), new LinkedHashSet<>(observed)); assertThat(new LinkedHashSet<>(observed)).overridingErrorMessage(message).isEqualTo(
new LinkedHashSet<>(expected));
} }
protected Story getStory() { protected Story getStory() {

View File

@ -47,6 +47,11 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -38,17 +38,13 @@ import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.ByteString; import okio.ByteString;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeThat; import static org.junit.Assume.assumeThat;
@ -91,11 +87,11 @@ public final class HttpLoggingInterceptorTest {
@Test public void levelGetter() { @Test public void levelGetter() {
// The default is NONE. // The default is NONE.
Assert.assertEquals(Level.NONE, applicationInterceptor.getLevel()); assertThat(applicationInterceptor.getLevel()).isEqualTo(Level.NONE);
for (Level level : Level.values()) { for (Level level : Level.values()) {
applicationInterceptor.setLevel(level); applicationInterceptor.setLevel(level);
assertEquals(level, applicationInterceptor.getLevel()); assertThat(applicationInterceptor.getLevel()).isEqualTo(level);
} }
} }
@ -104,13 +100,13 @@ public final class HttpLoggingInterceptorTest {
applicationInterceptor.setLevel(null); applicationInterceptor.setLevel(null);
fail(); fail();
} catch (NullPointerException expected) { } catch (NullPointerException expected) {
assertEquals("level == null. Use Level.NONE instead.", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("level == null. Use Level.NONE instead.");
} }
} }
@Test public void setLevelShouldReturnSameInstanceOfInterceptor() { @Test public void setLevelShouldReturnSameInstanceOfInterceptor() {
for (Level level : Level.values()) { for (Level level : Level.values()) {
assertSame(applicationInterceptor, applicationInterceptor.setLevel(level)); assertThat(applicationInterceptor.setLevel(level)).isSameAs(applicationInterceptor);
} }
} }
@ -545,7 +541,8 @@ public final class HttpLoggingInterceptorTest {
Response response = client.newCall(request().build()).execute(); Response response = client.newCall(request().build()).execute();
ResponseBody responseBody = response.body(); ResponseBody responseBody = response.body();
assertEquals("Expected response body to be valid","Hello, Hello, Hello", responseBody.string()); assertThat(responseBody.string()).overridingErrorMessage(
"Expected response body to be valid").isEqualTo("Hello, Hello, Hello");
responseBody.close(); responseBody.close();
networkLogs networkLogs
@ -649,13 +646,13 @@ public final class HttpLoggingInterceptorTest {
} }
@Test public void isPlaintext() { @Test public void isPlaintext() {
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer())); assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer())).isTrue();
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("abc"))); assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("abc"))).isTrue();
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("new\r\nlines"))); assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("new\r\nlines"))).isTrue();
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("white\t space"))); assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("white\t space"))).isTrue();
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0x80))); assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0x80))).isTrue();
assertFalse(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0x00))); assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0x00))).isFalse();
assertFalse(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0xc0))); assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0xc0))).isFalse();
} }
@Test public void responseBodyIsBinary() throws IOException { @Test public void responseBodyIsBinary() throws IOException {
@ -827,7 +824,7 @@ public final class HttpLoggingInterceptorTest {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assumeThat(response.protocol(), equalTo(Protocol.HTTP_2)); assumeThat(response.protocol(), equalTo(Protocol.HTTP_2));
assertEquals("Hello response!", response.body().string()); assertThat(response.body().string()).isEqualTo("Hello response!");
applicationLogs applicationLogs
.assertLogEqual("--> POST " + url) .assertLogEqual("--> POST " + url)
@ -849,22 +846,23 @@ public final class HttpLoggingInterceptorTest {
private int index; private int index;
LogRecorder assertLogEqual(String expected) { LogRecorder assertLogEqual(String expected) {
assertTrue("No more messages found", index < logs.size()); assertThat(index < logs.size()).overridingErrorMessage("No more messages found").isTrue();
String actual = logs.get(index++); String actual = logs.get(index++);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
return this; return this;
} }
LogRecorder assertLogMatch(String pattern) { LogRecorder assertLogMatch(String pattern) {
assertTrue("No more messages found", index < logs.size()); assertThat(index < logs.size()).overridingErrorMessage("No more messages found").isTrue();
String actual = logs.get(index++); String actual = logs.get(index++);
assertTrue("<" + actual + "> did not match pattern <" + pattern + ">", assertThat(Pattern.matches(pattern, actual)).overridingErrorMessage(
Pattern.matches(pattern, actual)); "<" + actual + "> did not match pattern <" + pattern + ">").isTrue();
return this; return this;
} }
void assertNoMoreLogs() { void assertNoMoreLogs() {
assertEquals("More messages remain: " + logs.subList(index, logs.size()), index, logs.size()); assertThat(logs.size()).overridingErrorMessage(
"More messages remain: " + logs.subList(index, logs.size())).isEqualTo(index);
} }
@Override public void log(String message) { @Override public void log(String message) {

View File

@ -35,7 +35,7 @@ import static java.util.Arrays.asList;
import static okhttp3.Protocol.HTTP_1_1; import static okhttp3.Protocol.HTTP_1_1;
import static okhttp3.Protocol.HTTP_2; import static okhttp3.Protocol.HTTP_2;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.junit.Assert.assertNotNull; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class LoggingEventListenerTest { public final class LoggingEventListenerTest {
@ -67,7 +67,7 @@ public final class LoggingEventListenerTest {
public void get() throws Exception { public void get() throws Exception {
server.enqueue(new MockResponse().setBody("Hello!").setHeader("Content-Type", PLAIN)); server.enqueue(new MockResponse().setBody("Hello!").setHeader("Content-Type", PLAIN));
Response response = client.newCall(request().build()).execute(); Response response = client.newCall(request().build()).execute();
assertNotNull(response.body()); assertThat(response.body()).isNotNull();
response.body().bytes(); response.body().bytes();
logRecorder logRecorder
@ -136,7 +136,7 @@ public final class LoggingEventListenerTest {
server.enqueue(new MockResponse()); server.enqueue(new MockResponse());
Response response = client.newCall(request().build()).execute(); Response response = client.newCall(request().build()).execute();
assertNotNull(response.body()); assertThat(response.body()).isNotNull();
response.body().bytes(); response.body().bytes();
logRecorder logRecorder

View File

@ -41,6 +41,11 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -27,7 +27,7 @@ import org.junit.After;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public final class EventSourceHttpTest { public final class EventSourceHttpTest {
@Rule public final MockWebServer server = new MockWebServer(); @Rule public final MockWebServer server = new MockWebServer();
@ -47,7 +47,7 @@ public final class EventSourceHttpTest {
EventSource source = newEventSource(); EventSource source = newEventSource();
assertEquals("/", source.request().url().encodedPath()); assertThat(source.request().url().encodedPath()).isEqualTo("/");
listener.assertOpen(); listener.assertOpen();
listener.assertEvent(null, null, "hey"); listener.assertEvent(null, null, "hey");
@ -84,7 +84,7 @@ public final class EventSourceHttpTest {
EventSource source = newEventSource(); EventSource source = newEventSource();
assertEquals("/", source.request().url().encodedPath()); assertThat(source.request().url().encodedPath()).isEqualTo("/");
listener.assertOpen(); listener.assertOpen();
listener.assertEvent(null, null, "hey"); listener.assertEvent(null, null, "hey");

View File

@ -25,9 +25,7 @@ import okhttp3.Response;
import okhttp3.internal.platform.Platform; import okhttp3.internal.platform.Platform;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public final class EventSourceRecorder extends EventSourceListener { public final class EventSourceRecorder extends EventSourceListener {
private final BlockingQueue<Object> events = new LinkedBlockingDeque<>(); private final BlockingQueue<Object> events = new LinkedBlockingDeque<>();
@ -67,12 +65,12 @@ public final class EventSourceRecorder extends EventSourceListener {
} }
public void assertExhausted() { public void assertExhausted() {
assertTrue("Remaining events: " + events, events.isEmpty()); assertThat(events.isEmpty()).overridingErrorMessage("Remaining events: " + events).isTrue();
} }
public void assertEvent(@Nullable String id, @Nullable String type, String data) { public void assertEvent(@Nullable String id, @Nullable String type, String data) {
Object actual = nextEvent(); Object actual = nextEvent();
assertEquals(new Event(id, type, data), actual); assertThat(actual).isEqualTo(new Event(id, type, data));
} }
public EventSource assertOpen() { public EventSource assertOpen() {
@ -96,9 +94,9 @@ public final class EventSourceRecorder extends EventSourceListener {
throw new AssertionError("Expected Failure but was " + event); throw new AssertionError("Expected Failure but was " + event);
} }
if (message != null) { if (message != null) {
assertEquals(message, ((Failure) event).t.getMessage()); assertThat(((Failure) event).t.getMessage()).isEqualTo(message);
} else { } else {
assertNull(((Failure) event).t); assertThat(((Failure) event).t).isNull();
} }
} }

View File

@ -23,15 +23,14 @@ import okio.Buffer;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public final class ServerSentEventIteratorTest { public final class ServerSentEventIteratorTest {
/** Either {@link Event} or {@link Long} items for events and retry changes, respectively. */ /** Either {@link Event} or {@link Long} items for events and retry changes, respectively. */
private final Deque<Object> callbacks = new ArrayDeque<>(); private final Deque<Object> callbacks = new ArrayDeque<>();
@After public void after() { @After public void after() {
assertTrue("Unconsumed events: " + callbacks, callbacks.isEmpty()); assertThat(callbacks.isEmpty()).overridingErrorMessage("Unconsumed events: " + callbacks).isTrue();
} }
@Test public void multiline() throws IOException { @Test public void multiline() throws IOException {
@ -40,7 +39,7 @@ public final class ServerSentEventIteratorTest {
+ "data: +2\n" + "data: +2\n"
+ "data: 10\n" + "data: 10\n"
+ "\n"); + "\n");
assertEquals(new Event(null, null, "YHOO\n+2\n10"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "YHOO\n+2\n10"));
} }
@Test public void multilineCr() throws IOException { @Test public void multilineCr() throws IOException {
@ -49,7 +48,7 @@ public final class ServerSentEventIteratorTest {
+ "data: +2\r" + "data: +2\r"
+ "data: 10\r" + "data: 10\r"
+ "\r"); + "\r");
assertEquals(new Event(null, null, "YHOO\n+2\n10"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "YHOO\n+2\n10"));
} }
@Test public void multilineCrLf() throws IOException { @Test public void multilineCrLf() throws IOException {
@ -58,7 +57,7 @@ public final class ServerSentEventIteratorTest {
+ "data: +2\r\n" + "data: +2\r\n"
+ "data: 10\r\n" + "data: 10\r\n"
+ "\r\n"); + "\r\n");
assertEquals(new Event(null, null, "YHOO\n+2\n10"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "YHOO\n+2\n10"));
} }
@Test public void eventType() throws IOException { @Test public void eventType() throws IOException {
@ -72,9 +71,9 @@ public final class ServerSentEventIteratorTest {
+ "event: add\n" + "event: add\n"
+ "data: 113411\n" + "data: 113411\n"
+ "\n"); + "\n");
assertEquals(new Event(null, "add", "73857293"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, "add", "73857293"));
assertEquals(new Event(null, "remove", "2153"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, "remove", "2153"));
assertEquals(new Event(null, "add", "113411"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, "add", "113411"));
} }
@Test public void commentsIgnored() throws IOException { @Test public void commentsIgnored() throws IOException {
@ -84,7 +83,7 @@ public final class ServerSentEventIteratorTest {
+ "data: first event\n" + "data: first event\n"
+ "id: 1\n" + "id: 1\n"
+ "\n"); + "\n");
assertEquals(new Event("1", null, "first event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "first event"));
} }
@Test public void idCleared() throws IOException { @Test public void idCleared() throws IOException {
@ -97,9 +96,9 @@ public final class ServerSentEventIteratorTest {
+ "\n" + "\n"
+ "data: third event\n" + "data: third event\n"
+ "\n"); + "\n");
assertEquals(new Event("1", null, "first event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "first event"));
assertEquals(new Event(null, null, "second event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "second event"));
assertEquals(new Event(null, null, "third event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "third event"));
} }
@Test public void nakedFieldNames() throws IOException { @Test public void nakedFieldNames() throws IOException {
@ -110,8 +109,8 @@ public final class ServerSentEventIteratorTest {
+ "data\n" + "data\n"
+ "\n" + "\n"
+ "data:\n"); + "data:\n");
assertEquals(new Event(null, null, ""), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, ""));
assertEquals(new Event(null, null, "\n"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "\n"));
} }
@Test public void colonSpaceOptional() throws IOException { @Test public void colonSpaceOptional() throws IOException {
@ -120,15 +119,15 @@ public final class ServerSentEventIteratorTest {
+ "\n" + "\n"
+ "data: test\n" + "data: test\n"
+ "\n"); + "\n");
assertEquals(new Event(null, null, "test"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "test"));
assertEquals(new Event(null, null, "test"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "test"));
} }
@Test public void leadingWhitespace() throws IOException { @Test public void leadingWhitespace() throws IOException {
consumeEvents("" consumeEvents(""
+ "data: test\n" + "data: test\n"
+ "\n"); + "\n");
assertEquals(new Event(null, null, " test"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event(null, null, " test"));
} }
@Test public void idReusedAcrossEvents() throws IOException { @Test public void idReusedAcrossEvents() throws IOException {
@ -141,9 +140,9 @@ public final class ServerSentEventIteratorTest {
+ "id: 2\n" + "id: 2\n"
+ "data: third event\n" + "data: third event\n"
+ "\n"); + "\n");
assertEquals(new Event("1", null, "first event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "first event"));
assertEquals(new Event("1", null, "second event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "second event"));
assertEquals(new Event("2", null, "third event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event("2", null, "third event"));
} }
@Test public void idIgnoredFromEmptyEvent() throws IOException { @Test public void idIgnoredFromEmptyEvent() throws IOException {
@ -155,8 +154,8 @@ public final class ServerSentEventIteratorTest {
+ "\n" + "\n"
+ "data: second event\n" + "data: second event\n"
+ "\n"); + "\n");
assertEquals(new Event("1", null, "first event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "first event"));
assertEquals(new Event("1", null, "second event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "second event"));
} }
@Test public void retry() throws IOException { @Test public void retry() throws IOException {
@ -166,8 +165,8 @@ public final class ServerSentEventIteratorTest {
+ "data: first event\n" + "data: first event\n"
+ "id: 1\n" + "id: 1\n"
+ "\n"); + "\n");
assertEquals(22L, callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(22L);
assertEquals(new Event("1", null, "first event"), callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "first event"));
} }
@Test public void retryInvalidFormatIgnored() throws IOException { @Test public void retryInvalidFormatIgnored() throws IOException {
@ -176,7 +175,7 @@ public final class ServerSentEventIteratorTest {
+ "\n" + "\n"
+ "retry: hey" + "retry: hey"
+ "\n"); + "\n");
assertEquals(22L, callbacks.remove()); assertThat(callbacks.remove()).isEqualTo(22L);
} }
private void consumeEvents(String source) throws IOException { private void consumeEvents(String source) throws IOException {
@ -191,6 +190,7 @@ public final class ServerSentEventIteratorTest {
Buffer buffer = new Buffer().writeUtf8(source); Buffer buffer = new Buffer().writeUtf8(source);
ServerSentEventReader reader = new ServerSentEventReader(buffer, callback); ServerSentEventReader reader = new ServerSentEventReader(buffer, callback);
while (reader.processNextEvent()); while (reader.processNextEvent());
assertEquals("Unconsumed buffer: " + buffer.readUtf8(), 0, buffer.size()); assertThat(buffer.size()).overridingErrorMessage("Unconsumed buffer: " + buffer.readUtf8())
.isEqualTo(0);
} }
} }

View File

@ -28,6 +28,10 @@
<artifactId>jsr305</artifactId> <artifactId>jsr305</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -18,12 +18,11 @@ package okhttp3;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public final class FakeDns implements Dns { public final class FakeDns implements Dns {
private final Map<String, List<InetAddress>> hostAddresses = new LinkedHashMap<>(); private final Map<String, List<InetAddress>> hostAddresses = new LinkedHashMap<>();
@ -56,7 +55,7 @@ public final class FakeDns implements Dns {
} }
public void assertRequests(String... expectedHosts) { public void assertRequests(String... expectedHosts) {
assertEquals(Arrays.asList(expectedHosts), requestedHosts); assertThat(requestedHosts).containsExactly(expectedHosts);
requestedHosts.clear(); requestedHosts.clear();
} }

View File

@ -22,7 +22,7 @@ import java.util.Collections;
import java.util.Deque; import java.util.Deque;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public final class RecordingCookieJar implements CookieJar { public final class RecordingCookieJar implements CookieJar {
private final Deque<List<Cookie>> requestCookies = new ArrayDeque<>(); private final Deque<List<Cookie>> requestCookies = new ArrayDeque<>();
@ -42,7 +42,7 @@ public final class RecordingCookieJar implements CookieJar {
for (Cookie cookie : actualCookies) { for (Cookie cookie : actualCookies) {
actualCookieStrings.add(cookie.toString()); actualCookieStrings.add(cookie.toString());
} }
assertEquals(Arrays.asList(cookies), actualCookieStrings); assertThat(actualCookieStrings).containsExactly(cookies);
} }
@Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {

View File

@ -23,7 +23,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import okhttp3.internal.http2.Header; import okhttp3.internal.http2.Header;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public final class TestUtil { public final class TestUtil {
public static final InetSocketAddress UNREACHABLE_ADDRESS public static final InetSocketAddress UNREACHABLE_ADDRESS
@ -88,6 +88,6 @@ public final class TestUtil {
public static void ensureAllConnectionsReleased(OkHttpClient client) { public static void ensureAllConnectionsReleased(OkHttpClient client) {
client.connectionPool().evictAll(); client.connectionPool().evictAll();
assertEquals(0, client.connectionPool().idleConnectionCount()); assertThat(client.connectionPool().idleConnectionCount()).isEqualTo(0);
} }
} }

View File

@ -66,6 +66,11 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -22,8 +22,7 @@ import okhttp3.internal.Util;
import okhttp3.internal.http.RecordingProxySelector; import okhttp3.internal.http.RecordingProxySelector;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotEquals;
public final class AddressTest { public final class AddressTest {
private Dns dns = Dns.SYSTEM; private Dns dns = Dns.SYSTEM;
@ -38,8 +37,8 @@ public final class AddressTest {
authenticator, null, protocols, connectionSpecs, proxySelector); authenticator, null, protocols, connectionSpecs, proxySelector);
Address b = new Address("square.com", 80, dns, socketFactory, null, null, null, Address b = new Address("square.com", 80, dns, socketFactory, null, null, null,
authenticator, null, protocols, connectionSpecs, proxySelector); authenticator, null, protocols, connectionSpecs, proxySelector);
assertEquals(a, b); assertThat(b).isEqualTo(a);
assertEquals(a.hashCode(), b.hashCode()); assertThat(b.hashCode()).isEqualTo(a.hashCode());
} }
@Test public void differentProxySelectorsAreDifferent() throws Exception { @Test public void differentProxySelectorsAreDifferent() throws Exception {
@ -47,19 +46,20 @@ public final class AddressTest {
authenticator, null, protocols, connectionSpecs, new RecordingProxySelector()); authenticator, null, protocols, connectionSpecs, new RecordingProxySelector());
Address b = new Address("square.com", 80, dns, socketFactory, null, null, null, Address b = new Address("square.com", 80, dns, socketFactory, null, null, null,
authenticator, null, protocols, connectionSpecs, new RecordingProxySelector()); authenticator, null, protocols, connectionSpecs, new RecordingProxySelector());
assertNotEquals(a, b); assertThat(b).isNotEqualTo(a);
} }
@Test public void addressToString() throws Exception { @Test public void addressToString() throws Exception {
Address address = new Address("square.com", 80, dns, socketFactory, null, null, null, Address address = new Address("square.com", 80, dns, socketFactory, null, null, null,
authenticator, null, protocols, connectionSpecs, proxySelector); authenticator, null, protocols, connectionSpecs, proxySelector);
assertEquals("Address{square.com:80, proxySelector=RecordingProxySelector}", assertThat(address.toString()).isEqualTo(
address.toString()); "Address{square.com:80, proxySelector=RecordingProxySelector}");
} }
@Test public void addressWithProxyToString() throws Exception { @Test public void addressWithProxyToString() throws Exception {
Address address = new Address("square.com", 80, dns, socketFactory, null, null, null, Address address = new Address("square.com", 80, dns, socketFactory, null, null, null,
authenticator, Proxy.NO_PROXY, protocols, connectionSpecs, proxySelector); authenticator, Proxy.NO_PROXY, protocols, connectionSpecs, proxySelector);
assertEquals("Address{square.com:80, proxy=" + Proxy.NO_PROXY + "}", address.toString()); assertThat(address.toString()).isEqualTo(
"Address{square.com:80, proxy=" + Proxy.NO_PROXY + "}");
} }
} }

View File

@ -18,28 +18,24 @@ package okhttp3;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
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 static org.junit.Assert.fail;
public final class CacheControlTest { public final class CacheControlTest {
@Test public void emptyBuilderIsEmpty() throws Exception { @Test public void emptyBuilderIsEmpty() throws Exception {
CacheControl cacheControl = new CacheControl.Builder().build(); CacheControl cacheControl = new CacheControl.Builder().build();
assertEquals("", cacheControl.toString()); assertThat(cacheControl.toString()).isEqualTo("");
assertFalse(cacheControl.noCache()); assertThat(cacheControl.noCache()).isFalse();
assertFalse(cacheControl.noStore()); assertThat(cacheControl.noStore()).isFalse();
assertEquals(-1, cacheControl.maxAgeSeconds()); assertThat(cacheControl.maxAgeSeconds()).isEqualTo(-1);
assertEquals(-1, cacheControl.sMaxAgeSeconds()); assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(-1);
assertFalse(cacheControl.isPrivate()); assertThat(cacheControl.isPrivate()).isFalse();
assertFalse(cacheControl.isPublic()); assertThat(cacheControl.isPublic()).isFalse();
assertFalse(cacheControl.mustRevalidate()); assertThat(cacheControl.mustRevalidate()).isFalse();
assertEquals(-1, cacheControl.maxStaleSeconds()); assertThat(cacheControl.maxStaleSeconds()).isEqualTo(-1);
assertEquals(-1, cacheControl.minFreshSeconds()); assertThat(cacheControl.minFreshSeconds()).isEqualTo(-1);
assertFalse(cacheControl.onlyIfCached()); assertThat(cacheControl.onlyIfCached()).isFalse();
assertFalse(cacheControl.mustRevalidate()); assertThat(cacheControl.mustRevalidate()).isFalse();
} }
@Test public void completeBuilder() throws Exception { @Test public void completeBuilder() throws Exception {
@ -53,38 +49,39 @@ public final class CacheControlTest {
.noTransform() .noTransform()
.immutable() .immutable()
.build(); .build();
assertEquals("no-cache, no-store, max-age=1, max-stale=2, min-fresh=3, only-if-cached, " assertThat(cacheControl.toString()).isEqualTo(
+ "no-transform, immutable", cacheControl.toString()); ("no-cache, no-store, max-age=1, max-stale=2, min-fresh=3, only-if-cached, "
assertTrue(cacheControl.noCache()); + "no-transform, immutable"));
assertTrue(cacheControl.noStore()); assertThat(cacheControl.noCache()).isTrue();
assertEquals(1, cacheControl.maxAgeSeconds()); assertThat(cacheControl.noStore()).isTrue();
assertEquals(2, cacheControl.maxStaleSeconds()); assertThat(cacheControl.maxAgeSeconds()).isEqualTo(1);
assertEquals(3, cacheControl.minFreshSeconds()); assertThat(cacheControl.maxStaleSeconds()).isEqualTo(2);
assertTrue(cacheControl.onlyIfCached()); assertThat(cacheControl.minFreshSeconds()).isEqualTo(3);
assertTrue(cacheControl.noTransform()); assertThat(cacheControl.onlyIfCached()).isTrue();
assertTrue(cacheControl.immutable()); assertThat(cacheControl.noTransform()).isTrue();
assertThat(cacheControl.immutable()).isTrue();
// These members are accessible to response headers only. // These members are accessible to response headers only.
assertEquals(-1, cacheControl.sMaxAgeSeconds()); assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(-1);
assertFalse(cacheControl.isPrivate()); assertThat(cacheControl.isPrivate()).isFalse();
assertFalse(cacheControl.isPublic()); assertThat(cacheControl.isPublic()).isFalse();
assertFalse(cacheControl.mustRevalidate()); assertThat(cacheControl.mustRevalidate()).isFalse();
} }
@Test public void parseEmpty() throws Exception { @Test public void parseEmpty() throws Exception {
CacheControl cacheControl = CacheControl.parse( CacheControl cacheControl = CacheControl.parse(
new Headers.Builder().set("Cache-Control", "").build()); new Headers.Builder().set("Cache-Control", "").build());
assertEquals("", cacheControl.toString()); assertThat(cacheControl.toString()).isEqualTo("");
assertFalse(cacheControl.noCache()); assertThat(cacheControl.noCache()).isFalse();
assertFalse(cacheControl.noStore()); assertThat(cacheControl.noStore()).isFalse();
assertEquals(-1, cacheControl.maxAgeSeconds()); assertThat(cacheControl.maxAgeSeconds()).isEqualTo(-1);
assertEquals(-1, cacheControl.sMaxAgeSeconds()); assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(-1);
assertFalse(cacheControl.isPublic()); assertThat(cacheControl.isPublic()).isFalse();
assertFalse(cacheControl.mustRevalidate()); assertThat(cacheControl.mustRevalidate()).isFalse();
assertEquals(-1, cacheControl.maxStaleSeconds()); assertThat(cacheControl.maxStaleSeconds()).isEqualTo(-1);
assertEquals(-1, cacheControl.minFreshSeconds()); assertThat(cacheControl.minFreshSeconds()).isEqualTo(-1);
assertFalse(cacheControl.onlyIfCached()); assertThat(cacheControl.onlyIfCached()).isFalse();
assertFalse(cacheControl.mustRevalidate()); assertThat(cacheControl.mustRevalidate()).isFalse();
} }
@Test public void parse() throws Exception { @Test public void parse() throws Exception {
@ -93,18 +90,18 @@ public final class CacheControlTest {
CacheControl cacheControl = CacheControl.parse(new Headers.Builder() CacheControl cacheControl = CacheControl.parse(new Headers.Builder()
.set("Cache-Control", header) .set("Cache-Control", header)
.build()); .build());
assertTrue(cacheControl.noCache()); assertThat(cacheControl.noCache()).isTrue();
assertTrue(cacheControl.noStore()); assertThat(cacheControl.noStore()).isTrue();
assertEquals(1, cacheControl.maxAgeSeconds()); assertThat(cacheControl.maxAgeSeconds()).isEqualTo(1);
assertEquals(2, cacheControl.sMaxAgeSeconds()); assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(2);
assertTrue(cacheControl.isPrivate()); assertThat(cacheControl.isPrivate()).isTrue();
assertTrue(cacheControl.isPublic()); assertThat(cacheControl.isPublic()).isTrue();
assertTrue(cacheControl.mustRevalidate()); assertThat(cacheControl.mustRevalidate()).isTrue();
assertEquals(3, cacheControl.maxStaleSeconds()); assertThat(cacheControl.maxStaleSeconds()).isEqualTo(3);
assertEquals(4, cacheControl.minFreshSeconds()); assertThat(cacheControl.minFreshSeconds()).isEqualTo(4);
assertTrue(cacheControl.onlyIfCached()); assertThat(cacheControl.onlyIfCached()).isTrue();
assertTrue(cacheControl.noTransform()); assertThat(cacheControl.noTransform()).isTrue();
assertEquals(header, cacheControl.toString()); assertThat(cacheControl.toString()).isEqualTo(header);
} }
@Test public void parseIgnoreCacheControlExtensions() throws Exception { @Test public void parseIgnoreCacheControlExtensions() throws Exception {
@ -113,26 +110,26 @@ public final class CacheControlTest {
CacheControl cacheControl = CacheControl.parse(new Headers.Builder() CacheControl cacheControl = CacheControl.parse(new Headers.Builder()
.set("Cache-Control", header) .set("Cache-Control", header)
.build()); .build());
assertFalse(cacheControl.noCache()); assertThat(cacheControl.noCache()).isFalse();
assertFalse(cacheControl.noStore()); assertThat(cacheControl.noStore()).isFalse();
assertEquals(-1, cacheControl.maxAgeSeconds()); assertThat(cacheControl.maxAgeSeconds()).isEqualTo(-1);
assertEquals(-1, cacheControl.sMaxAgeSeconds()); assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(-1);
assertTrue(cacheControl.isPrivate()); assertThat(cacheControl.isPrivate()).isTrue();
assertFalse(cacheControl.isPublic()); assertThat(cacheControl.isPublic()).isFalse();
assertFalse(cacheControl.mustRevalidate()); assertThat(cacheControl.mustRevalidate()).isFalse();
assertEquals(-1, cacheControl.maxStaleSeconds()); assertThat(cacheControl.maxStaleSeconds()).isEqualTo(-1);
assertEquals(-1, cacheControl.minFreshSeconds()); assertThat(cacheControl.minFreshSeconds()).isEqualTo(-1);
assertFalse(cacheControl.onlyIfCached()); assertThat(cacheControl.onlyIfCached()).isFalse();
assertFalse(cacheControl.noTransform()); assertThat(cacheControl.noTransform()).isFalse();
assertFalse(cacheControl.immutable()); assertThat(cacheControl.immutable()).isFalse();
assertEquals(header, cacheControl.toString()); assertThat(cacheControl.toString()).isEqualTo(header);
} }
@Test public void parseCacheControlAndPragmaAreCombined() { @Test public void parseCacheControlAndPragmaAreCombined() {
Headers headers = Headers headers =
Headers.of("Cache-Control", "max-age=12", "Pragma", "must-revalidate", "Pragma", "public"); Headers.of("Cache-Control", "max-age=12", "Pragma", "must-revalidate", "Pragma", "public");
CacheControl cacheControl = CacheControl.parse(headers); CacheControl cacheControl = CacheControl.parse(headers);
assertEquals("max-age=12, public, must-revalidate", cacheControl.toString()); assertThat(cacheControl.toString()).isEqualTo("max-age=12, public, must-revalidate");
} }
@SuppressWarnings("RedundantStringConstructorCall") // Testing instance equality. @SuppressWarnings("RedundantStringConstructorCall") // Testing instance equality.
@ -140,43 +137,43 @@ public final class CacheControlTest {
String value = new String("max-age=12"); String value = new String("max-age=12");
Headers headers = Headers.of("Cache-Control", value); Headers headers = Headers.of("Cache-Control", value);
CacheControl cacheControl = CacheControl.parse(headers); CacheControl cacheControl = CacheControl.parse(headers);
assertSame(value, cacheControl.toString()); assertThat(cacheControl.toString()).isSameAs(value);
} }
@Test public void parseCacheControlHeaderValueInvalidatedByPragma() { @Test public void parseCacheControlHeaderValueInvalidatedByPragma() {
Headers headers = Headers.of("Cache-Control", "max-age=12", "Pragma", "must-revalidate"); Headers headers = Headers.of("Cache-Control", "max-age=12", "Pragma", "must-revalidate");
CacheControl cacheControl = CacheControl.parse(headers); CacheControl cacheControl = CacheControl.parse(headers);
assertNull(cacheControl.headerValue); assertThat(cacheControl.headerValue).isNull();
} }
@Test public void parseCacheControlHeaderValueInvalidatedByTwoValues() { @Test public void parseCacheControlHeaderValueInvalidatedByTwoValues() {
Headers headers = Headers.of("Cache-Control", "max-age=12", "Cache-Control", "must-revalidate"); Headers headers = Headers.of("Cache-Control", "max-age=12", "Cache-Control", "must-revalidate");
CacheControl cacheControl = CacheControl.parse(headers); CacheControl cacheControl = CacheControl.parse(headers);
assertNull(cacheControl.headerValue); assertThat(cacheControl.headerValue).isNull();
} }
@Test public void parsePragmaHeaderValueIsNotRetained() { @Test public void parsePragmaHeaderValueIsNotRetained() {
Headers headers = Headers.of("Pragma", "must-revalidate"); Headers headers = Headers.of("Pragma", "must-revalidate");
CacheControl cacheControl = CacheControl.parse(headers); CacheControl cacheControl = CacheControl.parse(headers);
assertNull(cacheControl.headerValue); assertThat(cacheControl.headerValue).isNull();
} }
@Test public void computedHeaderValueIsCached() { @Test public void computedHeaderValueIsCached() {
CacheControl cacheControl = new CacheControl.Builder() CacheControl cacheControl = new CacheControl.Builder()
.maxAge(2, TimeUnit.DAYS) .maxAge(2, TimeUnit.DAYS)
.build(); .build();
assertNull(cacheControl.headerValue); assertThat(cacheControl.headerValue).isNull();
assertEquals("max-age=172800", cacheControl.toString()); assertThat(cacheControl.toString()).isEqualTo("max-age=172800");
assertEquals("max-age=172800", cacheControl.headerValue); assertThat(cacheControl.headerValue).isEqualTo("max-age=172800");
cacheControl.headerValue = "Hi"; cacheControl.headerValue = "Hi";
assertEquals("Hi", cacheControl.toString()); assertThat(cacheControl.toString()).isEqualTo("Hi");
} }
@Test public void timeDurationTruncatedToMaxValue() throws Exception { @Test public void timeDurationTruncatedToMaxValue() throws Exception {
CacheControl cacheControl = new CacheControl.Builder() CacheControl cacheControl = new CacheControl.Builder()
.maxAge(365 * 100, TimeUnit.DAYS) // Longer than Integer.MAX_VALUE seconds. .maxAge(365 * 100, TimeUnit.DAYS) // Longer than Integer.MAX_VALUE seconds.
.build(); .build();
assertEquals(Integer.MAX_VALUE, cacheControl.maxAgeSeconds()); assertThat(cacheControl.maxAgeSeconds()).isEqualTo(Integer.MAX_VALUE);
} }
@Test public void secondsMustBeNonNegative() throws Exception { @Test public void secondsMustBeNonNegative() throws Exception {
@ -192,6 +189,6 @@ public final class CacheControlTest {
CacheControl cacheControl = new CacheControl.Builder() CacheControl cacheControl = new CacheControl.Builder()
.maxAge(4999, TimeUnit.MILLISECONDS) .maxAge(4999, TimeUnit.MILLISECONDS)
.build(); .build();
assertEquals(4, cacheControl.maxAgeSeconds()); assertThat(cacheControl.maxAgeSeconds()).isEqualTo(4);
} }
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -26,7 +26,7 @@ import okhttp3.tls.HandshakeCertificates;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class CertificateChainCleanerTest { public final class CertificateChainCleanerTest {
@ -37,16 +37,14 @@ public final class CertificateChainCleanerTest {
HeldCertificate rootB = new HeldCertificate.Builder() HeldCertificate rootB = new HeldCertificate.Builder()
.serialNumber(2L) .serialNumber(2L)
.build(); .build();
assertEquals( assertThat(CertificateChainCleaner.get(rootB.certificate(), rootA.certificate())).isEqualTo(
CertificateChainCleaner.get(rootA.certificate(), rootB.certificate()), CertificateChainCleaner.get(rootA.certificate(), rootB.certificate()));
CertificateChainCleaner.get(rootB.certificate(), rootA.certificate()));
} }
@Test public void equalsFromTrustManager() { @Test public void equalsFromTrustManager() {
HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder().build(); HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder().build();
X509TrustManager x509TrustManager = handshakeCertificates.trustManager(); X509TrustManager x509TrustManager = handshakeCertificates.trustManager();
assertEquals( assertThat(CertificateChainCleaner.get(x509TrustManager)).isEqualTo(
CertificateChainCleaner.get(x509TrustManager),
CertificateChainCleaner.get(x509TrustManager)); CertificateChainCleaner.get(x509TrustManager));
} }
@ -55,7 +53,7 @@ public final class CertificateChainCleanerTest {
.serialNumber(1L) .serialNumber(1L)
.build(); .build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate()); CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(root), cleaner.clean(list(root), "hostname")); assertThat(cleaner.clean(list(root), "hostname")).isEqualTo(list(root));
} }
@Test public void normalizeUnknownSelfSignedCertificate() { @Test public void normalizeUnknownSelfSignedCertificate() {
@ -85,7 +83,8 @@ public final class CertificateChainCleanerTest {
.build(); .build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate()); CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(certB, certA, root), cleaner.clean(list(certB, certA, root), "hostname")); assertThat(cleaner.clean(list(certB, certA, root), "hostname")).isEqualTo(
list(certB, certA, root));
} }
@Test public void orderedChainOfCertificatesWithoutRoot() throws Exception { @Test public void orderedChainOfCertificatesWithoutRoot() throws Exception {
@ -102,8 +101,9 @@ public final class CertificateChainCleanerTest {
.build(); .build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate()); CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(certB, certA, root), // Root is added!
cleaner.clean(list(certB, certA), "hostname")); // Root is added! assertThat(cleaner.clean(list(certB, certA), "hostname")).isEqualTo(
list(certB, certA, root));
} }
@Test public void unorderedChainOfCertificatesWithRoot() throws Exception { @Test public void unorderedChainOfCertificatesWithRoot() throws Exception {
@ -124,8 +124,8 @@ public final class CertificateChainCleanerTest {
.build(); .build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate()); CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(certC, certB, certA, root), assertThat(cleaner.clean(list(certC, certA, root, certB), "hostname")).isEqualTo(
cleaner.clean(list(certC, certA, root, certB), "hostname")); list(certC, certB, certA, root));
} }
@Test public void unorderedChainOfCertificatesWithoutRoot() throws Exception { @Test public void unorderedChainOfCertificatesWithoutRoot() throws Exception {
@ -146,8 +146,8 @@ public final class CertificateChainCleanerTest {
.build(); .build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate()); CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(certC, certB, certA, root), assertThat(cleaner.clean(list(certC, certA, certB), "hostname")).isEqualTo(
cleaner.clean(list(certC, certA, certB), "hostname")); list(certC, certB, certA, root));
} }
@Test public void unrelatedCertificatesAreOmitted() throws Exception { @Test public void unrelatedCertificatesAreOmitted() throws Exception {
@ -167,8 +167,8 @@ public final class CertificateChainCleanerTest {
.build(); .build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate()); CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(certB, certA, root), assertThat(cleaner.clean(list(certB, certUnnecessary, certA, root), "hostname")).isEqualTo(
cleaner.clean(list(certB, certUnnecessary, certA, root), "hostname")); list(certB, certA, root));
} }
@Test public void chainGoesAllTheWayToSelfSignedRoot() throws Exception { @Test public void chainGoesAllTheWayToSelfSignedRoot() throws Exception {
@ -190,12 +190,12 @@ public final class CertificateChainCleanerTest {
CertificateChainCleaner cleaner = CertificateChainCleaner.get( CertificateChainCleaner cleaner = CertificateChainCleaner.get(
selfSigned.certificate(), trusted.certificate()); selfSigned.certificate(), trusted.certificate());
assertEquals(list(certB, certA, trusted, selfSigned), assertThat(cleaner.clean(list(certB, certA), "hostname")).isEqualTo(
cleaner.clean(list(certB, certA), "hostname")); list(certB, certA, trusted, selfSigned));
assertEquals(list(certB, certA, trusted, selfSigned), assertThat(cleaner.clean(list(certB, certA, trusted), "hostname")).isEqualTo(
cleaner.clean(list(certB, certA, trusted), "hostname")); list(certB, certA, trusted, selfSigned));
assertEquals(list(certB, certA, trusted, selfSigned), assertThat(cleaner.clean(list(certB, certA, trusted, selfSigned), "hostname")).isEqualTo(
cleaner.clean(list(certB, certA, trusted, selfSigned), "hostname")); list(certB, certA, trusted, selfSigned));
} }
@Test public void trustedRootNotSelfSigned() throws Exception { @Test public void trustedRootNotSelfSigned() throws Exception {
@ -216,10 +216,10 @@ public final class CertificateChainCleanerTest {
.build(); .build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(trusted.certificate()); CertificateChainCleaner cleaner = CertificateChainCleaner.get(trusted.certificate());
assertEquals(list(certificate, intermediateCa, trusted), assertThat(cleaner.clean(list(certificate, intermediateCa), "hostname")).isEqualTo(
cleaner.clean(list(certificate, intermediateCa), "hostname")); list(certificate, intermediateCa, trusted));
assertEquals(list(certificate, intermediateCa, trusted), assertThat(cleaner.clean(list(certificate, intermediateCa, trusted), "hostname")).isEqualTo(
cleaner.clean(list(certificate, intermediateCa, trusted), "hostname")); list(certificate, intermediateCa, trusted));
} }
@Test public void chainMaxLength() throws Exception { @Test public void chainMaxLength() throws Exception {
@ -231,8 +231,9 @@ public final class CertificateChainCleanerTest {
X509Certificate root = heldCertificates.get(heldCertificates.size() - 1).certificate(); X509Certificate root = heldCertificates.get(heldCertificates.size() - 1).certificate();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root); CertificateChainCleaner cleaner = CertificateChainCleaner.get(root);
assertEquals(certificates, cleaner.clean(certificates, "hostname")); assertThat(cleaner.clean(certificates, "hostname")).isEqualTo(certificates);
assertEquals(certificates, cleaner.clean(certificates.subList(0, 9), "hostname")); assertThat(cleaner.clean(certificates.subList(0, 9), "hostname")).isEqualTo(
certificates);
} }
@Test public void chainTooLong() { @Test public void chainTooLong() {

View File

@ -23,8 +23,7 @@ import okhttp3.CertificatePinner.Pin;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class CertificatePinnerTest { public final class CertificatePinnerTest {
@ -86,9 +85,9 @@ public final class CertificatePinnerTest {
.build(); .build();
String keypairBCertificate2Pin = CertificatePinner.pin(heldCertificateB2.certificate()); String keypairBCertificate2Pin = CertificatePinner.pin(heldCertificateB2.certificate());
assertEquals(certA1Sha256Pin, keypairACertificate2Pin); assertThat(keypairACertificate2Pin).isEqualTo(certA1Sha256Pin);
assertEquals(certB1Sha256Pin, keypairBCertificate2Pin); assertThat(keypairBCertificate2Pin).isEqualTo(certB1Sha256Pin);
assertNotEquals(certA1Sha256Pin, certB1Sha256Pin); assertThat(certB1Sha256Pin).isNotEqualTo(certA1Sha256Pin);
} }
@Test public void successfulCheck() throws Exception { @Test public void successfulCheck() throws Exception {
@ -223,7 +222,7 @@ public final class CertificatePinnerTest {
List<Pin> expectedPins = Arrays.asList( List<Pin> expectedPins = Arrays.asList(
new Pin("first.com", certA1Sha256Pin), new Pin("first.com", certA1Sha256Pin),
new Pin("first.com", certB1Sha256Pin)); new Pin("first.com", certB1Sha256Pin));
assertEquals(expectedPins, certificatePinner.findMatchingPins("first.com")); assertThat(certificatePinner.findMatchingPins("first.com")).isEqualTo(expectedPins);
} }
@Test public void successfulFindMatchingPinsForWildcardAndDirectCertificates() { @Test public void successfulFindMatchingPinsForWildcardAndDirectCertificates() {
@ -236,7 +235,7 @@ public final class CertificatePinnerTest {
List<Pin> expectedPins = Arrays.asList( List<Pin> expectedPins = Arrays.asList(
new Pin("*.example.com", certA1Sha256Pin), new Pin("*.example.com", certA1Sha256Pin),
new Pin("a.example.com", certB1Sha256Pin)); new Pin("a.example.com", certB1Sha256Pin));
assertEquals(expectedPins, certificatePinner.findMatchingPins("a.example.com")); assertThat(certificatePinner.findMatchingPins("a.example.com")).isEqualTo(expectedPins);
} }
@Test public void wildcardHostnameShouldNotMatchThroughDot() throws Exception { @Test public void wildcardHostnameShouldNotMatchThroughDot() throws Exception {
@ -244,8 +243,8 @@ public final class CertificatePinnerTest {
.add("*.example.com", certA1Sha256Pin) .add("*.example.com", certA1Sha256Pin)
.build(); .build();
assertEquals(Collections.emptyList(), certificatePinner.findMatchingPins("example.com")); assertThat(certificatePinner.findMatchingPins("example.com")).isEmpty();
assertEquals(Collections.emptyList(), certificatePinner.findMatchingPins("a.b.example.com")); assertThat(certificatePinner.findMatchingPins("a.b.example.com")).isEmpty();
} }
@Test public void successfulFindMatchingPinsIgnoresCase() { @Test public void successfulFindMatchingPinsIgnoresCase() {
@ -255,10 +254,10 @@ public final class CertificatePinnerTest {
.build(); .build();
List<Pin> expectedPin1 = Arrays.asList(new Pin("EXAMPLE.com", certA1Sha256Pin)); List<Pin> expectedPin1 = Arrays.asList(new Pin("EXAMPLE.com", certA1Sha256Pin));
assertEquals(expectedPin1, certificatePinner.findMatchingPins("example.com")); assertThat(certificatePinner.findMatchingPins("example.com")).isEqualTo(expectedPin1);
List<Pin> expectedPin2 = Arrays.asList(new Pin("*.MyExample.Com", certB1Sha256Pin)); List<Pin> expectedPin2 = Arrays.asList(new Pin("*.MyExample.Com", certB1Sha256Pin));
assertEquals(expectedPin2, certificatePinner.findMatchingPins("a.myexample.com")); assertThat(certificatePinner.findMatchingPins("a.myexample.com")).isEqualTo(expectedPin2);
} }
@Test public void successfulFindMatchingPinPunycode() { @Test public void successfulFindMatchingPinPunycode() {
@ -267,7 +266,7 @@ public final class CertificatePinnerTest {
.build(); .build();
List<Pin> expectedPin = Arrays.asList(new Pin("σkhttp.com", certA1Sha256Pin)); List<Pin> expectedPin = Arrays.asList(new Pin("σkhttp.com", certA1Sha256Pin));
assertEquals(expectedPin, certificatePinner.findMatchingPins("xn--khttp-fde.com")); assertThat(certificatePinner.findMatchingPins("xn--khttp-fde.com")).isEqualTo(expectedPin);
} }
/** https://github.com/square/okhttp/issues/3324 */ /** https://github.com/square/okhttp/issues/3324 */
@ -276,25 +275,17 @@ public final class CertificatePinnerTest {
.add("*.example.com", certA1Sha256Pin) .add("*.example.com", certA1Sha256Pin)
.build(); .build();
assertEquals(Collections.emptyList(), assertThat(certificatePinner.findMatchingPins("a.example.com.notexample.com")).isEmpty();
certificatePinner.findMatchingPins("a.example.com.notexample.com")); assertThat(certificatePinner.findMatchingPins("example.com.notexample.com")).isEmpty();
assertEquals(Collections.emptyList(), assertThat(certificatePinner.findMatchingPins("notexample.com")).isEmpty();
certificatePinner.findMatchingPins("example.com.notexample.com")); assertThat(certificatePinner.findMatchingPins("example.com")).isEmpty();
assertEquals(Collections.emptyList(), assertThat(certificatePinner.findMatchingPins("a.b.example.com")).isEmpty();
certificatePinner.findMatchingPins("notexample.com")); assertThat(certificatePinner.findMatchingPins("ple.com")).isEmpty();
assertEquals(Collections.emptyList(), assertThat(certificatePinner.findMatchingPins("com")).isEmpty();
certificatePinner.findMatchingPins("example.com"));
assertEquals(Collections.emptyList(),
certificatePinner.findMatchingPins("a.b.example.com"));
assertEquals(Collections.emptyList(),
certificatePinner.findMatchingPins("ple.com"));
assertEquals(Collections.emptyList(),
certificatePinner.findMatchingPins("com"));
Pin expectedPin = new Pin("*.example.com", certA1Sha256Pin); Pin expectedPin = new Pin("*.example.com", certA1Sha256Pin);
assertEquals(Collections.singletonList(expectedPin), assertThat(certificatePinner.findMatchingPins("a.example.com")).containsExactly(expectedPin);
certificatePinner.findMatchingPins("a.example.com")); assertThat(certificatePinner.findMatchingPins("example.example.com"))
assertEquals(Collections.singletonList(expectedPin), .containsExactly(expectedPin);
certificatePinner.findMatchingPins("example.example.com"));
} }
} }

View File

@ -21,10 +21,8 @@ import static okhttp3.CipherSuite.TLS_KRB5_WITH_DES_CBC_MD5;
import static okhttp3.CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5; import static okhttp3.CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5;
import static okhttp3.CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256; import static okhttp3.CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256;
import static okhttp3.CipherSuite.forJavaName; import static okhttp3.CipherSuite.forJavaName;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public class CipherSuiteTest { public class CipherSuiteTest {
@ -38,18 +36,20 @@ public class CipherSuiteTest {
@Test public void hashCode_usesIdentityHashCode_legacyCase() { @Test public void hashCode_usesIdentityHashCode_legacyCase() {
CipherSuite cs = TLS_RSA_EXPORT_WITH_RC4_40_MD5; // This one's javaName starts with "SSL_". CipherSuite cs = TLS_RSA_EXPORT_WITH_RC4_40_MD5; // This one's javaName starts with "SSL_".
assertEquals(cs.toString(), System.identityHashCode(cs), cs.hashCode()); assertThat(cs.hashCode()).overridingErrorMessage(cs.toString()).isEqualTo(
System.identityHashCode(cs));
} }
@Test public void hashCode_usesIdentityHashCode_regularCase() { @Test public void hashCode_usesIdentityHashCode_regularCase() {
CipherSuite cs = TLS_RSA_WITH_AES_128_CBC_SHA256; // This one's javaName matches the identifier. CipherSuite cs = TLS_RSA_WITH_AES_128_CBC_SHA256; // This one's javaName matches the identifier.
assertEquals(cs.toString(), System.identityHashCode(cs), cs.hashCode()); assertThat(cs.hashCode()).overridingErrorMessage(cs.toString()).isEqualTo(
System.identityHashCode(cs));
} }
@Test public void instancesAreInterned() { @Test public void instancesAreInterned() {
assertSame(forJavaName("TestCipherSuite"), forJavaName("TestCipherSuite")); assertThat(forJavaName("TestCipherSuite")).isSameAs(forJavaName("TestCipherSuite"));
assertSame(TLS_KRB5_WITH_DES_CBC_MD5, assertThat(forJavaName(TLS_KRB5_WITH_DES_CBC_MD5.javaName()))
forJavaName(TLS_KRB5_WITH_DES_CBC_MD5.javaName())); .isSameAs(TLS_KRB5_WITH_DES_CBC_MD5);
} }
/** /**
@ -61,14 +61,16 @@ public class CipherSuiteTest {
// We're not holding onto a reference to this String instance outside of the CipherSuite... // We're not holding onto a reference to this String instance outside of the CipherSuite...
CipherSuite cs = forJavaName(new String("FakeCipherSuite_instancesAreInterned")); CipherSuite cs = forJavaName(new String("FakeCipherSuite_instancesAreInterned"));
System.gc(); // Unless cs references the String instance, it may now be garbage collected. System.gc(); // Unless cs references the String instance, it may now be garbage collected.
assertSame(cs, forJavaName(new String(cs.javaName()))); assertThat(forJavaName(new String(cs.javaName()))).isSameAs(cs);
} }
@Test public void equals() { @Test public void equals() {
assertEquals(forJavaName("cipher"), forJavaName("cipher")); assertThat(forJavaName("cipher")).isEqualTo(forJavaName("cipher"));
assertNotEquals(forJavaName("cipherA"), forJavaName("cipherB")); assertThat(forJavaName("cipherB")).isNotEqualTo(forJavaName("cipherA"));
assertEquals(forJavaName("SSL_RSA_EXPORT_WITH_RC4_40_MD5"), TLS_RSA_EXPORT_WITH_RC4_40_MD5); assertThat(TLS_RSA_EXPORT_WITH_RC4_40_MD5).isEqualTo(
assertNotEquals(TLS_RSA_EXPORT_WITH_RC4_40_MD5, TLS_RSA_WITH_AES_128_CBC_SHA256); forJavaName("SSL_RSA_EXPORT_WITH_RC4_40_MD5"));
assertThat(TLS_RSA_WITH_AES_128_CBC_SHA256).isNotEqualTo(
TLS_RSA_EXPORT_WITH_RC4_40_MD5);
} }
@Test public void forJavaName_acceptsArbitraryStrings() { @Test public void forJavaName_acceptsArbitraryStrings() {
@ -77,16 +79,18 @@ public class CipherSuiteTest {
} }
@Test public void javaName_examples() { @Test public void javaName_examples() {
assertEquals("SSL_RSA_EXPORT_WITH_RC4_40_MD5", TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName()); assertThat(TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName()).isEqualTo(
assertEquals("TLS_RSA_WITH_AES_128_CBC_SHA256", TLS_RSA_WITH_AES_128_CBC_SHA256.javaName()); "SSL_RSA_EXPORT_WITH_RC4_40_MD5");
assertEquals("TestCipherSuite", forJavaName("TestCipherSuite").javaName()); assertThat(TLS_RSA_WITH_AES_128_CBC_SHA256.javaName()).isEqualTo(
"TLS_RSA_WITH_AES_128_CBC_SHA256");
assertThat(forJavaName("TestCipherSuite").javaName()).isEqualTo("TestCipherSuite");
} }
@Test public void javaName_equalsToString() { @Test public void javaName_equalsToString() {
assertEquals(TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName, assertThat(TLS_RSA_EXPORT_WITH_RC4_40_MD5.toString()).isEqualTo(
TLS_RSA_EXPORT_WITH_RC4_40_MD5.toString()); TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName);
assertEquals(TLS_RSA_WITH_AES_128_CBC_SHA256.javaName, assertThat(TLS_RSA_WITH_AES_128_CBC_SHA256.toString()).isEqualTo(
TLS_RSA_WITH_AES_128_CBC_SHA256.toString()); TLS_RSA_WITH_AES_128_CBC_SHA256.javaName);
} }
/** /**
@ -98,15 +102,12 @@ public class CipherSuiteTest {
*/ */
@Test public void forJavaName_fromLegacyEnumName() { @Test public void forJavaName_fromLegacyEnumName() {
// These would have been considered equal in OkHttp 3.3.1, but now aren't. // These would have been considered equal in OkHttp 3.3.1, but now aren't.
assertEquals( assertThat(forJavaName("SSL_RSA_EXPORT_WITH_RC4_40_MD5")).isEqualTo(
forJavaName("TLS_RSA_EXPORT_WITH_RC4_40_MD5"), forJavaName("TLS_RSA_EXPORT_WITH_RC4_40_MD5"));
forJavaName("SSL_RSA_EXPORT_WITH_RC4_40_MD5")); assertThat(forJavaName("SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA")).isEqualTo(
assertEquals( forJavaName("TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"));
forJavaName("TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"), assertThat(forJavaName("SSL_FAKE_NEW_CIPHER")).isEqualTo(
forJavaName("SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA")); forJavaName("TLS_FAKE_NEW_CIPHER"));
assertEquals(
forJavaName("TLS_FAKE_NEW_CIPHER"),
forJavaName("SSL_FAKE_NEW_CIPHER"));
} }
@Test public void applyIntersectionRetainsSslPrefixes() throws Exception { @Test public void applyIntersectionRetainsSslPrefixes() throws Exception {

View File

@ -34,7 +34,7 @@ import org.junit.Ignore;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class ConnectionCoalescingTest { public final class ConnectionCoalescingTest {
@ -104,7 +104,7 @@ public final class ConnectionCoalescingTest {
HttpUrl sanUrl = url.newBuilder().host("san.com").build(); HttpUrl sanUrl = url.newBuilder().host("san.com").build();
assert200Http2Response(execute(sanUrl), "san.com"); assert200Http2Response(execute(sanUrl), "san.com");
assertEquals(1, client.connectionPool().connectionCount()); assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
} }
/** /**
@ -120,7 +120,7 @@ public final class ConnectionCoalescingTest {
assert200Http2Response(execute(url), server.getHostName()); assert200Http2Response(execute(url), server.getHostName());
assertEquals(1, client.connectionPool().connectionCount()); assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
} }
/** Test a previously coalesced connection that's no longer healthy. */ /** Test a previously coalesced connection that's no longer healthy. */
@ -145,7 +145,7 @@ public final class ConnectionCoalescingTest {
HttpUrl sanUrl = url.newBuilder().host("san.com").build(); HttpUrl sanUrl = url.newBuilder().host("san.com").build();
assert200Http2Response(execute(sanUrl), "san.com"); assert200Http2Response(execute(sanUrl), "san.com");
assertEquals(1, client.connectionPool().connectionCount()); assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
} }
/** If the existing connection matches a SAN but not a match for DNS then skip. */ /** If the existing connection matches a SAN but not a match for DNS then skip. */
@ -193,7 +193,7 @@ public final class ConnectionCoalescingTest {
assert200Http2Response(execute(sanUrl), "san.com"); assert200Http2Response(execute(sanUrl), "san.com");
assertEquals(1, client.connectionPool().connectionCount()); assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
} }
/** Certificate pinning used and not a match will avoid coalescing and try to connect. */ /** Certificate pinning used and not a match will avoid coalescing and try to connect. */
@ -233,7 +233,7 @@ public final class ConnectionCoalescingTest {
assert200Http2Response(execute(sanUrl), "san.com"); assert200Http2Response(execute(sanUrl), "san.com");
assertEquals(2, client.connectionPool().connectionCount()); assertThat(client.connectionPool().connectionCount()).isEqualTo(2);
} }
/** /**
@ -263,8 +263,8 @@ public final class ConnectionCoalescingTest {
serverIps.get(0))); serverIps.get(0)));
assert200Http2Response(execute(sanUrl), "san.com"); assert200Http2Response(execute(sanUrl), "san.com");
assertEquals(1, client.connectionPool().connectionCount()); assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
assertEquals(1, connectCount.get()); assertThat(connectCount.get()).isEqualTo(1);
} }
/** Check that wildcard SANs are supported. */ /** Check that wildcard SANs are supported. */
@ -278,7 +278,7 @@ public final class ConnectionCoalescingTest {
HttpUrl sanUrl = url.newBuilder().host("www.wildcard.com").build(); HttpUrl sanUrl = url.newBuilder().host("www.wildcard.com").build();
assert200Http2Response(execute(sanUrl), "www.wildcard.com"); assert200Http2Response(execute(sanUrl), "www.wildcard.com");
assertEquals(1, client.connectionPool().connectionCount()); assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
} }
/** Network interceptors check for changes to target. */ /** Network interceptors check for changes to target. */
@ -295,7 +295,7 @@ public final class ConnectionCoalescingTest {
HttpUrl sanUrl = url.newBuilder().host("san.com").build(); HttpUrl sanUrl = url.newBuilder().host("san.com").build();
assert200Http2Response(execute(sanUrl), "san.com"); assert200Http2Response(execute(sanUrl), "san.com");
assertEquals(1, client.connectionPool().connectionCount()); assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
} }
/** Run against public external sites, doesn't run by default. */ /** Run against public external sites, doesn't run by default. */
@ -309,7 +309,7 @@ public final class ConnectionCoalescingTest {
assert200Http2Response(execute("https://messenger.com/robots.txt"), "messenger.com"); assert200Http2Response(execute("https://messenger.com/robots.txt"), "messenger.com");
assert200Http2Response(execute("https://m.facebook.com/robots.txt"), "m.facebook.com"); assert200Http2Response(execute("https://m.facebook.com/robots.txt"), "m.facebook.com");
assertEquals(3, client.connectionPool().connectionCount()); assertThat(client.connectionPool().connectionCount()).isEqualTo(3);
} }
private Response execute(String url) throws IOException { private Response execute(String url) throws IOException {
@ -321,9 +321,9 @@ public final class ConnectionCoalescingTest {
} }
private void assert200Http2Response(Response response, String expectedHost) { private void assert200Http2Response(Response response, String expectedHost) {
assertEquals(200, response.code()); assertThat(response.code()).isEqualTo(200);
assertEquals(expectedHost, response.request().url().host()); assertThat(response.request().url().host()).isEqualTo(expectedHost);
assertEquals(Protocol.HTTP_2, response.protocol()); assertThat(response.protocol()).isEqualTo(Protocol.HTTP_2);
response.body().close(); response.body().close();
} }
} }

View File

@ -31,7 +31,7 @@ import org.junit.rules.TestRule;
import org.junit.rules.Timeout; import org.junit.rules.Timeout;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class ConnectionReuseTest { public final class ConnectionReuseTest {
@ -132,9 +132,9 @@ public final class ConnectionReuseTest {
.url(server.url("/")) .url(server.url("/"))
.build(); .build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertEquals("b", response.body().string()); assertThat(response.body().string()).isEqualTo("b");
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(1, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void connectionsNotReusedWithRedirectIfDiscardingResponseIsSlow() throws Exception { @Test public void connectionsNotReusedWithRedirectIfDiscardingResponseIsSlow() throws Exception {
@ -152,9 +152,9 @@ public final class ConnectionReuseTest {
.url(server.url("/")) .url(server.url("/"))
.build(); .build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertEquals("b", response.body().string()); assertThat(response.body().string()).isEqualTo("b");
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void silentRetryWhenIdempotentRequestFailsOnReusedConnection() throws Exception { @Test public void silentRetryWhenIdempotentRequestFailsOnReusedConnection() throws Exception {
@ -167,13 +167,13 @@ public final class ConnectionReuseTest {
.build(); .build();
Response responseA = client.newCall(request).execute(); Response responseA = client.newCall(request).execute();
assertEquals("a", responseA.body().string()); assertThat(responseA.body().string()).isEqualTo("a");
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Response responseB = client.newCall(request).execute(); Response responseB = client.newCall(request).execute();
assertEquals("b", responseB.body().string()); assertThat(responseB.body().string()).isEqualTo("b");
assertEquals(1, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void staleConnectionNotReusedForNonIdempotentRequest() throws Exception { @Test public void staleConnectionNotReusedForNonIdempotentRequest() throws Exception {
@ -185,8 +185,8 @@ public final class ConnectionReuseTest {
.url(server.url("/")) .url(server.url("/"))
.build(); .build();
Response responseA = client.newCall(requestA).execute(); Response responseA = client.newCall(requestA).execute();
assertEquals("a", responseA.body().string()); assertThat(responseA.body().string()).isEqualTo("a");
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Give the socket a chance to become stale. // Give the socket a chance to become stale.
Thread.sleep(250); Thread.sleep(250);
@ -196,8 +196,8 @@ public final class ConnectionReuseTest {
.post(RequestBody.create(MediaType.get("text/plain"), "b")) .post(RequestBody.create(MediaType.get("text/plain"), "b"))
.build(); .build();
Response responseB = client.newCall(requestB).execute(); Response responseB = client.newCall(requestB).execute();
assertEquals("b", responseB.body().string()); assertThat(responseB.body().string()).isEqualTo("b");
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void http2ConnectionsAreSharedBeforeResponseIsConsumed() throws Exception { @Test public void http2ConnectionsAreSharedBeforeResponseIsConsumed() throws Exception {
@ -212,8 +212,8 @@ public final class ConnectionReuseTest {
Response response2 = client.newCall(request).execute(); Response response2 = client.newCall(request).execute();
response1.body().string(); // Discard the response body. response1.body().string(); // Discard the response body.
response2.body().string(); // Discard the response body. response2.body().string(); // Discard the response body.
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(1, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void connectionsAreEvicted() throws Exception { @Test public void connectionsAreEvicted() throws Exception {
@ -228,16 +228,16 @@ public final class ConnectionReuseTest {
.build(); .build();
Response response1 = client.newCall(request).execute(); Response response1 = client.newCall(request).execute();
assertEquals("a", response1.body().string()); assertThat(response1.body().string()).isEqualTo("a");
// Give the thread pool a chance to evict. // Give the thread pool a chance to evict.
Thread.sleep(500); Thread.sleep(500);
Response response2 = client.newCall(request).execute(); Response response2 = client.newCall(request).execute();
assertEquals("b", response2.body().string()); assertThat(response2.body().string()).isEqualTo("b");
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void connectionsAreNotReusedIfSslSocketFactoryChanges() throws Exception { @Test public void connectionsAreNotReusedIfSslSocketFactoryChanges() throws Exception {
@ -287,8 +287,8 @@ public final class ConnectionReuseTest {
Response response2 = anotherClient.newCall(request).execute(); Response response2 = anotherClient.newCall(request).execute();
response2.body().close(); response2.body().close();
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
/** /**
@ -330,11 +330,12 @@ public final class ConnectionReuseTest {
.build(); .build();
Call call = client.newCall(request); Call call = client.newCall(request);
try (Response response = call.execute()) { try (Response response = call.execute()) {
assertEquals("unrelated response body!", response.body().string()); assertThat(response.body().string()).isEqualTo("unrelated response body!");
} }
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(0, server.takeRequest().getSequenceNumber()); // No connection reuse. // No connection reuse.
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
for (Response response : responsesNotClosed) { for (Response response : responsesNotClosed) {
Util.closeQuietly(response); Util.closeQuietly(response);
@ -364,7 +365,7 @@ public final class ConnectionReuseTest {
for (int i = 0; i < requests.length; i++) { for (int i = 0; i < requests.length; i++) {
Response response = client.newCall(requests[i]).execute(); Response response = client.newCall(requests[i]).execute();
response.body().string(); // Discard the response body. response.body().string(); // Discard the response body.
assertEquals(i, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(i);
} }
} }
@ -372,7 +373,7 @@ public final class ConnectionReuseTest {
for (Request request : requests) { for (Request request : requests) {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
response.body().string(); // Discard the response body. response.body().string(); // Discard the response body.
assertEquals(0, server.takeRequest().getSequenceNumber()); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
} }
} }

View File

@ -23,10 +23,7 @@ import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
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 static org.junit.Assert.fail;
public final class ConnectionSpecTest { public final class ConnectionSpecTest {
@ -37,7 +34,7 @@ public final class ConnectionSpecTest {
.build(); .build();
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("At least one TLS version is required", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("At least one TLS version is required");
} }
} }
@ -48,13 +45,13 @@ public final class ConnectionSpecTest {
.build(); .build();
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("At least one cipher suite is required", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("At least one cipher suite is required");
} }
} }
@Test public void cleartextBuilder() throws Exception { @Test public void cleartextBuilder() throws Exception {
ConnectionSpec cleartextSpec = new ConnectionSpec.Builder(false).build(); ConnectionSpec cleartextSpec = new ConnectionSpec.Builder(false).build();
assertFalse(cleartextSpec.isTls()); assertThat(cleartextSpec.isTls()).isFalse();
} }
@Test public void tlsBuilder_explicitCiphers() throws Exception { @Test public void tlsBuilder_explicitCiphers() throws Exception {
@ -63,9 +60,9 @@ public final class ConnectionSpecTest {
.tlsVersions(TlsVersion.TLS_1_2) .tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(true) .supportsTlsExtensions(true)
.build(); .build();
assertEquals(Arrays.asList(CipherSuite.TLS_RSA_WITH_RC4_128_MD5), tlsSpec.cipherSuites()); assertThat(tlsSpec.cipherSuites()).containsExactly(CipherSuite.TLS_RSA_WITH_RC4_128_MD5);
assertEquals(Arrays.asList(TlsVersion.TLS_1_2), tlsSpec.tlsVersions()); assertThat(tlsSpec.tlsVersions()).containsExactly(TlsVersion.TLS_1_2);
assertTrue(tlsSpec.supportsTlsExtensions()); assertThat(tlsSpec.supportsTlsExtensions()).isTrue();
} }
@Test public void tlsBuilder_defaultCiphers() throws Exception { @Test public void tlsBuilder_defaultCiphers() throws Exception {
@ -73,9 +70,9 @@ public final class ConnectionSpecTest {
.tlsVersions(TlsVersion.TLS_1_2) .tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(true) .supportsTlsExtensions(true)
.build(); .build();
assertNull(tlsSpec.cipherSuites()); assertThat(tlsSpec.cipherSuites()).isNull();
assertEquals(Arrays.asList(TlsVersion.TLS_1_2), tlsSpec.tlsVersions()); assertThat(tlsSpec.tlsVersions()).containsExactly(TlsVersion.TLS_1_2);
assertTrue(tlsSpec.supportsTlsExtensions()); assertThat(tlsSpec.supportsTlsExtensions()).isTrue();
} }
@Test public void tls_defaultCiphers_noFallbackIndicator() throws Exception { @Test public void tls_defaultCiphers_noFallbackIndicator() throws Exception {
@ -94,16 +91,16 @@ public final class ConnectionSpecTest {
TlsVersion.TLS_1_1.javaName, TlsVersion.TLS_1_1.javaName,
}); });
assertTrue(tlsSpec.isCompatible(socket)); assertThat(tlsSpec.isCompatible(socket)).isTrue();
tlsSpec.apply(socket, false /* isFallback */); tlsSpec.apply(socket, false /* isFallback */);
assertEquals(set(TlsVersion.TLS_1_2.javaName), set(socket.getEnabledProtocols())); assertThat(set(socket.getEnabledProtocols())).isEqualTo(set(TlsVersion.TLS_1_2.javaName));
Set<String> expectedCipherSet = Set<String> expectedCipherSet =
set( set(
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName, CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName); CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName);
assertEquals(expectedCipherSet, expectedCipherSet); assertThat(expectedCipherSet).isEqualTo(expectedCipherSet);
} }
@Test public void tls_defaultCiphers_withFallbackIndicator() throws Exception { @Test public void tls_defaultCiphers_withFallbackIndicator() throws Exception {
@ -122,10 +119,10 @@ public final class ConnectionSpecTest {
TlsVersion.TLS_1_1.javaName, TlsVersion.TLS_1_1.javaName,
}); });
assertTrue(tlsSpec.isCompatible(socket)); assertThat(tlsSpec.isCompatible(socket)).isTrue();
tlsSpec.apply(socket, true /* isFallback */); tlsSpec.apply(socket, true /* isFallback */);
assertEquals(set(TlsVersion.TLS_1_2.javaName), set(socket.getEnabledProtocols())); assertThat(set(socket.getEnabledProtocols())).isEqualTo(set(TlsVersion.TLS_1_2.javaName));
Set<String> expectedCipherSet = Set<String> expectedCipherSet =
set( set(
@ -134,7 +131,7 @@ public final class ConnectionSpecTest {
if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) { if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) {
expectedCipherSet.add("TLS_FALLBACK_SCSV"); expectedCipherSet.add("TLS_FALLBACK_SCSV");
} }
assertEquals(expectedCipherSet, expectedCipherSet); assertThat(expectedCipherSet).isEqualTo(expectedCipherSet);
} }
@Test public void tls_explicitCiphers() throws Exception { @Test public void tls_explicitCiphers() throws Exception {
@ -154,16 +151,16 @@ public final class ConnectionSpecTest {
TlsVersion.TLS_1_1.javaName, TlsVersion.TLS_1_1.javaName,
}); });
assertTrue(tlsSpec.isCompatible(socket)); assertThat(tlsSpec.isCompatible(socket)).isTrue();
tlsSpec.apply(socket, true /* isFallback */); tlsSpec.apply(socket, true /* isFallback */);
assertEquals(set(TlsVersion.TLS_1_2.javaName), set(socket.getEnabledProtocols())); assertThat(set(socket.getEnabledProtocols())).isEqualTo(set(TlsVersion.TLS_1_2.javaName));
Set<String> expectedCipherSet = set(CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName); Set<String> expectedCipherSet = set(CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName);
if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) { if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) {
expectedCipherSet.add("TLS_FALLBACK_SCSV"); expectedCipherSet.add("TLS_FALLBACK_SCSV");
} }
assertEquals(expectedCipherSet, expectedCipherSet); assertThat(expectedCipherSet).isEqualTo(expectedCipherSet);
} }
@Test public void tls_stringCiphersAndVersions() throws Exception { @Test public void tls_stringCiphersAndVersions() throws Exception {
@ -192,19 +189,19 @@ public final class ConnectionSpecTest {
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName, CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName,
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName, CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
}); });
assertTrue(tlsSpec.isCompatible(socket)); assertThat(tlsSpec.isCompatible(socket)).isTrue();
socket.setEnabledCipherSuites(new String[] { socket.setEnabledCipherSuites(new String[] {
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName, CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName,
}); });
assertFalse(tlsSpec.isCompatible(socket)); assertThat(tlsSpec.isCompatible(socket)).isFalse();
} }
@Test public void allEnabledCipherSuites() throws Exception { @Test public void allEnabledCipherSuites() throws Exception {
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledCipherSuites() .allEnabledCipherSuites()
.build(); .build();
assertNull(tlsSpec.cipherSuites()); assertThat(tlsSpec.cipherSuites()).isNull();
SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
sslSocket.setEnabledCipherSuites(new String[] { sslSocket.setEnabledCipherSuites(new String[] {
@ -213,17 +210,16 @@ public final class ConnectionSpecTest {
}); });
tlsSpec.apply(sslSocket, false); tlsSpec.apply(sslSocket, false);
assertEquals(Arrays.asList( assertThat(Arrays.asList(sslSocket.getEnabledCipherSuites())).containsExactly(
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName, CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName,
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName), CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName);
Arrays.asList(sslSocket.getEnabledCipherSuites()));
} }
@Test public void allEnabledTlsVersions() throws Exception { @Test public void allEnabledTlsVersions() throws Exception {
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledTlsVersions() .allEnabledTlsVersions()
.build(); .build();
assertNull(tlsSpec.tlsVersions()); assertThat(tlsSpec.tlsVersions()).isNull();
SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
sslSocket.setEnabledProtocols(new String[] { sslSocket.setEnabledProtocols(new String[] {
@ -232,8 +228,8 @@ public final class ConnectionSpecTest {
}); });
tlsSpec.apply(sslSocket, false); tlsSpec.apply(sslSocket, false);
assertEquals(Arrays.asList(TlsVersion.SSL_3_0.javaName(), TlsVersion.TLS_1_1.javaName()), assertThat(Arrays.asList(sslSocket.getEnabledProtocols())).containsExactly(
Arrays.asList(sslSocket.getEnabledProtocols())); TlsVersion.SSL_3_0.javaName(), TlsVersion.TLS_1_1.javaName());
} }
@Test public void tls_missingTlsVersion() throws Exception { @Test public void tls_missingTlsVersion() throws Exception {
@ -250,10 +246,10 @@ public final class ConnectionSpecTest {
socket.setEnabledProtocols( socket.setEnabledProtocols(
new String[] {TlsVersion.TLS_1_2.javaName, TlsVersion.TLS_1_1.javaName}); new String[] {TlsVersion.TLS_1_2.javaName, TlsVersion.TLS_1_1.javaName});
assertTrue(tlsSpec.isCompatible(socket)); assertThat(tlsSpec.isCompatible(socket)).isTrue();
socket.setEnabledProtocols(new String[] {TlsVersion.TLS_1_1.javaName}); socket.setEnabledProtocols(new String[] {TlsVersion.TLS_1_1.javaName});
assertFalse(tlsSpec.isCompatible(socket)); assertThat(tlsSpec.isCompatible(socket)).isFalse();
} }
@Test public void equalsAndHashCode() throws Exception { @Test public void equalsAndHashCode() throws Exception {
@ -265,18 +261,18 @@ public final class ConnectionSpecTest {
.build(); .build();
Set<Object> set = new CopyOnWriteArraySet<>(); Set<Object> set = new CopyOnWriteArraySet<>();
assertTrue(set.add(ConnectionSpec.MODERN_TLS)); assertThat(set.add(ConnectionSpec.MODERN_TLS)).isTrue();
assertTrue(set.add(ConnectionSpec.COMPATIBLE_TLS)); assertThat(set.add(ConnectionSpec.COMPATIBLE_TLS)).isTrue();
assertTrue(set.add(ConnectionSpec.CLEARTEXT)); assertThat(set.add(ConnectionSpec.CLEARTEXT)).isTrue();
assertTrue(set.add(allTlsVersions)); assertThat(set.add(allTlsVersions)).isTrue();
assertTrue(set.add(allCipherSuites)); assertThat(set.add(allCipherSuites)).isTrue();
assertTrue(set.remove(ConnectionSpec.MODERN_TLS)); assertThat(set.remove(ConnectionSpec.MODERN_TLS)).isTrue();
assertTrue(set.remove(ConnectionSpec.COMPATIBLE_TLS)); assertThat(set.remove(ConnectionSpec.COMPATIBLE_TLS)).isTrue();
assertTrue(set.remove(ConnectionSpec.CLEARTEXT)); assertThat(set.remove(ConnectionSpec.CLEARTEXT)).isTrue();
assertTrue(set.remove(allTlsVersions)); assertThat(set.remove(allTlsVersions)).isTrue();
assertTrue(set.remove(allCipherSuites)); assertThat(set.remove(allCipherSuites)).isTrue();
assertTrue(set.isEmpty()); assertThat(set.isEmpty()).isTrue();
} }
@Test public void allEnabledToString() throws Exception { @Test public void allEnabledToString() throws Exception {
@ -284,8 +280,9 @@ public final class ConnectionSpecTest {
.allEnabledTlsVersions() .allEnabledTlsVersions()
.allEnabledCipherSuites() .allEnabledCipherSuites()
.build(); .build();
assertEquals("ConnectionSpec(cipherSuites=[all enabled], tlsVersions=[all enabled], " assertThat(connectionSpec.toString()).isEqualTo(
+ "supportsTlsExtensions=true)", connectionSpec.toString()); ("ConnectionSpec(cipherSuites=[all enabled], tlsVersions=[all enabled], "
+ "supportsTlsExtensions=true)"));
} }
@Test public void simpleToString() throws Exception { @Test public void simpleToString() throws Exception {
@ -293,8 +290,9 @@ public final class ConnectionSpecTest {
.tlsVersions(TlsVersion.TLS_1_2) .tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5) .cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)
.build(); .build();
assertEquals("ConnectionSpec(cipherSuites=[SSL_RSA_WITH_RC4_128_MD5], tlsVersions=[TLS_1_2], " assertThat(connectionSpec.toString()).isEqualTo(
+ "supportsTlsExtensions=true)", connectionSpec.toString()); ("ConnectionSpec(cipherSuites=[SSL_RSA_WITH_RC4_128_MD5], tlsVersions=[TLS_1_2], "
+ "supportsTlsExtensions=true)"));
} }
@SafeVarargs @SafeVarargs

View File

@ -27,9 +27,7 @@ import org.junit.After;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ConscryptTest { public class ConscryptTest {
public static final CipherSuite[] MANDATORY_CIPHER_SUITES = new CipherSuite[] { public static final CipherSuite[] MANDATORY_CIPHER_SUITES = new CipherSuite[] {
@ -79,7 +77,7 @@ public class ConscryptTest {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertEquals(Protocol.HTTP_2, response.protocol()); assertThat(response.protocol()).isEqualTo(Protocol.HTTP_2);
} }
@Test @Test
@ -91,12 +89,12 @@ public class ConscryptTest {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertEquals(Protocol.HTTP_2, response.protocol()); assertThat(response.protocol()).isEqualTo(Protocol.HTTP_2);
} }
@Test @Test
public void testBuild() { public void testBuild() {
assertNotNull(ConscryptPlatform.buildIfSupported()); assertThat(ConscryptPlatform.buildIfSupported()).isNotNull();
} }
@Test @Test
@ -105,7 +103,7 @@ public class ConscryptTest {
try { try {
Security.insertProviderAt(new OpenSSLProvider(), 1); Security.insertProviderAt(new OpenSSLProvider(), 1);
assertTrue(Platform.isConscryptPreferred()); assertThat(Platform.isConscryptPreferred()).isTrue();
} finally { } finally {
Security.removeProvider("Conscrypt"); Security.removeProvider("Conscrypt");
} }

View File

@ -25,12 +25,7 @@ import okhttp3.internal.Util;
import okhttp3.internal.http.HttpDate; import okhttp3.internal.http.HttpDate;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
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 static org.junit.Assert.fail;
public final class CookieTest { public final class CookieTest {
@ -38,263 +33,264 @@ public final class CookieTest {
@Test public void simpleCookie() throws Exception { @Test public void simpleCookie() throws Exception {
Cookie cookie = Cookie.parse(url, "SID=31d4d96e407aad42"); Cookie cookie = Cookie.parse(url, "SID=31d4d96e407aad42");
assertEquals("SID=31d4d96e407aad42; path=/", cookie.toString()); assertThat(cookie.toString()).isEqualTo("SID=31d4d96e407aad42; path=/");
} }
@Test public void noEqualsSign() throws Exception { @Test public void noEqualsSign() throws Exception {
assertNull(Cookie.parse(url, "foo")); assertThat(Cookie.parse(url, "foo")).isNull();
assertNull(Cookie.parse(url, "foo; Path=/")); assertThat(Cookie.parse(url, "foo; Path=/")).isNull();
} }
@Test public void emptyName() throws Exception { @Test public void emptyName() throws Exception {
assertNull(Cookie.parse(url, "=b")); assertThat(Cookie.parse(url, "=b")).isNull();
assertNull(Cookie.parse(url, " =b")); assertThat(Cookie.parse(url, " =b")).isNull();
assertNull(Cookie.parse(url, "\r\t \n=b")); assertThat(Cookie.parse(url, "\r\t \n=b")).isNull();
} }
@Test public void spaceInName() throws Exception { @Test public void spaceInName() throws Exception {
assertEquals("a b", Cookie.parse(url, "a b=cd").name()); assertThat(Cookie.parse(url, "a b=cd").name()).isEqualTo("a b");
} }
@Test public void spaceInValue() throws Exception { @Test public void spaceInValue() throws Exception {
assertEquals("c d", Cookie.parse(url, "ab=c d").value()); assertThat(Cookie.parse(url, "ab=c d").value()).isEqualTo("c d");
} }
@Test public void trimLeadingAndTrailingWhitespaceFromName() throws Exception { @Test public void trimLeadingAndTrailingWhitespaceFromName() throws Exception {
assertEquals("a", Cookie.parse(url, " a=b").name()); assertThat(Cookie.parse(url, " a=b").name()).isEqualTo("a");
assertEquals("a", Cookie.parse(url, "a =b").name()); assertThat(Cookie.parse(url, "a =b").name()).isEqualTo("a");
assertEquals("a", Cookie.parse(url, "\r\t \na\n\t \n=b").name()); assertThat(Cookie.parse(url, "\r\t \na\n\t \n=b").name()).isEqualTo("a");
} }
@Test public void emptyValue() throws Exception { @Test public void emptyValue() throws Exception {
assertEquals("", Cookie.parse(url, "a=").value()); assertThat(Cookie.parse(url, "a=").value()).isEqualTo("");
assertEquals("", Cookie.parse(url, "a= ").value()); assertThat(Cookie.parse(url, "a= ").value()).isEqualTo("");
assertEquals("", Cookie.parse(url, "a=\r\t \n").value()); assertThat(Cookie.parse(url, "a=\r\t \n").value()).isEqualTo("");
} }
@Test public void trimLeadingAndTrailingWhitespaceFromValue() throws Exception { @Test public void trimLeadingAndTrailingWhitespaceFromValue() throws Exception {
assertEquals("", Cookie.parse(url, "a= ").value()); assertThat(Cookie.parse(url, "a= ").value()).isEqualTo("");
assertEquals("b", Cookie.parse(url, "a= b").value()); assertThat(Cookie.parse(url, "a= b").value()).isEqualTo("b");
assertEquals("b", Cookie.parse(url, "a=b ").value()); assertThat(Cookie.parse(url, "a=b ").value()).isEqualTo("b");
assertEquals("b", Cookie.parse(url, "a=\r\t \nb\n\t \n").value()); assertThat(Cookie.parse(url, "a=\r\t \nb\n\t \n").value()).isEqualTo("b");
} }
@Test public void invalidCharacters() throws Exception { @Test public void invalidCharacters() throws Exception {
assertNull(Cookie.parse(url, "a\u0000b=cd")); assertThat(Cookie.parse(url, "a\u0000b=cd")).isNull();
assertNull(Cookie.parse(url, "ab=c\u0000d")); assertThat(Cookie.parse(url, "ab=c\u0000d")).isNull();
assertNull(Cookie.parse(url, "a\u0001b=cd")); assertThat(Cookie.parse(url, "a\u0001b=cd")).isNull();
assertNull(Cookie.parse(url, "ab=c\u0001d")); assertThat(Cookie.parse(url, "ab=c\u0001d")).isNull();
assertNull(Cookie.parse(url, "a\u0009b=cd")); assertThat(Cookie.parse(url, "a\u0009b=cd")).isNull();
assertNull(Cookie.parse(url, "ab=c\u0009d")); assertThat(Cookie.parse(url, "ab=c\u0009d")).isNull();
assertNull(Cookie.parse(url, "a\u001fb=cd")); assertThat(Cookie.parse(url, "a\u001fb=cd")).isNull();
assertNull(Cookie.parse(url, "ab=c\u001fd")); assertThat(Cookie.parse(url, "ab=c\u001fd")).isNull();
assertNull(Cookie.parse(url, "a\u007fb=cd")); assertThat(Cookie.parse(url, "a\u007fb=cd")).isNull();
assertNull(Cookie.parse(url, "ab=c\u007fd")); assertThat(Cookie.parse(url, "ab=c\u007fd")).isNull();
assertNull(Cookie.parse(url, "a\u0080b=cd")); assertThat(Cookie.parse(url, "a\u0080b=cd")).isNull();
assertNull(Cookie.parse(url, "ab=c\u0080d")); assertThat(Cookie.parse(url, "ab=c\u0080d")).isNull();
assertNull(Cookie.parse(url, "a\u00ffb=cd")); assertThat(Cookie.parse(url, "a\u00ffb=cd")).isNull();
assertNull(Cookie.parse(url, "ab=c\u00ffd")); assertThat(Cookie.parse(url, "ab=c\u00ffd")).isNull();
} }
@Test public void maxAge() throws Exception { @Test public void maxAge() throws Exception {
assertEquals(51000L, assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=1").expiresAt()).isEqualTo(51000L);
Cookie.parse(50000L, url, "a=b; Max-Age=1").expiresAt()); assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854724").expiresAt()).isEqualTo(
assertEquals(HttpDate.MAX_DATE, HttpDate.MAX_DATE);
Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854724").expiresAt()); assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854725").expiresAt()).isEqualTo(
assertEquals(HttpDate.MAX_DATE, HttpDate.MAX_DATE);
Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854725").expiresAt()); assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854726").expiresAt()).isEqualTo(
assertEquals(HttpDate.MAX_DATE, HttpDate.MAX_DATE);
Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854726").expiresAt()); assertThat(Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=1").expiresAt()).isEqualTo(
assertEquals(HttpDate.MAX_DATE, HttpDate.MAX_DATE);
Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=1").expiresAt()); assertThat(Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=2").expiresAt()).isEqualTo(
assertEquals(HttpDate.MAX_DATE, HttpDate.MAX_DATE);
Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=2").expiresAt()); assertThat(Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=3").expiresAt()).isEqualTo(
assertEquals(HttpDate.MAX_DATE, HttpDate.MAX_DATE);
Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=3").expiresAt()); assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=10000000000000000000").expiresAt()).isEqualTo(
assertEquals(HttpDate.MAX_DATE, HttpDate.MAX_DATE);
Cookie.parse(50000L, url, "a=b; Max-Age=10000000000000000000").expiresAt());
} }
@Test public void maxAgeNonPositive() throws Exception { @Test public void maxAgeNonPositive() throws Exception {
assertEquals(Long.MIN_VALUE, assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=-1").expiresAt()).isEqualTo(Long.MIN_VALUE);
Cookie.parse(50000L, url, "a=b; Max-Age=-1").expiresAt()); assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=0").expiresAt()).isEqualTo(Long.MIN_VALUE);
assertEquals(Long.MIN_VALUE, assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=-9223372036854775808").expiresAt()).isEqualTo(
Cookie.parse(50000L, url, "a=b; Max-Age=0").expiresAt()); Long.MIN_VALUE);
assertEquals(Long.MIN_VALUE, assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=-9223372036854775809").expiresAt()).isEqualTo(
Cookie.parse(50000L, url, "a=b; Max-Age=-9223372036854775808").expiresAt()); Long.MIN_VALUE);
assertEquals(Long.MIN_VALUE, assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=-10000000000000000000").expiresAt()).isEqualTo(
Cookie.parse(50000L, url, "a=b; Max-Age=-9223372036854775809").expiresAt()); Long.MIN_VALUE);
assertEquals(Long.MIN_VALUE,
Cookie.parse(50000L, url, "a=b; Max-Age=-10000000000000000000").expiresAt());
} }
@Test public void domainAndPath() throws Exception { @Test public void domainAndPath() throws Exception {
Cookie cookie = Cookie.parse(url, "SID=31d4d96e407aad42; Path=/; Domain=example.com"); Cookie cookie = Cookie.parse(url, "SID=31d4d96e407aad42; Path=/; Domain=example.com");
assertEquals("example.com", cookie.domain()); assertThat(cookie.domain()).isEqualTo("example.com");
assertEquals("/", cookie.path()); assertThat(cookie.path()).isEqualTo("/");
assertFalse(cookie.hostOnly()); assertThat(cookie.hostOnly()).isFalse();
assertEquals("SID=31d4d96e407aad42; domain=example.com; path=/", cookie.toString()); assertThat(cookie.toString()).isEqualTo(
"SID=31d4d96e407aad42; domain=example.com; path=/");
} }
@Test public void secureAndHttpOnly() throws Exception { @Test public void secureAndHttpOnly() throws Exception {
Cookie cookie = Cookie.parse(url, "SID=31d4d96e407aad42; Path=/; Secure; HttpOnly"); Cookie cookie = Cookie.parse(url, "SID=31d4d96e407aad42; Path=/; Secure; HttpOnly");
assertTrue(cookie.secure()); assertThat(cookie.secure()).isTrue();
assertTrue(cookie.httpOnly()); assertThat(cookie.httpOnly()).isTrue();
assertEquals("SID=31d4d96e407aad42; path=/; secure; httponly", cookie.toString()); assertThat(cookie.toString()).isEqualTo(
"SID=31d4d96e407aad42; path=/; secure; httponly");
} }
@Test public void expiresDate() throws Exception { @Test public void expiresDate() throws Exception {
assertEquals(date("1970-01-01T00:00:00.000+0000"), new Date( assertThat(new Date(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:00 GMT").expiresAt())); Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:00 GMT").expiresAt())).isEqualTo(
assertEquals(date("2021-06-09T10:18:14.000+0000"), new Date( date("1970-01-01T00:00:00.000+0000"));
Cookie.parse(url, "a=b; Expires=Wed, 09 Jun 2021 10:18:14 GMT").expiresAt())); assertThat(new Date(
assertEquals(date("1994-11-06T08:49:37.000+0000"), new Date( Cookie.parse(url, "a=b; Expires=Wed, 09 Jun 2021 10:18:14 GMT").expiresAt())).isEqualTo(
Cookie.parse(url, "a=b; Expires=Sun, 06 Nov 1994 08:49:37 GMT").expiresAt())); date("2021-06-09T10:18:14.000+0000"));
assertThat(new Date(
Cookie.parse(url, "a=b; Expires=Sun, 06 Nov 1994 08:49:37 GMT").expiresAt())).isEqualTo(
date("1994-11-06T08:49:37.000+0000"));
} }
@Test public void awkwardDates() throws Exception { @Test public void awkwardDates() throws Exception {
assertEquals(0L, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 70 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 70 00:00:00 GMT").expiresAt()); 0L);
assertEquals(0L, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 January 1970 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 January 1970 00:00:00 GMT").expiresAt()); 0L);
assertEquals(0L, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Janucember 1970 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Janucember 1970 00:00:00 GMT").expiresAt()); 0L);
assertEquals(0L, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 1 Jan 1970 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 1 Jan 1970 00:00:00 GMT").expiresAt()); 0L);
assertEquals(0L, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 0:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 0:00:00 GMT").expiresAt()); 0L);
assertEquals(0L, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:0:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:0:00 GMT").expiresAt()); 0L);
assertEquals(0L, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:0 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:0 GMT").expiresAt()); 0L);
assertEquals(0L, assertThat(Cookie.parse(url, "a=b; Expires=00:00:00 Thu, 01 Jan 1970 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=00:00:00 Thu, 01 Jan 1970 GMT").expiresAt()); 0L);
assertEquals(0L, assertThat(Cookie.parse(url, "a=b; Expires=00:00:00 1970 Jan 01").expiresAt()).isEqualTo(0L);
Cookie.parse(url, "a=b; Expires=00:00:00 1970 Jan 01").expiresAt()); assertThat(Cookie.parse(url, "a=b; Expires=00:00:00 1970 Jan 1").expiresAt()).isEqualTo(0L);
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=00:00:00 1970 Jan 1").expiresAt());
} }
@Test public void invalidYear() throws Exception { @Test public void invalidYear() throws Exception {
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1600 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1600 00:00:00 GMT").expiresAt()); HttpDate.MAX_DATE);
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 19999 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 19999 00:00:00 GMT").expiresAt()); HttpDate.MAX_DATE);
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 00:00:00 GMT").expiresAt()); HttpDate.MAX_DATE);
} }
@Test public void invalidMonth() throws Exception { @Test public void invalidMonth() throws Exception {
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Foo 1970 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Foo 1970 00:00:00 GMT").expiresAt()); HttpDate.MAX_DATE);
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Foocember 1970 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Foocember 1970 00:00:00 GMT").expiresAt()); HttpDate.MAX_DATE);
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 1970 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 1970 00:00:00 GMT").expiresAt()); HttpDate.MAX_DATE);
} }
@Test public void invalidDayOfMonth() throws Exception { @Test public void invalidDayOfMonth() throws Exception {
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 32 Jan 1970 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 32 Jan 1970 00:00:00 GMT").expiresAt()); HttpDate.MAX_DATE);
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, Jan 1970 00:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, Jan 1970 00:00:00 GMT").expiresAt()); HttpDate.MAX_DATE);
} }
@Test public void invalidHour() throws Exception { @Test public void invalidHour() throws Exception {
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 24:00:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 24:00:00 GMT").expiresAt()); HttpDate.MAX_DATE);
} }
@Test public void invalidMinute() throws Exception { @Test public void invalidMinute() throws Exception {
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:60:00 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:60:00 GMT").expiresAt()); HttpDate.MAX_DATE);
} }
@Test public void invalidSecond() throws Exception { @Test public void invalidSecond() throws Exception {
assertEquals(HttpDate.MAX_DATE, assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:60 GMT").expiresAt()).isEqualTo(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:60 GMT").expiresAt()); HttpDate.MAX_DATE);
} }
@Test public void domainMatches() throws Exception { @Test public void domainMatches() throws Exception {
Cookie cookie = Cookie.parse(url, "a=b; domain=example.com"); Cookie cookie = Cookie.parse(url, "a=b; domain=example.com");
assertTrue(cookie.matches(HttpUrl.get("http://example.com"))); assertThat(cookie.matches(HttpUrl.get("http://example.com"))).isTrue();
assertTrue(cookie.matches(HttpUrl.get("http://www.example.com"))); assertThat(cookie.matches(HttpUrl.get("http://www.example.com"))).isTrue();
assertFalse(cookie.matches(HttpUrl.get("http://square.com"))); assertThat(cookie.matches(HttpUrl.get("http://square.com"))).isFalse();
} }
/** If no domain is present, match only the origin domain. */ /** If no domain is present, match only the origin domain. */
@Test public void domainMatchesNoDomain() throws Exception { @Test public void domainMatchesNoDomain() throws Exception {
Cookie cookie = Cookie.parse(url, "a=b"); Cookie cookie = Cookie.parse(url, "a=b");
assertTrue(cookie.matches(HttpUrl.get("http://example.com"))); assertThat(cookie.matches(HttpUrl.get("http://example.com"))).isTrue();
assertFalse(cookie.matches(HttpUrl.get("http://www.example.com"))); assertThat(cookie.matches(HttpUrl.get("http://www.example.com"))).isFalse();
assertFalse(cookie.matches(HttpUrl.get("http://square.com"))); assertThat(cookie.matches(HttpUrl.get("http://square.com"))).isFalse();
} }
/** Ignore an optional leading `.` in the domain. */ /** Ignore an optional leading `.` in the domain. */
@Test public void domainMatchesIgnoresLeadingDot() throws Exception { @Test public void domainMatchesIgnoresLeadingDot() throws Exception {
Cookie cookie = Cookie.parse(url, "a=b; domain=.example.com"); Cookie cookie = Cookie.parse(url, "a=b; domain=.example.com");
assertTrue(cookie.matches(HttpUrl.get("http://example.com"))); assertThat(cookie.matches(HttpUrl.get("http://example.com"))).isTrue();
assertTrue(cookie.matches(HttpUrl.get("http://www.example.com"))); assertThat(cookie.matches(HttpUrl.get("http://www.example.com"))).isTrue();
assertFalse(cookie.matches(HttpUrl.get("http://square.com"))); assertThat(cookie.matches(HttpUrl.get("http://square.com"))).isFalse();
} }
/** Ignore the entire attribute if the domain ends with `.`. */ /** Ignore the entire attribute if the domain ends with `.`. */
@Test public void domainIgnoredWithTrailingDot() throws Exception { @Test public void domainIgnoredWithTrailingDot() throws Exception {
Cookie cookie = Cookie.parse(url, "a=b; domain=example.com."); Cookie cookie = Cookie.parse(url, "a=b; domain=example.com.");
assertTrue(cookie.matches(HttpUrl.get("http://example.com"))); assertThat(cookie.matches(HttpUrl.get("http://example.com"))).isTrue();
assertFalse(cookie.matches(HttpUrl.get("http://www.example.com"))); assertThat(cookie.matches(HttpUrl.get("http://www.example.com"))).isFalse();
assertFalse(cookie.matches(HttpUrl.get("http://square.com"))); assertThat(cookie.matches(HttpUrl.get("http://square.com"))).isFalse();
} }
@Test public void idnDomainMatches() throws Exception { @Test public void idnDomainMatches() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://☃.net/"), "a=b; domain=☃.net"); Cookie cookie = Cookie.parse(HttpUrl.get("http://☃.net/"), "a=b; domain=☃.net");
assertTrue(cookie.matches(HttpUrl.get("http://☃.net/"))); assertThat(cookie.matches(HttpUrl.get("http://☃.net/"))).isTrue();
assertTrue(cookie.matches(HttpUrl.get("http://xn--n3h.net/"))); assertThat(cookie.matches(HttpUrl.get("http://xn--n3h.net/"))).isTrue();
assertTrue(cookie.matches(HttpUrl.get("http://www.☃.net/"))); assertThat(cookie.matches(HttpUrl.get("http://www.☃.net/"))).isTrue();
assertTrue(cookie.matches(HttpUrl.get("http://www.xn--n3h.net/"))); assertThat(cookie.matches(HttpUrl.get("http://www.xn--n3h.net/"))).isTrue();
} }
@Test public void punycodeDomainMatches() throws Exception { @Test public void punycodeDomainMatches() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://xn--n3h.net/"), "a=b; domain=xn--n3h.net"); Cookie cookie = Cookie.parse(HttpUrl.get("http://xn--n3h.net/"), "a=b; domain=xn--n3h.net");
assertTrue(cookie.matches(HttpUrl.get("http://☃.net/"))); assertThat(cookie.matches(HttpUrl.get("http://☃.net/"))).isTrue();
assertTrue(cookie.matches(HttpUrl.get("http://xn--n3h.net/"))); assertThat(cookie.matches(HttpUrl.get("http://xn--n3h.net/"))).isTrue();
assertTrue(cookie.matches(HttpUrl.get("http://www.☃.net/"))); assertThat(cookie.matches(HttpUrl.get("http://www.☃.net/"))).isTrue();
assertTrue(cookie.matches(HttpUrl.get("http://www.xn--n3h.net/"))); assertThat(cookie.matches(HttpUrl.get("http://www.xn--n3h.net/"))).isTrue();
} }
@Test public void domainMatchesIpAddress() throws Exception { @Test public void domainMatchesIpAddress() throws Exception {
HttpUrl urlWithIp = HttpUrl.get("http://123.45.234.56/"); HttpUrl urlWithIp = HttpUrl.get("http://123.45.234.56/");
assertNull(Cookie.parse(urlWithIp, "a=b; domain=234.56")); assertThat(Cookie.parse(urlWithIp, "a=b; domain=234.56")).isNull();
assertEquals("123.45.234.56", Cookie.parse(urlWithIp, "a=b; domain=123.45.234.56").domain()); assertThat(Cookie.parse(urlWithIp, "a=b; domain=123.45.234.56").domain()).isEqualTo(
"123.45.234.56");
} }
@Test public void domainMatchesIpv6Address() throws Exception { @Test public void domainMatchesIpv6Address() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://[::1]/"), "a=b; domain=::1"); Cookie cookie = Cookie.parse(HttpUrl.get("http://[::1]/"), "a=b; domain=::1");
assertEquals("::1", cookie.domain()); assertThat(cookie.domain()).isEqualTo("::1");
assertTrue(cookie.matches(HttpUrl.get("http://[::1]/"))); assertThat(cookie.matches(HttpUrl.get("http://[::1]/"))).isTrue();
} }
@Test public void domainMatchesIpv6AddressWithCompression() throws Exception { @Test public void domainMatchesIpv6AddressWithCompression() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://[0001:0000::]/"), "a=b; domain=0001:0000::"); Cookie cookie = Cookie.parse(HttpUrl.get("http://[0001:0000::]/"), "a=b; domain=0001:0000::");
assertEquals("1::", cookie.domain()); assertThat(cookie.domain()).isEqualTo("1::");
assertTrue(cookie.matches(HttpUrl.get("http://[1::]/"))); assertThat(cookie.matches(HttpUrl.get("http://[1::]/"))).isTrue();
} }
@Test public void domainMatchesIpv6AddressWithIpv4Suffix() throws Exception { @Test public void domainMatchesIpv6AddressWithIpv4Suffix() throws Exception {
Cookie cookie = Cookie.parse( Cookie cookie = Cookie.parse(
HttpUrl.get("http://[::1:ffff:ffff]/"), "a=b; domain=::1:255.255.255.255"); HttpUrl.get("http://[::1:ffff:ffff]/"), "a=b; domain=::1:255.255.255.255");
assertEquals("::1:ffff:ffff", cookie.domain()); assertThat(cookie.domain()).isEqualTo("::1:ffff:ffff");
assertTrue(cookie.matches(HttpUrl.get("http://[::1:ffff:ffff]/"))); assertThat(cookie.matches(HttpUrl.get("http://[::1:ffff:ffff]/"))).isTrue();
} }
@Test public void ipv6AddressDoesntMatch() throws Exception { @Test public void ipv6AddressDoesntMatch() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://[::1]/"), "a=b; domain=::2"); Cookie cookie = Cookie.parse(HttpUrl.get("http://[::1]/"), "a=b; domain=::2");
assertNull(cookie); assertThat(cookie).isNull();
} }
@Test public void ipv6AddressMalformed() throws Exception { @Test public void ipv6AddressMalformed() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://[::1]/"), "a=b; domain=::2::2"); Cookie cookie = Cookie.parse(HttpUrl.get("http://[::1]/"), "a=b; domain=::2::2");
assertEquals("::1", cookie.domain()); assertThat(cookie.domain()).isEqualTo("::1");
} }
/** /**
@ -304,87 +300,95 @@ public final class CookieTest {
*/ */
@Test public void domainIsPublicSuffix() { @Test public void domainIsPublicSuffix() {
HttpUrl ascii = HttpUrl.get("https://foo1.foo.bar.elb.amazonaws.com"); HttpUrl ascii = HttpUrl.get("https://foo1.foo.bar.elb.amazonaws.com");
assertNotNull(Cookie.parse(ascii, "a=b; domain=foo.bar.elb.amazonaws.com")); assertThat(Cookie.parse(ascii, "a=b; domain=foo.bar.elb.amazonaws.com")).isNotNull();
assertNull(Cookie.parse(ascii, "a=b; domain=bar.elb.amazonaws.com")); assertThat(Cookie.parse(ascii, "a=b; domain=bar.elb.amazonaws.com")).isNull();
assertNull(Cookie.parse(ascii, "a=b; domain=com")); assertThat(Cookie.parse(ascii, "a=b; domain=com")).isNull();
HttpUrl unicode = HttpUrl.get("https://長.長.長崎.jp"); HttpUrl unicode = HttpUrl.get("https://長.長.長崎.jp");
assertNotNull(Cookie.parse(unicode, "a=b; domain=長.長崎.jp")); assertThat(Cookie.parse(unicode, "a=b; domain=長.長崎.jp")).isNotNull();
assertNull(Cookie.parse(unicode, "a=b; domain=長崎.jp")); assertThat(Cookie.parse(unicode, "a=b; domain=長崎.jp")).isNull();
HttpUrl punycode = HttpUrl.get("https://xn--ue5a.xn--ue5a.xn--8ltr62k.jp"); HttpUrl punycode = HttpUrl.get("https://xn--ue5a.xn--ue5a.xn--8ltr62k.jp");
assertNotNull(Cookie.parse(punycode, "a=b; domain=xn--ue5a.xn--8ltr62k.jp")); assertThat(Cookie.parse(punycode, "a=b; domain=xn--ue5a.xn--8ltr62k.jp")).isNotNull();
assertNull(Cookie.parse(punycode, "a=b; domain=xn--8ltr62k.jp")); assertThat(Cookie.parse(punycode, "a=b; domain=xn--8ltr62k.jp")).isNull();
} }
@Test public void hostOnly() throws Exception { @Test public void hostOnly() throws Exception {
assertTrue(Cookie.parse(url, "a=b").hostOnly()); assertThat(Cookie.parse(url, "a=b").hostOnly()).isTrue();
assertFalse(Cookie.parse(url, "a=b; domain=example.com").hostOnly()); assertThat(Cookie.parse(url, "a=b; domain=example.com").hostOnly()).isFalse();
} }
@Test public void defaultPath() throws Exception { @Test public void defaultPath() throws Exception {
assertEquals("/foo", Cookie.parse(HttpUrl.get("http://example.com/foo/bar"), "a=b").path()); assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/bar"), "a=b").path()).isEqualTo(
assertEquals("/foo", Cookie.parse(HttpUrl.get("http://example.com/foo/"), "a=b").path()); "/foo");
assertEquals("/", Cookie.parse(HttpUrl.get("http://example.com/foo"), "a=b").path()); assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/"), "a=b").path()).isEqualTo(
assertEquals("/", Cookie.parse(HttpUrl.get("http://example.com/"), "a=b").path()); "/foo");
assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo"), "a=b").path()).isEqualTo(
"/");
assertThat(Cookie.parse(HttpUrl.get("http://example.com/"), "a=b").path()).isEqualTo(
"/");
} }
@Test public void defaultPathIsUsedIfPathDoesntHaveLeadingSlash() throws Exception { @Test public void defaultPathIsUsedIfPathDoesntHaveLeadingSlash() throws Exception {
assertEquals("/foo", Cookie.parse(HttpUrl.get("http://example.com/foo/bar"), assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/bar"),
"a=b; path=quux").path()); "a=b; path=quux").path()).isEqualTo("/foo");
assertEquals("/foo", Cookie.parse(HttpUrl.get("http://example.com/foo/bar"), assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/bar"),
"a=b; path=").path()); "a=b; path=").path()).isEqualTo("/foo");
} }
@Test public void pathAttributeDoesntNeedToMatch() throws Exception { @Test public void pathAttributeDoesntNeedToMatch() throws Exception {
assertEquals("/quux", Cookie.parse(HttpUrl.get("http://example.com/"), assertThat(Cookie.parse(HttpUrl.get("http://example.com/"),
"a=b; path=/quux").path()); "a=b; path=/quux").path()).isEqualTo("/quux");
assertEquals("/quux", Cookie.parse(HttpUrl.get("http://example.com/foo/bar"), assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/bar"),
"a=b; path=/quux").path()); "a=b; path=/quux").path()).isEqualTo("/quux");
} }
@Test public void httpOnly() throws Exception { @Test public void httpOnly() throws Exception {
assertFalse(Cookie.parse(url, "a=b").httpOnly()); assertThat(Cookie.parse(url, "a=b").httpOnly()).isFalse();
assertTrue(Cookie.parse(url, "a=b; HttpOnly").httpOnly()); assertThat(Cookie.parse(url, "a=b; HttpOnly").httpOnly()).isTrue();
} }
@Test public void secure() throws Exception { @Test public void secure() throws Exception {
assertFalse(Cookie.parse(url, "a=b").secure()); assertThat(Cookie.parse(url, "a=b").secure()).isFalse();
assertTrue(Cookie.parse(url, "a=b; Secure").secure()); assertThat(Cookie.parse(url, "a=b; Secure").secure()).isTrue();
} }
@Test public void maxAgeTakesPrecedenceOverExpires() throws Exception { @Test public void maxAgeTakesPrecedenceOverExpires() throws Exception {
// Max-Age = 1, Expires = 2. In either order. // Max-Age = 1, Expires = 2. In either order.
assertEquals(1000L, Cookie.parse( assertThat(Cookie.parse(
0L, url, "a=b; Max-Age=1; Expires=Thu, 01 Jan 1970 00:00:02 GMT").expiresAt()); 0L, url, "a=b; Max-Age=1; Expires=Thu, 01 Jan 1970 00:00:02 GMT").expiresAt()).isEqualTo(
assertEquals(1000L, Cookie.parse( 1000L);
0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:02 GMT; Max-Age=1").expiresAt()); assertThat(Cookie.parse(
0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:02 GMT; Max-Age=1").expiresAt()).isEqualTo(
1000L);
// Max-Age = 2, Expires = 1. In either order. // Max-Age = 2, Expires = 1. In either order.
assertEquals(2000L, Cookie.parse( assertThat(Cookie.parse(
0L, url, "a=b; Max-Age=2; Expires=Thu, 01 Jan 1970 00:00:01 GMT").expiresAt()); 0L, url, "a=b; Max-Age=2; Expires=Thu, 01 Jan 1970 00:00:01 GMT").expiresAt()).isEqualTo(
assertEquals(2000L, Cookie.parse( 2000L);
0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=2").expiresAt()); assertThat(Cookie.parse(
0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=2").expiresAt()).isEqualTo(
2000L);
} }
/** If a cookie incorrectly defines multiple 'Max-Age' attributes, the last one defined wins. */ /** If a cookie incorrectly defines multiple 'Max-Age' attributes, the last one defined wins. */
@Test public void lastMaxAgeWins() throws Exception { @Test public void lastMaxAgeWins() throws Exception {
assertEquals(3000L, Cookie.parse( assertThat(Cookie.parse(
0L, url, "a=b; Max-Age=2; Max-Age=4; Max-Age=1; Max-Age=3").expiresAt()); 0L, url, "a=b; Max-Age=2; Max-Age=4; Max-Age=1; Max-Age=3").expiresAt()).isEqualTo(3000L);
} }
/** If a cookie incorrectly defines multiple 'Expires' attributes, the last one defined wins. */ /** If a cookie incorrectly defines multiple 'Expires' attributes, the last one defined wins. */
@Test public void lastExpiresAtWins() throws Exception { @Test public void lastExpiresAtWins() throws Exception {
assertEquals(3000L, Cookie.parse(0L, url, "a=b; " assertThat(Cookie.parse(0L, url, "a=b; "
+ "Expires=Thu, 01 Jan 1970 00:00:02 GMT; " + "Expires=Thu, 01 Jan 1970 00:00:02 GMT; "
+ "Expires=Thu, 01 Jan 1970 00:00:04 GMT; " + "Expires=Thu, 01 Jan 1970 00:00:04 GMT; "
+ "Expires=Thu, 01 Jan 1970 00:00:01 GMT; " + "Expires=Thu, 01 Jan 1970 00:00:01 GMT; "
+ "Expires=Thu, 01 Jan 1970 00:00:03 GMT").expiresAt()); + "Expires=Thu, 01 Jan 1970 00:00:03 GMT").expiresAt()).isEqualTo(3000L);
} }
@Test public void maxAgeOrExpiresMakesCookiePersistent() throws Exception { @Test public void maxAgeOrExpiresMakesCookiePersistent() throws Exception {
assertFalse(Cookie.parse(0L, url, "a=b").persistent()); assertThat(Cookie.parse(0L, url, "a=b").persistent()).isFalse();
assertTrue(Cookie.parse(0L, url, "a=b; Max-Age=1").persistent()); assertThat(Cookie.parse(0L, url, "a=b; Max-Age=1").persistent()).isTrue();
assertTrue(Cookie.parse(0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT").persistent()); assertThat(Cookie.parse(0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT").persistent()).isTrue();
} }
@Test public void parseAll() throws Exception { @Test public void parseAll() throws Exception {
@ -393,9 +397,9 @@ public final class CookieTest {
.add("Set-Cookie: c=d") .add("Set-Cookie: c=d")
.build(); .build();
List<Cookie> cookies = Cookie.parseAll(url, headers); List<Cookie> cookies = Cookie.parseAll(url, headers);
assertEquals(2, cookies.size()); assertThat(cookies.size()).isEqualTo(2);
assertEquals("a=b; path=/", cookies.get(0).toString()); assertThat(cookies.get(0).toString()).isEqualTo("a=b; path=/");
assertEquals("c=d; path=/", cookies.get(1).toString()); assertThat(cookies.get(1).toString()).isEqualTo("c=d; path=/");
} }
@Test public void builder() throws Exception { @Test public void builder() throws Exception {
@ -404,15 +408,15 @@ public final class CookieTest {
.value("b") .value("b")
.domain("example.com") .domain("example.com")
.build(); .build();
assertEquals("a", cookie.name()); assertThat(cookie.name()).isEqualTo("a");
assertEquals("b", cookie.value()); assertThat(cookie.value()).isEqualTo("b");
assertEquals(HttpDate.MAX_DATE, cookie.expiresAt()); assertThat(cookie.expiresAt()).isEqualTo(HttpDate.MAX_DATE);
assertEquals("example.com", cookie.domain()); assertThat(cookie.domain()).isEqualTo("example.com");
assertEquals("/", cookie.path()); assertThat(cookie.path()).isEqualTo("/");
assertFalse(cookie.secure()); assertThat(cookie.secure()).isFalse();
assertFalse(cookie.httpOnly()); assertThat(cookie.httpOnly()).isFalse();
assertFalse(cookie.persistent()); assertThat(cookie.persistent()).isFalse();
assertFalse(cookie.hostOnly()); assertThat(cookie.hostOnly()).isFalse();
} }
@Test public void builderNameValidation() throws Exception { @Test public void builderNameValidation() throws Exception {
@ -448,7 +452,8 @@ public final class CookieTest {
.hostOnlyDomain("example.com") .hostOnlyDomain("example.com")
.expiresAt(Long.MAX_VALUE) .expiresAt(Long.MAX_VALUE)
.build(); .build();
assertEquals("a=b; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/", cookie.toString()); assertThat(cookie.toString()).isEqualTo(
"a=b; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/");
} }
@Test public void builderExpiresAt() throws Exception { @Test public void builderExpiresAt() throws Exception {
@ -458,7 +463,8 @@ public final class CookieTest {
.hostOnlyDomain("example.com") .hostOnlyDomain("example.com")
.expiresAt(date("1970-01-01T00:00:01.000+0000").getTime()) .expiresAt(date("1970-01-01T00:00:01.000+0000").getTime())
.build(); .build();
assertEquals("a=b; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/", cookie.toString()); assertThat(cookie.toString()).isEqualTo(
"a=b; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/");
} }
@Test public void builderClampsMinDate() throws Exception { @Test public void builderClampsMinDate() throws Exception {
@ -468,7 +474,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com") .hostOnlyDomain("example.com")
.expiresAt(date("1970-01-01T00:00:00.000+0000").getTime()) .expiresAt(date("1970-01-01T00:00:00.000+0000").getTime())
.build(); .build();
assertEquals("a=b; max-age=0; path=/", cookie.toString()); assertThat(cookie.toString()).isEqualTo("a=b; max-age=0; path=/");
} }
@Test public void builderDomainValidation() throws Exception { @Test public void builderDomainValidation() throws Exception {
@ -490,8 +496,8 @@ public final class CookieTest {
.value("b") .value("b")
.hostOnlyDomain("squareup.com") .hostOnlyDomain("squareup.com")
.build(); .build();
assertEquals("squareup.com", cookie.domain()); assertThat(cookie.domain()).isEqualTo("squareup.com");
assertTrue(cookie.hostOnly()); assertThat(cookie.hostOnly()).isTrue();
} }
@Test public void builderPath() throws Exception { @Test public void builderPath() throws Exception {
@ -501,7 +507,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com") .hostOnlyDomain("example.com")
.path("/foo") .path("/foo")
.build(); .build();
assertEquals("/foo", cookie.path()); assertThat(cookie.path()).isEqualTo("/foo");
} }
@Test public void builderPathValidation() throws Exception { @Test public void builderPathValidation() throws Exception {
@ -524,7 +530,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com") .hostOnlyDomain("example.com")
.secure() .secure()
.build(); .build();
assertTrue(cookie.secure()); assertThat(cookie.secure()).isTrue();
} }
@Test public void builderHttpOnly() throws Exception { @Test public void builderHttpOnly() throws Exception {
@ -534,7 +540,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com") .hostOnlyDomain("example.com")
.httpOnly() .httpOnly()
.build(); .build();
assertTrue(cookie.httpOnly()); assertThat(cookie.httpOnly()).isTrue();
} }
@Test public void builderIpv6() throws Exception { @Test public void builderIpv6() throws Exception {
@ -543,7 +549,7 @@ public final class CookieTest {
.value("b") .value("b")
.domain("0:0:0:0:0:0:0:1") .domain("0:0:0:0:0:0:0:1")
.build(); .build();
assertEquals("::1", cookie.domain()); assertThat(cookie.domain()).isEqualTo("::1");
} }
@Test public void equalsAndHashCode() throws Exception { @Test public void equalsAndHashCode() throws Exception {
@ -561,14 +567,14 @@ public final class CookieTest {
for (String stringB : cookieStrings) { for (String stringB : cookieStrings) {
Cookie cookieB = Cookie.parse(0, url, stringB); Cookie cookieB = Cookie.parse(0, url, stringB);
if (Objects.equals(stringA, stringB)) { if (Objects.equals(stringA, stringB)) {
assertEquals(cookieA.hashCode(), cookieB.hashCode()); assertThat(cookieB.hashCode()).isEqualTo(cookieA.hashCode());
assertEquals(cookieA, cookieB); assertThat(cookieB).isEqualTo(cookieA);
} else { } else {
assertNotEquals(cookieA.hashCode(), cookieB.hashCode()); assertThat(cookieB.hashCode()).isNotEqualTo((long) cookieA.hashCode());
assertNotEquals(cookieA, cookieB); assertThat(cookieB).isNotEqualTo(cookieA);
} }
} }
assertNotEquals(null, cookieA); assertThat(cookieA).isNotEqualTo(null);
} }
} }

View File

@ -35,10 +35,8 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER; import static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse; import static org.assertj.core.data.Offset.offset;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
/** Derived from Android's CookiesTest. */ /** Derived from Android's CookiesTest. */
@ -65,17 +63,17 @@ public class CookiesTest {
get(urlWithIpAddress); get(urlWithIpAddress);
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
assertEquals(1, cookies.size()); assertThat(cookies.size()).isEqualTo(1);
HttpCookie cookie = cookies.get(0); HttpCookie cookie = cookies.get(0);
assertEquals("a", cookie.getName()); assertThat(cookie.getName()).isEqualTo("a");
assertEquals("android", cookie.getValue()); assertThat(cookie.getValue()).isEqualTo("android");
assertNull(cookie.getComment()); assertThat(cookie.getComment()).isNull();
assertNull(cookie.getCommentURL()); assertThat(cookie.getCommentURL()).isNull();
assertFalse(cookie.getDiscard()); assertThat(cookie.getDiscard()).isFalse();
assertTrue(cookie.getMaxAge() > 100000000000L); assertThat(cookie.getMaxAge() > 100000000000L).isTrue();
assertEquals("/path", cookie.getPath()); assertThat(cookie.getPath()).isEqualTo("/path");
assertTrue(cookie.getSecure()); assertThat(cookie.getSecure()).isTrue();
assertEquals(0, cookie.getVersion()); assertThat(cookie.getVersion()).isEqualTo(0);
} }
@Test public void testRfc2109Response() throws Exception { @Test public void testRfc2109Response() throws Exception {
@ -97,15 +95,16 @@ public class CookiesTest {
get(urlWithIpAddress); get(urlWithIpAddress);
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
assertEquals(1, cookies.size()); assertThat(cookies.size()).isEqualTo(1);
HttpCookie cookie = cookies.get(0); HttpCookie cookie = cookies.get(0);
assertEquals("a", cookie.getName()); assertThat(cookie.getName()).isEqualTo("a");
assertEquals("android", cookie.getValue()); assertThat(cookie.getValue()).isEqualTo("android");
assertNull(cookie.getCommentURL()); assertThat(cookie.getCommentURL()).isNull();
assertFalse(cookie.getDiscard()); assertThat(cookie.getDiscard()).isFalse();
assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding! // Converting to a fixed date can cause rounding!
assertEquals("/path", cookie.getPath()); assertThat((double) cookie.getMaxAge()).isCloseTo(60.0, offset(1.0));
assertTrue(cookie.getSecure()); assertThat(cookie.getPath()).isEqualTo("/path");
assertThat(cookie.getSecure()).isTrue();
} }
@Test public void testQuotedAttributeValues() throws Exception { @Test public void testQuotedAttributeValues() throws Exception {
@ -130,13 +129,14 @@ public class CookiesTest {
get(urlWithIpAddress); get(urlWithIpAddress);
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
assertEquals(1, cookies.size()); assertThat(cookies.size()).isEqualTo(1);
HttpCookie cookie = cookies.get(0); HttpCookie cookie = cookies.get(0);
assertEquals("a", cookie.getName()); assertThat(cookie.getName()).isEqualTo("a");
assertEquals("android", cookie.getValue()); assertThat(cookie.getValue()).isEqualTo("android");
assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding! // Converting to a fixed date can cause rounding!
assertEquals("/path", cookie.getPath()); assertThat((double) cookie.getMaxAge()).isCloseTo(60.0, offset(1.0));
assertTrue(cookie.getSecure()); assertThat(cookie.getPath()).isEqualTo("/path");
assertThat(cookie.getSecure()).isTrue();
} }
@Test public void testSendingCookiesFromStore() throws Exception { @Test public void testSendingCookiesFromStore() throws Exception {
@ -161,7 +161,7 @@ public class CookiesTest {
get(serverUrl); get(serverUrl);
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("a=android; b=banana", request.getHeader("Cookie")); assertThat(request.getHeader("Cookie")).isEqualTo("a=android; b=banana");
} }
@Test public void cookieHandlerLikeAndroid() throws Exception { @Test public void cookieHandlerLikeAndroid() throws Exception {
@ -189,7 +189,7 @@ public class CookiesTest {
get(serverUrl); get(serverUrl);
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("a=android; b=banana", request.getHeader("Cookie")); assertThat(request.getHeader("Cookie")).isEqualTo("a=android; b=banana");
} }
@Test public void receiveAndSendMultipleCookies() throws Exception { @Test public void receiveAndSendMultipleCookies() throws Exception {
@ -207,11 +207,11 @@ public class CookiesTest {
get(urlWithIpAddress(server, "/")); get(urlWithIpAddress(server, "/"));
RecordedRequest request1 = server.takeRequest(); RecordedRequest request1 = server.takeRequest();
assertNull(request1.getHeader("Cookie")); assertThat(request1.getHeader("Cookie")).isNull();
get(urlWithIpAddress(server, "/")); get(urlWithIpAddress(server, "/"));
RecordedRequest request2 = server.takeRequest(); RecordedRequest request2 = server.takeRequest();
assertEquals("a=android; b=banana", request2.getHeader("Cookie")); assertThat(request2.getHeader("Cookie")).isEqualTo("a=android; b=banana");
} }
@Test public void testRedirectsDoNotIncludeTooManyCookies() throws Exception { @Test public void testRedirectsDoNotIncludeTooManyCookies() throws Exception {
@ -241,7 +241,7 @@ public class CookiesTest {
get(redirectSourceUrl); get(redirectSourceUrl);
RecordedRequest request = redirectSource.takeRequest(); RecordedRequest request = redirectSource.takeRequest();
assertEquals("c=cookie", request.getHeader("Cookie")); assertThat(request.getHeader("Cookie")).isEqualTo("c=cookie");
for (String header : redirectTarget.takeRequest().getHeaders().names()) { for (String header : redirectTarget.takeRequest().getHeaders().names()) {
if (header.startsWith("Cookie")) { if (header.startsWith("Cookie")) {
@ -270,9 +270,9 @@ public class CookiesTest {
get(server.url("/")); get(server.url("/"));
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie")); assertThat(request.getHeader("Cookie")).isEqualTo("Bar=bar; Baz=baz");
assertNull(request.getHeader("Cookie2")); assertThat(request.getHeader("Cookie2")).isNull();
assertNull(request.getHeader("Quux")); assertThat(request.getHeader("Quux")).isNull();
} }
@Test public void acceptOriginalServerMatchesSubdomain() throws Exception { @Test public void acceptOriginalServerMatchesSubdomain() throws Exception {
@ -283,9 +283,9 @@ public class CookiesTest {
cookieJar.saveFromResponse(url, Arrays.asList( cookieJar.saveFromResponse(url, Arrays.asList(
Cookie.parse(url, "a=android; Domain=squareup.com"))); Cookie.parse(url, "a=android; Domain=squareup.com")));
List<Cookie> actualCookies = cookieJar.loadForRequest(url); List<Cookie> actualCookies = cookieJar.loadForRequest(url);
assertEquals(1, actualCookies.size()); assertThat(actualCookies.size()).isEqualTo(1);
assertEquals("a", actualCookies.get(0).name()); assertThat(actualCookies.get(0).name()).isEqualTo("a");
assertEquals("android", actualCookies.get(0).value()); assertThat(actualCookies.get(0).value()).isEqualTo("android");
} }
@Test public void acceptOriginalServerMatchesRfc2965Dot() throws Exception { @Test public void acceptOriginalServerMatchesRfc2965Dot() throws Exception {
@ -296,9 +296,9 @@ public class CookiesTest {
cookieJar.saveFromResponse(url, Arrays.asList( cookieJar.saveFromResponse(url, Arrays.asList(
Cookie.parse(url, "a=android; Domain=.squareup.com"))); Cookie.parse(url, "a=android; Domain=.squareup.com")));
List<Cookie> actualCookies = cookieJar.loadForRequest(url); List<Cookie> actualCookies = cookieJar.loadForRequest(url);
assertEquals(1, actualCookies.size()); assertThat(actualCookies.size()).isEqualTo(1);
assertEquals("a", actualCookies.get(0).name()); assertThat(actualCookies.get(0).name()).isEqualTo("a");
assertEquals("android", actualCookies.get(0).value()); assertThat(actualCookies.get(0).value()).isEqualTo("android");
} }
@Test public void acceptOriginalServerMatchesExactly() throws Exception { @Test public void acceptOriginalServerMatchesExactly() throws Exception {
@ -309,9 +309,9 @@ public class CookiesTest {
cookieJar.saveFromResponse(url, Arrays.asList( cookieJar.saveFromResponse(url, Arrays.asList(
Cookie.parse(url, "a=android; Domain=squareup.com"))); Cookie.parse(url, "a=android; Domain=squareup.com")));
List<Cookie> actualCookies = cookieJar.loadForRequest(url); List<Cookie> actualCookies = cookieJar.loadForRequest(url);
assertEquals(1, actualCookies.size()); assertThat(actualCookies.size()).isEqualTo(1);
assertEquals("a", actualCookies.get(0).name()); assertThat(actualCookies.get(0).name()).isEqualTo("a");
assertEquals("android", actualCookies.get(0).value()); assertThat(actualCookies.get(0).value()).isEqualTo("android");
} }
@Test public void acceptOriginalServerDoesNotMatchDifferentServer() throws Exception { @Test public void acceptOriginalServerDoesNotMatchDifferentServer() throws Exception {
@ -324,7 +324,7 @@ public class CookiesTest {
HttpUrl url2 = HttpUrl.get("https://www.squareup.com/"); HttpUrl url2 = HttpUrl.get("https://www.squareup.com/");
List<Cookie> actualCookies = cookieJar.loadForRequest(url2); List<Cookie> actualCookies = cookieJar.loadForRequest(url2);
assertEquals(Collections.<Cookie>emptyList(), actualCookies); assertThat(actualCookies).isEmpty();
} }
private HttpUrl urlWithIpAddress(MockWebServer server, String path) throws Exception { private HttpUrl urlWithIpAddress(MockWebServer server, String path) throws Exception {

View File

@ -4,7 +4,6 @@ import java.io.IOException;
import java.io.InterruptedIOException; import java.io.InterruptedIOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
@ -20,9 +19,7 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class DispatcherTest { public final class DispatcherTest {
@ -176,10 +173,10 @@ public final class DispatcherTest {
a3.enqueue(callback); a3.enqueue(callback);
a4.enqueue(callback); a4.enqueue(callback);
a5.enqueue(callback); a5.enqueue(callback);
assertEquals(3, dispatcher.runningCallsCount()); assertThat(dispatcher.runningCallsCount()).isEqualTo(3);
assertEquals(2, dispatcher.queuedCallsCount()); assertThat(dispatcher.queuedCallsCount()).isEqualTo(2);
assertEquals(set(a1, a2, a3), set(dispatcher.runningCalls())); assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2, a3));
assertEquals(set(a4, a5), set(dispatcher.queuedCalls())); assertThat(set(dispatcher.queuedCalls())).isEqualTo(set(a4, a5));
} }
@Test public void synchronousCallAccessors() throws Exception { @Test public void synchronousCallAccessors() throws Exception {
@ -206,16 +203,16 @@ public final class DispatcherTest {
// We created 4 calls and started 2 of them. That's 2 running calls and 0 queued. // We created 4 calls and started 2 of them. That's 2 running calls and 0 queued.
ready.await(); ready.await();
assertEquals(2, dispatcher.runningCallsCount()); assertThat(dispatcher.runningCallsCount()).isEqualTo(2);
assertEquals(0, dispatcher.queuedCallsCount()); assertThat(dispatcher.queuedCallsCount()).isEqualTo(0);
assertEquals(set(a1, a2), set(dispatcher.runningCalls())); assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2));
assertEquals(Collections.emptyList(), dispatcher.queuedCalls()); assertThat(dispatcher.queuedCalls()).isEmpty();
// Cancel some calls. That doesn't impact running or queued. // Cancel some calls. That doesn't impact running or queued.
a2.cancel(); a2.cancel();
a3.cancel(); a3.cancel();
assertEquals(set(a1, a2), set(dispatcher.runningCalls())); assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2));
assertEquals(Collections.emptyList(), dispatcher.queuedCalls()); assertThat(dispatcher.queuedCalls()).isEmpty();
// Let the calls finish. // Let the calls finish.
waiting.countDown(); waiting.countDown();
@ -223,22 +220,22 @@ public final class DispatcherTest {
t2.join(); t2.join();
// Now we should have 0 running calls and 0 queued calls. // Now we should have 0 running calls and 0 queued calls.
assertEquals(0, dispatcher.runningCallsCount()); assertThat(dispatcher.runningCallsCount()).isEqualTo(0);
assertEquals(0, dispatcher.queuedCallsCount()); assertThat(dispatcher.queuedCallsCount()).isEqualTo(0);
assertEquals(Collections.emptyList(), dispatcher.runningCalls()); assertThat(dispatcher.runningCalls()).isEmpty();
assertEquals(Collections.emptyList(), dispatcher.queuedCalls()); assertThat(dispatcher.queuedCalls()).isEmpty();
assertTrue(a1.isExecuted()); assertThat(a1.isExecuted()).isTrue();
assertFalse(a1.isCanceled()); assertThat(a1.isCanceled()).isFalse();
assertTrue(a2.isExecuted()); assertThat(a2.isExecuted()).isTrue();
assertTrue(a2.isCanceled()); assertThat(a2.isCanceled()).isTrue();
assertFalse(a3.isExecuted()); assertThat(a3.isExecuted()).isFalse();
assertTrue(a3.isCanceled()); assertThat(a3.isCanceled()).isTrue();
assertFalse(a4.isExecuted()); assertThat(a4.isExecuted()).isFalse();
assertFalse(a4.isCanceled()); assertThat(a4.isCanceled()).isFalse();
} }
@Test public void idleCallbackInvokedWhenIdle() throws Exception { @Test public void idleCallbackInvokedWhenIdle() throws Exception {
@ -248,7 +245,7 @@ public final class DispatcherTest {
client.newCall(newRequest("http://a/1")).enqueue(callback); client.newCall(newRequest("http://a/1")).enqueue(callback);
client.newCall(newRequest("http://a/2")).enqueue(callback); client.newCall(newRequest("http://a/2")).enqueue(callback);
executor.finishJob("http://a/1"); executor.finishJob("http://a/1");
assertFalse(idle.get()); assertThat(idle.get()).isFalse();
CountDownLatch ready = new CountDownLatch(1); CountDownLatch ready = new CountDownLatch(1);
CountDownLatch proceed = new CountDownLatch(1); CountDownLatch proceed = new CountDownLatch(1);
@ -267,11 +264,11 @@ public final class DispatcherTest {
Thread t1 = makeSynchronousCall(client.newCall(newRequest("http://a/3"))); Thread t1 = makeSynchronousCall(client.newCall(newRequest("http://a/3")));
ready.await(5, SECONDS); ready.await(5, SECONDS);
executor.finishJob("http://a/2"); executor.finishJob("http://a/2");
assertFalse(idle.get()); assertThat(idle.get()).isFalse();
proceed.countDown(); proceed.countDown();
t1.join(); t1.join();
assertTrue(idle.get()); assertThat(idle.get()).isTrue();
} }
@Test public void executionRejectedImmediately() throws Exception { @Test public void executionRejectedImmediately() throws Exception {
@ -279,7 +276,7 @@ public final class DispatcherTest {
executor.shutdown(); executor.shutdown();
client.newCall(request).enqueue(callback); client.newCall(request).enqueue(callback);
callback.await(request.url()).assertFailure(InterruptedIOException.class); callback.await(request.url()).assertFailure(InterruptedIOException.class);
assertEquals(Arrays.asList("CallStart", "CallFailed"), listener.recordedEventTypes()); assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallFailed");
} }
@Test public void executionRejectedAfterMaxRequestsChange() throws Exception { @Test public void executionRejectedAfterMaxRequestsChange() throws Exception {
@ -292,8 +289,8 @@ public final class DispatcherTest {
dispatcher.setMaxRequests(2); // Trigger promotion. dispatcher.setMaxRequests(2); // Trigger promotion.
callback.await(request2.url()).assertFailure(InterruptedIOException.class); callback.await(request2.url()).assertFailure(InterruptedIOException.class);
assertEquals(Arrays.asList("CallStart", "CallStart", "CallFailed"), assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallStart",
listener.recordedEventTypes()); "CallFailed");
} }
@Test public void executionRejectedAfterMaxRequestsPerHostChange() throws Exception { @Test public void executionRejectedAfterMaxRequestsPerHostChange() throws Exception {
@ -305,8 +302,8 @@ public final class DispatcherTest {
client.newCall(request2).enqueue(callback); client.newCall(request2).enqueue(callback);
dispatcher.setMaxRequestsPerHost(2); // Trigger promotion. dispatcher.setMaxRequestsPerHost(2); // Trigger promotion.
callback.await(request2.url()).assertFailure(InterruptedIOException.class); callback.await(request2.url()).assertFailure(InterruptedIOException.class);
assertEquals(Arrays.asList("CallStart", "CallStart", "CallFailed"), assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallStart",
listener.recordedEventTypes()); "CallFailed");
} }
@Test public void executionRejectedAfterPrecedingCallFinishes() throws Exception { @Test public void executionRejectedAfterPrecedingCallFinishes() throws Exception {
@ -318,8 +315,8 @@ public final class DispatcherTest {
client.newCall(request2).enqueue(callback); client.newCall(request2).enqueue(callback);
executor.finishJob("http://a/1"); // Trigger promotion. executor.finishJob("http://a/1"); // Trigger promotion.
callback.await(request2.url()).assertFailure(InterruptedIOException.class); callback.await(request2.url()).assertFailure(InterruptedIOException.class);
assertEquals(Arrays.asList("CallStart", "CallStart", "CallFailed"), assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallStart",
listener.recordedEventTypes()); "CallFailed");
} }
@SafeVarargs @SafeVarargs
@ -357,7 +354,7 @@ public final class DispatcherTest {
for (AsyncCall call : calls) { for (AsyncCall call : calls) {
actualUrls.add(call.request().url().toString()); actualUrls.add(call.request().url().toString());
} }
assertEquals(Arrays.asList(expectedUrls), actualUrls); assertThat(actualUrls).containsExactly(expectedUrls);
} }
public void finishJob(String url) { public void finishJob(String url) {

View File

@ -38,8 +38,7 @@ import org.junit.rules.Timeout;
import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.assertTrue;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class DuplexTest { public final class DuplexTest {
@ -92,18 +91,18 @@ public final class DuplexTest {
requestBody.flush(); requestBody.flush();
BufferedSource responseBody = response.body().source(); BufferedSource responseBody = response.body().source();
assertEquals("response B", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("response B");
requestBody.writeUtf8("request C\n"); requestBody.writeUtf8("request C\n");
requestBody.flush(); requestBody.flush();
assertEquals("response D", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("response D");
requestBody.writeUtf8("request E\n"); requestBody.writeUtf8("request E\n");
requestBody.flush(); requestBody.flush();
assertEquals("response F", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("response F");
requestBody.close(); requestBody.close();
assertNull(responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isNull();
} }
mockDuplexResponseBody.awaitSuccess(); mockDuplexResponseBody.awaitSuccess();
@ -133,19 +132,19 @@ public final class DuplexTest {
BufferedSink requestBody = ((AsyncRequestBody) call.request().body()).takeSink(); BufferedSink requestBody = ((AsyncRequestBody) call.request().body()).takeSink();
BufferedSource responseBody = response.body().source(); BufferedSource responseBody = response.body().source();
assertEquals("response A", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("response A");
requestBody.writeUtf8("request B\n"); requestBody.writeUtf8("request B\n");
requestBody.flush(); requestBody.flush();
assertEquals("response C", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("response C");
requestBody.writeUtf8("request D\n"); requestBody.writeUtf8("request D\n");
requestBody.flush(); requestBody.flush();
assertEquals("response E", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("response E");
requestBody.writeUtf8("request F\n"); requestBody.writeUtf8("request F\n");
requestBody.flush(); requestBody.flush();
assertNull(responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isNull();
requestBody.close(); requestBody.close();
} }
@ -169,12 +168,12 @@ public final class DuplexTest {
.build()); .build());
try (Response response = call.execute()) { try (Response response = call.execute()) {
assertEquals(Headers.of("h1", "v1", "h2", "v2"), response.headers()); assertThat(response.headers()).isEqualTo(Headers.of("h1", "v1", "h2", "v2"));
BufferedSource responseBody = response.body().source(); BufferedSource responseBody = response.body().source();
assertEquals("ok", responseBody.readUtf8(2)); assertThat(responseBody.readUtf8(2)).isEqualTo("ok");
assertTrue(responseBody.exhausted()); assertTrue(responseBody.exhausted());
assertEquals(Headers.of("trailers", "boom"), response.trailers()); assertThat(response.trailers()).isEqualTo(Headers.of("trailers", "boom"));
} }
mockDuplexResponseBody.awaitSuccess(); mockDuplexResponseBody.awaitSuccess();
@ -240,7 +239,7 @@ public final class DuplexTest {
"RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart", "RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestBodyEnd", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestBodyEnd",
"ConnectionReleased", "CallEnd"); "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void duplexWith100Continue() throws Exception { @Test public void duplexWith100Continue() throws Exception {
@ -267,10 +266,10 @@ public final class DuplexTest {
requestBody.flush(); requestBody.flush();
BufferedSource responseBody = response.body().source(); BufferedSource responseBody = response.body().source();
assertEquals("response body", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("response body");
requestBody.close(); requestBody.close();
assertNull(responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isNull();
} }
mockDuplexResponseBody.awaitSuccess(); mockDuplexResponseBody.awaitSuccess();
@ -303,7 +302,7 @@ public final class DuplexTest {
try (Response response = call.execute()) { try (Response response = call.execute()) {
BufferedSource responseBody = response.body().source(); BufferedSource responseBody = response.body().source();
assertEquals("this is /b", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("this is /b");
} }
BufferedSink requestBody = ((AsyncRequestBody) call.request().body()).takeSink(); BufferedSink requestBody = ((AsyncRequestBody) call.request().body()).takeSink();
@ -312,7 +311,7 @@ public final class DuplexTest {
requestBody.flush(); requestBody.flush();
fail(); fail();
} catch (IOException expected) { } catch (IOException expected) {
assertEquals("stream was reset: CANCEL", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("stream was reset: CANCEL");
} }
mockDuplexResponseBody.awaitSuccess(); mockDuplexResponseBody.awaitSuccess();
@ -323,7 +322,7 @@ public final class DuplexTest {
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd", "RequestFailed"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd", "RequestFailed");
assertEquals(expectedEvents, listener.recordedEventTypes()); assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
/** /**
@ -369,7 +368,7 @@ public final class DuplexTest {
requestBody1.flush(); requestBody1.flush();
fail(); fail();
} catch (IOException expected) { } catch (IOException expected) {
assertEquals("stream was reset: CANCEL", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("stream was reset: CANCEL");
} }
mockResponseBody1.awaitSuccess(); mockResponseBody1.awaitSuccess();
@ -378,7 +377,7 @@ public final class DuplexTest {
requestBody2.writeUtf8("request body\n"); requestBody2.writeUtf8("request body\n");
requestBody2.close(); requestBody2.close();
BufferedSource responseBody2 = response2.body().source(); BufferedSource responseBody2 = response2.body().source();
assertEquals("response body", responseBody2.readUtf8Line()); assertThat(responseBody2.readUtf8Line()).isEqualTo("response body");
assertTrue(responseBody2.exhausted()); assertTrue(responseBody2.exhausted());
mockResponseBody2.awaitSuccess(); mockResponseBody2.awaitSuccess();
@ -403,7 +402,7 @@ public final class DuplexTest {
call.execute(); call.execute();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("timeout", e.getMessage()); assertThat(e.getMessage()).isEqualTo("timeout");
assertTrue(call.isCanceled()); assertTrue(call.isCanceled());
} }
} }
@ -434,12 +433,12 @@ public final class DuplexTest {
BufferedSink requestBody = ((AsyncRequestBody) call.request().body()).takeSink(); BufferedSink requestBody = ((AsyncRequestBody) call.request().body()).takeSink();
BufferedSource responseBody = response.body().source(); BufferedSource responseBody = response.body().source();
assertEquals("response A", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("response A");
assertEquals("response B", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("response B");
requestBody.writeUtf8("request C\n"); requestBody.writeUtf8("request C\n");
requestBody.close(); requestBody.close();
assertNull(responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isNull();
} }
mockDuplexResponseBody.awaitSuccess(); mockDuplexResponseBody.awaitSuccess();
@ -472,10 +471,10 @@ public final class DuplexTest {
requestBody.flush(); requestBody.flush();
BufferedSource responseBody = response.body().source(); BufferedSource responseBody = response.body().source();
assertEquals("RESPONSE B", responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isEqualTo("RESPONSE B");
requestBody.close(); requestBody.close();
assertNull(responseBody.readUtf8Line()); assertThat(responseBody.readUtf8Line()).isNull();
} }
mockDuplexResponseBody.awaitSuccess(); mockDuplexResponseBody.awaitSuccess();

View File

@ -52,6 +52,7 @@ import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.HandshakeCertificates; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import org.assertj.core.api.Assertions;
import org.hamcrest.BaseMatcher; import org.hamcrest.BaseMatcher;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.hamcrest.Description; import org.hamcrest.Description;
@ -66,13 +67,7 @@ import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.any;
import static org.hamcrest.CoreMatchers.either; import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
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.assertSame;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeThat; import static org.junit.Assume.assumeThat;
@ -110,15 +105,15 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
assertEquals("abc", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("abc");
response.body().close(); response.body().close();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void successfulCallEventSequenceForEnqueue() throws Exception { @Test public void successfulCallEventSequenceForEnqueue() throws Exception {
@ -149,7 +144,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void failedCallEventSequence() { @Test public void failedCallEventSequence() {
@ -171,7 +166,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseFailed", "ConnectionReleased", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseFailed", "ConnectionReleased",
"CallFailed"); "CallFailed");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void failedDribbledCallEventSequence() throws IOException { @Test public void failedDribbledCallEventSequence() throws IOException {
@ -200,9 +195,10 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseFailed", "ConnectionReleased", "CallFailed"); "ResponseFailed", "ConnectionReleased", "CallFailed");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
ResponseFailed responseFailed = listener.removeUpToEvent(ResponseFailed.class); ResponseFailed responseFailed = listener.removeUpToEvent(ResponseFailed.class);
assertEquals("unexpected end of stream", responseFailed.ioe.getMessage()); Assertions.assertThat(responseFailed.ioe.getMessage()).isEqualTo(
"unexpected end of stream");
} }
@Test public void canceledCallEventSequence() { @Test public void canceledCallEventSequence() {
@ -214,11 +210,11 @@ public final class EventListenerTest {
call.execute(); call.execute();
fail(); fail();
} catch (IOException expected) { } catch (IOException expected) {
assertEquals("Canceled", expected.getMessage()); Assertions.assertThat(expected.getMessage()).isEqualTo("Canceled");
} }
List<String> expectedEvents = Arrays.asList("CallStart", "CallFailed"); List<String> expectedEvents = Arrays.asList("CallStart", "CallFailed");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
private void assertSuccessfulEventOrder(Matcher<Response> responseMatcher) throws IOException { private void assertSuccessfulEventOrder(Matcher<Response> responseMatcher) throws IOException {
@ -226,7 +222,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().string(); response.body().string();
response.body().close(); response.body().close();
@ -237,7 +233,7 @@ public final class EventListenerTest {
"RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd",
"ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void secondCallEventSequence() throws IOException { @Test public void secondCallEventSequence() throws IOException {
@ -262,7 +258,7 @@ public final class EventListenerTest {
"RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd",
"ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
private void assertBytesReadWritten(RecordingEventListener listener, private void assertBytesReadWritten(RecordingEventListener listener,
@ -273,31 +269,32 @@ public final class EventListenerTest {
RequestHeadersEnd responseHeadersEnd = listener.removeUpToEvent(RequestHeadersEnd.class); RequestHeadersEnd responseHeadersEnd = listener.removeUpToEvent(RequestHeadersEnd.class);
assertThat("request header length", responseHeadersEnd.headerLength, requestHeaderLength); assertThat("request header length", responseHeadersEnd.headerLength, requestHeaderLength);
} else { } else {
assertFalse("Found RequestHeadersEnd", Assertions.assertThat(listener.recordedEventTypes().contains("RequestHeadersEnd")).overridingErrorMessage(
listener.recordedEventTypes().contains("RequestHeadersEnd")); "Found RequestHeadersEnd").isFalse();
} }
if (requestBodyBytes != null) { if (requestBodyBytes != null) {
RequestBodyEnd responseBodyEnd = listener.removeUpToEvent(RequestBodyEnd.class); RequestBodyEnd responseBodyEnd = listener.removeUpToEvent(RequestBodyEnd.class);
assertThat("request body bytes", responseBodyEnd.bytesWritten, requestBodyBytes); assertThat("request body bytes", responseBodyEnd.bytesWritten, requestBodyBytes);
} else { } else {
assertFalse("Found RequestBodyEnd", listener.recordedEventTypes().contains("RequestBodyEnd")); Assertions.assertThat(listener.recordedEventTypes().contains("RequestBodyEnd")).overridingErrorMessage(
"Found RequestBodyEnd").isFalse();
} }
if (responseHeaderLength != null) { if (responseHeaderLength != null) {
ResponseHeadersEnd responseHeadersEnd = listener.removeUpToEvent(ResponseHeadersEnd.class); ResponseHeadersEnd responseHeadersEnd = listener.removeUpToEvent(ResponseHeadersEnd.class);
assertThat("response header length", responseHeadersEnd.headerLength, responseHeaderLength); assertThat("response header length", responseHeadersEnd.headerLength, responseHeaderLength);
} else { } else {
assertFalse("Found ResponseHeadersEnd", Assertions.assertThat(listener.recordedEventTypes().contains("ResponseHeadersEnd")).overridingErrorMessage(
listener.recordedEventTypes().contains("ResponseHeadersEnd")); "Found ResponseHeadersEnd").isFalse();
} }
if (responseBodyBytes != null) { if (responseBodyBytes != null) {
ResponseBodyEnd responseBodyEnd = listener.removeUpToEvent(ResponseBodyEnd.class); ResponseBodyEnd responseBodyEnd = listener.removeUpToEvent(ResponseBodyEnd.class);
assertThat("response body bytes", responseBodyEnd.bytesRead, responseBodyBytes); assertThat("response body bytes", responseBodyEnd.bytesRead, responseBodyBytes);
} else { } else {
assertFalse("Found ResponseBodyEnd", Assertions.assertThat(listener.recordedEventTypes().contains("ResponseBodyEnd")).overridingErrorMessage(
listener.recordedEventTypes().contains("ResponseBodyEnd")); "Found ResponseBodyEnd").isFalse();
} }
} }
@ -391,17 +388,17 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
DnsStart dnsStart = listener.removeUpToEvent(DnsStart.class); DnsStart dnsStart = listener.removeUpToEvent(DnsStart.class);
assertSame(call, dnsStart.call); Assertions.assertThat(dnsStart.call).isSameAs(call);
assertEquals(server.getHostName(), dnsStart.domainName); Assertions.assertThat(dnsStart.domainName).isEqualTo(server.getHostName());
DnsEnd dnsEnd = listener.removeUpToEvent(DnsEnd.class); DnsEnd dnsEnd = listener.removeUpToEvent(DnsEnd.class);
assertSame(call, dnsEnd.call); Assertions.assertThat(dnsEnd.call).isSameAs(call);
assertEquals(server.getHostName(), dnsEnd.domainName); Assertions.assertThat(dnsEnd.domainName).isEqualTo(server.getHostName());
assertEquals(1, dnsEnd.inetAddressList.size()); Assertions.assertThat(dnsEnd.inetAddressList.size()).isEqualTo(1);
} }
@Test public void noDnsLookupOnPooledConnection() throws IOException { @Test public void noDnsLookupOnPooledConnection() throws IOException {
@ -413,7 +410,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals(200, response1.code()); Assertions.assertThat(response1.code()).isEqualTo(200);
response1.body().close(); response1.body().close();
listener.clearAllEvents(); listener.clearAllEvents();
@ -422,12 +419,12 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals(200, response2.code()); Assertions.assertThat(response2.code()).isEqualTo(200);
response2.body().close(); response2.body().close();
List<String> recordedEvents = listener.recordedEventTypes(); List<String> recordedEvents = listener.recordedEventTypes();
assertFalse(recordedEvents.contains("DnsStart")); Assertions.assertThat(recordedEvents.contains("DnsStart")).isFalse();
assertFalse(recordedEvents.contains("DnsEnd")); Assertions.assertThat(recordedEvents.contains("DnsEnd")).isFalse();
} }
@Test public void multipleDnsLookupsForSingleCall() throws IOException { @Test public void multipleDnsLookupsForSingleCall() throws IOException {
@ -448,7 +445,7 @@ public final class EventListenerTest {
.url("http://fakeurl:" + server.getPort()) .url("http://fakeurl:" + server.getPort())
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
listener.removeUpToEvent(DnsStart.class); listener.removeUpToEvent(DnsStart.class);
@ -473,8 +470,9 @@ public final class EventListenerTest {
listener.removeUpToEvent(DnsStart.class); listener.removeUpToEvent(DnsStart.class);
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertSame(call, callFailed.call); Assertions.assertThat(callFailed.call).isSameAs(call);
assertTrue(callFailed.ioe instanceof UnknownHostException); boolean condition = callFailed.ioe instanceof UnknownHostException;
Assertions.assertThat(condition).isTrue();
} }
@Test public void emptyDnsLookup() { @Test public void emptyDnsLookup() {
@ -495,8 +493,9 @@ public final class EventListenerTest {
listener.removeUpToEvent(DnsStart.class); listener.removeUpToEvent(DnsStart.class);
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertSame(call, callFailed.call); Assertions.assertThat(callFailed.call).isSameAs(call);
assertTrue(callFailed.ioe instanceof UnknownHostException); boolean condition = callFailed.ioe instanceof UnknownHostException;
Assertions.assertThat(condition).isTrue();
} }
@Test public void successfulConnect() throws IOException { @Test public void successfulConnect() throws IOException {
@ -506,21 +505,21 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
InetAddress address = client.dns().lookup(server.getHostName()).get(0); InetAddress address = client.dns().lookup(server.getHostName()).get(0);
InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort()); InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class); ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
assertSame(call, connectStart.call); Assertions.assertThat(connectStart.call).isSameAs(call);
assertEquals(expectedAddress, connectStart.inetSocketAddress); Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
assertEquals(Proxy.NO_PROXY, connectStart.proxy); Assertions.assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY);
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
assertSame(call, connectEnd.call); Assertions.assertThat(connectEnd.call).isSameAs(call);
assertEquals(expectedAddress, connectEnd.inetSocketAddress); Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress);
assertEquals(Protocol.HTTP_1_1, connectEnd.protocol); Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1);
} }
@Test public void failedConnect() throws UnknownHostException { @Test public void failedConnect() throws UnknownHostException {
@ -541,15 +540,15 @@ public final class EventListenerTest {
InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort()); InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class); ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
assertSame(call, connectStart.call); Assertions.assertThat(connectStart.call).isSameAs(call);
assertEquals(expectedAddress, connectStart.inetSocketAddress); Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
assertEquals(Proxy.NO_PROXY, connectStart.proxy); Assertions.assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY);
ConnectFailed connectFailed = listener.removeUpToEvent(ConnectFailed.class); ConnectFailed connectFailed = listener.removeUpToEvent(ConnectFailed.class);
assertSame(call, connectFailed.call); Assertions.assertThat(connectFailed.call).isSameAs(call);
assertEquals(expectedAddress, connectFailed.inetSocketAddress); Assertions.assertThat(connectFailed.inetSocketAddress).isEqualTo(expectedAddress);
assertNull(connectFailed.protocol); Assertions.assertThat(connectFailed.protocol).isNull();
assertNotNull(connectFailed.ioe); Assertions.assertThat(connectFailed.ioe).isNotNull();
} }
@Test public void multipleConnectsForSingleCall() throws IOException { @Test public void multipleConnectsForSingleCall() throws IOException {
@ -566,7 +565,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
listener.removeUpToEvent(ConnectStart.class); listener.removeUpToEvent(ConnectStart.class);
@ -586,21 +585,21 @@ public final class EventListenerTest {
.url("http://www.fakeurl") .url("http://www.fakeurl")
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
InetAddress address = client.dns().lookup(server.getHostName()).get(0); InetAddress address = client.dns().lookup(server.getHostName()).get(0);
InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort()); InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class); ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
assertSame(call, connectStart.call); Assertions.assertThat(connectStart.call).isSameAs(call);
assertEquals(expectedAddress, connectStart.inetSocketAddress); Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
assertEquals(server.toProxyAddress(), connectStart.proxy); Assertions.assertThat(connectStart.proxy).isEqualTo(server.toProxyAddress());
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
assertSame(call, connectEnd.call); Assertions.assertThat(connectEnd.call).isSameAs(call);
assertEquals(expectedAddress, connectEnd.inetSocketAddress); Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress);
assertEquals(Protocol.HTTP_1_1, connectEnd.protocol); Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1);
} }
@Test public void successfulSocksProxyConnect() throws Exception { @Test public void successfulSocksProxyConnect() throws Exception {
@ -618,21 +617,21 @@ public final class EventListenerTest {
.url("http://" + SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS + ":" + server.getPort()) .url("http://" + SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS + ":" + server.getPort())
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
InetSocketAddress expectedAddress = InetSocketAddress.createUnresolved( InetSocketAddress expectedAddress = InetSocketAddress.createUnresolved(
SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS, server.getPort()); SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class); ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
assertSame(call, connectStart.call); Assertions.assertThat(connectStart.call).isSameAs(call);
assertEquals(expectedAddress, connectStart.inetSocketAddress); Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
assertEquals(proxy, connectStart.proxy); Assertions.assertThat(connectStart.proxy).isEqualTo(proxy);
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
assertSame(call, connectEnd.call); Assertions.assertThat(connectEnd.call).isSameAs(call);
assertEquals(expectedAddress, connectEnd.inetSocketAddress); Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress);
assertEquals(Protocol.HTTP_1_1, connectEnd.protocol); Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1);
} }
@Test public void authenticatingTunnelProxyConnect() throws IOException { @Test public void authenticatingTunnelProxyConnect() throws IOException {
@ -654,13 +653,13 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
listener.removeUpToEvent(ConnectStart.class); listener.removeUpToEvent(ConnectStart.class);
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
assertNull(connectEnd.protocol); Assertions.assertThat(connectEnd.protocol).isNull();
listener.removeUpToEvent(ConnectStart.class); listener.removeUpToEvent(ConnectStart.class);
listener.removeUpToEvent(ConnectEnd.class); listener.removeUpToEvent(ConnectEnd.class);
@ -674,15 +673,15 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class); SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class);
assertSame(call, secureStart.call); Assertions.assertThat(secureStart.call).isSameAs(call);
SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class); SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class);
assertSame(call, secureEnd.call); Assertions.assertThat(secureEnd.call).isSameAs(call);
assertNotNull(secureEnd.handshake); Assertions.assertThat(secureEnd.handshake).isNotNull();
} }
@Test public void failedSecureConnect() { @Test public void failedSecureConnect() {
@ -700,11 +699,11 @@ public final class EventListenerTest {
} }
SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class); SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class);
assertSame(call, secureStart.call); Assertions.assertThat(secureStart.call).isSameAs(call);
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertSame(call, callFailed.call); Assertions.assertThat(callFailed.call).isSameAs(call);
assertNotNull(callFailed.ioe); Assertions.assertThat(callFailed.ioe).isNotNull();
} }
@Test public void secureConnectWithTunnel() throws IOException { @Test public void secureConnectWithTunnel() throws IOException {
@ -721,15 +720,15 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class); SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class);
assertSame(call, secureStart.call); Assertions.assertThat(secureStart.call).isSameAs(call);
SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class); SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class);
assertSame(call, secureEnd.call); Assertions.assertThat(secureEnd.call).isSameAs(call);
assertNotNull(secureEnd.handshake); Assertions.assertThat(secureEnd.handshake).isNotNull();
} }
@Test public void multipleSecureConnectsForSingleCall() throws IOException { @Test public void multipleSecureConnectsForSingleCall() throws IOException {
@ -746,7 +745,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
listener.removeUpToEvent(SecureConnectStart.class); listener.removeUpToEvent(SecureConnectStart.class);
@ -770,7 +769,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals(200, response1.code()); Assertions.assertThat(response1.code()).isEqualTo(200);
response1.body().close(); response1.body().close();
listener.clearAllEvents(); listener.clearAllEvents();
@ -779,12 +778,12 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals(200, response2.code()); Assertions.assertThat(response2.code()).isEqualTo(200);
response2.body().close(); response2.body().close();
List<String> recordedEvents = listener.recordedEventTypes(); List<String> recordedEvents = listener.recordedEventTypes();
assertFalse(recordedEvents.contains("SecureConnectStart")); Assertions.assertThat(recordedEvents.contains("SecureConnectStart")).isFalse();
assertFalse(recordedEvents.contains("SecureConnectEnd")); Assertions.assertThat(recordedEvents.contains("SecureConnectEnd")).isFalse();
} }
@Test public void successfulConnectionFound() throws IOException { @Test public void successfulConnectionFound() throws IOException {
@ -794,12 +793,12 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
ConnectionAcquired connectionAcquired = listener.removeUpToEvent(ConnectionAcquired.class); ConnectionAcquired connectionAcquired = listener.removeUpToEvent(ConnectionAcquired.class);
assertSame(call, connectionAcquired.call); Assertions.assertThat(connectionAcquired.call).isSameAs(call);
assertNotNull(connectionAcquired.connection); Assertions.assertThat(connectionAcquired.connection).isNotNull();
} }
@Test public void noConnectionFoundOnFollowUp() throws IOException { @Test public void noConnectionFoundOnFollowUp() throws IOException {
@ -813,12 +812,12 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABC", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABC");
listener.removeUpToEvent(ConnectionAcquired.class); listener.removeUpToEvent(ConnectionAcquired.class);
List<String> remainingEvents = listener.recordedEventTypes(); List<String> remainingEvents = listener.recordedEventTypes();
assertFalse(remainingEvents.contains("ConnectionAcquired")); Assertions.assertThat(remainingEvents.contains("ConnectionAcquired")).isFalse();
} }
@Test public void pooledConnectionFound() throws IOException { @Test public void pooledConnectionFound() throws IOException {
@ -830,7 +829,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals(200, response1.code()); Assertions.assertThat(response1.code()).isEqualTo(200);
response1.body().close(); response1.body().close();
ConnectionAcquired connectionAcquired1 = listener.removeUpToEvent(ConnectionAcquired.class); ConnectionAcquired connectionAcquired1 = listener.removeUpToEvent(ConnectionAcquired.class);
@ -840,11 +839,12 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals(200, response2.code()); Assertions.assertThat(response2.code()).isEqualTo(200);
response2.body().close(); response2.body().close();
ConnectionAcquired connectionAcquired2 = listener.removeUpToEvent(ConnectionAcquired.class); ConnectionAcquired connectionAcquired2 = listener.removeUpToEvent(ConnectionAcquired.class);
assertSame(connectionAcquired1.connection, connectionAcquired2.connection); Assertions.assertThat(connectionAcquired2.connection).isSameAs(
connectionAcquired1.connection);
} }
@Test public void multipleConnectionsFoundForSingleCall() throws IOException { @Test public void multipleConnectionsFoundForSingleCall() throws IOException {
@ -859,7 +859,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABC", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABC");
listener.removeUpToEvent(ConnectionAcquired.class); listener.removeUpToEvent(ConnectionAcquired.class);
listener.removeUpToEvent(ConnectionAcquired.class); listener.removeUpToEvent(ConnectionAcquired.class);
@ -896,7 +896,7 @@ public final class EventListenerTest {
// soft failure since client may not support depending on Platform // soft failure since client may not support depending on Platform
assumeThat(response, matchesProtocol(Protocol.HTTP_2)); assumeThat(response, matchesProtocol(Protocol.HTTP_2));
} }
assertEquals(expectedProtocol, response.protocol()); Assertions.assertThat(response.protocol()).isEqualTo(expectedProtocol);
try { try {
response.body.string(); response.body.string();
fail(); fail();
@ -904,7 +904,7 @@ public final class EventListenerTest {
} }
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertNotNull(callFailed.ioe); Assertions.assertThat(callFailed.ioe).isNotNull();
} }
@Test public void emptyResponseBody() throws IOException { @Test public void emptyResponseBody() throws IOException {
@ -923,7 +923,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void emptyResponseBodyConnectionClose() throws IOException { @Test public void emptyResponseBodyConnectionClose() throws IOException {
@ -941,7 +941,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void responseBodyClosedClosedWithoutReadingAllData() throws IOException { @Test public void responseBodyClosedClosedWithoutReadingAllData() throws IOException {
@ -960,7 +960,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void requestBodyFailHttp1OverHttps() throws IOException { @Test public void requestBodyFailHttp1OverHttps() throws IOException {
@ -1012,7 +1012,7 @@ public final class EventListenerTest {
} }
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertNotNull(callFailed.ioe); Assertions.assertThat(callFailed.ioe).isNotNull();
} }
@Test public void requestBodyMultipleFailuresReportedOnlyOnce() { @Test public void requestBodyMultipleFailuresReportedOnlyOnce() {
@ -1055,7 +1055,7 @@ public final class EventListenerTest {
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart",
"ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd",
"RequestBodyStart", "RequestFailed", "ConnectionReleased", "CallFailed"); "RequestBodyStart", "RequestFailed", "ConnectionReleased", "CallFailed");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void requestBodySuccessHttp1OverHttps() throws IOException { @Test public void requestBodySuccessHttp1OverHttps() throws IOException {
@ -1108,15 +1108,15 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
assertEquals("abc", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("abc");
response.body().close(); response.body().close();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
private void requestBodySuccess(RequestBody body, Matcher<Long> requestBodyBytes, private void requestBodySuccess(RequestBody body, Matcher<Long> requestBodyBytes,
@ -1128,7 +1128,7 @@ public final class EventListenerTest {
.post(body) .post(body)
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("World!", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("World!");
assertBytesReadWritten(listener, any(Long.class), requestBodyBytes, responseHeaderLength, assertBytesReadWritten(listener, any(Long.class), requestBodyBytes, responseHeaderLength,
equalTo(6L)); equalTo(6L));
@ -1159,7 +1159,7 @@ public final class EventListenerTest {
"ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased",
"CallEnd"); "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test @Test
@ -1181,7 +1181,7 @@ public final class EventListenerTest {
"ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased",
"CallEnd"); "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void applicationInterceptorProceedsMultipleTimes() throws Exception { @Test public void applicationInterceptorProceedsMultipleTimes() throws Exception {
@ -1191,7 +1191,7 @@ public final class EventListenerTest {
client = client.newBuilder() client = client.newBuilder()
.addInterceptor(chain -> { .addInterceptor(chain -> {
try (Response a = chain.proceed(chain.request())) { try (Response a = chain.proceed(chain.request())) {
assertEquals("a", a.body().string()); Assertions.assertThat(a.body().string()).isEqualTo("a");
} }
return chain.proceed(chain.request()); return chain.proceed(chain.request());
}) })
@ -1199,7 +1199,7 @@ public final class EventListenerTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
assertEquals("b", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("b");
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
@ -1207,10 +1207,10 @@ public final class EventListenerTest {
"ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased",
"CallEnd"); "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(1, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void applicationInterceptorShortCircuit() throws Exception { @Test public void applicationInterceptorShortCircuit() throws Exception {
@ -1226,10 +1226,10 @@ public final class EventListenerTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
assertEquals("a", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("a");
List<String> expectedEvents = Arrays.asList("CallStart", "CallEnd"); List<String> expectedEvents = Arrays.asList("CallStart", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
/** Response headers start, then the entire request body, then response headers end. */ /** Response headers start, then the entire request body, then response headers end. */
@ -1250,6 +1250,6 @@ public final class EventListenerTest {
"ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd",
"ResponseHeadersStart", "RequestBodyStart", "RequestBodyEnd", "ResponseHeadersEnd", "ResponseHeadersStart", "RequestBodyStart", "RequestBodyEnd", "ResponseHeadersEnd",
"ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes()); Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
} }

View File

@ -20,7 +20,7 @@ import okio.Buffer;
import org.junit.Test; import org.junit.Test;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public final class FormBodyTest { public final class FormBodyTest {
@Test public void urlEncoding() throws Exception { @Test public void urlEncoding() throws Exception {
@ -30,32 +30,33 @@ public final class FormBodyTest {
.add("%25", "%25") .add("%25", "%25")
.build(); .build();
assertEquals(3, body.size()); assertThat(body.size()).isEqualTo(3);
assertEquals("a%2B%3D%26%20b", body.encodedName(0)); assertThat(body.encodedName(0)).isEqualTo("a%2B%3D%26%20b");
assertEquals("space%2C%20the", body.encodedName(1)); assertThat(body.encodedName(1)).isEqualTo("space%2C%20the");
assertEquals("%2525", body.encodedName(2)); assertThat(body.encodedName(2)).isEqualTo("%2525");
assertEquals("a+=& b", body.name(0)); assertThat(body.name(0)).isEqualTo("a+=& b");
assertEquals("space, the", body.name(1)); assertThat(body.name(1)).isEqualTo("space, the");
assertEquals("%25", body.name(2)); assertThat(body.name(2)).isEqualTo("%25");
assertEquals("c%2B%3D%26%20d", body.encodedValue(0)); assertThat(body.encodedValue(0)).isEqualTo("c%2B%3D%26%20d");
assertEquals("final%20frontier", body.encodedValue(1)); assertThat(body.encodedValue(1)).isEqualTo("final%20frontier");
assertEquals("%2525", body.encodedValue(2)); assertThat(body.encodedValue(2)).isEqualTo("%2525");
assertEquals("c+=& d", body.value(0)); assertThat(body.value(0)).isEqualTo("c+=& d");
assertEquals("final frontier", body.value(1)); assertThat(body.value(1)).isEqualTo("final frontier");
assertEquals("%25", body.value(2)); assertThat(body.value(2)).isEqualTo("%25");
assertEquals("application/x-www-form-urlencoded", body.contentType().toString()); assertThat(body.contentType().toString()).isEqualTo(
"application/x-www-form-urlencoded");
String expected = "a%2B%3D%26%20b=c%2B%3D%26%20d&space%2C%20the=final%20frontier&%2525=%2525"; String expected = "a%2B%3D%26%20b=c%2B%3D%26%20d&space%2C%20the=final%20frontier&%2525=%2525";
assertEquals(expected.length(), body.contentLength()); assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer out = new Buffer(); Buffer out = new Buffer();
body.writeTo(out); body.writeTo(out);
assertEquals(expected, out.readUtf8()); assertThat(out.readUtf8()).isEqualTo(expected);
} }
@Test public void addEncoded() throws Exception { @Test public void addEncoded() throws Exception {
@ -68,7 +69,7 @@ public final class FormBodyTest {
String expected = "a+%3D%26%20b=c+%3D%26%20d&e+%3D%26%20f=g+%3D%26%20h&%25=%25"; String expected = "a+%3D%26%20b=c+%3D%26%20d&e+%3D%26%20f=g+%3D%26%20h&%25=%25";
Buffer out = new Buffer(); Buffer out = new Buffer();
body.writeTo(out); body.writeTo(out);
assertEquals(expected, out.readUtf8()); assertThat(out.readUtf8()).isEqualTo(expected);
} }
@Test public void encodedPair() throws Exception { @Test public void encodedPair() throws Exception {
@ -77,11 +78,11 @@ public final class FormBodyTest {
.build(); .build();
String expected = "sim=ple"; String expected = "sim=ple";
assertEquals(expected.length(), body.contentLength()); assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
body.writeTo(buffer); body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo(expected);
} }
@Test public void encodeMultiplePairs() throws Exception { @Test public void encodeMultiplePairs() throws Exception {
@ -92,99 +93,103 @@ public final class FormBodyTest {
.build(); .build();
String expected = "sim=ple&hey=there&help=me"; String expected = "sim=ple&hey=there&help=me";
assertEquals(expected.length(), body.contentLength()); assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
body.writeTo(buffer); body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo(expected);
} }
@Test public void buildEmptyForm() throws Exception { @Test public void buildEmptyForm() throws Exception {
FormBody body = new FormBody.Builder().build(); FormBody body = new FormBody.Builder().build();
String expected = ""; String expected = "";
assertEquals(expected.length(), body.contentLength()); assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
body.writeTo(buffer); body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo(expected);
} }
@Test public void characterEncoding() throws Exception { @Test public void characterEncoding() throws Exception {
assertEquals("%00", formEncode(0)); // Browsers convert '\u0000' to '%EF%BF%BD'. // Browsers convert '\u0000' to '%EF%BF%BD'.
assertEquals("%01", formEncode(1)); assertThat(formEncode(0)).isEqualTo("%00");
assertEquals("%02", formEncode(2)); assertThat(formEncode(1)).isEqualTo("%01");
assertEquals("%03", formEncode(3)); assertThat(formEncode(2)).isEqualTo("%02");
assertEquals("%04", formEncode(4)); assertThat(formEncode(3)).isEqualTo("%03");
assertEquals("%05", formEncode(5)); assertThat(formEncode(4)).isEqualTo("%04");
assertEquals("%06", formEncode(6)); assertThat(formEncode(5)).isEqualTo("%05");
assertEquals("%07", formEncode(7)); assertThat(formEncode(6)).isEqualTo("%06");
assertEquals("%08", formEncode(8)); assertThat(formEncode(7)).isEqualTo("%07");
assertEquals("%09", formEncode(9)); assertThat(formEncode(8)).isEqualTo("%08");
assertEquals("%0A", formEncode(10)); // Browsers convert '\n' to '\r\n' assertThat(formEncode(9)).isEqualTo("%09");
assertEquals("%0B", formEncode(11)); // Browsers convert '\n' to '\r\n'
assertEquals("%0C", formEncode(12)); assertThat(formEncode(10)).isEqualTo("%0A");
assertEquals("%0D", formEncode(13)); // Browsers convert '\r' to '\r\n' assertThat(formEncode(11)).isEqualTo("%0B");
assertEquals("%0E", formEncode(14)); assertThat(formEncode(12)).isEqualTo("%0C");
assertEquals("%0F", formEncode(15)); // Browsers convert '\r' to '\r\n'
assertEquals("%10", formEncode(16)); assertThat(formEncode(13)).isEqualTo("%0D");
assertEquals("%11", formEncode(17)); assertThat(formEncode(14)).isEqualTo("%0E");
assertEquals("%12", formEncode(18)); assertThat(formEncode(15)).isEqualTo("%0F");
assertEquals("%13", formEncode(19)); assertThat(formEncode(16)).isEqualTo("%10");
assertEquals("%14", formEncode(20)); assertThat(formEncode(17)).isEqualTo("%11");
assertEquals("%15", formEncode(21)); assertThat(formEncode(18)).isEqualTo("%12");
assertEquals("%16", formEncode(22)); assertThat(formEncode(19)).isEqualTo("%13");
assertEquals("%17", formEncode(23)); assertThat(formEncode(20)).isEqualTo("%14");
assertEquals("%18", formEncode(24)); assertThat(formEncode(21)).isEqualTo("%15");
assertEquals("%19", formEncode(25)); assertThat(formEncode(22)).isEqualTo("%16");
assertEquals("%1A", formEncode(26)); assertThat(formEncode(23)).isEqualTo("%17");
assertEquals("%1B", formEncode(27)); assertThat(formEncode(24)).isEqualTo("%18");
assertEquals("%1C", formEncode(28)); assertThat(formEncode(25)).isEqualTo("%19");
assertEquals("%1D", formEncode(29)); assertThat(formEncode(26)).isEqualTo("%1A");
assertEquals("%1E", formEncode(30)); assertThat(formEncode(27)).isEqualTo("%1B");
assertEquals("%1F", formEncode(31)); assertThat(formEncode(28)).isEqualTo("%1C");
assertEquals("%20", formEncode(32)); // Browsers use '+' for space. assertThat(formEncode(29)).isEqualTo("%1D");
assertEquals("%21", formEncode(33)); assertThat(formEncode(30)).isEqualTo("%1E");
assertEquals("%22", formEncode(34)); assertThat(formEncode(31)).isEqualTo("%1F");
assertEquals("%23", formEncode(35)); // Browsers use '+' for space.
assertEquals("%24", formEncode(36)); assertThat(formEncode(32)).isEqualTo("%20");
assertEquals("%25", formEncode(37)); assertThat(formEncode(33)).isEqualTo("%21");
assertEquals("%26", formEncode(38)); assertThat(formEncode(34)).isEqualTo("%22");
assertEquals("%27", formEncode(39)); assertThat(formEncode(35)).isEqualTo("%23");
assertEquals("%28", formEncode(40)); assertThat(formEncode(36)).isEqualTo("%24");
assertEquals("%29", formEncode(41)); assertThat(formEncode(37)).isEqualTo("%25");
assertEquals("*", formEncode(42)); assertThat(formEncode(38)).isEqualTo("%26");
assertEquals("%2B", formEncode(43)); assertThat(formEncode(39)).isEqualTo("%27");
assertEquals("%2C", formEncode(44)); assertThat(formEncode(40)).isEqualTo("%28");
assertEquals("-", formEncode(45)); assertThat(formEncode(41)).isEqualTo("%29");
assertEquals(".", formEncode(46)); assertThat(formEncode(42)).isEqualTo("*");
assertEquals("%2F", formEncode(47)); assertThat(formEncode(43)).isEqualTo("%2B");
assertEquals("0", formEncode(48)); assertThat(formEncode(44)).isEqualTo("%2C");
assertEquals("9", formEncode(57)); assertThat(formEncode(45)).isEqualTo("-");
assertEquals("%3A", formEncode(58)); assertThat(formEncode(46)).isEqualTo(".");
assertEquals("%3B", formEncode(59)); assertThat(formEncode(47)).isEqualTo("%2F");
assertEquals("%3C", formEncode(60)); assertThat(formEncode(48)).isEqualTo("0");
assertEquals("%3D", formEncode(61)); assertThat(formEncode(57)).isEqualTo("9");
assertEquals("%3E", formEncode(62)); assertThat(formEncode(58)).isEqualTo("%3A");
assertEquals("%3F", formEncode(63)); assertThat(formEncode(59)).isEqualTo("%3B");
assertEquals("%40", formEncode(64)); assertThat(formEncode(60)).isEqualTo("%3C");
assertEquals("A", formEncode(65)); assertThat(formEncode(61)).isEqualTo("%3D");
assertEquals("Z", formEncode(90)); assertThat(formEncode(62)).isEqualTo("%3E");
assertEquals("%5B", formEncode(91)); assertThat(formEncode(63)).isEqualTo("%3F");
assertEquals("%5C", formEncode(92)); assertThat(formEncode(64)).isEqualTo("%40");
assertEquals("%5D", formEncode(93)); assertThat(formEncode(65)).isEqualTo("A");
assertEquals("%5E", formEncode(94)); assertThat(formEncode(90)).isEqualTo("Z");
assertEquals("_", formEncode(95)); assertThat(formEncode(91)).isEqualTo("%5B");
assertEquals("%60", formEncode(96)); assertThat(formEncode(92)).isEqualTo("%5C");
assertEquals("a", formEncode(97)); assertThat(formEncode(93)).isEqualTo("%5D");
assertEquals("z", formEncode(122)); assertThat(formEncode(94)).isEqualTo("%5E");
assertEquals("%7B", formEncode(123)); assertThat(formEncode(95)).isEqualTo("_");
assertEquals("%7C", formEncode(124)); assertThat(formEncode(96)).isEqualTo("%60");
assertEquals("%7D", formEncode(125)); assertThat(formEncode(97)).isEqualTo("a");
assertEquals("%7E", formEncode(126)); assertThat(formEncode(122)).isEqualTo("z");
assertEquals("%7F", formEncode(127)); assertThat(formEncode(123)).isEqualTo("%7B");
assertEquals("%C2%80", formEncode(128)); assertThat(formEncode(124)).isEqualTo("%7C");
assertEquals("%C3%BF", formEncode(255)); assertThat(formEncode(125)).isEqualTo("%7D");
assertThat(formEncode(126)).isEqualTo("%7E");
assertThat(formEncode(127)).isEqualTo("%7F");
assertThat(formEncode(128)).isEqualTo("%C2%80");
assertThat(formEncode(255)).isEqualTo("%C3%BF");
} }
private String formEncode(int codePoint) throws IOException { private String formEncode(int codePoint) throws IOException {
@ -204,10 +209,10 @@ public final class FormBodyTest {
.build(); .build();
String expected = "name=Nicol%E1s"; String expected = "name=Nicol%E1s";
assertEquals(expected.length(), body.contentLength()); assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer out = new Buffer(); Buffer out = new Buffer();
body.writeTo(out); body.writeTo(out);
assertEquals(expected, out.readUtf8()); assertThat(out.readUtf8()).isEqualTo(expected);
} }
} }

View File

@ -36,9 +36,7 @@ import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap; import static java.util.Collections.singletonMap;
import static okhttp3.TestUtil.headerEntries; import static okhttp3.TestUtil.headerEntries;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class HeadersTest { public final class HeadersTest {
@ -54,9 +52,9 @@ public final class HeadersTest {
Request request = new Request.Builder().url("http://square.com/").build(); Request request = new Request.Builder().url("http://square.com/").build();
Response response = Http2ExchangeCodec.readHttp2HeadersList(headerBlock, Protocol.HTTP_2).request(request).build(); Response response = Http2ExchangeCodec.readHttp2HeadersList(headerBlock, Protocol.HTTP_2).request(request).build();
Headers headers = response.headers(); Headers headers = response.headers();
assertEquals(1, headers.size()); assertThat(headers.size()).isEqualTo(1);
assertEquals(":version", headers.name(0)); assertThat(headers.name(0)).isEqualTo(":version");
assertEquals("HTTP/1.1", headers.value(0)); assertThat(headers.value(0)).isEqualTo("HTTP/1.1");
} }
@Test public void http2HeadersListDropsForbiddenHeadersHttp2() { @Test public void http2HeadersListDropsForbiddenHeadersHttp2() {
@ -72,7 +70,7 @@ public final class HeadersTest {
":path", "/", ":path", "/",
":authority", "square.com", ":authority", "square.com",
":scheme", "http"); ":scheme", "http");
assertEquals(expected, Http2ExchangeCodec.http2HeadersList(request)); assertThat(Http2ExchangeCodec.http2HeadersList(request)).isEqualTo(expected);
} }
@Test public void http2HeadersListDontDropTeIfTrailersHttp2() { @Test public void http2HeadersListDontDropTeIfTrailersHttp2() {
@ -85,13 +83,13 @@ public final class HeadersTest {
":path", "/", ":path", "/",
":scheme", "http", ":scheme", "http",
"te", "trailers"); "te", "trailers");
assertEquals(expected, Http2ExchangeCodec.http2HeadersList(request)); assertThat(Http2ExchangeCodec.http2HeadersList(request)).isEqualTo(expected);
} }
@Test public void ofTrims() { @Test public void ofTrims() {
Headers headers = Headers.of("\t User-Agent \n", " \r OkHttp "); Headers headers = Headers.of("\t User-Agent \n", " \r OkHttp ");
assertEquals("User-Agent", headers.name(0)); assertThat(headers.name(0)).isEqualTo("User-Agent");
assertEquals("OkHttp", headers.value(0)); assertThat(headers.value(0)).isEqualTo("OkHttp");
} }
@Test public void addParsing() { @Test public void addParsing() {
@ -103,10 +101,10 @@ public final class HeadersTest {
.add("ping: pong ") // Value whitespace is trimmed. .add("ping: pong ") // Value whitespace is trimmed.
.add("kit:kat") // Space after colon is not required. .add("kit:kat") // Space after colon is not required.
.build(); .build();
assertEquals(Arrays.asList("bar", "baz", "bak"), headers.values("foo")); assertThat(headers.values("foo")).isEqualTo(Arrays.asList("bar", "baz", "bak"));
assertEquals(Arrays.asList("value"), headers.values("key")); assertThat(headers.values("key")).isEqualTo(Arrays.asList("value"));
assertEquals(Arrays.asList("pong"), headers.values("ping")); assertThat(headers.values("ping")).isEqualTo(Arrays.asList("pong"));
assertEquals(Arrays.asList("kat"), headers.values("kit")); assertThat(headers.values("kit")).isEqualTo(Arrays.asList("kat"));
} }
@Test public void addThrowsOnEmptyName() { @Test public void addThrowsOnEmptyName() {
@ -145,8 +143,8 @@ public final class HeadersTest {
.build(); .build();
fail("Should have complained about invalid value"); fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 1 in header name: héader1", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); "Unexpected char 0xe9 at 1 in header name: héader1");
} }
} }
@ -154,7 +152,7 @@ public final class HeadersTest {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.addUnsafeNonAscii("header1", "valué1") .addUnsafeNonAscii("header1", "valué1")
.build(); .build();
assertEquals("header1: valué1\n", headers.toString()); assertThat(headers.toString()).isEqualTo("header1: valué1\n");
} }
@Test public void ofThrowsOddNumberOfHeaders() { @Test public void ofThrowsOddNumberOfHeaders() {
@ -183,7 +181,7 @@ public final class HeadersTest {
@Test public void ofAcceptsEmptyValue() { @Test public void ofAcceptsEmptyValue() {
Headers headers = Headers.of("User-Agent", ""); Headers headers = Headers.of("User-Agent", "");
assertEquals("", headers.value(0)); assertThat(headers.value(0)).isEqualTo("");
} }
@Test public void ofMakesDefensiveCopy() { @Test public void ofMakesDefensiveCopy() {
@ -193,7 +191,7 @@ public final class HeadersTest {
}; };
Headers headers = Headers.of(namesAndValues); Headers headers = Headers.of(namesAndValues);
namesAndValues[1] = "Chrome"; namesAndValues[1] = "Chrome";
assertEquals("OkHttp", headers.value(0)); assertThat(headers.value(0)).isEqualTo("OkHttp");
} }
@Test public void ofRejectsNullChar() { @Test public void ofRejectsNullChar() {
@ -230,17 +228,17 @@ public final class HeadersTest {
@Test public void ofMapAcceptsEmptyValue() { @Test public void ofMapAcceptsEmptyValue() {
Headers headers = Headers.of(singletonMap("User-Agent", "")); Headers headers = Headers.of(singletonMap("User-Agent", ""));
assertEquals("", headers.value(0)); assertThat(headers.value(0)).isEqualTo("");
} }
@Test public void ofMapTrimsKey() { @Test public void ofMapTrimsKey() {
Headers headers = Headers.of(singletonMap(" User-Agent ", "OkHttp")); Headers headers = Headers.of(singletonMap(" User-Agent ", "OkHttp"));
assertEquals("User-Agent", headers.name(0)); assertThat(headers.name(0)).isEqualTo("User-Agent");
} }
@Test public void ofMapTrimsValue() { @Test public void ofMapTrimsValue() {
Headers headers = Headers.of(singletonMap("User-Agent", " OkHttp ")); Headers headers = Headers.of(singletonMap("User-Agent", " OkHttp "));
assertEquals("OkHttp", headers.value(0)); assertThat(headers.value(0)).isEqualTo("OkHttp");
} }
@Test public void ofMapMakesDefensiveCopy() { @Test public void ofMapMakesDefensiveCopy() {
@ -249,7 +247,7 @@ public final class HeadersTest {
Headers headers = Headers.of(namesAndValues); Headers headers = Headers.of(namesAndValues);
namesAndValues.put("User-Agent", "Chrome"); namesAndValues.put("User-Agent", "Chrome");
assertEquals("OkHttp", headers.value(0)); assertThat(headers.value(0)).isEqualTo("OkHttp");
} }
@Test public void ofMapRejectsNullCharInName() { @Test public void ofMapRejectsNullCharInName() {
@ -274,8 +272,8 @@ public final class HeadersTest {
"cache-control", "no-store", "cache-control", "no-store",
"user-agent", "OkHttp"); "user-agent", "OkHttp");
Map<String, List<String>> headerMap = headers.toMultimap(); Map<String, List<String>> headerMap = headers.toMultimap();
assertEquals(2, headerMap.get("cache-control").size()); assertThat(headerMap.get("cache-control").size()).isEqualTo(2);
assertEquals(1, headerMap.get("user-agent").size()); assertThat(headerMap.get("user-agent").size()).isEqualTo(1);
} }
@Test public void toMultimapUsesCanonicalCase() { @Test public void toMultimapUsesCanonicalCase() {
@ -284,8 +282,8 @@ public final class HeadersTest {
"Cache-Control", "no-cache", "Cache-Control", "no-cache",
"User-Agent", "OkHttp"); "User-Agent", "OkHttp");
Map<String, List<String>> headerMap = headers.toMultimap(); Map<String, List<String>> headerMap = headers.toMultimap();
assertEquals(2, headerMap.get("cache-control").size()); assertThat(headerMap.get("cache-control").size()).isEqualTo(2);
assertEquals(1, headerMap.get("user-agent").size()); assertThat(headerMap.get("user-agent").size()).isEqualTo(1);
} }
@Test public void toMultimapAllowsCaseInsensitiveGet() { @Test public void toMultimapAllowsCaseInsensitiveGet() {
@ -293,8 +291,8 @@ public final class HeadersTest {
"cache-control", "no-store", "cache-control", "no-store",
"Cache-Control", "no-cache"); "Cache-Control", "no-cache");
Map<String, List<String>> headerMap = headers.toMultimap(); Map<String, List<String>> headerMap = headers.toMultimap();
assertEquals(2, headerMap.get("cache-control").size()); assertThat(headerMap.get("cache-control").size()).isEqualTo(2);
assertEquals(2, headerMap.get("Cache-Control").size()); assertThat(headerMap.get("Cache-Control").size()).isEqualTo(2);
} }
@Test public void nameIndexesAreStrict() { @Test public void nameIndexesAreStrict() {
@ -304,8 +302,8 @@ public final class HeadersTest {
fail(); fail();
} catch (IndexOutOfBoundsException expected) { } catch (IndexOutOfBoundsException expected) {
} }
assertEquals("a", headers.name(0)); assertThat(headers.name(0)).isEqualTo("a");
assertEquals("c", headers.name(1)); assertThat(headers.name(1)).isEqualTo("c");
try { try {
headers.name(2); headers.name(2);
fail(); fail();
@ -320,8 +318,8 @@ public final class HeadersTest {
fail(); fail();
} catch (IndexOutOfBoundsException expected) { } catch (IndexOutOfBoundsException expected) {
} }
assertEquals("b", headers.value(0)); assertThat(headers.value(0)).isEqualTo("b");
assertEquals("d", headers.value(1)); assertThat(headers.value(1)).isEqualTo("d");
try { try {
headers.value(2); headers.value(2);
fail(); fail();
@ -334,8 +332,8 @@ public final class HeadersTest {
new Headers.Builder().add("héader1", "value1"); new Headers.Builder().add("héader1", "value1");
fail("Should have complained about invalid name"); fail("Should have complained about invalid name");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 1 in header name: héader1", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); "Unexpected char 0xe9 at 1 in header name: héader1");
} }
} }
@ -344,8 +342,8 @@ public final class HeadersTest {
new Headers.Builder().add("header1", "valué1"); new Headers.Builder().add("header1", "valué1");
fail("Should have complained about invalid value"); fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 4 in header1 value: valué1", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); "Unexpected char 0xe9 at 4 in header1 value: valué1");
} }
} }
@ -354,8 +352,8 @@ public final class HeadersTest {
Headers.of("héader1", "value1"); Headers.of("héader1", "value1");
fail("Should have complained about invalid value"); fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 1 in header name: héader1", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); "Unexpected char 0xe9 at 1 in header name: héader1");
} }
} }
@ -364,8 +362,8 @@ public final class HeadersTest {
Headers.of("header1", "valué1"); Headers.of("header1", "valué1");
fail("Should have complained about invalid value"); fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 4 in header1 value: valué1", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); "Unexpected char 0xe9 at 4 in header1 value: valué1");
} }
} }
@ -374,8 +372,8 @@ public final class HeadersTest {
Headers.of(singletonMap("héader1", "value1")); Headers.of(singletonMap("héader1", "value1"));
fail("Should have complained about invalid value"); fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 1 in header name: héader1", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); "Unexpected char 0xe9 at 1 in header name: héader1");
} }
} }
@ -384,8 +382,8 @@ public final class HeadersTest {
Headers.of(singletonMap("header1", "valué1")); Headers.of(singletonMap("header1", "valué1"));
fail("Should have complained about invalid value"); fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 4 in header1 value: valué1", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); "Unexpected char 0xe9 at 4 in header1 value: valué1");
} }
} }
@ -398,8 +396,8 @@ public final class HeadersTest {
.add("Connection", "close") .add("Connection", "close")
.add("Transfer-Encoding", "chunked") .add("Transfer-Encoding", "chunked")
.build(); .build();
assertEquals(headers1, headers2); assertThat(headers2).isEqualTo(headers1);
assertEquals(headers1.hashCode(), headers2.hashCode()); assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode());
} }
@Test public void headersNotEquals() { @Test public void headersNotEquals() {
@ -411,8 +409,8 @@ public final class HeadersTest {
.add("Connection", "keep-alive") .add("Connection", "keep-alive")
.add("Transfer-Encoding", "chunked") .add("Transfer-Encoding", "chunked")
.build(); .build();
assertNotEquals(headers1, headers2); assertThat(headers2).isNotEqualTo(headers1);
assertNotEquals(headers1.hashCode(), headers2.hashCode()); assertThat(headers2.hashCode()).isNotEqualTo((long) headers1.hashCode());
} }
@Test public void headersToString() { @Test public void headersToString() {
@ -420,7 +418,7 @@ public final class HeadersTest {
.add("A", "a") .add("A", "a")
.add("B", "bb") .add("B", "bb")
.build(); .build();
assertEquals("A: a\nB: bb\n", headers.toString()); assertThat(headers.toString()).isEqualTo("A: a\nB: bb\n");
} }
@Test public void headersAddAll() { @Test public void headersAddAll() {
@ -434,7 +432,7 @@ public final class HeadersTest {
.addAll(sourceHeaders) .addAll(sourceHeaders)
.add("C", "c") .add("C", "c")
.build(); .build();
assertEquals("A: a\nA: aa\na: aa\nB: bb\nC: c\n", headers.toString()); assertThat(headers.toString()).isEqualTo("A: a\nA: aa\na: aa\nB: bb\nC: c\n");
} }
/** See https://github.com/square/okhttp/issues/2780. */ /** See https://github.com/square/okhttp/issues/2780. */
@ -444,15 +442,15 @@ public final class HeadersTest {
+ "jdflkasdf\", qop=\"auth\", stale=\"FALSE\"") + "jdflkasdf\", qop=\"auth\", stale=\"FALSE\"")
.build(); .build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("Digest", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertEquals("myrealm", challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf"); expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth"); expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE"); expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
} }
@Test public void testDigestChallengeWithDifferentlyOrderedAuthParams() { @Test public void testDigestChallengeWithDifferentlyOrderedAuthParams() {
@ -461,15 +459,15 @@ public final class HeadersTest {
+ "dfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"") + "dfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"")
.build(); .build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("Digest", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertEquals("myrealm", challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf"); expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth"); expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE"); expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
} }
@Test public void testDigestChallengeWithDifferentlyOrderedAuthParams2() { @Test public void testDigestChallengeWithDifferentlyOrderedAuthParams2() {
@ -478,15 +476,15 @@ public final class HeadersTest {
+ "asdf\", realm=\"myrealm\", stale=\"FALSE\"") + "asdf\", realm=\"myrealm\", stale=\"FALSE\"")
.build(); .build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("Digest", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertEquals("myrealm", challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf"); expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth"); expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE"); expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
} }
@Test public void testDigestChallengeWithMissingRealm() { @Test public void testDigestChallengeWithMissingRealm() {
@ -495,15 +493,15 @@ public final class HeadersTest {
+ "rlaskdfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"") + "rlaskdfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"")
.build(); .build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("Digest", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertNull(challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isNull();
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("underrealm", "myrealm"); expectedAuthParams.put("underrealm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf"); expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth"); expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE"); expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
} }
@Test public void testDigestChallengeWithAdditionalSpaces() { @Test public void testDigestChallengeWithAdditionalSpaces() {
@ -512,15 +510,15 @@ public final class HeadersTest {
+ "askdfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"") + "askdfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"")
.build(); .build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("Digest", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertEquals("myrealm", challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf"); expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth"); expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE"); expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
} }
@Test public void testDigestChallengeWithAdditionalSpacesBeforeFirstAuthParam() { @Test public void testDigestChallengeWithAdditionalSpacesBeforeFirstAuthParam() {
@ -529,15 +527,15 @@ public final class HeadersTest {
+ "aksjdflkasdf\", qop=\"auth\", stale=\"FALSE\"") + "aksjdflkasdf\", qop=\"auth\", stale=\"FALSE\"")
.build(); .build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("Digest", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertEquals("myrealm", challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf"); expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth"); expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE"); expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
} }
@Test public void testDigestChallengeWithCamelCasedNames() { @Test public void testDigestChallengeWithCamelCasedNames() {
@ -546,15 +544,15 @@ public final class HeadersTest {
+ "dfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"") + "dfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"")
.build(); .build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("DiGeSt", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("DiGeSt");
assertEquals("myrealm", challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf"); expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth"); expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE"); expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
} }
@Test public void testDigestChallengeWithCamelCasedNames2() { @Test public void testDigestChallengeWithCamelCasedNames2() {
@ -564,25 +562,25 @@ public final class HeadersTest {
+ "jdflkasdf\", qop=\"auth\", stale=\"FALSE\"") + "jdflkasdf\", qop=\"auth\", stale=\"FALSE\"")
.build(); .build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("DIgEsT", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("DIgEsT");
assertEquals("myrealm", challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf"); expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth"); expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE"); expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
} }
@Test public void testDigestChallengeWithTokenFormOfAuthParam() { @Test public void testDigestChallengeWithTokenFormOfAuthParam() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest realm=myrealm").build(); .add("WWW-Authenticate", "Digest realm=myrealm").build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("Digest", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertEquals("myrealm", challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
assertEquals(singletonMap("realm", "myrealm"), challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(singletonMap("realm", "myrealm"));
} }
@Test public void testDigestChallengeWithoutAuthParams() { @Test public void testDigestChallengeWithoutAuthParams() {
@ -590,18 +588,18 @@ public final class HeadersTest {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest").build(); .add("WWW-Authenticate", "Digest").build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate"); List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size()); assertThat(challenges.size()).isEqualTo(1);
assertEquals("Digest", challenges.get(0).scheme()); assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertNull(challenges.get(0).realm()); assertThat(challenges.get(0).realm()).isNull();
assertEquals(emptyMap(), challenges.get(0).authParams()); assertThat(challenges.get(0).authParams()).isEqualTo(emptyMap());
} }
@Test public void basicChallenge() { @Test public void basicChallenge() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate: Basic realm=\"protected area\"") .add("WWW-Authenticate: Basic realm=\"protected area\"")
.build(); .build();
assertEquals(singletonList(new Challenge("Basic", singletonMap("realm", "protected area"))), assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
HttpHeaders.parseChallenges(headers, "WWW-Authenticate")); singletonList(new Challenge("Basic", singletonMap("realm", "protected area"))));
} }
@Test public void basicChallengeWithCharset() { @Test public void basicChallengeWithCharset() {
@ -611,8 +609,8 @@ public final class HeadersTest {
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "protected area"); expectedAuthParams.put("realm", "protected area");
expectedAuthParams.put("charset", "UTF-8"); expectedAuthParams.put("charset", "UTF-8");
assertEquals(singletonList(new Challenge("Basic", expectedAuthParams)), assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
HttpHeaders.parseChallenges(headers, "WWW-Authenticate")); singletonList(new Challenge("Basic", expectedAuthParams)));
} }
@Test public void basicChallengeWithUnexpectedCharset() { @Test public void basicChallengeWithUnexpectedCharset() {
@ -623,74 +621,69 @@ public final class HeadersTest {
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "protected area"); expectedAuthParams.put("realm", "protected area");
expectedAuthParams.put("charset", "US-ASCII"); expectedAuthParams.put("charset", "US-ASCII");
assertEquals(singletonList(new Challenge("Basic", expectedAuthParams)), assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
HttpHeaders.parseChallenges(headers, "WWW-Authenticate")); singletonList(new Challenge("Basic", expectedAuthParams)));
} }
@Test public void separatorsBeforeFirstChallenge() { @Test public void separatorsBeforeFirstChallenge() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", " , , Basic realm=myrealm") .add("WWW-Authenticate", " , , Basic realm=myrealm")
.build(); .build();
assertEquals(singletonList(new Challenge("Basic", singletonMap("realm", "myrealm"))), assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
HttpHeaders.parseChallenges(headers, "WWW-Authenticate")); singletonList(new Challenge("Basic", singletonMap("realm", "myrealm"))));
} }
@Test public void spacesAroundKeyValueSeparator() { @Test public void spacesAroundKeyValueSeparator() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Basic realm = \"myrealm\"") .add("WWW-Authenticate", "Basic realm = \"myrealm\"")
.build(); .build();
assertEquals(singletonList(new Challenge("Basic", singletonMap("realm", "myrealm"))), assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
HttpHeaders.parseChallenges(headers, "WWW-Authenticate")); singletonList(new Challenge("Basic", singletonMap("realm", "myrealm"))));
} }
@Test public void multipleChallengesInOneHeader() { @Test public void multipleChallengesInOneHeader() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Basic realm = \"myrealm\",Digest") .add("WWW-Authenticate", "Basic realm = \"myrealm\",Digest")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Basic", singletonMap("realm", "myrealm")), new Challenge("Basic", singletonMap("realm", "myrealm")),
new Challenge("Digest", Collections.emptyMap())), new Challenge("Digest", Collections.emptyMap())));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void multipleChallengesWithSameSchemeButDifferentRealmInOneHeader() { @Test public void multipleChallengesWithSameSchemeButDifferentRealmInOneHeader() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Basic realm = \"myrealm\",Basic realm=myotherrealm") .add("WWW-Authenticate", "Basic realm = \"myrealm\",Basic realm=myotherrealm")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Basic", singletonMap("realm", "myrealm")), new Challenge("Basic", singletonMap("realm", "myrealm")),
new Challenge("Basic", singletonMap("realm", "myotherrealm"))), new Challenge("Basic", singletonMap("realm", "myotherrealm"))));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void separatorsBeforeFirstAuthParam() { @Test public void separatorsBeforeFirstAuthParam() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest, Basic ,,realm=\"myrealm\"") .add("WWW-Authenticate", "Digest, Basic ,,realm=\"myrealm\"")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm"))), new Challenge("Basic", singletonMap("realm", "myrealm"))));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void onlyCommaBetweenChallenges() { @Test public void onlyCommaBetweenChallenges() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest,Basic realm=\"myrealm\"") .add("WWW-Authenticate", "Digest,Basic realm=\"myrealm\"")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm"))), new Challenge("Basic", singletonMap("realm", "myrealm"))));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void multipleSeparatorsBetweenChallenges() { @Test public void multipleSeparatorsBetweenChallenges() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest,,,, Basic ,,realm=\"myrealm\"") .add("WWW-Authenticate", "Digest,,,, Basic ,,realm=\"myrealm\"")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm"))), new Challenge("Basic", singletonMap("realm", "myrealm"))));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void unknownAuthParams() { @Test public void unknownAuthParams() {
@ -701,10 +694,9 @@ public final class HeadersTest {
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("foo", "bar"); expectedAuthParams.put("foo", "bar");
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", expectedAuthParams)), new Challenge("Basic", expectedAuthParams)));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void escapedCharactersInQuotedString() { @Test public void escapedCharactersInQuotedString() {
@ -712,10 +704,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\"r\\ealm\"") .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\"r\\ealm\"")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "my\\\"realm"))), new Challenge("Basic", singletonMap("realm", "my\\\"realm"))));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void commaInQuotedStringAndBeforeFirstChallenge() { @Test public void commaInQuotedStringAndBeforeFirstChallenge() {
@ -723,10 +714,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", ",Digest,,,, Basic ,,,realm=\"my, realm,\"") .add("WWW-Authenticate", ",Digest,,,, Basic ,,,realm=\"my, realm,\"")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "my, realm,"))), new Challenge("Basic", singletonMap("realm", "my, realm,"))));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void unescapedDoubleQuoteInQuotedStringWithEvenNumberOfBackslashesInFront() { @Test public void unescapedDoubleQuoteInQuotedStringWithEvenNumberOfBackslashesInFront() {
@ -734,9 +724,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\\\"r\\ealm\"") .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\\\"r\\ealm\"")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap())), new Challenge("Digest", Collections.emptyMap())));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void unescapedDoubleQuoteInQuotedString() { @Test public void unescapedDoubleQuoteInQuotedString() {
@ -744,9 +733,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\"realm\"") .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\"realm\"")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap())), new Challenge("Digest", Collections.emptyMap())));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Ignore("TODO(jwilson): reject parameters that use invalid characters") @Ignore("TODO(jwilson): reject parameters that use invalid characters")
@ -755,9 +743,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=my\"realm") .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=my\"realm")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap())), new Challenge("Digest", Collections.emptyMap())));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void token68InsteadOfAuthParams() { @Test public void token68InsteadOfAuthParams() {
@ -765,9 +752,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Other abc==") .add("WWW-Authenticate", "Other abc==")
.build(); .build();
assertEquals(singletonList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
new Challenge("Other", singletonMap(null, "abc=="))), singletonList(
HttpHeaders.parseChallenges(headers, "WWW-Authenticate")); new Challenge("Other", singletonMap(null, "abc=="))));
} }
@Test public void token68AndAuthParams() { @Test public void token68AndAuthParams() {
@ -775,9 +762,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Other abc==, realm=myrealm") .add("WWW-Authenticate", "Other abc==, realm=myrealm")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Other", singletonMap(null, "abc=="))), new Challenge("Other", singletonMap(null, "abc=="))));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void repeatedAuthParamKey() { @Test public void repeatedAuthParamKey() {
@ -785,7 +771,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Other realm=myotherrealm, realm=myrealm") .add("WWW-Authenticate", "Other realm=myotherrealm, realm=myrealm")
.build(); .build();
assertEquals(emptyList(), HttpHeaders.parseChallenges(headers, "WWW-Authenticate")); assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
emptyList());
} }
@Test public void multipleAuthenticateHeaders() { @Test public void multipleAuthenticateHeaders() {
@ -794,10 +781,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Basic realm=myrealm") .add("WWW-Authenticate", "Basic realm=myrealm")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm"))), new Challenge("Basic", singletonMap("realm", "myrealm"))));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void multipleAuthenticateHeadersInDifferentOrder() { @Test public void multipleAuthenticateHeadersInDifferentOrder() {
@ -806,10 +792,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest") .add("WWW-Authenticate", "Digest")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Basic", singletonMap("realm", "myrealm")), new Challenge("Basic", singletonMap("realm", "myrealm")),
new Challenge("Digest", Collections.emptyMap())), new Challenge("Digest", Collections.emptyMap())));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void multipleBasicAuthenticateHeaders() { @Test public void multipleBasicAuthenticateHeaders() {
@ -818,23 +803,22 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Basic realm=myotherrealm") .add("WWW-Authenticate", "Basic realm=myotherrealm")
.build(); .build();
assertEquals(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Basic", singletonMap("realm", "myrealm")), new Challenge("Basic", singletonMap("realm", "myrealm")),
new Challenge("Basic", singletonMap("realm", "myotherrealm"))), new Challenge("Basic", singletonMap("realm", "myotherrealm"))));
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
} }
@Test public void byteCount() { @Test public void byteCount() {
assertEquals(0L, Util.EMPTY_HEADERS.byteCount()); assertThat(Util.EMPTY_HEADERS.byteCount()).isEqualTo(0L);
assertEquals(10L, new Headers.Builder() assertThat(new Headers.Builder()
.add("abc", "def") .add("abc", "def")
.build() .build()
.byteCount()); .byteCount()).isEqualTo(10L);
assertEquals(20L, new Headers.Builder() assertThat(new Headers.Builder()
.add("abc", "def") .add("abc", "def")
.add("ghi", "jkl") .add("ghi", "jkl")
.build() .build()
.byteCount()); .byteCount()).isEqualTo(20L);
} }
@Test public void addDate() { @Test public void addDate() {
@ -842,8 +826,8 @@ public final class HeadersTest {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("testDate", expected) .add("testDate", expected)
.build(); .build();
assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", headers.get("testDate")); assertThat(headers.get("testDate")).isEqualTo("Thu, 01 Jan 1970 00:00:00 GMT");
assertEquals(new Date(0L), headers.getDate("testDate")); assertThat(headers.getDate("testDate")).isEqualTo(new Date(0L));
} }
@Test public void addDateNull() { @Test public void addDateNull() {
@ -853,7 +837,7 @@ public final class HeadersTest {
.build(); .build();
fail(); fail();
} catch (NullPointerException expected) { } catch (NullPointerException expected) {
assertEquals("value for name testDate == null", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("value for name testDate == null");
} }
} }
@ -862,8 +846,8 @@ public final class HeadersTest {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("Test-Instant", expected) .add("Test-Instant", expected)
.build(); .build();
assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", headers.get("Test-Instant")); assertThat(headers.get("Test-Instant")).isEqualTo("Thu, 01 Jan 1970 00:00:00 GMT");
assertEquals(expected, headers.getInstant("Test-Instant")); assertThat(headers.getInstant("Test-Instant")).isEqualTo(expected);
} }
@Test public void addInstantNull() { @Test public void addInstantNull() {
@ -873,7 +857,7 @@ public final class HeadersTest {
.build(); .build();
fail(); fail();
} catch (NullPointerException expected) { } catch (NullPointerException expected) {
assertEquals("value for name Test-Instant == null", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("value for name Test-Instant == null");
} }
} }
@ -883,8 +867,8 @@ public final class HeadersTest {
.add("testDate", new Date(0L)) .add("testDate", new Date(0L))
.set("testDate", expected) .set("testDate", expected)
.build(); .build();
assertEquals("Thu, 01 Jan 1970 00:00:01 GMT", headers.get("testDate")); assertThat(headers.get("testDate")).isEqualTo("Thu, 01 Jan 1970 00:00:01 GMT");
assertEquals(expected, headers.getDate("testDate")); assertThat(headers.getDate("testDate")).isEqualTo(expected);
} }
@Test public void setDateNull() { @Test public void setDateNull() {
@ -894,7 +878,7 @@ public final class HeadersTest {
.build(); .build();
fail(); fail();
} catch (NullPointerException expected) { } catch (NullPointerException expected) {
assertEquals("value for name testDate == null", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("value for name testDate == null");
} }
} }
@ -904,8 +888,8 @@ public final class HeadersTest {
.add("Test-Instant", Instant.ofEpochMilli(0L)) .add("Test-Instant", Instant.ofEpochMilli(0L))
.set("Test-Instant", expected) .set("Test-Instant", expected)
.build(); .build();
assertEquals("Thu, 01 Jan 1970 00:00:01 GMT", headers.get("Test-Instant")); assertThat(headers.get("Test-Instant")).isEqualTo("Thu, 01 Jan 1970 00:00:01 GMT");
assertEquals(expected, headers.getInstant("Test-Instant")); assertThat(headers.getInstant("Test-Instant")).isEqualTo(expected);
} }
@Test public void setInstantNull() { @Test public void setInstantNull() {
@ -915,7 +899,7 @@ public final class HeadersTest {
.build(); .build();
fail(); fail();
} catch (NullPointerException expected) { } catch (NullPointerException expected) {
assertEquals("value for name Test-Instant == null", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("value for name Test-Instant == null");
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -42,12 +42,7 @@ import okio.Source;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
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 static org.junit.Assert.fail;
public final class InterceptorTest { public final class InterceptorTest {
@ -77,7 +72,7 @@ public final class InterceptorTest {
.build(); .build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertSame(interceptorResponse, response); assertThat(response).isSameAs(interceptorResponse);
} }
@Test public void networkInterceptorsCannotShortCircuitResponses() throws Exception { @Test public void networkInterceptorsCannotShortCircuitResponses() throws Exception {
@ -102,8 +97,8 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
fail(); fail();
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
assertEquals("network interceptor " + interceptor + " must call proceed() exactly once", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); ("network interceptor " + interceptor + " must call proceed() exactly once"));
} }
} }
@ -127,8 +122,8 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
fail(); fail();
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
assertEquals("network interceptor " + interceptor + " must call proceed() exactly once", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); ("network interceptor " + interceptor + " must call proceed() exactly once"));
} }
} }
@ -155,8 +150,8 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
fail(); fail();
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
assertEquals("network interceptor " + interceptor + " must retain the same host and port", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); ("network interceptor " + interceptor + " must retain the same host and port"));
} }
} }
@ -165,7 +160,7 @@ public final class InterceptorTest {
Interceptor interceptor = chain -> { Interceptor interceptor = chain -> {
Connection connection = chain.connection(); Connection connection = chain.connection();
assertNotNull(connection); assertThat(connection).isNotNull();
return chain.proceed(chain.request()); return chain.proceed(chain.request());
}; };
client = client.newBuilder() client = client.newBuilder()
@ -186,14 +181,14 @@ public final class InterceptorTest {
Interceptor interceptor = chain -> { Interceptor interceptor = chain -> {
// The network request has everything: User-Agent, Host, Accept-Encoding. // The network request has everything: User-Agent, Host, Accept-Encoding.
Request networkRequest = chain.request(); Request networkRequest = chain.request();
assertNotNull(networkRequest.header("User-Agent")); assertThat(networkRequest.header("User-Agent")).isNotNull();
assertEquals(server.getHostName() + ":" + server.getPort(), assertThat(networkRequest.header("Host")).isEqualTo(
networkRequest.header("Host")); (server.getHostName() + ":" + server.getPort()));
assertNotNull(networkRequest.header("Accept-Encoding")); assertThat(networkRequest.header("Accept-Encoding")).isNotNull();
// The network response also has everything, including the raw gzipped content. // The network response also has everything, including the raw gzipped content.
Response networkResponse = chain.proceed(networkRequest); Response networkResponse = chain.proceed(networkRequest);
assertEquals("gzip", networkResponse.header("Content-Encoding")); assertThat(networkResponse.header("Content-Encoding")).isEqualTo("gzip");
return networkResponse; return networkResponse;
}; };
client = client.newBuilder() client = client.newBuilder()
@ -205,14 +200,14 @@ public final class InterceptorTest {
.build(); .build();
// No extra headers in the application's request. // No extra headers in the application's request.
assertNull(request.header("User-Agent")); assertThat(request.header("User-Agent")).isNull();
assertNull(request.header("Host")); assertThat(request.header("Host")).isNull();
assertNull(request.header("Accept-Encoding")); assertThat(request.header("Accept-Encoding")).isNull();
// No extra headers in the application's response. // No extra headers in the application's response.
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertNull(request.header("Content-Encoding")); assertThat(request.header("Content-Encoding")).isNull();
assertEquals("abcabcabc", response.body().string()); assertThat(response.body().string()).isEqualTo("abcabcabc");
} }
@Test public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception { @Test public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception {
@ -240,8 +235,8 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertEquals("POST", recordedRequest.getMethod()); assertThat(recordedRequest.getMethod()).isEqualTo("POST");
assertEquals("abc", recordedRequest.getBody().readUtf8()); assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("abc");
} }
@Test public void applicationInterceptorsRewriteRequestToServer() throws Exception { @Test public void applicationInterceptorsRewriteRequestToServer() throws Exception {
@ -272,10 +267,10 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertEquals("ABC", recordedRequest.getBody().readUtf8()); assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("ABC");
assertEquals("foo", recordedRequest.getHeader("Original-Header")); assertThat(recordedRequest.getHeader("Original-Header")).isEqualTo("foo");
assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted")); assertThat(recordedRequest.getHeader("OkHttp-Intercepted")).isEqualTo("yep");
assertEquals("POST", recordedRequest.getMethod()); assertThat(recordedRequest.getMethod()).isEqualTo("POST");
} }
@Test public void applicationInterceptorsRewriteResponseFromServer() throws Exception { @Test public void applicationInterceptorsRewriteResponseFromServer() throws Exception {
@ -304,9 +299,9 @@ public final class InterceptorTest {
.build(); .build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertEquals("ABC", response.body().string()); assertThat(response.body().string()).isEqualTo("ABC");
assertEquals("yep", response.header("OkHttp-Intercepted")); assertThat(response.header("OkHttp-Intercepted")).isEqualTo("yep");
assertEquals("foo", response.header("Original-Header")); assertThat(response.header("Original-Header")).isEqualTo("foo");
} }
@Test public void multipleApplicationInterceptors() throws Exception { @Test public void multipleApplicationInterceptors() throws Exception {
@ -344,12 +339,12 @@ public final class InterceptorTest {
.build(); .build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertEquals(Arrays.asList("Cupcake", "Donut"), assertThat(response.headers("Response-Interceptor")).isEqualTo(
response.headers("Response-Interceptor")); Arrays.asList("Cupcake", "Donut"));
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertEquals(Arrays.asList("Android", "Bob"), assertThat(recordedRequest.getHeaders().values("Request-Interceptor")).isEqualTo(
recordedRequest.getHeaders().values("Request-Interceptor")); Arrays.asList("Android", "Bob"));
} }
@Test public void asyncApplicationInterceptors() throws Exception { @Test public void asyncApplicationInterceptors() throws Exception {
@ -397,7 +392,7 @@ public final class InterceptorTest {
.build(); .build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertEquals(response.body().string(), "b"); assertThat("b").isEqualTo(response.body().string());
} }
/** Make sure interceptors can interact with the OkHttp client. */ /** Make sure interceptors can interact with the OkHttp client. */
@ -412,7 +407,7 @@ public final class InterceptorTest {
.url(server.url("/a")) .url(server.url("/a"))
.build(); .build();
Response responseA = client.newCall(requestA).execute(); Response responseA = client.newCall(requestA).execute();
assertEquals("a", responseA.body().string()); assertThat(responseA.body().string()).isEqualTo("a");
} }
return chain.proceed(chain.request()); return chain.proceed(chain.request());
@ -423,7 +418,7 @@ public final class InterceptorTest {
.url(server.url("/b")) .url(server.url("/b"))
.build(); .build();
Response responseB = client.newCall(requestB).execute(); Response responseB = client.newCall(requestB).execute();
assertEquals("b", responseB.body().string()); assertThat(responseB.body().string()).isEqualTo("b");
} }
/** Make sure interceptors can interact with the OkHttp client asynchronously. */ /** Make sure interceptors can interact with the OkHttp client asynchronously. */
@ -482,7 +477,7 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
fail(); fail();
} catch (RuntimeException expected) { } catch (RuntimeException expected) {
assertEquals("boom!", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("boom!");
} }
} }
@ -507,9 +502,10 @@ public final class InterceptorTest {
.build(); .build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertNotNull(response.request().header("User-Agent")); assertThat(response.request().header("User-Agent")).isNotNull();
assertEquals("user request", response.request().header("User-Agent")); assertThat(response.request().header("User-Agent")).isEqualTo("user request");
assertEquals("intercepted request", response.networkResponse().request().header("User-Agent")); assertThat(response.networkResponse().request().header("User-Agent")).isEqualTo(
"intercepted request");
} }
@Test public void applicationInterceptorThrowsRuntimeExceptionAsynchronous() throws Exception { @Test public void applicationInterceptorThrowsRuntimeExceptionAsynchronous() throws Exception {
@ -537,7 +533,7 @@ public final class InterceptorTest {
.build(); .build();
client.newCall(request).enqueue(callback); client.newCall(request).enqueue(callback);
assertEquals("boom!", executor.takeException().getMessage()); assertThat(executor.takeException().getMessage()).isEqualTo("boom!");
} }
@Test public void applicationInterceptorReturnsNull() throws Exception { @Test public void applicationInterceptorReturnsNull() throws Exception {
@ -563,7 +559,8 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
fail(); fail();
} catch (NullPointerException expected) { } catch (NullPointerException expected) {
assertEquals("interceptor " + interceptor + " returned null", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo(
("interceptor " + interceptor + " returned null"));
} }
} }
@ -590,7 +587,8 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
fail(); fail();
} catch (NullPointerException expected) { } catch (NullPointerException expected) {
assertEquals("interceptor " + interceptor + " returned null", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo(
("interceptor " + interceptor + " returned null"));
} }
} }
@ -601,7 +599,7 @@ public final class InterceptorTest {
Interceptor interceptor = chain -> { Interceptor interceptor = chain -> {
Response response = chain.proceed(chain.request()); Response response = chain.proceed(chain.request());
assertNotNull(chain.connection()); assertThat(chain.connection()).isNotNull();
return response; return response;
}; };
@ -637,8 +635,8 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
fail(); fail();
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
assertEquals("interceptor " + interceptor + " returned a response with no body", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); ("interceptor " + interceptor + " returned a response with no body"));
} }
} }
@ -662,23 +660,23 @@ public final class InterceptorTest {
client.newCall(request).execute(); client.newCall(request).execute();
fail(); fail();
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
assertEquals("interceptor " + interceptor + " returned a response with no body", assertThat(expected.getMessage()).isEqualTo(
expected.getMessage()); ("interceptor " + interceptor + " returned a response with no body"));
} }
} }
@Test public void connectTimeout() throws Exception { @Test public void connectTimeout() throws Exception {
Interceptor interceptor1 = chainA -> { Interceptor interceptor1 = chainA -> {
assertEquals(5000, chainA.connectTimeoutMillis()); assertThat(chainA.connectTimeoutMillis()).isEqualTo(5000);
Interceptor.Chain chainB = chainA.withConnectTimeout(100, TimeUnit.MILLISECONDS); Interceptor.Chain chainB = chainA.withConnectTimeout(100, TimeUnit.MILLISECONDS);
assertEquals(100, chainB.connectTimeoutMillis()); assertThat(chainB.connectTimeoutMillis()).isEqualTo(100);
return chainB.proceed(chainA.request()); return chainB.proceed(chainA.request());
}; };
Interceptor interceptor2 = chain -> { Interceptor interceptor2 = chain -> {
assertEquals(100, chain.connectTimeoutMillis()); assertThat(chain.connectTimeoutMillis()).isEqualTo(100);
return chain.proceed(chain.request()); return chain.proceed(chain.request());
}; };
@ -713,16 +711,16 @@ public final class InterceptorTest {
@Test public void chainWithReadTimeout() throws Exception { @Test public void chainWithReadTimeout() throws Exception {
Interceptor interceptor1 = chainA -> { Interceptor interceptor1 = chainA -> {
assertEquals(5000, chainA.readTimeoutMillis()); assertThat(chainA.readTimeoutMillis()).isEqualTo(5000);
Interceptor.Chain chainB = chainA.withReadTimeout(100, TimeUnit.MILLISECONDS); Interceptor.Chain chainB = chainA.withReadTimeout(100, TimeUnit.MILLISECONDS);
assertEquals(100, chainB.readTimeoutMillis()); assertThat(chainB.readTimeoutMillis()).isEqualTo(100);
return chainB.proceed(chainA.request()); return chainB.proceed(chainA.request());
}; };
Interceptor interceptor2 = chain -> { Interceptor interceptor2 = chain -> {
assertEquals(100, chain.readTimeoutMillis()); assertThat(chain.readTimeoutMillis()).isEqualTo(100);
return chain.proceed(chain.request()); return chain.proceed(chain.request());
}; };
@ -751,16 +749,16 @@ public final class InterceptorTest {
@Test public void chainWithWriteTimeout() throws Exception { @Test public void chainWithWriteTimeout() throws Exception {
Interceptor interceptor1 = chainA -> { Interceptor interceptor1 = chainA -> {
assertEquals(5000, chainA.writeTimeoutMillis()); assertThat(chainA.writeTimeoutMillis()).isEqualTo(5000);
Interceptor.Chain chainB = chainA.withWriteTimeout(100, TimeUnit.MILLISECONDS); Interceptor.Chain chainB = chainA.withWriteTimeout(100, TimeUnit.MILLISECONDS);
assertEquals(100, chainB.writeTimeoutMillis()); assertThat(chainB.writeTimeoutMillis()).isEqualTo(100);
return chainB.proceed(chainA.request()); return chainB.proceed(chainA.request());
}; };
Interceptor interceptor2 = chain -> { Interceptor interceptor2 = chain -> {
assertEquals(100, chain.writeTimeoutMillis()); assertThat(chain.writeTimeoutMillis()).isEqualTo(100);
return chain.proceed(chain.request()); return chain.proceed(chain.request());
}; };
@ -795,9 +793,9 @@ public final class InterceptorTest {
Call call = chain.call(); Call call = chain.call();
callRef.set(call); callRef.set(call);
assertFalse(call.isCanceled()); assertThat(call.isCanceled()).isFalse();
call.cancel(); call.cancel();
assertTrue(call.isCanceled()); assertThat(call.isCanceled()).isTrue();
return chain.proceed(chain.request()); return chain.proceed(chain.request());
}; };
@ -817,7 +815,7 @@ public final class InterceptorTest {
} catch (IOException expected) { } catch (IOException expected) {
} }
assertSame(call, callRef.get()); assertThat(callRef.get()).isSameAs(call);
} }
private RequestBody uppercase(RequestBody original) { private RequestBody uppercase(RequestBody original) {

View File

@ -24,8 +24,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
/** /**
@ -55,13 +54,13 @@ public class MediaTypeTest {
@Test public void testParse() throws Exception { @Test public void testParse() throws Exception {
MediaType mediaType = parse("text/plain;boundary=foo;charset=utf-8"); MediaType mediaType = parse("text/plain;boundary=foo;charset=utf-8");
assertEquals("text", mediaType.type()); assertThat(mediaType.type()).isEqualTo("text");
assertEquals("plain", mediaType.subtype()); assertThat(mediaType.subtype()).isEqualTo("plain");
assertEquals("UTF-8", mediaType.charset().name()); assertThat(mediaType.charset().name()).isEqualTo("UTF-8");
assertEquals("text/plain;boundary=foo;charset=utf-8", mediaType.toString()); assertThat(mediaType.toString()).isEqualTo("text/plain;boundary=foo;charset=utf-8");
assertEquals(mediaType, parse("text/plain;boundary=foo;charset=utf-8")); assertThat(parse("text/plain;boundary=foo;charset=utf-8")).isEqualTo(mediaType);
assertEquals(mediaType.hashCode(), assertThat(parse("text/plain;boundary=foo;charset=utf-8").hashCode()).isEqualTo(
parse("text/plain;boundary=foo;charset=utf-8").hashCode()); (long) mediaType.hashCode());
} }
@Test public void testValidParse() throws Exception { @Test public void testValidParse() throws Exception {
@ -119,36 +118,36 @@ public class MediaTypeTest {
@Test public void testDoubleQuotesAreSpecial() throws Exception { @Test public void testDoubleQuotesAreSpecial() throws Exception {
MediaType mediaType = parse("text/plain;a=\";charset=utf-8;b=\""); MediaType mediaType = parse("text/plain;a=\";charset=utf-8;b=\"");
assertNull(mediaType.charset()); assertThat(mediaType.charset()).isNull();
} }
@Test public void testSingleQuotesAreNotSpecial() throws Exception { @Test public void testSingleQuotesAreNotSpecial() throws Exception {
MediaType mediaType = parse("text/plain;a=';charset=utf-8;b='"); MediaType mediaType = parse("text/plain;a=';charset=utf-8;b='");
assertEquals("UTF-8", mediaType.charset().name()); assertThat(mediaType.charset().name()).isEqualTo("UTF-8");
} }
@Test public void testParseWithSpecialCharacters() throws Exception { @Test public void testParseWithSpecialCharacters() throws Exception {
MediaType mediaType = parse("!#$%&'*+-.{|}~/!#$%&'*+-.{|}~; !#$%&'*+-.{|}~=!#$%&'*+-.{|}~"); MediaType mediaType = parse("!#$%&'*+-.{|}~/!#$%&'*+-.{|}~; !#$%&'*+-.{|}~=!#$%&'*+-.{|}~");
assertEquals("!#$%&'*+-.{|}~", mediaType.type()); assertThat(mediaType.type()).isEqualTo("!#$%&'*+-.{|}~");
assertEquals("!#$%&'*+-.{|}~", mediaType.subtype()); assertThat(mediaType.subtype()).isEqualTo("!#$%&'*+-.{|}~");
} }
@Test public void testCharsetIsOneOfManyParameters() throws Exception { @Test public void testCharsetIsOneOfManyParameters() throws Exception {
MediaType mediaType = parse("text/plain;a=1;b=2;charset=utf-8;c=3"); MediaType mediaType = parse("text/plain;a=1;b=2;charset=utf-8;c=3");
assertEquals("text", mediaType.type()); assertThat(mediaType.type()).isEqualTo("text");
assertEquals("plain", mediaType.subtype()); assertThat(mediaType.subtype()).isEqualTo("plain");
assertEquals("UTF-8", mediaType.charset().name()); assertThat(mediaType.charset().name()).isEqualTo("UTF-8");
} }
@Test public void testCharsetAndQuoting() throws Exception { @Test public void testCharsetAndQuoting() throws Exception {
MediaType mediaType = parse( MediaType mediaType = parse(
"text/plain;a=\";charset=us-ascii\";charset=\"utf-8\";b=\"iso-8859-1\""); "text/plain;a=\";charset=us-ascii\";charset=\"utf-8\";b=\"iso-8859-1\"");
assertEquals("UTF-8", mediaType.charset().name()); assertThat(mediaType.charset().name()).isEqualTo("UTF-8");
} }
@Test public void testDuplicatedCharsets() { @Test public void testDuplicatedCharsets() {
MediaType mediaType = parse("text/plain; charset=utf-8; charset=UTF-8"); MediaType mediaType = parse("text/plain; charset=utf-8; charset=UTF-8");
assertEquals("UTF-8", mediaType.charset().name()); assertThat(mediaType.charset().name()).isEqualTo("UTF-8");
} }
@Test public void testMultipleCharsets() { @Test public void testMultipleCharsets() {
@ -158,12 +157,12 @@ public class MediaTypeTest {
@Test public void testIllegalCharsetName() { @Test public void testIllegalCharsetName() {
MediaType mediaType = parse("text/plain; charset=\"!@#$%^&*()\""); MediaType mediaType = parse("text/plain; charset=\"!@#$%^&*()\"");
assertNull(mediaType.charset()); assertThat(mediaType.charset()).isNull();
} }
@Test public void testUnsupportedCharset() { @Test public void testUnsupportedCharset() {
MediaType mediaType = parse("text/plain; charset=utf-wtf"); MediaType mediaType = parse("text/plain; charset=utf-wtf");
assertNull(mediaType.charset()); assertThat(mediaType.charset()).isNull();
} }
/** /**
@ -172,39 +171,39 @@ public class MediaTypeTest {
*/ */
@Test public void testCharsetNameIsSingleQuoted() throws Exception { @Test public void testCharsetNameIsSingleQuoted() throws Exception {
MediaType mediaType = parse("text/plain;charset='utf-8'"); MediaType mediaType = parse("text/plain;charset='utf-8'");
assertEquals("UTF-8", mediaType.charset().name()); assertThat(mediaType.charset().name()).isEqualTo("UTF-8");
} }
@Test public void testCharsetNameIsDoubleQuotedAndSingleQuoted() throws Exception { @Test public void testCharsetNameIsDoubleQuotedAndSingleQuoted() throws Exception {
MediaType mediaType = parse("text/plain;charset=\"'utf-8'\""); MediaType mediaType = parse("text/plain;charset=\"'utf-8'\"");
assertNull(mediaType.charset()); assertThat(mediaType.charset()).isNull();
} }
@Test public void testCharsetNameIsDoubleQuotedSingleQuote() throws Exception { @Test public void testCharsetNameIsDoubleQuotedSingleQuote() throws Exception {
MediaType mediaType = parse("text/plain;charset=\"'\""); MediaType mediaType = parse("text/plain;charset=\"'\"");
assertNull(mediaType.charset()); assertThat(mediaType.charset()).isNull();
} }
@Test public void testDefaultCharset() throws Exception { @Test public void testDefaultCharset() throws Exception {
MediaType noCharset = parse("text/plain"); MediaType noCharset = parse("text/plain");
assertEquals("UTF-8", noCharset.charset(UTF_8).name()); assertThat(noCharset.charset(UTF_8).name()).isEqualTo("UTF-8");
assertEquals("US-ASCII", noCharset.charset(Charset.forName("US-ASCII")).name()); assertThat(noCharset.charset(Charset.forName("US-ASCII")).name()).isEqualTo("US-ASCII");
MediaType charset = parse("text/plain; charset=iso-8859-1"); MediaType charset = parse("text/plain; charset=iso-8859-1");
assertEquals("ISO-8859-1", charset.charset(UTF_8).name()); assertThat(charset.charset(UTF_8).name()).isEqualTo("ISO-8859-1");
assertEquals("ISO-8859-1", charset.charset(Charset.forName("US-ASCII")).name()); assertThat(charset.charset(Charset.forName("US-ASCII")).name()).isEqualTo("ISO-8859-1");
} }
@Test public void testParseDanglingSemicolon() throws Exception { @Test public void testParseDanglingSemicolon() throws Exception {
MediaType mediaType = parse("text/plain;"); MediaType mediaType = parse("text/plain;");
assertEquals("text", mediaType.type()); assertThat(mediaType.type()).isEqualTo("text");
assertEquals("plain", mediaType.subtype()); assertThat(mediaType.subtype()).isEqualTo("plain");
assertNull(mediaType.charset()); assertThat(mediaType.charset()).isNull();
assertEquals("text/plain;", mediaType.toString()); assertThat(mediaType.toString()).isEqualTo("text/plain;");
} }
private void assertMediaType(String string) { private void assertMediaType(String string) {
assertEquals(string, parse(string).toString()); assertThat(parse(string).toString()).isEqualTo(string);
} }
private void assertInvalid(String string, String exceptionMessage) { private void assertInvalid(String string, String exceptionMessage) {
@ -213,10 +212,10 @@ public class MediaTypeTest {
parse(string); parse(string);
fail("Expected get of \"" + string + "\" to throw with: " + exceptionMessage); fail("Expected get of \"" + string + "\" to throw with: " + exceptionMessage);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals(exceptionMessage, e.getMessage()); assertThat(e.getMessage()).isEqualTo(exceptionMessage);
} }
} else { } else {
assertNull(string, parse(string)); assertThat(parse(string)).overridingErrorMessage(string).isNull();
} }
} }
} }

View File

@ -21,7 +21,7 @@ import okio.BufferedSink;
import org.junit.Test; import org.junit.Test;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class MultipartBodyTest { public final class MultipartBodyTest {
@ -30,7 +30,7 @@ public final class MultipartBodyTest {
new MultipartBody.Builder().build(); new MultipartBody.Builder().build();
fail(); fail();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
assertEquals("Multipart body must have at least one part.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Multipart body must have at least one part.");
} }
} }
@ -46,16 +46,16 @@ public final class MultipartBodyTest {
.addPart(RequestBody.create(null, "Hello, World!")) .addPart(RequestBody.create(null, "Hello, World!"))
.build(); .build();
assertEquals("123", body.boundary()); assertThat(body.boundary()).isEqualTo("123");
assertEquals(MultipartBody.MIXED, body.type()); assertThat(body.type()).isEqualTo(MultipartBody.MIXED);
assertEquals("multipart/mixed; boundary=123", body.contentType().toString()); assertThat(body.contentType().toString()).isEqualTo("multipart/mixed; boundary=123");
assertEquals(1, body.parts().size()); assertThat(body.parts().size()).isEqualTo(1);
assertEquals(53, body.contentLength()); assertThat(body.contentLength()).isEqualTo(53);
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
body.writeTo(buffer); body.writeTo(buffer);
assertEquals(buffer.size(), body.contentLength()); assertThat(body.contentLength()).isEqualTo(buffer.size());
assertEquals(expected, buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo(expected);
} }
@Test public void threeParts() throws Exception { @Test public void threeParts() throws Exception {
@ -80,16 +80,16 @@ public final class MultipartBodyTest {
.addPart(RequestBody.create(null, "Fox")) .addPart(RequestBody.create(null, "Fox"))
.build(); .build();
assertEquals("123", body.boundary()); assertThat(body.boundary()).isEqualTo("123");
assertEquals(MultipartBody.MIXED, body.type()); assertThat(body.type()).isEqualTo(MultipartBody.MIXED);
assertEquals("multipart/mixed; boundary=123", body.contentType().toString()); assertThat(body.contentType().toString()).isEqualTo("multipart/mixed; boundary=123");
assertEquals(3, body.parts().size()); assertThat(body.parts().size()).isEqualTo(3);
assertEquals(112, body.contentLength()); assertThat(body.contentLength()).isEqualTo(112);
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
body.writeTo(buffer); body.writeTo(buffer);
assertEquals(buffer.size(), body.contentLength()); assertThat(body.contentLength()).isEqualTo(buffer.size());
assertEquals(expected, buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo(expected);
} }
@Test public void fieldAndTwoFiles() throws Exception { @Test public void fieldAndTwoFiles() throws Exception {
@ -140,16 +140,17 @@ public final class MultipartBodyTest {
.build()) .build())
.build(); .build();
assertEquals("AaB03x", body.boundary()); assertThat(body.boundary()).isEqualTo("AaB03x");
assertEquals(MultipartBody.FORM, body.type()); assertThat(body.type()).isEqualTo(MultipartBody.FORM);
assertEquals("multipart/form-data; boundary=AaB03x", body.contentType().toString()); assertThat(body.contentType().toString()).isEqualTo(
assertEquals(2, body.parts().size()); "multipart/form-data; boundary=AaB03x");
assertEquals(568, body.contentLength()); assertThat(body.parts().size()).isEqualTo(2);
assertThat(body.contentLength()).isEqualTo(568);
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
body.writeTo(buffer); body.writeTo(buffer);
assertEquals(buffer.size(), body.contentLength()); assertThat(body.contentLength()).isEqualTo(buffer.size());
assertEquals(expected, buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo(expected);
} }
@Test public void stringEscapingIsWeird() throws Exception { @Test public void stringEscapingIsWeird() throws Exception {
@ -188,7 +189,7 @@ public final class MultipartBodyTest {
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
body.writeTo(buffer); body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo(expected);
} }
@Test public void streamingPartHasNoLength() throws Exception { @Test public void streamingPartHasNoLength() throws Exception {
@ -228,15 +229,15 @@ public final class MultipartBodyTest {
.addPart(RequestBody.create(null, "Fox")) .addPart(RequestBody.create(null, "Fox"))
.build(); .build();
assertEquals("123", body.boundary()); assertThat(body.boundary()).isEqualTo("123");
assertEquals(MultipartBody.MIXED, body.type()); assertThat(body.type()).isEqualTo(MultipartBody.MIXED);
assertEquals("multipart/mixed; boundary=123", body.contentType().toString()); assertThat(body.contentType().toString()).isEqualTo("multipart/mixed; boundary=123");
assertEquals(3, body.parts().size()); assertThat(body.parts().size()).isEqualTo(3);
assertEquals(-1, body.contentLength()); assertThat(body.contentLength()).isEqualTo(-1);
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
body.writeTo(buffer); body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo(expected);
} }
@Test public void contentTypeHeaderIsForbidden() throws Exception { @Test public void contentTypeHeaderIsForbidden() throws Exception {
@ -263,13 +264,13 @@ public final class MultipartBodyTest {
MultipartBody body = new MultipartBody.Builder() MultipartBody body = new MultipartBody.Builder()
.addPart(Headers.of("Foo", "Bar"), RequestBody.create(null, "Baz")) .addPart(Headers.of("Foo", "Bar"), RequestBody.create(null, "Baz"))
.build(); .build();
assertEquals(1, body.parts().size()); assertThat(body.parts().size()).isEqualTo(1);
Buffer part1Buffer = new Buffer(); Buffer part1Buffer = new Buffer();
MultipartBody.Part part1 = body.part(0); MultipartBody.Part part1 = body.part(0);
part1.body().writeTo(part1Buffer); part1.body().writeTo(part1Buffer);
assertEquals(Headers.of("Foo", "Bar"), part1.headers()); assertThat(part1.headers()).isEqualTo(Headers.of("Foo", "Bar"));
assertEquals("Baz", part1Buffer.readUtf8()); assertThat(part1Buffer.readUtf8()).isEqualTo("Baz");
} }
@Test public void nonAsciiFilename() throws Exception { @Test public void nonAsciiFilename() throws Exception {
@ -290,6 +291,6 @@ public final class MultipartBodyTest {
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
body.writeTo(buffer); body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo(expected);
} }
} }

View File

@ -29,9 +29,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static okhttp3.TestUtil.defaultClient; import static okhttp3.TestUtil.defaultClient;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class OkHttpClientTest { public final class OkHttpClientTest {
@ -53,11 +51,11 @@ public final class OkHttpClientTest {
@Test public void durationDefaults() { @Test public void durationDefaults() {
OkHttpClient client = defaultClient(); OkHttpClient client = defaultClient();
assertEquals(0, client.callTimeoutMillis()); assertThat(client.callTimeoutMillis()).isEqualTo(0);
assertEquals(10_000, client.connectTimeoutMillis()); assertThat(client.connectTimeoutMillis()).isEqualTo(10_000);
assertEquals(10_000, client.readTimeoutMillis()); assertThat(client.readTimeoutMillis()).isEqualTo(10_000);
assertEquals(10_000, client.writeTimeoutMillis()); assertThat(client.writeTimeoutMillis()).isEqualTo(10_000);
assertEquals(0, client.pingIntervalMillis()); assertThat(client.pingIntervalMillis()).isEqualTo(0);
} }
@Test public void timeoutValidRange() { @Test public void timeoutValidRange() {
@ -103,8 +101,8 @@ public final class OkHttpClientTest {
.addInterceptor(interceptor) .addInterceptor(interceptor)
.addNetworkInterceptor(interceptor) .addNetworkInterceptor(interceptor)
.build(); .build();
assertEquals(0, original.interceptors().size()); assertThat(original.interceptors().size()).isEqualTo(0);
assertEquals(0, original.networkInterceptors().size()); assertThat(original.networkInterceptors().size()).isEqualTo(0);
} }
/** /**
@ -116,15 +114,15 @@ public final class OkHttpClientTest {
// Values should be non-null. // Values should be non-null.
OkHttpClient a = client.newBuilder().build(); OkHttpClient a = client.newBuilder().build();
assertNotNull(a.dispatcher()); assertThat(a.dispatcher()).isNotNull();
assertNotNull(a.connectionPool()); assertThat(a.connectionPool()).isNotNull();
assertNotNull(a.sslSocketFactory()); assertThat(a.sslSocketFactory()).isNotNull();
// Multiple clients share the instances. // Multiple clients share the instances.
OkHttpClient b = client.newBuilder().build(); OkHttpClient b = client.newBuilder().build();
assertSame(a.dispatcher(), b.dispatcher()); assertThat(b.dispatcher()).isSameAs(a.dispatcher());
assertSame(a.connectionPool(), b.connectionPool()); assertThat(b.connectionPool()).isSameAs(a.connectionPool());
assertSame(a.sslSocketFactory(), b.sslSocketFactory()); assertThat(b.sslSocketFactory()).isSameAs(a.sslSocketFactory());
} }
@Test public void setProtocolsRejectsHttp10() throws Exception { @Test public void setProtocolsRejectsHttp10() throws Exception {
@ -139,7 +137,7 @@ public final class OkHttpClientTest {
@Test public void certificatePinnerEquality() { @Test public void certificatePinnerEquality() {
OkHttpClient clientA = TestUtil.defaultClient(); OkHttpClient clientA = TestUtil.defaultClient();
OkHttpClient clientB = TestUtil.defaultClient(); OkHttpClient clientB = TestUtil.defaultClient();
assertEquals(clientA.certificatePinner(), clientB.certificatePinner()); assertThat(clientB.certificatePinner()).isEqualTo(clientA.certificatePinner());
} }
@Test public void nullInterceptor() { @Test public void nullInterceptor() {
@ -148,7 +146,7 @@ public final class OkHttpClientTest {
builder.addInterceptor(null); builder.addInterceptor(null);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("interceptor == null", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("interceptor == null");
} }
} }
@ -158,7 +156,7 @@ public final class OkHttpClientTest {
builder.addNetworkInterceptor(null); builder.addNetworkInterceptor(null);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("interceptor == null", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("interceptor == null");
} }
} }
@ -169,7 +167,7 @@ public final class OkHttpClientTest {
builder.build(); builder.build();
fail(); fail();
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
assertEquals("Null interceptor: [null]", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("Null interceptor: [null]");
} }
} }
@ -180,7 +178,7 @@ public final class OkHttpClientTest {
builder.build(); builder.build();
fail(); fail();
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
assertEquals("Null network interceptor: [null]", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("Null network interceptor: [null]");
} }
} }
@ -190,8 +188,9 @@ public final class OkHttpClientTest {
.protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)); .protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1));
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("protocols containing h2_prior_knowledge cannot use other protocols: " assertThat(expected.getMessage()).isEqualTo(
+ "[h2_prior_knowledge, http/1.1]", expected.getMessage()); ("protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, http/1.1]"));
} }
} }
@ -201,8 +200,9 @@ public final class OkHttpClientTest {
.protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)); .protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE));
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("protocols containing h2_prior_knowledge cannot use other protocols: " assertThat(expected.getMessage()).isEqualTo(
+ "[h2_prior_knowledge, h2_prior_knowledge]", expected.getMessage()); ("protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, h2_prior_knowledge]"));
} }
} }
@ -210,8 +210,8 @@ public final class OkHttpClientTest {
OkHttpClient okHttpClient = new OkHttpClient.Builder() OkHttpClient okHttpClient = new OkHttpClient.Builder()
.protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)) .protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE))
.build(); .build();
assertEquals(1, okHttpClient.protocols().size()); assertThat(okHttpClient.protocols().size()).isEqualTo(1);
assertEquals(Protocol.H2_PRIOR_KNOWLEDGE, okHttpClient.protocols().get(0)); assertThat(okHttpClient.protocols().get(0)).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE);
} }
@Test public void nullDefaultProxySelector() throws Exception { @Test public void nullDefaultProxySelector() throws Exception {
@ -224,7 +224,7 @@ public final class OkHttpClientTest {
Request request = new Request.Builder().url(server.url("/")).build(); Request request = new Request.Builder().url(server.url("/")).build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertEquals("abc", response.body().string()); assertThat(response.body().string()).isEqualTo("abc");
} }
@Test public void sslSocketFactorySetAsSocketFactory() throws Exception { @Test public void sslSocketFactorySetAsSocketFactory() throws Exception {

View File

@ -18,17 +18,17 @@ package okhttp3;
import java.io.IOException; import java.io.IOException;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public class ProtocolTest { public class ProtocolTest {
@Test @Test
public void testGetKnown() throws IOException { public void testGetKnown() throws IOException {
assertEquals(Protocol.HTTP_1_0, Protocol.get("http/1.0")); assertThat(Protocol.get("http/1.0")).isEqualTo(Protocol.HTTP_1_0);
assertEquals(Protocol.HTTP_1_1, Protocol.get("http/1.1")); assertThat(Protocol.get("http/1.1")).isEqualTo(Protocol.HTTP_1_1);
assertEquals(Protocol.SPDY_3, Protocol.get("spdy/3.1")); assertThat(Protocol.get("spdy/3.1")).isEqualTo(Protocol.SPDY_3);
assertEquals(Protocol.HTTP_2, Protocol.get("h2")); assertThat(Protocol.get("h2")).isEqualTo(Protocol.HTTP_2);
assertEquals(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.get("h2_prior_knowledge")); assertThat(Protocol.get("h2_prior_knowledge")).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE);
assertEquals(Protocol.QUIC, Protocol.get("quic")); assertThat(Protocol.get("quic")).isEqualTo(Protocol.QUIC);
} }
@Test(expected = IOException.class) @Test(expected = IOException.class)
@ -38,11 +38,11 @@ public class ProtocolTest {
@Test @Test
public void testToString() throws IOException { public void testToString() throws IOException {
assertEquals("http/1.0", Protocol.HTTP_1_0.toString()); assertThat(Protocol.HTTP_1_0.toString()).isEqualTo("http/1.0");
assertEquals("http/1.1", Protocol.HTTP_1_1.toString()); assertThat(Protocol.HTTP_1_1.toString()).isEqualTo("http/1.1");
assertEquals("spdy/3.1", Protocol.SPDY_3.toString()); assertThat(Protocol.SPDY_3.toString()).isEqualTo("spdy/3.1");
assertEquals("h2", Protocol.HTTP_2.toString()); assertThat(Protocol.HTTP_2.toString()).isEqualTo("h2");
assertEquals("h2_prior_knowledge", Protocol.H2_PRIOR_KNOWLEDGE.toString()); assertThat(Protocol.H2_PRIOR_KNOWLEDGE.toString()).isEqualTo("h2_prior_knowledge");
assertEquals("quic", Protocol.QUIC.toString()); assertThat(Protocol.QUIC.toString()).isEqualTo("quic");
} }
} }

View File

@ -21,11 +21,7 @@ import java.util.Arrays;
import java.util.Date; import java.util.Date;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/** /**
* A received response or failure recorded by the response recorder. * A received response or failure recorded by the response recorder.
@ -47,58 +43,58 @@ public final class RecordedResponse {
} }
public RecordedResponse assertRequestUrl(HttpUrl url) { public RecordedResponse assertRequestUrl(HttpUrl url) {
assertEquals(url, request.url()); assertThat(request.url()).isEqualTo(url);
return this; return this;
} }
public RecordedResponse assertRequestMethod(String method) { public RecordedResponse assertRequestMethod(String method) {
assertEquals(method, request.method()); assertThat(request.method()).isEqualTo(method);
return this; return this;
} }
public RecordedResponse assertRequestHeader(String name, String... values) { public RecordedResponse assertRequestHeader(String name, String... values) {
assertEquals(Arrays.asList(values), request.headers(name)); assertThat(request.headers(name)).isEqualTo(Arrays.asList(values));
return this; return this;
} }
public RecordedResponse assertCode(int expectedCode) { public RecordedResponse assertCode(int expectedCode) {
assertEquals(expectedCode, response.code()); assertThat(response.code()).isEqualTo(expectedCode);
return this; return this;
} }
public RecordedResponse assertSuccessful() { public RecordedResponse assertSuccessful() {
assertTrue(response.isSuccessful()); assertThat(response.isSuccessful()).isTrue();
return this; return this;
} }
public RecordedResponse assertNotSuccessful() { public RecordedResponse assertNotSuccessful() {
assertFalse(response.isSuccessful()); assertThat(response.isSuccessful()).isFalse();
return this; return this;
} }
public RecordedResponse assertHeader(String name, String... values) { public RecordedResponse assertHeader(String name, String... values) {
assertEquals(Arrays.asList(values), response.headers(name)); assertThat(response.headers(name)).isEqualTo(Arrays.asList(values));
return this; return this;
} }
public RecordedResponse assertHeaders(Headers headers) { public RecordedResponse assertHeaders(Headers headers) {
assertEquals(headers, response.headers()); assertThat(response.headers()).isEqualTo(headers);
return this; return this;
} }
public RecordedResponse assertBody(String expectedBody) { public RecordedResponse assertBody(String expectedBody) {
assertEquals(expectedBody, body); assertThat(body).isEqualTo(expectedBody);
return this; return this;
} }
public RecordedResponse assertHandshake() { public RecordedResponse assertHandshake() {
Handshake handshake = response.handshake(); Handshake handshake = response.handshake();
assertNotNull(handshake.tlsVersion()); assertThat(handshake.tlsVersion()).isNotNull();
assertNotNull(handshake.cipherSuite()); assertThat(handshake.cipherSuite()).isNotNull();
assertNotNull(handshake.peerPrincipal()); assertThat(handshake.peerPrincipal()).isNotNull();
assertEquals(1, handshake.peerCertificates().size()); assertThat(handshake.peerCertificates().size()).isEqualTo(1);
assertNull(handshake.localPrincipal()); assertThat(handshake.localPrincipal()).isNull();
assertEquals(0, handshake.localCertificates().size()); assertThat(handshake.localCertificates().size()).isEqualTo(0);
return this; return this;
} }
@ -107,8 +103,8 @@ public final class RecordedResponse {
*/ */
public RecordedResponse priorResponse() { public RecordedResponse priorResponse() {
Response priorResponse = response.priorResponse(); Response priorResponse = response.priorResponse();
assertNotNull(priorResponse); assertThat(priorResponse).isNotNull();
assertNull(priorResponse.body()); assertThat(priorResponse.body()).isNull();
return new RecordedResponse(priorResponse.request(), priorResponse, null, null, null); return new RecordedResponse(priorResponse.request(), priorResponse, null, null, null);
} }
@ -117,20 +113,20 @@ public final class RecordedResponse {
*/ */
public RecordedResponse networkResponse() { public RecordedResponse networkResponse() {
Response networkResponse = response.networkResponse(); Response networkResponse = response.networkResponse();
assertNotNull(networkResponse); assertThat(networkResponse).isNotNull();
assertNull(networkResponse.body()); assertThat(networkResponse.body()).isNull();
return new RecordedResponse(networkResponse.request(), networkResponse, null, null, null); return new RecordedResponse(networkResponse.request(), networkResponse, null, null, null);
} }
/** Asserts that the current response didn't use the network. */ /** Asserts that the current response didn't use the network. */
public RecordedResponse assertNoNetworkResponse() { public RecordedResponse assertNoNetworkResponse() {
assertNull(response.networkResponse()); assertThat(response.networkResponse()).isNull();
return this; return this;
} }
/** Asserts that the current response didn't use the cache. */ /** Asserts that the current response didn't use the cache. */
public RecordedResponse assertNoCacheResponse() { public RecordedResponse assertNoCacheResponse() {
assertNull(response.cacheResponse()); assertThat(response.cacheResponse()).isNull();
return this; return this;
} }
@ -139,8 +135,8 @@ public final class RecordedResponse {
*/ */
public RecordedResponse cacheResponse() { public RecordedResponse cacheResponse() {
Response cacheResponse = response.cacheResponse(); Response cacheResponse = response.cacheResponse();
assertNotNull(cacheResponse); assertThat(cacheResponse).isNotNull();
assertNull(cacheResponse.body()); assertThat(cacheResponse.body()).isNull();
return new RecordedResponse(cacheResponse.request(), cacheResponse, null, null, null); return new RecordedResponse(cacheResponse.request(), cacheResponse, null, null, null);
} }
@ -152,19 +148,20 @@ public final class RecordedResponse {
break; break;
} }
} }
assertTrue("Expected exception type among " + Arrays.toString(allowedExceptionTypes) assertThat(found).overridingErrorMessage("Expected exception type among " + Arrays.toString(allowedExceptionTypes)
+ ", got " + failure, found); + ", got " + failure).isTrue();
return this; return this;
} }
public RecordedResponse assertFailure(String... messages) { public RecordedResponse assertFailure(String... messages) {
assertNotNull("No failure found", failure); assertThat(failure).overridingErrorMessage("No failure found").isNotNull();
assertTrue(failure.getMessage(), Arrays.asList(messages).contains(failure.getMessage())); assertThat(Arrays.asList(messages).contains(failure.getMessage())).overridingErrorMessage(
failure.getMessage()).isTrue();
return this; return this;
} }
public RecordedResponse assertFailureMatches(String... patterns) { public RecordedResponse assertFailureMatches(String... patterns) {
assertNotNull(failure); assertThat(failure).isNotNull();
for (String pattern : patterns) { for (String pattern : patterns) {
if (failure.getMessage().matches(pattern)) return this; if (failure.getMessage().matches(pattern)) return this;
} }
@ -182,8 +179,10 @@ public final class RecordedResponse {
} }
private void assertDateInRange(long minimum, long actual, long maximum) { private void assertDateInRange(long minimum, long actual, long maximum) {
assertTrue("actual " + format(actual) + " < minimum " + format(maximum), actual >= minimum); assertThat(actual >= minimum).overridingErrorMessage(
assertTrue("actual " + format(actual) + " > maximum " + format(minimum), actual <= maximum); "actual " + format(actual) + " < minimum " + format(maximum)).isTrue();
assertThat(actual <= maximum).overridingErrorMessage(
"actual " + format(actual) + " > maximum " + format(minimum)).isTrue();
} }
private String format(long time) { private String format(long time) {

View File

@ -26,8 +26,7 @@ import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedDeque;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static org.junit.Assert.assertFalse; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public final class RecordingEventListener extends EventListener { public final class RecordingEventListener extends EventListener {
final Deque<CallEvent> eventSequence = new ConcurrentLinkedDeque<>(); final Deque<CallEvent> eventSequence = new ConcurrentLinkedDeque<>();
@ -66,14 +65,14 @@ public final class RecordingEventListener extends EventListener {
private void logEvent(CallEvent e) { private void logEvent(CallEvent e) {
for (Object lock : forbiddenLocks) { for (Object lock : forbiddenLocks) {
assertFalse(lock.toString(), Thread.holdsLock(lock)); assertThat(Thread.holdsLock(lock)).overridingErrorMessage(lock.toString()).isFalse();
} }
CallEvent startEvent = e.closes(); CallEvent startEvent = e.closes();
if (startEvent != null) { if (startEvent != null) {
assertTrue(e.getName() + " without matching " + startEvent.getName(), assertThat(eventSequence.contains(startEvent)).overridingErrorMessage(
eventSequence.contains(startEvent)); e.getName() + " without matching " + startEvent.getName()).isTrue();
} }
eventSequence.offer(e); eventSequence.offer(e);

View File

@ -19,60 +19,59 @@ import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.UUID; import java.util.UUID;
import okio.Buffer; import okio.Buffer;
import org.junit.Test; import org.junit.Test;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class RequestTest { public final class RequestTest {
@Test public void string() throws Exception { @Test public void string() throws Exception {
MediaType contentType = MediaType.get("text/plain; charset=utf-8"); MediaType contentType = MediaType.get("text/plain; charset=utf-8");
RequestBody body = RequestBody.create(contentType, "abc".getBytes(UTF_8)); RequestBody body = RequestBody.create(contentType, "abc".getBytes(UTF_8));
assertEquals(contentType, body.contentType()); assertThat(body.contentType()).isEqualTo(contentType);
assertEquals(3, body.contentLength()); assertThat(body.contentLength()).isEqualTo(3);
assertEquals("616263", bodyToHex(body)); assertThat(bodyToHex(body)).isEqualTo("616263");
assertEquals("Retransmit body", "616263", bodyToHex(body)); assertThat(bodyToHex(body)).overridingErrorMessage("Retransmit body").isEqualTo(
"616263");
} }
@Test public void stringWithDefaultCharsetAdded() throws Exception { @Test public void stringWithDefaultCharsetAdded() throws Exception {
MediaType contentType = MediaType.get("text/plain"); MediaType contentType = MediaType.get("text/plain");
RequestBody body = RequestBody.create(contentType, "\u0800"); RequestBody body = RequestBody.create(contentType, "\u0800");
assertEquals(MediaType.get("text/plain; charset=utf-8"), body.contentType()); assertThat(body.contentType()).isEqualTo(MediaType.get("text/plain; charset=utf-8"));
assertEquals(3, body.contentLength()); assertThat(body.contentLength()).isEqualTo(3);
assertEquals("e0a080", bodyToHex(body)); assertThat(bodyToHex(body)).isEqualTo("e0a080");
} }
@Test public void stringWithNonDefaultCharsetSpecified() throws Exception { @Test public void stringWithNonDefaultCharsetSpecified() throws Exception {
MediaType contentType = MediaType.get("text/plain; charset=utf-16be"); MediaType contentType = MediaType.get("text/plain; charset=utf-16be");
RequestBody body = RequestBody.create(contentType, "\u0800"); RequestBody body = RequestBody.create(contentType, "\u0800");
assertEquals(contentType, body.contentType()); assertThat(body.contentType()).isEqualTo(contentType);
assertEquals(2, body.contentLength()); assertThat(body.contentLength()).isEqualTo(2);
assertEquals("0800", bodyToHex(body)); assertThat(bodyToHex(body)).isEqualTo("0800");
} }
@Test public void byteArray() throws Exception { @Test public void byteArray() throws Exception {
MediaType contentType = MediaType.get("text/plain"); MediaType contentType = MediaType.get("text/plain");
RequestBody body = RequestBody.create(contentType, "abc".getBytes(UTF_8)); RequestBody body = RequestBody.create(contentType, "abc".getBytes(UTF_8));
assertEquals(contentType, body.contentType()); assertThat(body.contentType()).isEqualTo(contentType);
assertEquals(3, body.contentLength()); assertThat(body.contentLength()).isEqualTo(3);
assertEquals("616263", bodyToHex(body)); assertThat(bodyToHex(body)).isEqualTo("616263");
assertEquals("Retransmit body", "616263", bodyToHex(body)); assertThat(bodyToHex(body)).overridingErrorMessage("Retransmit body").isEqualTo(
"616263");
} }
@Test public void byteArrayRange() throws Exception { @Test public void byteArrayRange() throws Exception {
MediaType contentType = MediaType.get("text/plain"); MediaType contentType = MediaType.get("text/plain");
RequestBody body = RequestBody.create(contentType, ".abcd".getBytes(UTF_8), 1, 3); RequestBody body = RequestBody.create(contentType, ".abcd".getBytes(UTF_8), 1, 3);
assertEquals(contentType, body.contentType()); assertThat(body.contentType()).isEqualTo(contentType);
assertEquals(3, body.contentLength()); assertThat(body.contentLength()).isEqualTo(3);
assertEquals("616263", bodyToHex(body)); assertThat(bodyToHex(body)).isEqualTo("616263");
assertEquals("Retransmit body", "616263", bodyToHex(body)); assertThat(bodyToHex(body)).overridingErrorMessage("Retransmit body").isEqualTo(
"616263");
} }
@Test public void file() throws Exception { @Test public void file() throws Exception {
@ -83,10 +82,11 @@ public final class RequestTest {
MediaType contentType = MediaType.get("text/plain"); MediaType contentType = MediaType.get("text/plain");
RequestBody body = RequestBody.create(contentType, file); RequestBody body = RequestBody.create(contentType, file);
assertEquals(contentType, body.contentType()); assertThat(body.contentType()).isEqualTo(contentType);
assertEquals(3, body.contentLength()); assertThat(body.contentLength()).isEqualTo(3);
assertEquals("616263", bodyToHex(body)); assertThat(bodyToHex(body)).isEqualTo("616263");
assertEquals("Retransmit body", "616263", bodyToHex(body)); assertThat(bodyToHex(body)).overridingErrorMessage("Retransmit body").isEqualTo(
"616263");
} }
/** Common verbs used for apis such as GitHub, AWS, and Google Cloud. */ /** Common verbs used for apis such as GitHub, AWS, and Google Cloud. */
@ -95,48 +95,50 @@ public final class RequestTest {
RequestBody body = RequestBody.create(contentType, "{}"); RequestBody body = RequestBody.create(contentType, "{}");
Request get = new Request.Builder().url("http://localhost/api").get().build(); Request get = new Request.Builder().url("http://localhost/api").get().build();
assertEquals("GET", get.method()); assertThat(get.method()).isEqualTo("GET");
assertNull(get.body()); assertThat(get.body()).isNull();
Request head = new Request.Builder().url("http://localhost/api").head().build(); Request head = new Request.Builder().url("http://localhost/api").head().build();
assertEquals("HEAD", head.method()); assertThat(head.method()).isEqualTo("HEAD");
assertNull(head.body()); assertThat(head.body()).isNull();
Request delete = new Request.Builder().url("http://localhost/api").delete().build(); Request delete = new Request.Builder().url("http://localhost/api").delete().build();
assertEquals("DELETE", delete.method()); assertThat(delete.method()).isEqualTo("DELETE");
assertEquals(0L, delete.body().contentLength()); assertThat(delete.body().contentLength()).isEqualTo(0L);
Request post = new Request.Builder().url("http://localhost/api").post(body).build(); Request post = new Request.Builder().url("http://localhost/api").post(body).build();
assertEquals("POST", post.method()); assertThat(post.method()).isEqualTo("POST");
assertEquals(body, post.body()); assertThat(post.body()).isEqualTo(body);
Request put = new Request.Builder().url("http://localhost/api").put(body).build(); Request put = new Request.Builder().url("http://localhost/api").put(body).build();
assertEquals("PUT", put.method()); assertThat(put.method()).isEqualTo("PUT");
assertEquals(body, put.body()); assertThat(put.body()).isEqualTo(body);
Request patch = new Request.Builder().url("http://localhost/api").patch(body).build(); Request patch = new Request.Builder().url("http://localhost/api").patch(body).build();
assertEquals("PATCH", patch.method()); assertThat(patch.method()).isEqualTo("PATCH");
assertEquals(body, patch.body()); assertThat(patch.body()).isEqualTo(body);
} }
@Test public void uninitializedURI() throws Exception { @Test public void uninitializedURI() throws Exception {
Request request = new Request.Builder().url("http://localhost/api").build(); Request request = new Request.Builder().url("http://localhost/api").build();
assertEquals(new URI("http://localhost/api"), request.url().uri()); assertThat(request.url().uri()).isEqualTo(new URI("http://localhost/api"));
assertEquals(HttpUrl.get("http://localhost/api"), request.url()); assertThat(request.url()).isEqualTo(HttpUrl.get("http://localhost/api"));
} }
@Test public void newBuilderUrlResetsUrl() { @Test public void newBuilderUrlResetsUrl() {
Request requestWithoutCache = new Request.Builder().url("http://localhost/api").build(); Request requestWithoutCache = new Request.Builder().url("http://localhost/api").build();
Request builtRequestWithoutCache = Request builtRequestWithoutCache =
requestWithoutCache.newBuilder().url("http://localhost/api/foo").build(); requestWithoutCache.newBuilder().url("http://localhost/api/foo").build();
assertEquals(HttpUrl.get("http://localhost/api/foo"), builtRequestWithoutCache.url()); assertThat(builtRequestWithoutCache.url()).isEqualTo(
HttpUrl.get("http://localhost/api/foo"));
Request requestWithCache = new Request.Builder().url("http://localhost/api").build(); Request requestWithCache = new Request.Builder().url("http://localhost/api").build();
// cache url object // cache url object
requestWithCache.url(); requestWithCache.url();
Request builtRequestWithCache = requestWithCache.newBuilder().url( Request builtRequestWithCache = requestWithCache.newBuilder().url(
"http://localhost/api/foo").build(); "http://localhost/api/foo").build();
assertEquals(HttpUrl.get("http://localhost/api/foo"), builtRequestWithCache.url()); assertThat(builtRequestWithCache.url()).isEqualTo(
HttpUrl.get("http://localhost/api/foo"));
} }
@Test public void cacheControl() { @Test public void cacheControl() {
@ -144,7 +146,7 @@ public final class RequestTest {
.cacheControl(new CacheControl.Builder().noCache().build()) .cacheControl(new CacheControl.Builder().noCache().build())
.url("https://square.com") .url("https://square.com")
.build(); .build();
assertEquals(Arrays.asList("no-cache"), request.headers("Cache-Control")); assertThat(request.headers("Cache-Control")).containsExactly("no-cache");
} }
@Test public void emptyCacheControlClearsAllCacheControlHeaders() { @Test public void emptyCacheControlClearsAllCacheControlHeaders() {
@ -153,7 +155,7 @@ public final class RequestTest {
.cacheControl(new CacheControl.Builder().build()) .cacheControl(new CacheControl.Builder().build())
.url("https://square.com") .url("https://square.com")
.build(); .build();
assertEquals(Collections.<String>emptyList(), request.headers("Cache-Control")); assertThat(request.headers("Cache-Control")).isEmpty();
} }
@Test public void headerAcceptsPermittedCharacters() { @Test public void headerAcceptsPermittedCharacters() {
@ -248,10 +250,10 @@ public final class RequestTest {
Request request = new Request.Builder() Request request = new Request.Builder()
.url("https://square.com") .url("https://square.com")
.build(); .build();
assertNull(request.tag()); assertThat(request.tag()).isNull();
assertNull(request.tag(Object.class)); assertThat(request.tag(Object.class)).isNull();
assertNull(request.tag(UUID.class)); assertThat(request.tag(UUID.class)).isNull();
assertNull(request.tag(String.class)); assertThat(request.tag(String.class)).isNull();
} }
@Test public void defaultTag() { @Test public void defaultTag() {
@ -260,10 +262,10 @@ public final class RequestTest {
.url("https://square.com") .url("https://square.com")
.tag(tag) .tag(tag)
.build(); .build();
assertSame(tag, request.tag()); assertThat(request.tag()).isSameAs(tag);
assertSame(tag, request.tag(Object.class)); assertThat(request.tag(Object.class)).isSameAs(tag);
assertNull(request.tag(UUID.class)); assertThat(request.tag(UUID.class)).isNull();
assertNull(request.tag(String.class)); assertThat(request.tag(String.class)).isNull();
} }
@Test public void nullRemovesTag() { @Test public void nullRemovesTag() {
@ -272,7 +274,7 @@ public final class RequestTest {
.tag("a") .tag("a")
.tag(null) .tag(null)
.build(); .build();
assertNull(request.tag()); assertThat(request.tag()).isNull();
} }
@Test public void removeAbsentTag() { @Test public void removeAbsentTag() {
@ -280,7 +282,7 @@ public final class RequestTest {
.url("https://square.com") .url("https://square.com")
.tag(null) .tag(null)
.build(); .build();
assertNull(request.tag()); assertThat(request.tag()).isNull();
} }
@Test public void objectTag() { @Test public void objectTag() {
@ -289,10 +291,10 @@ public final class RequestTest {
.url("https://square.com") .url("https://square.com")
.tag(Object.class, tag) .tag(Object.class, tag)
.build(); .build();
assertSame(tag, request.tag()); assertThat(request.tag()).isSameAs(tag);
assertSame(tag, request.tag(Object.class)); assertThat(request.tag(Object.class)).isSameAs(tag);
assertNull(request.tag(UUID.class)); assertThat(request.tag(UUID.class)).isNull();
assertNull(request.tag(String.class)); assertThat(request.tag(String.class)).isNull();
} }
@Test public void typedTag() { @Test public void typedTag() {
@ -301,10 +303,10 @@ public final class RequestTest {
.url("https://square.com") .url("https://square.com")
.tag(UUID.class, uuidTag) .tag(UUID.class, uuidTag)
.build(); .build();
assertNull(request.tag()); assertThat(request.tag()).isNull();
assertNull(request.tag(Object.class)); assertThat(request.tag(Object.class)).isNull();
assertSame(uuidTag, request.tag(UUID.class)); assertThat(request.tag(UUID.class)).isSameAs(uuidTag);
assertNull(request.tag(String.class)); assertThat(request.tag(String.class)).isNull();
} }
@Test public void replaceOnlyTag() { @Test public void replaceOnlyTag() {
@ -315,7 +317,7 @@ public final class RequestTest {
.tag(UUID.class, uuidTag1) .tag(UUID.class, uuidTag1)
.tag(UUID.class, uuidTag2) .tag(UUID.class, uuidTag2)
.build(); .build();
assertSame(uuidTag2, request.tag(UUID.class)); assertThat(request.tag(UUID.class)).isSameAs(uuidTag2);
} }
@Test public void multipleTags() { @Test public void multipleTags() {
@ -330,11 +332,11 @@ public final class RequestTest {
.tag(String.class, stringTag) .tag(String.class, stringTag)
.tag(Long.class, longTag) .tag(Long.class, longTag)
.build(); .build();
assertSame(objectTag, request.tag()); assertThat(request.tag()).isSameAs(objectTag);
assertSame(objectTag, request.tag(Object.class)); assertThat(request.tag(Object.class)).isSameAs(objectTag);
assertSame(uuidTag, request.tag(UUID.class)); assertThat(request.tag(UUID.class)).isSameAs(uuidTag);
assertSame(stringTag, request.tag(String.class)); assertThat(request.tag(String.class)).isSameAs(stringTag);
assertSame(longTag, request.tag(Long.class)); assertThat(request.tag(Long.class)).isSameAs(longTag);
} }
/** Confirm that we don't accidentally share the backing map between objects. */ /** Confirm that we don't accidentally share the backing map between objects. */
@ -344,9 +346,9 @@ public final class RequestTest {
Request requestA = builder.tag(String.class, "a").build(); Request requestA = builder.tag(String.class, "a").build();
Request requestB = builder.tag(String.class, "b").build(); Request requestB = builder.tag(String.class, "b").build();
Request requestC = requestA.newBuilder().tag(String.class, "c").build(); Request requestC = requestA.newBuilder().tag(String.class, "c").build();
assertSame("a", requestA.tag(String.class)); assertThat(requestA.tag(String.class)).isSameAs("a");
assertSame("b", requestB.tag(String.class)); assertThat(requestB.tag(String.class)).isSameAs("b");
assertSame("c", requestC.tag(String.class)); assertThat(requestC.tag(String.class)).isSameAs("c");
} }
private String bodyToHex(RequestBody body) throws IOException { private String bodyToHex(RequestBody body) throws IOException {

View File

@ -28,59 +28,58 @@ import okio.Okio;
import org.junit.Test; import org.junit.Test;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class ResponseBodyTest { public final class ResponseBodyTest {
@Test public void stringEmpty() throws IOException { @Test public void stringEmpty() throws IOException {
ResponseBody body = body(""); ResponseBody body = body("");
assertEquals("", body.string()); assertThat(body.string()).isEqualTo("");
} }
@Test public void stringLooksLikeBomButTooShort() throws IOException { @Test public void stringLooksLikeBomButTooShort() throws IOException {
ResponseBody body = body("000048"); ResponseBody body = body("000048");
assertEquals("\0\0H", body.string()); assertThat(body.string()).isEqualTo("\0\0H");
} }
@Test public void stringDefaultsToUtf8() throws IOException { @Test public void stringDefaultsToUtf8() throws IOException {
ResponseBody body = body("68656c6c6f"); ResponseBody body = body("68656c6c6f");
assertEquals("hello", body.string()); assertThat(body.string()).isEqualTo("hello");
} }
@Test public void stringExplicitCharset() throws IOException { @Test public void stringExplicitCharset() throws IOException {
ResponseBody body = body("00000068000000650000006c0000006c0000006f", "utf-32be"); ResponseBody body = body("00000068000000650000006c0000006c0000006f", "utf-32be");
assertEquals("hello", body.string()); assertThat(body.string()).isEqualTo("hello");
} }
@Test public void stringBomOverridesExplicitCharset() throws IOException { @Test public void stringBomOverridesExplicitCharset() throws IOException {
ResponseBody body = body("0000ffff00000068000000650000006c0000006c0000006f", "utf-8"); ResponseBody body = body("0000ffff00000068000000650000006c0000006c0000006f", "utf-8");
assertEquals("hello", body.string()); assertThat(body.string()).isEqualTo("hello");
} }
@Test public void stringBomUtf8() throws IOException { @Test public void stringBomUtf8() throws IOException {
ResponseBody body = body("efbbbf68656c6c6f"); ResponseBody body = body("efbbbf68656c6c6f");
assertEquals("hello", body.string()); assertThat(body.string()).isEqualTo("hello");
} }
@Test public void stringBomUtf16Be() throws IOException { @Test public void stringBomUtf16Be() throws IOException {
ResponseBody body = body("feff00680065006c006c006f"); ResponseBody body = body("feff00680065006c006c006f");
assertEquals("hello", body.string()); assertThat(body.string()).isEqualTo("hello");
} }
@Test public void stringBomUtf16Le() throws IOException { @Test public void stringBomUtf16Le() throws IOException {
ResponseBody body = body("fffe680065006c006c006f00"); ResponseBody body = body("fffe680065006c006c006f00");
assertEquals("hello", body.string()); assertThat(body.string()).isEqualTo("hello");
} }
@Test public void stringBomUtf32Be() throws IOException { @Test public void stringBomUtf32Be() throws IOException {
ResponseBody body = body("0000ffff00000068000000650000006c0000006c0000006f"); ResponseBody body = body("0000ffff00000068000000650000006c0000006c0000006f");
assertEquals("hello", body.string()); assertThat(body.string()).isEqualTo("hello");
} }
@Test public void stringBomUtf32Le() throws IOException { @Test public void stringBomUtf32Le() throws IOException {
ResponseBody body = body("ffff000068000000650000006c0000006c0000006f000000"); ResponseBody body = body("ffff000068000000650000006c0000006c0000006f000000");
assertEquals("hello", body.string()); assertThat(body.string()).isEqualTo("hello");
} }
@Test public void stringClosesUnderlyingSource() throws IOException { @Test public void stringClosesUnderlyingSource() throws IOException {
@ -104,53 +103,53 @@ public final class ResponseBodyTest {
}); });
} }
}; };
assertEquals("hello", body.string()); assertThat(body.string()).isEqualTo("hello");
assertTrue(closed.get()); assertThat(closed.get()).isTrue();
} }
@Test public void readerEmpty() throws IOException { @Test public void readerEmpty() throws IOException {
ResponseBody body = body(""); ResponseBody body = body("");
assertEquals("", exhaust(body.charStream())); assertThat(exhaust(body.charStream())).isEqualTo("");
} }
@Test public void readerLooksLikeBomButTooShort() throws IOException { @Test public void readerLooksLikeBomButTooShort() throws IOException {
ResponseBody body = body("000048"); ResponseBody body = body("000048");
assertEquals("\0\0H", exhaust(body.charStream())); assertThat(exhaust(body.charStream())).isEqualTo("\0\0H");
} }
@Test public void readerDefaultsToUtf8() throws IOException { @Test public void readerDefaultsToUtf8() throws IOException {
ResponseBody body = body("68656c6c6f"); ResponseBody body = body("68656c6c6f");
assertEquals("hello", exhaust(body.charStream())); assertThat(exhaust(body.charStream())).isEqualTo("hello");
} }
@Test public void readerExplicitCharset() throws IOException { @Test public void readerExplicitCharset() throws IOException {
ResponseBody body = body("00000068000000650000006c0000006c0000006f", "utf-32be"); ResponseBody body = body("00000068000000650000006c0000006c0000006f", "utf-32be");
assertEquals("hello", exhaust(body.charStream())); assertThat(exhaust(body.charStream())).isEqualTo("hello");
} }
@Test public void readerBomUtf8() throws IOException { @Test public void readerBomUtf8() throws IOException {
ResponseBody body = body("efbbbf68656c6c6f"); ResponseBody body = body("efbbbf68656c6c6f");
assertEquals("hello", exhaust(body.charStream())); assertThat(exhaust(body.charStream())).isEqualTo("hello");
} }
@Test public void readerBomUtf16Be() throws IOException { @Test public void readerBomUtf16Be() throws IOException {
ResponseBody body = body("feff00680065006c006c006f"); ResponseBody body = body("feff00680065006c006c006f");
assertEquals("hello", exhaust(body.charStream())); assertThat(exhaust(body.charStream())).isEqualTo("hello");
} }
@Test public void readerBomUtf16Le() throws IOException { @Test public void readerBomUtf16Le() throws IOException {
ResponseBody body = body("fffe680065006c006c006f00"); ResponseBody body = body("fffe680065006c006c006f00");
assertEquals("hello", exhaust(body.charStream())); assertThat(exhaust(body.charStream())).isEqualTo("hello");
} }
@Test public void readerBomUtf32Be() throws IOException { @Test public void readerBomUtf32Be() throws IOException {
ResponseBody body = body("0000ffff00000068000000650000006c0000006c0000006f"); ResponseBody body = body("0000ffff00000068000000650000006c0000006c0000006f");
assertEquals("hello", exhaust(body.charStream())); assertThat(exhaust(body.charStream())).isEqualTo("hello");
} }
@Test public void readerBomUtf32Le() throws IOException { @Test public void readerBomUtf32Le() throws IOException {
ResponseBody body = body("ffff000068000000650000006c0000006c0000006f000000"); ResponseBody body = body("ffff000068000000650000006c0000006c0000006f000000");
assertEquals("hello", exhaust(body.charStream())); assertThat(exhaust(body.charStream())).isEqualTo("hello");
} }
@Test public void readerClosedBeforeBomClosesUnderlyingSource() throws IOException { @Test public void readerClosedBeforeBomClosesUnderlyingSource() throws IOException {
@ -175,7 +174,7 @@ public final class ResponseBodyTest {
} }
}; };
body.charStream().close(); body.charStream().close();
assertTrue(closed.get()); assertThat(closed.get()).isTrue();
} }
@Test public void readerClosedAfterBomClosesUnderlyingSource() throws IOException { @Test public void readerClosedAfterBomClosesUnderlyingSource() throws IOException {
@ -200,25 +199,25 @@ public final class ResponseBodyTest {
} }
}; };
Reader reader = body.charStream(); Reader reader = body.charStream();
assertEquals('h', reader.read()); assertThat(reader.read()).isEqualTo('h');
reader.close(); reader.close();
assertTrue(closed.get()); assertThat(closed.get()).isTrue();
} }
@Test public void sourceEmpty() throws IOException { @Test public void sourceEmpty() throws IOException {
ResponseBody body = body(""); ResponseBody body = body("");
BufferedSource source = body.source(); BufferedSource source = body.source();
assertTrue(source.exhausted()); assertThat(source.exhausted()).isTrue();
assertEquals("", source.readUtf8()); assertThat(source.readUtf8()).isEqualTo("");
} }
@Test public void sourceSeesBom() throws IOException { @Test public void sourceSeesBom() throws IOException {
ResponseBody body = body("efbbbf68656c6c6f"); ResponseBody body = body("efbbbf68656c6c6f");
BufferedSource source = body.source(); BufferedSource source = body.source();
assertEquals(0xef, source.readByte() & 0xff); assertThat((source.readByte() & 0xff)).isEqualTo(0xef);
assertEquals(0xbb, source.readByte() & 0xff); assertThat((source.readByte() & 0xff)).isEqualTo(0xbb);
assertEquals(0xbf, source.readByte() & 0xff); assertThat((source.readByte() & 0xff)).isEqualTo(0xbf);
assertEquals("hello", source.readUtf8()); assertThat(source.readUtf8()).isEqualTo("hello");
} }
@Test public void sourceClosesUnderlyingSource() throws IOException { @Test public void sourceClosesUnderlyingSource() throws IOException {
@ -243,21 +242,21 @@ public final class ResponseBodyTest {
} }
}; };
body.source().close(); body.source().close();
assertTrue(closed.get()); assertThat(closed.get()).isTrue();
} }
@Test public void bytesEmpty() throws IOException { @Test public void bytesEmpty() throws IOException {
ResponseBody body = body(""); ResponseBody body = body("");
assertEquals(0, body.bytes().length); assertThat(body.bytes().length).isEqualTo(0);
} }
@Test public void bytesSeesBom() throws IOException { @Test public void bytesSeesBom() throws IOException {
ResponseBody body = body("efbbbf68656c6c6f"); ResponseBody body = body("efbbbf68656c6c6f");
byte[] bytes = body.bytes(); byte[] bytes = body.bytes();
assertEquals(0xef, bytes[0] & 0xff); assertThat((bytes[0] & 0xff)).isEqualTo(0xef);
assertEquals(0xbb, bytes[1] & 0xff); assertThat((bytes[1] & 0xff)).isEqualTo(0xbb);
assertEquals(0xbf, bytes[2] & 0xff); assertThat((bytes[2] & 0xff)).isEqualTo(0xbf);
assertEquals("hello", new String(bytes, 3, 5, UTF_8)); assertThat(new String(bytes, 3, 5, UTF_8)).isEqualTo("hello");
} }
@Test public void bytesClosesUnderlyingSource() throws IOException { @Test public void bytesClosesUnderlyingSource() throws IOException {
@ -281,8 +280,8 @@ public final class ResponseBodyTest {
}); });
} }
}; };
assertEquals(5, body.bytes().length); assertThat(body.bytes().length).isEqualTo(5);
assertTrue(closed.get()); assertThat(closed.get()).isTrue();
} }
@Test public void bytesThrowsWhenLengthsDisagree() { @Test public void bytesThrowsWhenLengthsDisagree() {
@ -303,7 +302,8 @@ public final class ResponseBodyTest {
body.bytes(); body.bytes();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("Content-Length (10) and stream length (5) disagree", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"Content-Length (10) and stream length (5) disagree");
} }
} }
@ -325,23 +325,24 @@ public final class ResponseBodyTest {
body.bytes(); body.bytes();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("Cannot buffer entire body for content length: 2147483648", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"Cannot buffer entire body for content length: 2147483648");
} }
} }
@Test public void byteStreamEmpty() throws IOException { @Test public void byteStreamEmpty() throws IOException {
ResponseBody body = body(""); ResponseBody body = body("");
InputStream bytes = body.byteStream(); InputStream bytes = body.byteStream();
assertEquals(-1, bytes.read()); assertThat(bytes.read()).isEqualTo(-1);
} }
@Test public void byteStreamSeesBom() throws IOException { @Test public void byteStreamSeesBom() throws IOException {
ResponseBody body = body("efbbbf68656c6c6f"); ResponseBody body = body("efbbbf68656c6c6f");
InputStream bytes = body.byteStream(); InputStream bytes = body.byteStream();
assertEquals(0xef, bytes.read()); assertThat(bytes.read()).isEqualTo(0xef);
assertEquals(0xbb, bytes.read()); assertThat(bytes.read()).isEqualTo(0xbb);
assertEquals(0xbf, bytes.read()); assertThat(bytes.read()).isEqualTo(0xbf);
assertEquals("hello", exhaust(new InputStreamReader(bytes, UTF_8))); assertThat(exhaust(new InputStreamReader(bytes, UTF_8))).isEqualTo("hello");
} }
@Test public void byteStreamClosesUnderlyingSource() throws IOException { @Test public void byteStreamClosesUnderlyingSource() throws IOException {
@ -366,7 +367,7 @@ public final class ResponseBodyTest {
} }
}; };
body.byteStream().close(); body.byteStream().close();
assertTrue(closed.get()); assertThat(closed.get()).isTrue();
} }
@Test public void throwingUnderlyingSourceClosesQuietly() throws IOException { @Test public void throwingUnderlyingSourceClosesQuietly() throws IOException {
@ -388,7 +389,7 @@ public final class ResponseBodyTest {
}); });
} }
}; };
assertEquals("hello", body.source().readUtf8()); assertThat(body.source().readUtf8()).isEqualTo("hello");
body.close(); body.close();
} }

View File

@ -23,27 +23,27 @@ import okio.Source;
import okio.Timeout; import okio.Timeout;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class ResponseTest { public final class ResponseTest {
@Test public void peekShorterThanResponse() throws Exception { @Test public void peekShorterThanResponse() throws Exception {
Response response = newResponse(responseBody("abcdef")); Response response = newResponse(responseBody("abcdef"));
ResponseBody peekedBody = response.peekBody(3); ResponseBody peekedBody = response.peekBody(3);
assertEquals("abc", peekedBody.string()); assertThat(peekedBody.string()).isEqualTo("abc");
assertEquals("abcdef", response.body().string()); assertThat(response.body().string()).isEqualTo("abcdef");
} }
@Test public void peekLongerThanResponse() throws Exception { @Test public void peekLongerThanResponse() throws Exception {
Response response = newResponse(responseBody("abc")); Response response = newResponse(responseBody("abc"));
ResponseBody peekedBody = response.peekBody(6); ResponseBody peekedBody = response.peekBody(6);
assertEquals("abc", peekedBody.string()); assertThat(peekedBody.string()).isEqualTo("abc");
assertEquals("abc", response.body().string()); assertThat(response.body().string()).isEqualTo("abc");
} }
@Test public void peekAfterReadingResponse() throws Exception { @Test public void peekAfterReadingResponse() throws Exception {
Response response = newResponse(responseBody("abc")); Response response = newResponse(responseBody("abc"));
assertEquals("abc", response.body().string()); assertThat(response.body().string()).isEqualTo("abc");
try { try {
response.peekBody(3); response.peekBody(3);
@ -56,9 +56,9 @@ public final class ResponseTest {
Response response = newResponse(responseBody("abcdef")); Response response = newResponse(responseBody("abcdef"));
ResponseBody p1 = response.peekBody(4); ResponseBody p1 = response.peekBody(4);
ResponseBody p2 = response.peekBody(2); ResponseBody p2 = response.peekBody(2);
assertEquals("abcdef", response.body().string()); assertThat(response.body().string()).isEqualTo("abcdef");
assertEquals("abcd", p1.string()); assertThat(p1.string()).isEqualTo("abcd");
assertEquals("ab", p2.string()); assertThat(p2.string()).isEqualTo("ab");
} }
/** /**

View File

@ -29,7 +29,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static okhttp3.TestUtil.defaultClient; import static okhttp3.TestUtil.defaultClient;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public final class SocksProxyTest { public final class SocksProxyTest {
private final SocksProxy socksProxy = new SocksProxy(); private final SocksProxy socksProxy = new SocksProxy();
@ -55,14 +55,14 @@ public final class SocksProxyTest {
Request request1 = new Request.Builder().url(server.url("/")).build(); Request request1 = new Request.Builder().url(server.url("/")).build();
Response response1 = client.newCall(request1).execute(); Response response1 = client.newCall(request1).execute();
assertEquals("abc", response1.body().string()); assertThat(response1.body().string()).isEqualTo("abc");
Request request2 = new Request.Builder().url(server.url("/")).build(); Request request2 = new Request.Builder().url(server.url("/")).build();
Response response2 = client.newCall(request2).execute(); Response response2 = client.newCall(request2).execute();
assertEquals("def", response2.body().string()); assertThat(response2.body().string()).isEqualTo("def");
// The HTTP calls should share a single connection. // The HTTP calls should share a single connection.
assertEquals(1, socksProxy.connectionCount()); assertThat(socksProxy.connectionCount()).isEqualTo(1);
} }
@Test public void proxySelector() throws Exception { @Test public void proxySelector() throws Exception {
@ -84,9 +84,9 @@ public final class SocksProxyTest {
Request request = new Request.Builder().url(server.url("/")).build(); Request request = new Request.Builder().url(server.url("/")).build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertEquals("abc", response.body().string()); assertThat(response.body().string()).isEqualTo("abc");
assertEquals(1, socksProxy.connectionCount()); assertThat(socksProxy.connectionCount()).isEqualTo(1);
} }
@Test public void checkRemoteDNSResolve() throws Exception { @Test public void checkRemoteDNSResolve() throws Exception {
@ -104,8 +104,8 @@ public final class SocksProxyTest {
Request request = new Request.Builder().url(url).build(); Request request = new Request.Builder().url(url).build();
Response response1 = client.newCall(request).execute(); Response response1 = client.newCall(request).execute();
assertEquals("abc", response1.body().string()); assertThat(response1.body().string()).isEqualTo("abc");
assertEquals(1, socksProxy.connectionCount()); assertThat(socksProxy.connectionCount()).isEqualTo(1);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -26,9 +26,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameter;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/** Runs the web platform URL tests against Java URL models. */ /** Runs the web platform URL tests against Java URL models. */
@RunWith(Parameterized.class) @RunWith(Parameterized.class)
@ -101,9 +99,10 @@ public final class WebPlatformUrlTest {
} }
if (testData.expectParseFailure()) { if (testData.expectParseFailure()) {
assertNull("Expected URL to fail parsing", url); assertThat(url).overridingErrorMessage("Expected URL to fail parsing").isNull();
} else { } else {
assertNotNull("Expected URL to parse successfully, but was null", url); assertThat(url).overridingErrorMessage(
"Expected URL to parse successfully, but was null").isNotNull();
String effectivePort = url.port() != HttpUrl.defaultPort(url.scheme()) String effectivePort = url.port() != HttpUrl.defaultPort(url.scheme())
? Integer.toString(url.port()) ? Integer.toString(url.port())
: ""; : "";
@ -112,12 +111,13 @@ public final class WebPlatformUrlTest {
String effectiveHost = url.host().contains(":") String effectiveHost = url.host().contains(":")
? ("[" + url.host() + "]") ? ("[" + url.host() + "]")
: url.host(); : url.host();
assertEquals("scheme", testData.scheme, url.scheme()); assertThat(url.scheme()).overridingErrorMessage("scheme").isEqualTo(testData.scheme);
assertEquals("host", testData.host, effectiveHost); assertThat(effectiveHost).overridingErrorMessage("host").isEqualTo(testData.host);
assertEquals("port", testData.port, effectivePort); assertThat(effectivePort).overridingErrorMessage("port").isEqualTo(testData.port);
assertEquals("path", testData.path, url.encodedPath()); assertThat(url.encodedPath()).overridingErrorMessage("path").isEqualTo(testData.path);
assertEquals("query", testData.query, effectiveQuery); assertThat(effectiveQuery).overridingErrorMessage("query").isEqualTo(testData.query);
assertEquals("fragment", testData.fragment, effectiveFragment); assertThat(effectiveFragment).overridingErrorMessage("fragment").isEqualTo(
testData.fragment);
} }
} }

View File

@ -27,10 +27,7 @@ import okio.BufferedSink;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class WholeOperationTimeoutTest { public final class WholeOperationTimeoutTest {
@ -47,7 +44,7 @@ public final class WholeOperationTimeoutTest {
.url(server.url("/")) .url(server.url("/"))
.build(); .build();
Call call = client.newCall(request); Call call = client.newCall(request);
assertEquals(0, call.timeout().timeoutNanos()); assertThat(call.timeout().timeoutNanos()).isEqualTo(0);
} }
@Test public void configureClientDefault() throws Exception { @Test public void configureClientDefault() throws Exception {
@ -60,7 +57,7 @@ public final class WholeOperationTimeoutTest {
.build(); .build();
Call call = timeoutClient.newCall(request); Call call = timeoutClient.newCall(request);
assertEquals(TimeUnit.MILLISECONDS.toNanos(456), call.timeout().timeoutNanos()); assertThat(call.timeout().timeoutNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(456));
} }
@Test public void timeoutWritingRequest() throws Exception { @Test public void timeoutWritingRequest() throws Exception {
@ -77,8 +74,8 @@ public final class WholeOperationTimeoutTest {
call.execute(); call.execute();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("timeout", e.getMessage()); assertThat(e.getMessage()).isEqualTo("timeout");
assertTrue(call.isCanceled()); assertThat(call.isCanceled()).isTrue();
} }
} }
@ -108,8 +105,8 @@ public final class WholeOperationTimeoutTest {
}); });
latch.await(); latch.await();
assertTrue(call.isCanceled()); assertThat(call.isCanceled()).isTrue();
assertNotNull(exceptionRef.get()); assertThat(exceptionRef.get()).isNotNull();
} }
@Test public void timeoutProcessing() throws Exception { @Test public void timeoutProcessing() throws Exception {
@ -126,8 +123,8 @@ public final class WholeOperationTimeoutTest {
call.execute(); call.execute();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("timeout", e.getMessage()); assertThat(e.getMessage()).isEqualTo("timeout");
assertTrue(call.isCanceled()); assertThat(call.isCanceled()).isTrue();
} }
} }
@ -157,8 +154,8 @@ public final class WholeOperationTimeoutTest {
}); });
latch.await(); latch.await();
assertTrue(call.isCanceled()); assertThat(call.isCanceled()).isTrue();
assertNotNull(exceptionRef.get()); assertThat(exceptionRef.get()).isNotNull();
} }
@Test public void timeoutReadingResponse() throws Exception { @Test public void timeoutReadingResponse() throws Exception {
@ -177,8 +174,8 @@ public final class WholeOperationTimeoutTest {
response.body().source().readUtf8(); response.body().source().readUtf8();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("timeout", e.getMessage()); assertThat(e.getMessage()).isEqualTo("timeout");
assertTrue(call.isCanceled()); assertThat(call.isCanceled()).isTrue();
} }
} }
@ -218,8 +215,8 @@ public final class WholeOperationTimeoutTest {
}); });
latch.await(); latch.await();
assertTrue(call.isCanceled()); assertThat(call.isCanceled()).isTrue();
assertNotNull(exceptionRef.get()); assertThat(exceptionRef.get()).isNotNull();
} }
@Test public void singleTimeoutForAllFollowUpRequests() throws Exception { @Test public void singleTimeoutForAllFollowUpRequests() throws Exception {
@ -255,8 +252,8 @@ public final class WholeOperationTimeoutTest {
call.execute(); call.execute();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("timeout", e.getMessage()); assertThat(e.getMessage()).isEqualTo("timeout");
assertTrue(call.isCanceled()); assertThat(call.isCanceled()).isTrue();
} }
} }
@ -279,8 +276,8 @@ public final class WholeOperationTimeoutTest {
call.execute(); call.execute();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("timeout", e.getMessage()); assertThat(e.getMessage()).isEqualTo("timeout");
assertTrue(call.isCanceled()); assertThat(call.isCanceled()).isTrue();
} }
} }
@ -300,7 +297,7 @@ public final class WholeOperationTimeoutTest {
Thread.sleep(250); Thread.sleep(250);
response.body().source().readUtf8(); response.body().source().readUtf8();
response.close(); response.close();
assertFalse(call.isCanceled()); assertThat(call.isCanceled()).isFalse();
} }
private RequestBody sleepingRequestBody(final int sleepMillis) { private RequestBody sleepingRequestBody(final int sleepMillis) {

View File

@ -20,7 +20,7 @@ import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class UtilTest { public final class UtilTest {
@ -28,9 +28,9 @@ public final class UtilTest {
Map<String, String> map = new LinkedHashMap<>(); Map<String, String> map = new LinkedHashMap<>();
map.put("a", "A"); map.put("a", "A");
Map<String, String> immutableCopy = Util.immutableMap(map); Map<String, String> immutableCopy = Util.immutableMap(map);
assertEquals(immutableCopy, Collections.singletonMap("a", "A")); assertThat(Collections.singletonMap("a", "A")).isEqualTo(immutableCopy);
map.clear(); map.clear();
assertEquals(immutableCopy, Collections.singletonMap("a", "A")); assertThat(Collections.singletonMap("a", "A")).isEqualTo(immutableCopy);
try { try {
immutableCopy.clear(); immutableCopy.clear();
fail(); fail();

View File

@ -42,11 +42,7 @@ import static okhttp3.internal.cache.DiskLruCache.JOURNAL_FILE;
import static okhttp3.internal.cache.DiskLruCache.JOURNAL_FILE_BACKUP; import static okhttp3.internal.cache.DiskLruCache.JOURNAL_FILE_BACKUP;
import static okhttp3.internal.cache.DiskLruCache.MAGIC; import static okhttp3.internal.cache.DiskLruCache.MAGIC;
import static okhttp3.internal.cache.DiskLruCache.VERSION_1; import static okhttp3.internal.cache.DiskLruCache.VERSION_1;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
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 static org.junit.Assert.fail;
public final class DiskLruCacheTest { public final class DiskLruCacheTest {
@ -120,7 +116,7 @@ public final class DiskLruCacheTest {
fileSystem.setFaultyDelete(cacheDir, false); fileSystem.setFaultyDelete(cacheDir, false);
DiskLruCache.Snapshot snapshot = cache.get("k1"); DiskLruCache.Snapshot snapshot = cache.get("k1");
assertNull(snapshot); assertThat(snapshot).isNull();
} }
@Test public void validateKey() throws Exception { @Test public void validateKey() throws Exception {
@ -130,35 +126,40 @@ public final class DiskLruCacheTest {
cache.edit(key); cache.edit(key);
fail("Expecting an IllegalArgumentException as the key was invalid."); fail("Expecting an IllegalArgumentException as the key was invalid.");
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
assertEquals("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\"", iae.getMessage()); assertThat(iae.getMessage()).isEqualTo(
("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\""));
} }
try { try {
key = "has_CR\r"; key = "has_CR\r";
cache.edit(key); cache.edit(key);
fail("Expecting an IllegalArgumentException as the key was invalid."); fail("Expecting an IllegalArgumentException as the key was invalid.");
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
assertEquals("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\"", iae.getMessage()); assertThat(iae.getMessage()).isEqualTo(
("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\""));
} }
try { try {
key = "has_LF\n"; key = "has_LF\n";
cache.edit(key); cache.edit(key);
fail("Expecting an IllegalArgumentException as the key was invalid."); fail("Expecting an IllegalArgumentException as the key was invalid.");
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
assertEquals("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\"", iae.getMessage()); assertThat(iae.getMessage()).isEqualTo(
("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\""));
} }
try { try {
key = "has_invalid/"; key = "has_invalid/";
cache.edit(key); cache.edit(key);
fail("Expecting an IllegalArgumentException as the key was invalid."); fail("Expecting an IllegalArgumentException as the key was invalid.");
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
assertEquals("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\"", iae.getMessage()); assertThat(iae.getMessage()).isEqualTo(
("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\""));
} }
try { try {
key = "has_invalid\u2603"; key = "has_invalid\u2603";
cache.edit(key); cache.edit(key);
fail("Expecting an IllegalArgumentException as the key was invalid."); fail("Expecting an IllegalArgumentException as the key was invalid.");
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
assertEquals("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\"", iae.getMessage()); assertThat(iae.getMessage()).isEqualTo(
("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\""));
} }
try { try {
key = "this_is_way_too_long_this_is_way_too_long_this_is_way_too_long_" key = "this_is_way_too_long_this_is_way_too_long_this_is_way_too_long_"
@ -166,7 +167,8 @@ public final class DiskLruCacheTest {
cache.edit(key); cache.edit(key);
fail("Expecting an IllegalArgumentException as the key was too long."); fail("Expecting an IllegalArgumentException as the key was too long.");
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
assertEquals("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\"", iae.getMessage()); assertThat(iae.getMessage()).isEqualTo(
("keys must match regex [a-z0-9_-]{1,120}: \"" + key + "\""));
} }
// Test valid cases. // Test valid cases.
@ -187,8 +189,8 @@ public final class DiskLruCacheTest {
DiskLruCache.Editor creator = cache.edit("k1"); DiskLruCache.Editor creator = cache.edit("k1");
setString(creator, 0, "ABC"); setString(creator, 0, "ABC");
setString(creator, 1, "DE"); setString(creator, 1, "DE");
assertNull(creator.newSource(0)); assertThat(creator.newSource(0)).isNull();
assertNull(creator.newSource(1)); assertThat(creator.newSource(1)).isNull();
creator.commit(); creator.commit();
DiskLruCache.Snapshot snapshot = cache.get("k1"); DiskLruCache.Snapshot snapshot = cache.get("k1");
@ -252,7 +254,7 @@ public final class DiskLruCacheTest {
@Test public void journalDoesNotIncludeReadOfYetUnpublishedValue() throws Exception { @Test public void journalDoesNotIncludeReadOfYetUnpublishedValue() throws Exception {
DiskLruCache.Editor creator = cache.edit("k1"); DiskLruCache.Editor creator = cache.edit("k1");
assertNull(cache.get("k1")); assertThat(cache.get("k1")).isNull();
setString(creator, 0, "A"); setString(creator, 0, "A");
setString(creator, 1, "BC"); setString(creator, 1, "BC");
creator.commit(); creator.commit();
@ -297,16 +299,16 @@ public final class DiskLruCacheTest {
setString(editor, 1, "B"); setString(editor, 1, "B");
editor.commit(); editor.commit();
File k1 = getCleanFile("k1", 0); File k1 = getCleanFile("k1", 0);
assertEquals("ABC", readFile(k1)); assertThat(readFile(k1)).isEqualTo("ABC");
cache.remove("k1"); cache.remove("k1");
assertFalse(fileSystem.exists(k1)); assertThat(fileSystem.exists(k1)).isFalse();
} }
@Test public void removePreventsActiveEditFromStoringAValue() throws Exception { @Test public void removePreventsActiveEditFromStoringAValue() throws Exception {
set("a", "a", "a"); set("a", "a", "a");
DiskLruCache.Editor a = cache.edit("a"); DiskLruCache.Editor a = cache.edit("a");
setString(a, 0, "a1"); setString(a, 0, "a1");
assertTrue(cache.remove("a")); assertThat(cache.remove("a")).isTrue();
setString(a, 1, "a2"); setString(a, 1, "a2");
a.commit(); a.commit();
assertAbsent("a"); assertAbsent("a");
@ -324,8 +326,8 @@ public final class DiskLruCacheTest {
DiskLruCache.Snapshot snapshot1 = cache.get("k1"); DiskLruCache.Snapshot snapshot1 = cache.get("k1");
BufferedSource inV1 = Okio.buffer(snapshot1.getSource(0)); BufferedSource inV1 = Okio.buffer(snapshot1.getSource(0));
assertEquals('A', inV1.readByte()); assertThat(inV1.readByte()).isEqualTo((byte) 'A');
assertEquals('A', inV1.readByte()); assertThat(inV1.readByte()).isEqualTo((byte) 'A');
DiskLruCache.Editor v1Updater = cache.edit("k1"); DiskLruCache.Editor v1Updater = cache.edit("k1");
setString(v1Updater, 0, "CCcc"); setString(v1Updater, 0, "CCcc");
@ -337,8 +339,8 @@ public final class DiskLruCacheTest {
assertSnapshotValue(snapshot2, 1, "DDdd"); assertSnapshotValue(snapshot2, 1, "DDdd");
snapshot2.close(); snapshot2.close();
assertEquals('a', inV1.readByte()); assertThat(inV1.readByte()).isEqualTo((byte) 'a');
assertEquals('a', inV1.readByte()); assertThat(inV1.readByte()).isEqualTo((byte) 'a');
assertSnapshotValue(snapshot1, 1, "BBbb"); assertSnapshotValue(snapshot1, 1, "BBbb");
snapshot1.close(); snapshot1.close();
} }
@ -355,11 +357,11 @@ public final class DiskLruCacheTest {
writeFile(dirtyFile1, "D"); writeFile(dirtyFile1, "D");
createJournal("CLEAN k1 1 1", "DIRTY k1"); createJournal("CLEAN k1 1 1", "DIRTY k1");
createNewCache(); createNewCache();
assertFalse(fileSystem.exists(cleanFile0)); assertThat(fileSystem.exists(cleanFile0)).isFalse();
assertFalse(fileSystem.exists(cleanFile1)); assertThat(fileSystem.exists(cleanFile1)).isFalse();
assertFalse(fileSystem.exists(dirtyFile0)); assertThat(fileSystem.exists(dirtyFile0)).isFalse();
assertFalse(fileSystem.exists(dirtyFile1)); assertThat(fileSystem.exists(dirtyFile1)).isFalse();
assertNull(cache.get("k1")); assertThat(cache.get("k1")).isNull();
} }
@Test public void openWithInvalidVersionClearsDirectory() throws Exception { @Test public void openWithInvalidVersionClearsDirectory() throws Exception {
@ -400,7 +402,7 @@ public final class DiskLruCacheTest {
createJournal("CLEAN k1 1 1", "BOGUS"); createJournal("CLEAN k1 1 1", "BOGUS");
createNewCache(); createNewCache();
assertGarbageFilesAllDeleted(); assertGarbageFilesAllDeleted();
assertNull(cache.get("k1")); assertThat(cache.get("k1")).isNull();
} }
@Test public void openWithInvalidFileSizeClearsDirectory() throws Exception { @Test public void openWithInvalidFileSizeClearsDirectory() throws Exception {
@ -409,7 +411,7 @@ public final class DiskLruCacheTest {
createJournal("CLEAN k1 0000x001 1"); createJournal("CLEAN k1 0000x001 1");
createNewCache(); createNewCache();
assertGarbageFilesAllDeleted(); assertGarbageFilesAllDeleted();
assertNull(cache.get("k1")); assertThat(cache.get("k1")).isNull();
} }
@Test public void openWithTruncatedLineDiscardsThatLine() throws Exception { @Test public void openWithTruncatedLineDiscardsThatLine() throws Exception {
@ -421,7 +423,7 @@ public final class DiskLruCacheTest {
sink.writeUtf8(MAGIC + "\n" + VERSION_1 + "\n100\n2\n\nCLEAN k1 1 1"); // no trailing newline sink.writeUtf8(MAGIC + "\n" + VERSION_1 + "\n100\n2\n\nCLEAN k1 1 1"); // no trailing newline
sink.close(); sink.close();
createNewCache(); createNewCache();
assertNull(cache.get("k1")); assertThat(cache.get("k1")).isNull();
// The journal is not corrupt when editing after a truncated line. // The journal is not corrupt when editing after a truncated line.
set("k1", "C", "D"); set("k1", "C", "D");
@ -437,7 +439,7 @@ public final class DiskLruCacheTest {
createJournal("CLEAN k1 1 1 1"); createJournal("CLEAN k1 1 1 1");
createNewCache(); createNewCache();
assertGarbageFilesAllDeleted(); assertGarbageFilesAllDeleted();
assertNull(cache.get("k1")); assertThat(cache.get("k1")).isNull();
} }
@Test public void keyWithSpaceNotPermitted() throws Exception { @Test public void keyWithSpaceNotPermitted() throws Exception {
@ -481,11 +483,11 @@ public final class DiskLruCacheTest {
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
} }
assertFalse(fileSystem.exists(getCleanFile("k1", 0))); assertThat(fileSystem.exists(getCleanFile("k1", 0))).isFalse();
assertFalse(fileSystem.exists(getCleanFile("k1", 1))); assertThat(fileSystem.exists(getCleanFile("k1", 1))).isFalse();
assertFalse(fileSystem.exists(getDirtyFile("k1", 0))); assertThat(fileSystem.exists(getDirtyFile("k1", 0))).isFalse();
assertFalse(fileSystem.exists(getDirtyFile("k1", 1))); assertThat(fileSystem.exists(getDirtyFile("k1", 1))).isFalse();
assertNull(cache.get("k1")); assertThat(cache.get("k1")).isNull();
DiskLruCache.Editor creator2 = cache.edit("k1"); DiskLruCache.Editor creator2 = cache.edit("k1");
setString(creator2, 0, "B"); setString(creator2, 0, "B");
@ -497,11 +499,11 @@ public final class DiskLruCacheTest {
DiskLruCache.Editor creator = cache.edit("k1"); DiskLruCache.Editor creator = cache.edit("k1");
setString(creator, 1, "A"); setString(creator, 1, "A");
creator.abort(); creator.abort();
assertFalse(fileSystem.exists(getCleanFile("k1", 0))); assertThat(fileSystem.exists(getCleanFile("k1", 0))).isFalse();
assertFalse(fileSystem.exists(getCleanFile("k1", 1))); assertThat(fileSystem.exists(getCleanFile("k1", 1))).isFalse();
assertFalse(fileSystem.exists(getDirtyFile("k1", 0))); assertThat(fileSystem.exists(getDirtyFile("k1", 0))).isFalse();
assertFalse(fileSystem.exists(getDirtyFile("k1", 1))); assertThat(fileSystem.exists(getDirtyFile("k1", 1))).isFalse();
assertNull(cache.get("k1")); assertThat(cache.get("k1")).isNull();
} }
@Test public void updateExistingEntryWithTooFewValuesReusesPreviousValues() throws Exception { @Test public void updateExistingEntryWithTooFewValuesReusesPreviousValues() throws Exception {
@ -527,7 +529,7 @@ public final class DiskLruCacheTest {
set("b", "bb", "bbbb"); // size 6 set("b", "bb", "bbbb"); // size 6
cache.setMaxSize(20); cache.setMaxSize(20);
set("c", "c", "c"); // size 12 set("c", "c", "c"); // size 12
assertEquals(12, cache.size()); assertThat(cache.size()).isEqualTo(12);
} }
@Test public void shrinkMaxSizeEvicts() throws Exception { @Test public void shrinkMaxSizeEvicts() throws Exception {
@ -537,7 +539,7 @@ public final class DiskLruCacheTest {
set("b", "bb", "bbbb"); // size 6 set("b", "bb", "bbbb"); // size 6
set("c", "c", "c"); // size 12 set("c", "c", "c"); // size 12
cache.setMaxSize(10); cache.setMaxSize(10);
assertEquals(1, executor.jobs.size()); assertThat(executor.jobs.size()).isEqualTo(1);
} }
@Test public void evictOnInsert() throws Exception { @Test public void evictOnInsert() throws Exception {
@ -546,12 +548,12 @@ public final class DiskLruCacheTest {
set("a", "a", "aaa"); // size 4 set("a", "a", "aaa"); // size 4
set("b", "bb", "bbbb"); // size 6 set("b", "bb", "bbbb"); // size 6
assertEquals(10, cache.size()); assertThat(cache.size()).isEqualTo(10);
// Cause the size to grow to 12 should evict 'A'. // Cause the size to grow to 12 should evict 'A'.
set("c", "c", "c"); set("c", "c", "c");
cache.flush(); cache.flush();
assertEquals(8, cache.size()); assertThat(cache.size()).isEqualTo(8);
assertAbsent("a"); assertAbsent("a");
assertValue("b", "bb", "bbbb"); assertValue("b", "bb", "bbbb");
assertValue("c", "c", "c"); assertValue("c", "c", "c");
@ -559,7 +561,7 @@ public final class DiskLruCacheTest {
// Causing the size to grow to 10 should evict nothing. // Causing the size to grow to 10 should evict nothing.
set("d", "d", "d"); set("d", "d", "d");
cache.flush(); cache.flush();
assertEquals(10, cache.size()); assertThat(cache.size()).isEqualTo(10);
assertAbsent("a"); assertAbsent("a");
assertValue("b", "bb", "bbbb"); assertValue("b", "bb", "bbbb");
assertValue("c", "c", "c"); assertValue("c", "c", "c");
@ -568,7 +570,7 @@ public final class DiskLruCacheTest {
// Causing the size to grow to 18 should evict 'B' and 'C'. // Causing the size to grow to 18 should evict 'B' and 'C'.
set("e", "eeee", "eeee"); set("e", "eeee", "eeee");
cache.flush(); cache.flush();
assertEquals(10, cache.size()); assertThat(cache.size()).isEqualTo(10);
assertAbsent("a"); assertAbsent("a");
assertAbsent("b"); assertAbsent("b");
assertAbsent("c"); assertAbsent("c");
@ -583,12 +585,12 @@ public final class DiskLruCacheTest {
set("a", "a", "aa"); // size 3 set("a", "a", "aa"); // size 3
set("b", "b", "bb"); // size 3 set("b", "b", "bb"); // size 3
set("c", "c", "cc"); // size 3 set("c", "c", "cc"); // size 3
assertEquals(9, cache.size()); assertThat(cache.size()).isEqualTo(9);
// Causing the size to grow to 11 should evict 'A'. // Causing the size to grow to 11 should evict 'A'.
set("b", "b", "bbbb"); set("b", "b", "bbbb");
cache.flush(); cache.flush();
assertEquals(8, cache.size()); assertThat(cache.size()).isEqualTo(8);
assertAbsent("a"); assertAbsent("a");
assertValue("b", "b", "bbbb"); assertValue("b", "b", "bbbb");
assertValue("c", "c", "cc"); assertValue("c", "c", "cc");
@ -609,7 +611,7 @@ public final class DiskLruCacheTest {
// Causing the size to grow to 12 should evict 'C'. // Causing the size to grow to 12 should evict 'C'.
set("g", "g", "g"); set("g", "g", "g");
cache.flush(); cache.flush();
assertEquals(10, cache.size()); assertThat(cache.size()).isEqualTo(10);
assertAbsent("a"); assertAbsent("a");
assertValue("b", "b", "b"); assertValue("b", "b", "b");
assertAbsent("c"); assertAbsent("c");
@ -626,13 +628,13 @@ public final class DiskLruCacheTest {
set("e", "e", "e"); set("e", "e", "e");
set("f", "f", "f"); set("f", "f", "f");
cache.get("b").close(); // 'B' is now least recently used. cache.get("b").close(); // 'B' is now least recently used.
assertEquals(12, cache.size()); assertThat(cache.size()).isEqualTo(12);
cache.close(); cache.close();
createNewCacheWithSize(10); createNewCacheWithSize(10);
set("g", "g", "g"); set("g", "g", "g");
cache.flush(); cache.flush();
assertEquals(10, cache.size()); assertThat(cache.size()).isEqualTo(10);
assertAbsent("a"); assertAbsent("a");
assertValue("b", "b", "b"); assertValue("b", "b", "b");
assertAbsent("c"); assertAbsent("c");
@ -681,7 +683,7 @@ public final class DiskLruCacheTest {
@Test public void readingTheSameStreamMultipleTimes() throws Exception { @Test public void readingTheSameStreamMultipleTimes() throws Exception {
set("a", "a", "b"); set("a", "a", "b");
DiskLruCache.Snapshot snapshot = cache.get("a"); DiskLruCache.Snapshot snapshot = cache.get("a");
assertSame(snapshot.getSource(0), snapshot.getSource(0)); assertThat(snapshot.getSource(0)).isSameAs(snapshot.getSource(0));
snapshot.close(); snapshot.close();
} }
@ -739,10 +741,10 @@ public final class DiskLruCacheTest {
executor.jobs.removeFirst().run(); executor.jobs.removeFirst().run();
// Don't allow edits under any circumstances. // Don't allow edits under any circumstances.
assertNull(cache.edit("a")); assertThat(cache.edit("a")).isNull();
assertNull(cache.edit("c")); assertThat(cache.edit("c")).isNull();
DiskLruCache.Snapshot snapshot = cache.get("a"); DiskLruCache.Snapshot snapshot = cache.get("a");
assertNull(snapshot.edit()); assertThat(snapshot.edit()).isNull();
snapshot.close(); snapshot.close();
} }
@ -759,12 +761,12 @@ public final class DiskLruCacheTest {
// The rebuild is retried on cache hits and on cache edits. // The rebuild is retried on cache hits and on cache edits.
DiskLruCache.Snapshot snapshot = cache.get("b"); DiskLruCache.Snapshot snapshot = cache.get("b");
snapshot.close(); snapshot.close();
assertNull(cache.edit("d")); assertThat(cache.edit("d")).isNull();
assertEquals(2, executor.jobs.size()); assertThat(executor.jobs.size()).isEqualTo(2);
// On cache misses, no retry job is queued. // On cache misses, no retry job is queued.
assertNull(cache.get("c")); assertThat(cache.get("c")).isNull();
assertEquals(2, executor.jobs.size()); assertThat(executor.jobs.size()).isEqualTo(2);
// Let the rebuild complete successfully. // Let the rebuild complete successfully.
fileSystem.setFaultyRename(new File(cacheDir, DiskLruCache.JOURNAL_FILE_BACKUP), false); fileSystem.setFaultyRename(new File(cacheDir, DiskLruCache.JOURNAL_FILE_BACKUP), false);
@ -825,7 +827,7 @@ public final class DiskLruCacheTest {
// Although 'c' successfully committed above, the journal wasn't available to issue a CLEAN op. // Although 'c' successfully committed above, the journal wasn't available to issue a CLEAN op.
// Because the last state of 'c' was DIRTY before the journal failed, it should be removed // Because the last state of 'c' was DIRTY before the journal failed, it should be removed
// entirely on a subsequent open. // entirely on a subsequent open.
assertEquals(4, cache.size()); assertThat(cache.size()).isEqualTo(4);
assertAbsent("c"); assertAbsent("c");
assertAbsent("d"); assertAbsent("d");
assertAbsent("e"); assertAbsent("e");
@ -841,7 +843,7 @@ public final class DiskLruCacheTest {
fileSystem.setFaultyRename(new File(cacheDir, DiskLruCache.JOURNAL_FILE_BACKUP), true); fileSystem.setFaultyRename(new File(cacheDir, DiskLruCache.JOURNAL_FILE_BACKUP), true);
executor.jobs.removeFirst().run(); executor.jobs.removeFirst().run();
assertTrue(cache.remove("a")); assertThat(cache.remove("a")).isTrue();
assertAbsent("a"); assertAbsent("a");
// Let the rebuild complete successfully. // Let the rebuild complete successfully.
@ -861,7 +863,7 @@ public final class DiskLruCacheTest {
fileSystem.setFaultyRename(new File(cacheDir, DiskLruCache.JOURNAL_FILE_BACKUP), true); fileSystem.setFaultyRename(new File(cacheDir, DiskLruCache.JOURNAL_FILE_BACKUP), true);
executor.jobs.removeFirst().run(); executor.jobs.removeFirst().run();
assertTrue(cache.remove("a")); assertThat(cache.remove("a")).isTrue();
assertAbsent("a"); assertAbsent("a");
cache.close(); cache.close();
@ -870,9 +872,9 @@ public final class DiskLruCacheTest {
// The journal will have no record that 'a' was removed. It will have an entry for 'a', but when // The journal will have no record that 'a' was removed. It will have an entry for 'a', but when
// it tries to read the cache files, it will find they were deleted. Once it encounters an entry // it tries to read the cache files, it will find they were deleted. Once it encounters an entry
// with missing cache files, it should remove it from the cache entirely. // with missing cache files, it should remove it from the cache entirely.
assertEquals(4, cache.size()); assertThat(cache.size()).isEqualTo(4);
assertNull(cache.get("a")); assertThat(cache.get("a")).isNull();
assertEquals(2, cache.size()); assertThat(cache.size()).isEqualTo(2);
} }
@Test public void rebuildJournalFailureAllowsEvictAll() throws Exception { @Test public void rebuildJournalFailureAllowsEvictAll() throws Exception {
@ -887,7 +889,7 @@ public final class DiskLruCacheTest {
cache.evictAll(); cache.evictAll();
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
assertAbsent("a"); assertAbsent("a");
assertAbsent("b"); assertAbsent("b");
@ -897,10 +899,10 @@ public final class DiskLruCacheTest {
// The journal has no record that 'a' and 'b' were removed. It will have an entry for both, but // The journal has no record that 'a' and 'b' were removed. It will have an entry for both, but
// when it tries to read the cache files for either entry, it will discover the cache files are // when it tries to read the cache files for either entry, it will discover the cache files are
// missing and remove the entries from the cache. // missing and remove the entries from the cache.
assertEquals(4, cache.size()); assertThat(cache.size()).isEqualTo(4);
assertNull(cache.get("a")); assertThat(cache.get("a")).isNull();
assertNull(cache.get("b")); assertThat(cache.get("b")).isNull();
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
} }
@Test public void rebuildJournalFailureWithCacheTrim() throws Exception { @Test public void rebuildJournalFailureWithCacheTrim() throws Exception {
@ -929,7 +931,7 @@ public final class DiskLruCacheTest {
cache.close(); cache.close();
fileSystem.rename(journalFile, journalBkpFile); fileSystem.rename(journalFile, journalBkpFile);
assertFalse(fileSystem.exists(journalFile)); assertThat(fileSystem.exists(journalFile)).isFalse();
createNewCache(); createNewCache();
@ -937,8 +939,8 @@ public final class DiskLruCacheTest {
assertSnapshotValue(snapshot, 0, "ABC"); assertSnapshotValue(snapshot, 0, "ABC");
assertSnapshotValue(snapshot, 1, "DE"); assertSnapshotValue(snapshot, 1, "DE");
assertFalse(fileSystem.exists(journalBkpFile)); assertThat(fileSystem.exists(journalBkpFile)).isFalse();
assertTrue(fileSystem.exists(journalFile)); assertThat(fileSystem.exists(journalFile)).isTrue();
} }
@Test public void journalFileIsPreferredOverBackupFile() throws Exception { @Test public void journalFileIsPreferredOverBackupFile() throws Exception {
@ -956,8 +958,8 @@ public final class DiskLruCacheTest {
creator.commit(); creator.commit();
cache.close(); cache.close();
assertTrue(fileSystem.exists(journalFile)); assertThat(fileSystem.exists(journalFile)).isTrue();
assertTrue(fileSystem.exists(journalBkpFile)); assertThat(fileSystem.exists(journalBkpFile)).isTrue();
createNewCache(); createNewCache();
@ -969,8 +971,8 @@ public final class DiskLruCacheTest {
assertSnapshotValue(snapshotB, 0, "F"); assertSnapshotValue(snapshotB, 0, "F");
assertSnapshotValue(snapshotB, 1, "GH"); assertSnapshotValue(snapshotB, 1, "GH");
assertFalse(fileSystem.exists(journalBkpFile)); assertThat(fileSystem.exists(journalBkpFile)).isFalse();
assertTrue(fileSystem.exists(journalFile)); assertThat(fileSystem.exists(journalFile)).isTrue();
} }
@Test public void openCreatesDirectoryIfNecessary() throws Exception { @Test public void openCreatesDirectoryIfNecessary() throws Exception {
@ -978,16 +980,16 @@ public final class DiskLruCacheTest {
File dir = tempDir.newFolder("testOpenCreatesDirectoryIfNecessary"); File dir = tempDir.newFolder("testOpenCreatesDirectoryIfNecessary");
cache = DiskLruCache.create(fileSystem, dir, appVersion, 2, Integer.MAX_VALUE); cache = DiskLruCache.create(fileSystem, dir, appVersion, 2, Integer.MAX_VALUE);
set("a", "a", "a"); set("a", "a", "a");
assertTrue(fileSystem.exists(new File(dir, "a.0"))); assertThat(fileSystem.exists(new File(dir, "a.0"))).isTrue();
assertTrue(fileSystem.exists(new File(dir, "a.1"))); assertThat(fileSystem.exists(new File(dir, "a.1"))).isTrue();
assertTrue(fileSystem.exists(new File(dir, "journal"))); assertThat(fileSystem.exists(new File(dir, "journal"))).isTrue();
} }
@Test public void fileDeletedExternally() throws Exception { @Test public void fileDeletedExternally() throws Exception {
set("a", "a", "a"); set("a", "a", "a");
fileSystem.delete(getCleanFile("a", 1)); fileSystem.delete(getCleanFile("a", 1));
assertNull(cache.get("a")); assertThat(cache.get("a")).isNull();
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
} }
@Test public void editSameVersion() throws Exception { @Test public void editSameVersion() throws Exception {
@ -1017,7 +1019,7 @@ public final class DiskLruCacheTest {
DiskLruCache.Editor toAbort = snapshot.edit(); DiskLruCache.Editor toAbort = snapshot.edit();
setString(toAbort, 0, "b"); setString(toAbort, 0, "b");
toAbort.commit(); toAbort.commit();
assertNull(snapshot.edit()); assertThat(snapshot.edit()).isNull();
} }
@Test public void editSinceEvicted() throws Exception { @Test public void editSinceEvicted() throws Exception {
@ -1028,7 +1030,7 @@ public final class DiskLruCacheTest {
set("b", "bb", "bbb"); // size 5 set("b", "bb", "bbb"); // size 5
set("c", "cc", "ccc"); // size 5; will evict 'A' set("c", "cc", "ccc"); // size 5; will evict 'A'
cache.flush(); cache.flush();
assertNull(snapshot.edit()); assertThat(snapshot.edit()).isNull();
} }
@Test public void editSinceEvictedAndRecreated() throws Exception { @Test public void editSinceEvictedAndRecreated() throws Exception {
@ -1040,7 +1042,7 @@ public final class DiskLruCacheTest {
set("c", "cc", "ccc"); // size 5; will evict 'A' set("c", "cc", "ccc"); // size 5; will evict 'A'
set("a", "a", "aaaa"); // size 5; will evict 'B' set("a", "a", "aaaa"); // size 5; will evict 'B'
cache.flush(); cache.flush();
assertNull(snapshot.edit()); assertThat(snapshot.edit()).isNull();
} }
/** @see <a href="https://github.com/JakeWharton/DiskLruCache/issues/2">Issue #2</a> */ /** @see <a href="https://github.com/JakeWharton/DiskLruCache/issues/2">Issue #2</a> */
@ -1074,13 +1076,13 @@ public final class DiskLruCacheTest {
fileSystem.deleteContents(tempDir.getRoot()); fileSystem.deleteContents(tempDir.getRoot());
setString(a, 1, "a2"); setString(a, 1, "a2");
a.commit(); a.commit();
assertNull(cache.get("a")); assertThat(cache.get("a")).isNull();
} }
/** @see <a href="https://github.com/JakeWharton/DiskLruCache/issues/2">Issue #2</a> */ /** @see <a href="https://github.com/JakeWharton/DiskLruCache/issues/2">Issue #2</a> */
@Test public void aggressiveClearingHandlesRead() throws Exception { @Test public void aggressiveClearingHandlesRead() throws Exception {
fileSystem.deleteContents(tempDir.getRoot()); fileSystem.deleteContents(tempDir.getRoot());
assertNull(cache.get("a")); assertThat(cache.get("a")).isNull();
} }
/** /**
@ -1094,21 +1096,21 @@ public final class DiskLruCacheTest {
cache.setMaxSize(8); // Smaller than the sum of active edits! cache.setMaxSize(8); // Smaller than the sum of active edits!
cache.flush(); // Force trimToSize(). cache.flush(); // Force trimToSize().
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
assertNull(cache.get("a")); assertThat(cache.get("a")).isNull();
// After the edit is completed, its entry is still gone. // After the edit is completed, its entry is still gone.
setString(a, 1, "a1"); setString(a, 1, "a1");
a.commit(); a.commit();
assertAbsent("a"); assertAbsent("a");
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
} }
@Test public void evictAll() throws Exception { @Test public void evictAll() throws Exception {
set("a", "a", "a"); set("a", "a", "a");
set("b", "b", "b"); set("b", "b", "b");
cache.evictAll(); cache.evictAll();
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
assertAbsent("a"); assertAbsent("a");
assertAbsent("b"); assertAbsent("b");
} }
@ -1118,7 +1120,7 @@ public final class DiskLruCacheTest {
setString(a, 0, "a1"); setString(a, 0, "a1");
setString(a, 1, "a2"); setString(a, 1, "a2");
cache.evictAll(); cache.evictAll();
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
a.commit(); a.commit();
assertAbsent("a"); assertAbsent("a");
} }
@ -1129,7 +1131,7 @@ public final class DiskLruCacheTest {
setString(a, 0, "a1"); setString(a, 0, "a1");
setString(a, 1, "a2"); setString(a, 1, "a2");
cache.evictAll(); cache.evictAll();
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
a.commit(); a.commit();
assertAbsent("a"); assertAbsent("a");
} }
@ -1139,7 +1141,7 @@ public final class DiskLruCacheTest {
DiskLruCache.Snapshot a = cache.get("a"); DiskLruCache.Snapshot a = cache.get("a");
assertSnapshotValue(a, 0, "a"); assertSnapshotValue(a, 0, "a");
cache.evictAll(); cache.evictAll();
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
assertAbsent("a"); assertAbsent("a");
assertSnapshotValue(a, 1, "a"); assertSnapshotValue(a, 1, "a");
a.close(); a.close();
@ -1149,9 +1151,9 @@ public final class DiskLruCacheTest {
set("a", "a", "a"); set("a", "a", "a");
DiskLruCache.Snapshot a = cache.get("a"); DiskLruCache.Snapshot a = cache.get("a");
cache.evictAll(); cache.evictAll();
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
assertAbsent("a"); assertAbsent("a");
assertNull(a.edit()); assertThat(a.edit()).isNull();
a.close(); a.close();
} }
@ -1161,28 +1163,28 @@ public final class DiskLruCacheTest {
set("c", "c1", "c2"); set("c", "c1", "c2");
Iterator<DiskLruCache.Snapshot> iterator = cache.snapshots(); Iterator<DiskLruCache.Snapshot> iterator = cache.snapshots();
assertTrue(iterator.hasNext()); assertThat(iterator.hasNext()).isTrue();
DiskLruCache.Snapshot a = iterator.next(); DiskLruCache.Snapshot a = iterator.next();
assertEquals("a", a.key()); assertThat(a.key()).isEqualTo("a");
assertSnapshotValue(a, 0, "a1"); assertSnapshotValue(a, 0, "a1");
assertSnapshotValue(a, 1, "a2"); assertSnapshotValue(a, 1, "a2");
a.close(); a.close();
assertTrue(iterator.hasNext()); assertThat(iterator.hasNext()).isTrue();
DiskLruCache.Snapshot b = iterator.next(); DiskLruCache.Snapshot b = iterator.next();
assertEquals("b", b.key()); assertThat(b.key()).isEqualTo("b");
assertSnapshotValue(b, 0, "b1"); assertSnapshotValue(b, 0, "b1");
assertSnapshotValue(b, 1, "b2"); assertSnapshotValue(b, 1, "b2");
b.close(); b.close();
assertTrue(iterator.hasNext()); assertThat(iterator.hasNext()).isTrue();
DiskLruCache.Snapshot c = iterator.next(); DiskLruCache.Snapshot c = iterator.next();
assertEquals("c", c.key()); assertThat(c.key()).isEqualTo("c");
assertSnapshotValue(c, 0, "c1"); assertSnapshotValue(c, 0, "c1");
assertSnapshotValue(c, 1, "c2"); assertSnapshotValue(c, 1, "c2");
c.close(); c.close();
assertFalse(iterator.hasNext()); assertThat(iterator.hasNext()).isFalse();
try { try {
iterator.next(); iterator.next();
fail(); fail();
@ -1196,16 +1198,16 @@ public final class DiskLruCacheTest {
Iterator<DiskLruCache.Snapshot> iterator = cache.snapshots(); Iterator<DiskLruCache.Snapshot> iterator = cache.snapshots();
DiskLruCache.Snapshot a = iterator.next(); DiskLruCache.Snapshot a = iterator.next();
assertEquals("a", a.key()); assertThat(a.key()).isEqualTo("a");
a.close(); a.close();
set("c", "c1", "c2"); set("c", "c1", "c2");
DiskLruCache.Snapshot b = iterator.next(); DiskLruCache.Snapshot b = iterator.next();
assertEquals("b", b.key()); assertThat(b.key()).isEqualTo("b");
b.close(); b.close();
assertFalse(iterator.hasNext()); assertThat(iterator.hasNext()).isFalse();
} }
@Test public void iteratorElementsUpdatedDuringIterationAreUpdated() throws Exception { @Test public void iteratorElementsUpdatedDuringIterationAreUpdated() throws Exception {
@ -1214,13 +1216,13 @@ public final class DiskLruCacheTest {
Iterator<DiskLruCache.Snapshot> iterator = cache.snapshots(); Iterator<DiskLruCache.Snapshot> iterator = cache.snapshots();
DiskLruCache.Snapshot a = iterator.next(); DiskLruCache.Snapshot a = iterator.next();
assertEquals("a", a.key()); assertThat(a.key()).isEqualTo("a");
a.close(); a.close();
set("b", "b3", "b4"); set("b", "b3", "b4");
DiskLruCache.Snapshot b = iterator.next(); DiskLruCache.Snapshot b = iterator.next();
assertEquals("b", b.key()); assertThat(b.key()).isEqualTo("b");
assertSnapshotValue(b, 0, "b3"); assertSnapshotValue(b, 0, "b3");
assertSnapshotValue(b, 1, "b4"); assertSnapshotValue(b, 1, "b4");
b.close(); b.close();
@ -1234,10 +1236,10 @@ public final class DiskLruCacheTest {
cache.remove("b"); cache.remove("b");
DiskLruCache.Snapshot a = iterator.next(); DiskLruCache.Snapshot a = iterator.next();
assertEquals("a", a.key()); assertThat(a.key()).isEqualTo("a");
a.close(); a.close();
assertFalse(iterator.hasNext()); assertThat(iterator.hasNext()).isFalse();
} }
@Test public void iteratorRemove() throws Exception { @Test public void iteratorRemove() throws Exception {
@ -1248,7 +1250,7 @@ public final class DiskLruCacheTest {
a.close(); a.close();
iterator.remove(); iterator.remove();
assertNull(cache.get("a")); assertThat(cache.get("a")).isNull();
} }
@Test public void iteratorRemoveBeforeNext() throws Exception { @Test public void iteratorRemoveBeforeNext() throws Exception {
@ -1280,7 +1282,7 @@ public final class DiskLruCacheTest {
set("a", "a1", "a2"); set("a", "a1", "a2");
Iterator<DiskLruCache.Snapshot> iterator = cache.snapshots(); Iterator<DiskLruCache.Snapshot> iterator = cache.snapshots();
cache.close(); cache.close();
assertFalse(iterator.hasNext()); assertThat(iterator.hasNext()).isFalse();
} }
@Test public void isClosed_uninitializedCache() throws Exception { @Test public void isClosed_uninitializedCache() throws Exception {
@ -1288,9 +1290,9 @@ public final class DiskLruCacheTest {
cache = new DiskLruCache(fileSystem, cacheDir, appVersion, 2, Integer.MAX_VALUE, executor); cache = new DiskLruCache(fileSystem, cacheDir, appVersion, 2, Integer.MAX_VALUE, executor);
toClose.add(cache); toClose.add(cache);
assertFalse(cache.isClosed()); assertThat(cache.isClosed()).isFalse();
cache.close(); cache.close();
assertTrue(cache.isClosed()); assertThat(cache.isClosed()).isTrue();
} }
@Test public void journalWriteFailsDuringEdit() throws Exception { @Test public void journalWriteFailsDuringEdit() throws Exception {
@ -1299,11 +1301,11 @@ public final class DiskLruCacheTest {
// We can't begin the edit if writing 'DIRTY' fails. // We can't begin the edit if writing 'DIRTY' fails.
fileSystem.setFaultyWrite(journalFile, true); fileSystem.setFaultyWrite(journalFile, true);
assertNull(cache.edit("c")); assertThat(cache.edit("c")).isNull();
// Once the journal has a failure, subsequent writes aren't permitted. // Once the journal has a failure, subsequent writes aren't permitted.
fileSystem.setFaultyWrite(journalFile, false); fileSystem.setFaultyWrite(journalFile, false);
assertNull(cache.edit("d")); assertThat(cache.edit("d")).isNull();
// Confirm that the fault didn't corrupt entries stored before the fault was introduced. // Confirm that the fault didn't corrupt entries stored before the fault was introduced.
cache.close(); cache.close();
@ -1331,7 +1333,7 @@ public final class DiskLruCacheTest {
// Once the journal has a failure, subsequent writes aren't permitted. // Once the journal has a failure, subsequent writes aren't permitted.
fileSystem.setFaultyWrite(journalFile, false); fileSystem.setFaultyWrite(journalFile, false);
assertNull(cache.edit("d")); assertThat(cache.edit("d")).isNull();
// Confirm that the fault didn't corrupt entries stored before the fault was introduced. // Confirm that the fault didn't corrupt entries stored before the fault was introduced.
cache.close(); cache.close();
@ -1355,7 +1357,7 @@ public final class DiskLruCacheTest {
// Once the journal has a failure, subsequent writes aren't permitted. // Once the journal has a failure, subsequent writes aren't permitted.
fileSystem.setFaultyWrite(journalFile, false); fileSystem.setFaultyWrite(journalFile, false);
assertNull(cache.edit("d")); assertThat(cache.edit("d")).isNull();
// Confirm that the fault didn't corrupt entries stored before the fault was introduced. // Confirm that the fault didn't corrupt entries stored before the fault was introduced.
cache.close(); cache.close();
@ -1372,7 +1374,7 @@ public final class DiskLruCacheTest {
// Remove, but the journal write will fail. // Remove, but the journal write will fail.
fileSystem.setFaultyWrite(journalFile, true); fileSystem.setFaultyWrite(journalFile, true);
assertTrue(cache.remove("a")); assertThat(cache.remove("a")).isTrue();
// Confirm that the entry was still removed. // Confirm that the entry was still removed.
fileSystem.setFaultyWrite(journalFile, false); fileSystem.setFaultyWrite(journalFile, false);
@ -1393,9 +1395,9 @@ public final class DiskLruCacheTest {
executor.jobs.pop().run(); executor.jobs.pop().run();
// Confirm that edits are prevented after a cache trim failure. // Confirm that edits are prevented after a cache trim failure.
assertNull(cache.edit("a")); assertThat(cache.edit("a")).isNull();
assertNull(cache.edit("b")); assertThat(cache.edit("b")).isNull();
assertNull(cache.edit("c")); assertThat(cache.edit("c")).isNull();
// Allow the test to clean up. // Allow the test to clean up.
fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false); fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false);
@ -1412,12 +1414,12 @@ public final class DiskLruCacheTest {
executor.jobs.pop().run(); executor.jobs.pop().run();
// An edit should now add a job to clean up if the most recent trim failed. // An edit should now add a job to clean up if the most recent trim failed.
assertNull(cache.edit("b")); assertThat(cache.edit("b")).isNull();
executor.jobs.pop().run(); executor.jobs.pop().run();
// Confirm a successful cache trim now allows edits. // Confirm a successful cache trim now allows edits.
fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false); fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false);
assertNull(cache.edit("c")); assertThat(cache.edit("c")).isNull();
executor.jobs.pop().run(); executor.jobs.pop().run();
set("c", "cc", "cc"); set("c", "cc", "cc");
assertValue("c", "cc", "cc"); assertValue("c", "cc", "cc");
@ -1475,10 +1477,10 @@ public final class DiskLruCacheTest {
// Confirm snapshot writes are prevented after a trim failure. // Confirm snapshot writes are prevented after a trim failure.
DiskLruCache.Snapshot snapshot1 = cache.get("a"); DiskLruCache.Snapshot snapshot1 = cache.get("a");
assertNull(snapshot1.edit()); assertThat(snapshot1.edit()).isNull();
snapshot1.close(); snapshot1.close();
DiskLruCache.Snapshot snapshot2 = cache.get("b"); DiskLruCache.Snapshot snapshot2 = cache.get("b");
assertNull(snapshot2.edit()); assertThat(snapshot2.edit()).isNull();
snapshot2.close(); snapshot2.close();
// Allow the test to clean up. // Allow the test to clean up.
@ -1496,7 +1498,7 @@ public final class DiskLruCacheTest {
executor.jobs.pop().run(); executor.jobs.pop().run();
// Confirm we prevent edits after a trim failure. // Confirm we prevent edits after a trim failure.
assertNull(cache.edit("c")); assertThat(cache.edit("c")).isNull();
// A successful eviction should allow new writes. // A successful eviction should allow new writes.
fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false); fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false);
@ -1516,7 +1518,7 @@ public final class DiskLruCacheTest {
executor.jobs.pop().run(); executor.jobs.pop().run();
// Confirm we prevent edits after a trim failure. // Confirm we prevent edits after a trim failure.
assertNull(cache.edit("c")); assertThat(cache.edit("c")).isNull();
// A successful removal which trims the cache should allow new writes. // A successful removal which trims the cache should allow new writes.
fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false); fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false);
@ -1536,7 +1538,7 @@ public final class DiskLruCacheTest {
executor.jobs.pop().run(); executor.jobs.pop().run();
// Confirm we prevent edits after a trim failure. // Confirm we prevent edits after a trim failure.
assertNull(cache.edit("c")); assertThat(cache.edit("c")).isNull();
// A successful flush trims the cache and should allow new writes. // A successful flush trims the cache and should allow new writes.
fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false); fileSystem.setFaultyDelete(new File(cacheDir, "a.0"), false);
@ -1556,15 +1558,15 @@ public final class DiskLruCacheTest {
executor.jobs.pop().run(); executor.jobs.pop().run();
// Confirm the partial snapshot is not returned. // Confirm the partial snapshot is not returned.
assertNull(cache.get("a")); assertThat(cache.get("a")).isNull();
// Confirm we prevent edits after a trim failure. // Confirm we prevent edits after a trim failure.
assertNull(cache.edit("a")); assertThat(cache.edit("a")).isNull();
// Confirm the partial snapshot is not returned after a successful trim. // Confirm the partial snapshot is not returned after a successful trim.
fileSystem.setFaultyDelete(new File(cacheDir, "a.1"), false); fileSystem.setFaultyDelete(new File(cacheDir, "a.1"), false);
executor.jobs.pop().run(); executor.jobs.pop().run();
assertNull(cache.get("a")); assertThat(cache.get("a")).isNull();
} }
@Test public void noSizeCorruptionAfterCreatorDetached() throws Exception { @Test public void noSizeCorruptionAfterCreatorDetached() throws Exception {
@ -1576,11 +1578,11 @@ public final class DiskLruCacheTest {
// Create a new value in its place. // Create a new value in its place.
set("k1", "bb", "bb"); set("k1", "bb", "bb");
assertEquals(4, cache.size()); assertThat(cache.size()).isEqualTo(4);
// Committing the detached editor should not change the cache's size. // Committing the detached editor should not change the cache's size.
editor.commit(); editor.commit();
assertEquals(4, cache.size()); assertThat(cache.size()).isEqualTo(4);
assertValue("k1", "bb", "bb"); assertValue("k1", "bb", "bb");
} }
@ -1595,11 +1597,11 @@ public final class DiskLruCacheTest {
// Create a new value in its place. // Create a new value in its place.
set("k1", "ccc", "ccc"); set("k1", "ccc", "ccc");
assertEquals(6, cache.size()); assertThat(cache.size()).isEqualTo(6);
// Committing the detached editor should not change the cache's size. // Committing the detached editor should not change the cache's size.
editor.commit(); editor.commit();
assertEquals(6, cache.size()); assertThat(cache.size()).isEqualTo(6);
assertValue("k1", "ccc", "ccc"); assertValue("k1", "ccc", "ccc");
} }
@ -1609,7 +1611,7 @@ public final class DiskLruCacheTest {
DiskLruCache.Editor editor = cache.edit("k1"); DiskLruCache.Editor editor = cache.edit("k1");
cache.evictAll(); cache.evictAll();
assertNull(editor.newSource(0)); assertThat(editor.newSource(0)).isNull();
} }
@Test public void editsDiscardedAfterEditorDetached() throws Exception { @Test public void editsDiscardedAfterEditorDetached() throws Exception {
@ -1637,7 +1639,7 @@ public final class DiskLruCacheTest {
cache.evictAll(); cache.evictAll();
editor.abort(); editor.abort();
assertEquals(0, cache.size()); assertThat(cache.size()).isEqualTo(0);
assertAbsent("k1"); assertAbsent("k1");
} }
@ -1649,7 +1651,7 @@ public final class DiskLruCacheTest {
expectedLines.add("2"); expectedLines.add("2");
expectedLines.add(""); expectedLines.add("");
expectedLines.addAll(Arrays.asList(expectedBodyLines)); expectedLines.addAll(Arrays.asList(expectedBodyLines));
assertEquals(expectedLines, readJournalLines()); assertThat(readJournalLines()).isEqualTo(expectedLines);
} }
private void createJournal(String... bodyLines) throws Exception { private void createJournal(String... bodyLines) throws Exception {
@ -1743,12 +1745,12 @@ public final class DiskLruCacheTest {
} }
private void assertGarbageFilesAllDeleted() { private void assertGarbageFilesAllDeleted() {
assertFalse(fileSystem.exists(getCleanFile("g1", 0))); assertThat(fileSystem.exists(getCleanFile("g1", 0))).isFalse();
assertFalse(fileSystem.exists(getCleanFile("g1", 1))); assertThat(fileSystem.exists(getCleanFile("g1", 1))).isFalse();
assertFalse(fileSystem.exists(getCleanFile("g2", 0))); assertThat(fileSystem.exists(getCleanFile("g2", 0))).isFalse();
assertFalse(fileSystem.exists(getCleanFile("g2", 1))); assertThat(fileSystem.exists(getCleanFile("g2", 1))).isFalse();
assertFalse(fileSystem.exists(new File(cacheDir, "otherFile0"))); assertThat(fileSystem.exists(new File(cacheDir, "otherFile0"))).isFalse();
assertFalse(fileSystem.exists(new File(cacheDir, "dir1"))); assertThat(fileSystem.exists(new File(cacheDir, "dir1"))).isFalse();
} }
private void set(String key, String value0, String value1) throws Exception { private void set(String key, String value0, String value1) throws Exception {
@ -1771,25 +1773,25 @@ public final class DiskLruCacheTest {
snapshot.close(); snapshot.close();
fail(); fail();
} }
assertFalse(fileSystem.exists(getCleanFile(key, 0))); assertThat(fileSystem.exists(getCleanFile(key, 0))).isFalse();
assertFalse(fileSystem.exists(getCleanFile(key, 1))); assertThat(fileSystem.exists(getCleanFile(key, 1))).isFalse();
assertFalse(fileSystem.exists(getDirtyFile(key, 0))); assertThat(fileSystem.exists(getDirtyFile(key, 0))).isFalse();
assertFalse(fileSystem.exists(getDirtyFile(key, 1))); assertThat(fileSystem.exists(getDirtyFile(key, 1))).isFalse();
} }
private void assertValue(String key, String value0, String value1) throws Exception { private void assertValue(String key, String value0, String value1) throws Exception {
DiskLruCache.Snapshot snapshot = cache.get(key); DiskLruCache.Snapshot snapshot = cache.get(key);
assertSnapshotValue(snapshot, 0, value0); assertSnapshotValue(snapshot, 0, value0);
assertSnapshotValue(snapshot, 1, value1); assertSnapshotValue(snapshot, 1, value1);
assertTrue(fileSystem.exists(getCleanFile(key, 0))); assertThat(fileSystem.exists(getCleanFile(key, 0))).isTrue();
assertTrue(fileSystem.exists(getCleanFile(key, 1))); assertThat(fileSystem.exists(getCleanFile(key, 1))).isTrue();
snapshot.close(); snapshot.close();
} }
private void assertSnapshotValue(DiskLruCache.Snapshot snapshot, int index, String value) private void assertSnapshotValue(DiskLruCache.Snapshot snapshot, int index, String value)
throws IOException { throws IOException {
assertEquals(value, sourceAsString(snapshot.getSource(index))); assertThat(sourceAsString(snapshot.getSource(index))).isEqualTo(value);
assertEquals(value.length(), snapshot.getLength(index)); assertThat(snapshot.getLength(index)).isEqualTo(value.length());
} }
private String sourceAsString(Source source) throws IOException { private String sourceAsString(Source source) throws IOException {

View File

@ -30,7 +30,7 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class FileOperatorTest { public final class FileOperatorTest {
@ -55,10 +55,10 @@ public final class FileOperatorTest {
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
operator.read(0, buffer, 5); operator.read(0, buffer, 5);
assertEquals("Hello", buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo("Hello");
operator.read(4, buffer, 5); operator.read(4, buffer, 5);
assertEquals("o, Wo", buffer.readUtf8()); assertThat(buffer.readUtf8()).isEqualTo("o, Wo");
} }
@Test public void write() throws Exception { @Test public void write() throws Exception {
@ -66,13 +66,13 @@ public final class FileOperatorTest {
Buffer buffer1 = new Buffer().writeUtf8("Hello, World"); Buffer buffer1 = new Buffer().writeUtf8("Hello, World");
operator.write(0, buffer1, 5); operator.write(0, buffer1, 5);
assertEquals(", World", buffer1.readUtf8()); assertThat(buffer1.readUtf8()).isEqualTo(", World");
Buffer buffer2 = new Buffer().writeUtf8("icopter!"); Buffer buffer2 = new Buffer().writeUtf8("icopter!");
operator.write(3, buffer2, 7); operator.write(3, buffer2, 7);
assertEquals("!", buffer2.readUtf8()); assertThat(buffer2.readUtf8()).isEqualTo("!");
assertEquals(ByteString.encodeUtf8("Helicopter"), snapshot()); assertThat(snapshot()).isEqualTo(ByteString.encodeUtf8("Helicopter"));
} }
@Test public void readAndWrite() throws Exception { @Test public void readAndWrite() throws Exception {
@ -99,12 +99,12 @@ public final class FileOperatorTest {
operator.read(4, buffer, 19); operator.read(4, buffer, 19);
operator.write(80, buffer, buffer.size()); operator.write(80, buffer, buffer.size());
assertEquals(snapshot(), ByteString.encodeUtf8("" assertThat(ByteString.encodeUtf8(""
+ "god creates dinosaurs. " + "god creates dinosaurs. "
+ "god destroys dinosaurs. " + "god destroys dinosaurs. "
+ "god creates man. " + "god creates man. "
+ "man destroys god. " + "man destroys god. "
+ "man creates dinosaurs. ")); + "man creates dinosaurs. ")).isEqualTo(snapshot());
} }
@Test public void multipleOperatorsShareOneFile() throws Exception { @Test public void multipleOperatorsShareOneFile() throws Exception {
@ -124,13 +124,13 @@ public final class FileOperatorTest {
operatorA.write(36, bufferA, 33); operatorA.write(36, bufferA, 33);
operatorB.read(0, bufferB, 9); operatorB.read(0, bufferB, 9);
assertEquals("Dodgson!\n", bufferB.readUtf8()); assertThat(bufferB.readUtf8()).isEqualTo("Dodgson!\n");
operatorA.read(9, bufferA, 27); operatorA.read(9, bufferA, 27);
assertEquals("You shouldn't use my name.\n", bufferA.readUtf8()); assertThat(bufferA.readUtf8()).isEqualTo("You shouldn't use my name.\n");
operatorB.read(36, bufferB, 33); operatorB.read(36, bufferB, 33);
assertEquals("Dodgson, we've got Dodgson here!\n", bufferB.readUtf8()); assertThat(bufferB.readUtf8()).isEqualTo("Dodgson, we've got Dodgson here!\n");
} }
@Test public void largeRead() throws Exception { @Test public void largeRead() throws Exception {
@ -141,7 +141,7 @@ public final class FileOperatorTest {
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
operator.read(0, buffer, data.size()); operator.read(0, buffer, data.size());
assertEquals(data, buffer.readByteString()); assertThat(buffer.readByteString()).isEqualTo(data);
} }
@Test public void largeWrite() throws Exception { @Test public void largeWrite() throws Exception {
@ -152,7 +152,7 @@ public final class FileOperatorTest {
Buffer buffer = new Buffer().write(data); Buffer buffer = new Buffer().write(data);
operator.write(0, buffer, data.size()); operator.write(0, buffer, data.size());
assertEquals(data, snapshot()); assertThat(snapshot()).isEqualTo(data);
} }
@Test public void readBounds() throws Exception { @Test public void readBounds() throws Exception {

View File

@ -34,10 +34,7 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
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 static org.junit.Assert.fail;
public final class RelayTest { public final class RelayTest {
@ -63,17 +60,17 @@ public final class RelayTest {
Source source = relay.newSource(); Source source = relay.newSource();
Buffer sourceBuffer = new Buffer(); Buffer sourceBuffer = new Buffer();
assertEquals(5, source.read(sourceBuffer, 5)); assertThat(source.read(sourceBuffer, 5)).isEqualTo(5);
assertEquals("abcde", sourceBuffer.readUtf8()); assertThat(sourceBuffer.readUtf8()).isEqualTo("abcde");
assertEquals(8, source.read(sourceBuffer, 1024)); assertThat(source.read(sourceBuffer, 1024)).isEqualTo(8);
assertEquals("fghijklm", sourceBuffer.readUtf8()); assertThat(sourceBuffer.readUtf8()).isEqualTo("fghijklm");
assertEquals(-1, source.read(sourceBuffer, 1024)); assertThat(source.read(sourceBuffer, 1024)).isEqualTo(-1);
assertEquals(0, sourceBuffer.size()); assertThat(sourceBuffer.size()).isEqualTo(0);
source.close(); source.close();
assertTrue(relay.isClosed()); assertThat(relay.isClosed()).isTrue();
assertFile(Relay.PREFIX_CLEAN, 13L, metadata.size(), "abcdefghijklm", metadata); assertFile(Relay.PREFIX_CLEAN, 13L, metadata.size(), "abcdefghijklm", metadata);
} }
@ -85,11 +82,11 @@ public final class RelayTest {
BufferedSource source1 = Okio.buffer(relay.newSource()); BufferedSource source1 = Okio.buffer(relay.newSource());
BufferedSource source2 = Okio.buffer(relay.newSource()); BufferedSource source2 = Okio.buffer(relay.newSource());
assertEquals("abcdefghijklm", source1.readUtf8()); assertThat(source1.readUtf8()).isEqualTo("abcdefghijklm");
assertEquals("abcdefghijklm", source2.readUtf8()); assertThat(source2.readUtf8()).isEqualTo("abcdefghijklm");
source1.close(); source1.close();
source2.close(); source2.close();
assertTrue(relay.isClosed()); assertThat(relay.isClosed()).isTrue();
assertFile(Relay.PREFIX_CLEAN, 13L, metadata.size(), "abcdefghijklm", metadata); assertFile(Relay.PREFIX_CLEAN, 13L, metadata.size(), "abcdefghijklm", metadata);
} }
@ -102,15 +99,15 @@ public final class RelayTest {
BufferedSource source1 = Okio.buffer(relay.newSource()); BufferedSource source1 = Okio.buffer(relay.newSource());
BufferedSource source2 = Okio.buffer(relay.newSource()); BufferedSource source2 = Okio.buffer(relay.newSource());
assertEquals("abcde", source1.readUtf8(5)); assertThat(source1.readUtf8(5)).isEqualTo("abcde");
assertEquals("abcde", source2.readUtf8(5)); assertThat(source2.readUtf8(5)).isEqualTo("abcde");
assertEquals("fghij", source2.readUtf8(5)); assertThat(source2.readUtf8(5)).isEqualTo("fghij");
assertEquals("fghij", source1.readUtf8(5)); assertThat(source1.readUtf8(5)).isEqualTo("fghij");
assertTrue(source1.exhausted()); assertThat(source1.exhausted()).isTrue();
assertTrue(source2.exhausted()); assertThat(source2.exhausted()).isTrue();
source1.close(); source1.close();
source2.close(); source2.close();
assertTrue(relay.isClosed()); assertThat(relay.isClosed()).isTrue();
assertFile(Relay.PREFIX_CLEAN, 10L, metadata.size(), "abcdefghij", metadata); assertFile(Relay.PREFIX_CLEAN, 10L, metadata.size(), "abcdefghij", metadata);
} }
@ -123,15 +120,15 @@ public final class RelayTest {
BufferedSource source1 = Okio.buffer(relay.newSource()); BufferedSource source1 = Okio.buffer(relay.newSource());
BufferedSource source2 = Okio.buffer(relay.newSource()); BufferedSource source2 = Okio.buffer(relay.newSource());
assertEquals("abcdefghij", source1.readUtf8(10)); assertThat(source1.readUtf8(10)).isEqualTo("abcdefghij");
assertEquals("abcdefghij", source2.readUtf8(10)); assertThat(source2.readUtf8(10)).isEqualTo("abcdefghij");
assertEquals("klmnopqrst", source2.readUtf8(10)); assertThat(source2.readUtf8(10)).isEqualTo("klmnopqrst");
assertEquals("klmnopqrst", source1.readUtf8(10)); assertThat(source1.readUtf8(10)).isEqualTo("klmnopqrst");
assertTrue(source1.exhausted()); assertThat(source1.exhausted()).isTrue();
assertTrue(source2.exhausted()); assertThat(source2.exhausted()).isTrue();
source1.close(); source1.close();
source2.close(); source2.close();
assertTrue(relay.isClosed()); assertThat(relay.isClosed()).isTrue();
assertFile(Relay.PREFIX_CLEAN, 20L, metadata.size(), "abcdefghijklmnopqrst", metadata); assertFile(Relay.PREFIX_CLEAN, 20L, metadata.size(), "abcdefghijklmnopqrst", metadata);
} }
@ -142,24 +139,24 @@ public final class RelayTest {
Relay relay1 = Relay.edit(file, upstream, metadata, 5); Relay relay1 = Relay.edit(file, upstream, metadata, 5);
BufferedSource source1 = Okio.buffer(relay1.newSource()); BufferedSource source1 = Okio.buffer(relay1.newSource());
assertEquals("abcdefghij", source1.readUtf8(10)); assertThat(source1.readUtf8(10)).isEqualTo("abcdefghij");
assertTrue(source1.exhausted()); assertThat(source1.exhausted()).isTrue();
source1.close(); source1.close();
assertTrue(relay1.isClosed()); assertThat(relay1.isClosed()).isTrue();
// Since relay1 is closed, new sources cannot be created. // Since relay1 is closed, new sources cannot be created.
assertNull(relay1.newSource()); assertThat(relay1.newSource()).isNull();
Relay relay2 = Relay.read(file); Relay relay2 = Relay.read(file);
assertEquals(metadata, relay2.metadata()); assertThat(relay2.metadata()).isEqualTo(metadata);
BufferedSource source2 = Okio.buffer(relay2.newSource()); BufferedSource source2 = Okio.buffer(relay2.newSource());
assertEquals("abcdefghij", source2.readUtf8(10)); assertThat(source2.readUtf8(10)).isEqualTo("abcdefghij");
assertTrue(source2.exhausted()); assertThat(source2.exhausted()).isTrue();
source2.close(); source2.close();
assertTrue(relay2.isClosed()); assertThat(relay2.isClosed()).isTrue();
// Since relay2 is closed, new sources cannot be created. // Since relay2 is closed, new sources cannot be created.
assertNull(relay2.newSource()); assertThat(relay2.newSource()).isNull();
assertFile(Relay.PREFIX_CLEAN, 10L, metadata.size(), "abcdefghij", metadata); assertFile(Relay.PREFIX_CLEAN, 10L, metadata.size(), "abcdefghij", metadata);
} }
@ -170,15 +167,15 @@ public final class RelayTest {
Relay relay1 = Relay.edit(file, upstream, metadata, 5); Relay relay1 = Relay.edit(file, upstream, metadata, 5);
BufferedSource source1 = Okio.buffer(relay1.newSource()); BufferedSource source1 = Okio.buffer(relay1.newSource());
assertEquals("abcdefghij", source1.readUtf8(10)); assertThat(source1.readUtf8(10)).isEqualTo("abcdefghij");
source1.close(); // Not exhausted! source1.close(); // Not exhausted!
assertTrue(relay1.isClosed()); assertThat(relay1.isClosed()).isTrue();
try { try {
Relay.read(file); Relay.read(file);
fail(); fail();
} catch (IOException expected) { } catch (IOException expected) {
assertEquals("unreadable cache file", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("unreadable cache file");
} }
assertFile(Relay.PREFIX_DIRTY, -1L, -1, null, null); assertFile(Relay.PREFIX_DIRTY, -1L, -1, null, null);
@ -194,10 +191,10 @@ public final class RelayTest {
source1.close(); source1.close();
source1.close(); // Unnecessary. Shouldn't decrement the reference count. source1.close(); // Unnecessary. Shouldn't decrement the reference count.
assertFalse(relay.isClosed()); assertThat(relay.isClosed()).isFalse();
source2.close(); source2.close();
assertTrue(relay.isClosed()); assertThat(relay.isClosed()).isTrue();
assertFile(Relay.PREFIX_DIRTY, -1L, -1, null, null); assertFile(Relay.PREFIX_DIRTY, -1L, -1, null, null);
} }
@ -217,10 +214,10 @@ public final class RelayTest {
sink.writeUtf8("klmnopqrst"); sink.writeUtf8("klmnopqrst");
sink.close(); sink.close();
assertEquals(ByteString.encodeUtf8("abcdefghijklmnopqrst"), future1.get()); assertThat(future1.get()).isEqualTo(ByteString.encodeUtf8("abcdefghijklmnopqrst"));
assertEquals(ByteString.encodeUtf8("abcdefghijklmnopqrst"), future2.get()); assertThat(future2.get()).isEqualTo(ByteString.encodeUtf8("abcdefghijklmnopqrst"));
assertTrue(relay.isClosed()); assertThat(relay.isClosed()).isTrue();
assertFile(Relay.PREFIX_CLEAN, 20L, metadata.size(), "abcdefghijklmnopqrst", metadata); assertFile(Relay.PREFIX_CLEAN, 20L, metadata.size(), "abcdefghijklmnopqrst", metadata);
} }
@ -239,14 +236,14 @@ public final class RelayTest {
private void assertFile(ByteString prefix, long upstreamSize, int metadataSize, String upstream, private void assertFile(ByteString prefix, long upstreamSize, int metadataSize, String upstream,
ByteString metadata) throws IOException { ByteString metadata) throws IOException {
BufferedSource source = Okio.buffer(Okio.source(file)); BufferedSource source = Okio.buffer(Okio.source(file));
assertEquals(prefix, source.readByteString(prefix.size())); assertThat(source.readByteString(prefix.size())).isEqualTo(prefix);
assertEquals(upstreamSize, source.readLong()); assertThat(source.readLong()).isEqualTo(upstreamSize);
assertEquals(metadataSize, source.readLong()); assertThat(source.readLong()).isEqualTo(metadataSize);
if (upstream != null) { if (upstream != null) {
assertEquals(upstream, source.readUtf8(upstreamSize)); assertThat(source.readUtf8(upstreamSize)).isEqualTo(upstream);
} }
if (metadata != null) { if (metadata != null) {
assertEquals(metadata, source.readByteString(metadataSize)); assertThat(source.readByteString(metadataSize)).isEqualTo(metadata);
} }
source.close(); source.close();
} }

View File

@ -34,9 +34,7 @@ import okhttp3.internal.RecordingOkAuthenticator;
import org.junit.Test; import org.junit.Test;
import static okhttp3.TestUtil.awaitGarbageCollection; import static okhttp3.TestUtil.awaitGarbageCollection;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class ConnectionPoolTest { public final class ConnectionPoolTest {
private final Address addressA = newAddress("a"); private final Address addressA = newAddress("a");
@ -57,29 +55,29 @@ public final class ConnectionPoolTest {
RealConnection c1 = newConnection(pool, routeA1, 50L); RealConnection c1 = newConnection(pool, routeA1, 50L);
// Running at time 50, the pool returns that nothing can be evicted until time 150. // Running at time 50, the pool returns that nothing can be evicted until time 150.
assertEquals(100L, pool.cleanup(50L)); assertThat(pool.cleanup(50L)).isEqualTo(100L);
assertEquals(1, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(1);
assertFalse(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isFalse();
// Running at time 60, the pool returns that nothing can be evicted until time 150. // Running at time 60, the pool returns that nothing can be evicted until time 150.
assertEquals(90L, pool.cleanup(60L)); assertThat(pool.cleanup(60L)).isEqualTo(90L);
assertEquals(1, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(1);
assertFalse(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isFalse();
// Running at time 149, the pool returns that nothing can be evicted until time 150. // Running at time 149, the pool returns that nothing can be evicted until time 150.
assertEquals(1L, pool.cleanup(149L)); assertThat(pool.cleanup(149L)).isEqualTo(1L);
assertEquals(1, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(1);
assertFalse(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isFalse();
// Running at time 150, the pool evicts. // Running at time 150, the pool evicts.
assertEquals(0, pool.cleanup(150L)); assertThat(pool.cleanup(150L)).isEqualTo(0);
assertEquals(0, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(0);
assertTrue(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isTrue();
// Running again, the pool reports that no further runs are necessary. // Running again, the pool reports that no further runs are necessary.
assertEquals(-1, pool.cleanup(150L)); assertThat(pool.cleanup(150L)).isEqualTo(-1);
assertEquals(0, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(0);
assertTrue(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isTrue();
} }
@Test public void inUseConnectionsNotEvicted() throws Exception { @Test public void inUseConnectionsNotEvicted() throws Exception {
@ -99,19 +97,19 @@ public final class ConnectionPoolTest {
} }
// Running at time 50, the pool returns that nothing can be evicted until time 150. // Running at time 50, the pool returns that nothing can be evicted until time 150.
assertEquals(100L, pool.cleanup(50L)); assertThat(pool.cleanup(50L)).isEqualTo(100L);
assertEquals(1, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(1);
assertFalse(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isFalse();
// Running at time 60, the pool returns that nothing can be evicted until time 160. // Running at time 60, the pool returns that nothing can be evicted until time 160.
assertEquals(100L, pool.cleanup(60L)); assertThat(pool.cleanup(60L)).isEqualTo(100L);
assertEquals(1, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(1);
assertFalse(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isFalse();
// Running at time 160, the pool returns that nothing can be evicted until time 260. // Running at time 160, the pool returns that nothing can be evicted until time 260.
assertEquals(100L, pool.cleanup(160L)); assertThat(pool.cleanup(160L)).isEqualTo(100L);
assertEquals(1, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(1);
assertFalse(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isFalse();
} }
@Test public void cleanupPrioritizesEarliestEviction() throws Exception { @Test public void cleanupPrioritizesEarliestEviction() throws Exception {
@ -122,28 +120,28 @@ public final class ConnectionPoolTest {
RealConnection c2 = newConnection(pool, routeB1, 50L); RealConnection c2 = newConnection(pool, routeB1, 50L);
// Running at time 75, the pool returns that nothing can be evicted until time 150. // Running at time 75, the pool returns that nothing can be evicted until time 150.
assertEquals(75L, pool.cleanup(75L)); assertThat(pool.cleanup(75L)).isEqualTo(75L);
assertEquals(2, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(2);
// Running at time 149, the pool returns that nothing can be evicted until time 150. // Running at time 149, the pool returns that nothing can be evicted until time 150.
assertEquals(1L, pool.cleanup(149L)); assertThat(pool.cleanup(149L)).isEqualTo(1L);
assertEquals(2, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(2);
// Running at time 150, the pool evicts c2. // Running at time 150, the pool evicts c2.
assertEquals(0L, pool.cleanup(150L)); assertThat(pool.cleanup(150L)).isEqualTo(0L);
assertEquals(1, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(1);
assertFalse(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isFalse();
assertTrue(c2.socket().isClosed()); assertThat(c2.socket().isClosed()).isTrue();
// Running at time 150, the pool returns that nothing can be evicted until time 175. // Running at time 150, the pool returns that nothing can be evicted until time 175.
assertEquals(25L, pool.cleanup(150L)); assertThat(pool.cleanup(150L)).isEqualTo(25L);
assertEquals(1, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(1);
// Running at time 175, the pool evicts c1. // Running at time 175, the pool evicts c1.
assertEquals(0L, pool.cleanup(175L)); assertThat(pool.cleanup(175L)).isEqualTo(0L);
assertEquals(0, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(0);
assertTrue(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isTrue();
assertTrue(c2.socket().isClosed()); assertThat(c2.socket().isClosed()).isTrue();
} }
@Test public void oldestConnectionsEvictedIfIdleLimitExceeded() throws Exception { @Test public void oldestConnectionsEvictedIfIdleLimitExceeded() throws Exception {
@ -154,20 +152,20 @@ public final class ConnectionPoolTest {
RealConnection c2 = newConnection(pool, routeB1, 75L); RealConnection c2 = newConnection(pool, routeB1, 75L);
// With 2 connections, there's no need to evict until the connections time out. // With 2 connections, there's no need to evict until the connections time out.
assertEquals(50L, pool.cleanup(100L)); assertThat(pool.cleanup(100L)).isEqualTo(50L);
assertEquals(2, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(2);
assertFalse(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isFalse();
assertFalse(c2.socket().isClosed()); assertThat(c2.socket().isClosed()).isFalse();
// Add a third connection // Add a third connection
RealConnection c3 = newConnection(pool, routeC1, 75L); RealConnection c3 = newConnection(pool, routeC1, 75L);
// The third connection bounces the first. // The third connection bounces the first.
assertEquals(0L, pool.cleanup(100L)); assertThat(pool.cleanup(100L)).isEqualTo(0L);
assertEquals(2, pool.connectionCount()); assertThat(pool.connectionCount()).isEqualTo(2);
assertTrue(c1.socket().isClosed()); assertThat(c1.socket().isClosed()).isTrue();
assertFalse(c2.socket().isClosed()); assertThat(c2.socket().isClosed()).isFalse();
assertFalse(c3.socket().isClosed()); assertThat(c3.socket().isClosed()).isFalse();
} }
@Test public void leakedAllocation() throws Exception { @Test public void leakedAllocation() throws Exception {
@ -179,10 +177,11 @@ public final class ConnectionPoolTest {
allocateAndLeakAllocation(poolApi, c1); allocateAndLeakAllocation(poolApi, c1);
awaitGarbageCollection(); awaitGarbageCollection();
assertEquals(0L, pool.cleanup(100L)); assertThat(pool.cleanup(100L)).isEqualTo(0L);
assertEquals(Collections.emptyList(), c1.transmitters); assertThat(c1.transmitters).isEmpty();
assertTrue(c1.noNewExchanges); // Can't allocate once a leak has been detected. // Can't allocate once a leak has been detected.
assertThat(c1.noNewExchanges).isTrue();
} }
/** Use a helper method so there's no hidden reference remaining on the stack. */ /** Use a helper method so there's no hidden reference remaining on the stack. */

View File

@ -29,9 +29,7 @@ import okhttp3.tls.HandshakeCertificates;
import org.junit.Test; import org.junit.Test;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConnectionSpecSelectorTest { public class ConnectionSpecSelectorTest {
static { static {
@ -52,7 +50,7 @@ public class ConnectionSpecSelectorTest {
boolean retry = connectionSpecSelector.connectionFailed( boolean retry = connectionSpecSelector.connectionFailed(
new IOException("Non-handshake exception")); new IOException("Non-handshake exception"));
assertFalse(retry); assertThat(retry).isFalse();
socket.close(); socket.close();
} }
@ -67,7 +65,7 @@ public class ConnectionSpecSelectorTest {
new SSLHandshakeException("Certificate handshake exception"); new SSLHandshakeException("Certificate handshake exception");
trustIssueException.initCause(new CertificateException()); trustIssueException.initCause(new CertificateException());
boolean retry = connectionSpecSelector.connectionFailed(trustIssueException); boolean retry = connectionSpecSelector.connectionFailed(trustIssueException);
assertFalse(retry); assertThat(retry).isFalse();
socket.close(); socket.close();
} }
@ -80,7 +78,7 @@ public class ConnectionSpecSelectorTest {
connectionSpecSelector.configureSecureSocket(socket); connectionSpecSelector.configureSecureSocket(socket);
boolean retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION); boolean retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION);
assertTrue(retry); assertThat(retry).isTrue();
socket.close(); socket.close();
} }
@ -103,7 +101,7 @@ public class ConnectionSpecSelectorTest {
assertEnabledProtocols(socket, TlsVersion.TLS_1_2); assertEnabledProtocols(socket, TlsVersion.TLS_1_2);
boolean retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION); boolean retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION);
assertTrue(retry); assertThat(retry).isTrue();
socket.close(); socket.close();
// COMPATIBLE_TLS is used here. // COMPATIBLE_TLS is used here.
@ -112,7 +110,7 @@ public class ConnectionSpecSelectorTest {
assertEnabledProtocols(socket, TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0); assertEnabledProtocols(socket, TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0);
retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION); retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION);
assertFalse(retry); assertThat(retry).isFalse();
socket.close(); socket.close();
// sslV3 is not used because SSLv3 is not enabled on the socket. // sslV3 is not used because SSLv3 is not enabled on the socket.
@ -132,7 +130,7 @@ public class ConnectionSpecSelectorTest {
private static void assertEnabledProtocols(SSLSocket socket, TlsVersion... required) { private static void assertEnabledProtocols(SSLSocket socket, TlsVersion... required) {
Set<String> actual = new LinkedHashSet<>(Arrays.asList(socket.getEnabledProtocols())); Set<String> actual = new LinkedHashSet<>(Arrays.asList(socket.getEnabledProtocols()));
Set<String> expected = new LinkedHashSet<>(Arrays.asList(javaNames(required))); Set<String> expected = new LinkedHashSet<>(Arrays.asList(javaNames(required)));
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
private static String[] javaNames(TlsVersion... tlsVersions) { private static String[] javaNames(TlsVersion... tlsVersions) {

View File

@ -18,16 +18,15 @@ package okhttp3.internal.connection;
import java.io.IOException; import java.io.IOException;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
public class RouteExceptionTest { public class RouteExceptionTest {
@Test public void getConnectionIOException_single() { @Test public void getConnectionIOException_single() {
IOException firstException = new IOException(); IOException firstException = new IOException();
RouteException re = new RouteException(firstException); RouteException re = new RouteException(firstException);
assertSame(firstException, re.getFirstConnectException()); assertThat(re.getFirstConnectException()).isSameAs(firstException);
assertSame(firstException, re.getLastConnectException()); assertThat(re.getLastConnectException()).isSameAs(firstException);
} }
@Test public void getConnectionIOException_multiple() { @Test public void getConnectionIOException_multiple() {
@ -39,12 +38,12 @@ public class RouteExceptionTest {
re.addConnectException(thirdException); re.addConnectException(thirdException);
IOException connectionIOException = re.getFirstConnectException(); IOException connectionIOException = re.getFirstConnectException();
assertSame(firstException, connectionIOException); assertThat(connectionIOException).isSameAs(firstException);
Throwable[] suppressedExceptions = connectionIOException.getSuppressed(); Throwable[] suppressedExceptions = connectionIOException.getSuppressed();
assertEquals(2, suppressedExceptions.length); assertThat(suppressedExceptions.length).isEqualTo(2);
assertSame(secondException, suppressedExceptions[0]); assertThat(suppressedExceptions[0]).isSameAs(secondException);
assertSame(thirdException, suppressedExceptions[1]); assertThat(suppressedExceptions[1]).isSameAs(thirdException);
assertSame(thirdException, re.getLastConnectException()); assertThat(re.getLastConnectException()).isSameAs(thirdException);
} }
} }

View File

@ -45,10 +45,7 @@ import org.junit.Test;
import static java.net.Proxy.NO_PROXY; import static java.net.Proxy.NO_PROXY;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class RouteSelectorTest { public final class RouteSelectorTest {
@ -89,19 +86,19 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null, RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE); EventListener.NONE);
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(1)); dns.set(uriHost, dns.allocate(1));
RouteSelector.Selection selection = routeSelector.next(); RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort); assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
dns.assertRequests(uriHost); dns.assertRequests(uriHost);
assertFalse(selection.hasNext()); assertThat(selection.hasNext()).isFalse();
try { try {
selection.next(); selection.next();
fail(); fail();
} catch (NoSuchElementException expected) { } catch (NoSuchElementException expected) {
} }
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
try { try {
routeSelector.next(); routeSelector.next();
fail(); fail();
@ -114,7 +111,7 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null, RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE); EventListener.NONE);
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(1)); dns.set(uriHost, dns.allocate(1));
RouteSelector.Selection selection = routeSelector.next(); RouteSelector.Selection selection = routeSelector.next();
Route route = selection.next(); Route route = selection.next();
@ -122,7 +119,7 @@ public final class RouteSelectorTest {
routeSelector = new RouteSelector(address, routeDatabase, null, EventListener.NONE); routeSelector = new RouteSelector(address, routeDatabase, null, EventListener.NONE);
selection = routeSelector.next(); selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort); assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
assertFalse(selection.hasNext()); assertThat(selection.hasNext()).isFalse();
try { try {
selection.next(); selection.next();
@ -130,7 +127,7 @@ public final class RouteSelectorTest {
} catch (NoSuchElementException expected) { } catch (NoSuchElementException expected) {
} }
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
try { try {
routeSelector.next(); routeSelector.next();
fail(); fail();
@ -144,14 +141,14 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null, RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE); EventListener.NONE);
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyAHost, dns.allocate(2)); dns.set(proxyAHost, dns.allocate(2));
RouteSelector.Selection selection = routeSelector.next(); RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort); assertRoute(selection.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
assertRoute(selection.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort); assertRoute(selection.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort);
assertFalse(selection.hasNext()); assertThat(selection.hasNext()).isFalse();
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
dns.assertRequests(proxyAHost); dns.assertRequests(proxyAHost);
proxySelector.assertRequests(); // No proxy selector requests! proxySelector.assertRequests(); // No proxy selector requests!
} }
@ -162,14 +159,14 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null, RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE); EventListener.NONE);
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(2)); dns.set(uriHost, dns.allocate(2));
RouteSelector.Selection selection = routeSelector.next(); RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort); assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 1), uriPort); assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 1), uriPort);
assertFalse(selection.hasNext()); assertThat(selection.hasNext()).isFalse();
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
dns.assertRequests(uriHost); dns.assertRequests(uriHost);
proxySelector.assertRequests(); // No proxy selector requests! proxySelector.assertRequests(); // No proxy selector requests!
} }
@ -177,7 +174,7 @@ public final class RouteSelectorTest {
@Test public void proxySelectorReturnsNull() throws Exception { @Test public void proxySelectorReturnsNull() throws Exception {
ProxySelector nullProxySelector = new ProxySelector() { ProxySelector nullProxySelector = new ProxySelector() {
@Override public List<Proxy> select(URI uri) { @Override public List<Proxy> select(URI uri) {
assertEquals(uriHost, uri.getHost()); assertThat(uri.getHost()).isEqualTo(uriHost);
return null; return null;
} }
@ -191,14 +188,14 @@ public final class RouteSelectorTest {
authenticator, null, protocols, connectionSpecs, nullProxySelector); authenticator, null, protocols, connectionSpecs, nullProxySelector);
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null, RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE); EventListener.NONE);
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(1)); dns.set(uriHost, dns.allocate(1));
RouteSelector.Selection selection = routeSelector.next(); RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort); assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
dns.assertRequests(uriHost); dns.assertRequests(uriHost);
assertFalse(selection.hasNext()); assertThat(selection.hasNext()).isFalse();
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
} }
@Test public void proxySelectorReturnsNoProxies() throws Exception { @Test public void proxySelectorReturnsNoProxies() throws Exception {
@ -206,14 +203,14 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null, RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE); EventListener.NONE);
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(2)); dns.set(uriHost, dns.allocate(2));
RouteSelector.Selection selection = routeSelector.next(); RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort); assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 1), uriPort); assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 1), uriPort);
assertFalse(selection.hasNext()); assertThat(selection.hasNext()).isFalse();
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
dns.assertRequests(uriHost); dns.assertRequests(uriHost);
proxySelector.assertRequests(address.url().uri()); proxySelector.assertRequests(address.url().uri());
} }
@ -228,24 +225,24 @@ public final class RouteSelectorTest {
proxySelector.assertRequests(address.url().uri()); proxySelector.assertRequests(address.url().uri());
// First try the IP addresses of the first proxy, in sequence. // First try the IP addresses of the first proxy, in sequence.
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyAHost, dns.allocate(2)); dns.set(proxyAHost, dns.allocate(2));
RouteSelector.Selection selection1 = routeSelector.next(); RouteSelector.Selection selection1 = routeSelector.next();
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort); assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort); assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort);
dns.assertRequests(proxyAHost); dns.assertRequests(proxyAHost);
assertFalse(selection1.hasNext()); assertThat(selection1.hasNext()).isFalse();
// Next try the IP address of the second proxy. // Next try the IP address of the second proxy.
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyBHost, dns.allocate(1)); dns.set(proxyBHost, dns.allocate(1));
RouteSelector.Selection selection2 = routeSelector.next(); RouteSelector.Selection selection2 = routeSelector.next();
assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort); assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort);
dns.assertRequests(proxyBHost); dns.assertRequests(proxyBHost);
assertFalse(selection2.hasNext()); assertThat(selection2.hasNext()).isFalse();
// No more proxies to try. // No more proxies to try.
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
} }
@Test public void proxySelectorDirectConnectionsAreSkipped() throws Exception { @Test public void proxySelectorDirectConnectionsAreSkipped() throws Exception {
@ -257,14 +254,14 @@ public final class RouteSelectorTest {
proxySelector.assertRequests(address.url().uri()); proxySelector.assertRequests(address.url().uri());
// Only the origin server will be attempted. // Only the origin server will be attempted.
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(1)); dns.set(uriHost, dns.allocate(1));
RouteSelector.Selection selection = routeSelector.next(); RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort); assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
dns.assertRequests(uriHost); dns.assertRequests(uriHost);
assertFalse(selection.hasNext()); assertThat(selection.hasNext()).isFalse();
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
} }
@Test public void proxyDnsFailureContinuesToNextProxy() throws Exception { @Test public void proxyDnsFailureContinuesToNextProxy() throws Exception {
@ -277,14 +274,14 @@ public final class RouteSelectorTest {
EventListener.NONE); EventListener.NONE);
proxySelector.assertRequests(address.url().uri()); proxySelector.assertRequests(address.url().uri());
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyAHost, dns.allocate(1)); dns.set(proxyAHost, dns.allocate(1));
RouteSelector.Selection selection1 = routeSelector.next(); RouteSelector.Selection selection1 = routeSelector.next();
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort); assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
dns.assertRequests(proxyAHost); dns.assertRequests(proxyAHost);
assertFalse(selection1.hasNext()); assertThat(selection1.hasNext()).isFalse();
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.clear(proxyBHost); dns.clear(proxyBHost);
try { try {
routeSelector.next(); routeSelector.next();
@ -293,14 +290,14 @@ public final class RouteSelectorTest {
} }
dns.assertRequests(proxyBHost); dns.assertRequests(proxyBHost);
assertTrue(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyAHost, dns.allocate(1)); dns.set(proxyAHost, dns.allocate(1));
RouteSelector.Selection selection2 = routeSelector.next(); RouteSelector.Selection selection2 = routeSelector.next();
assertRoute(selection2.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort); assertRoute(selection2.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
dns.assertRequests(proxyAHost); dns.assertRequests(proxyAHost);
assertFalse(selection2.hasNext()); assertThat(selection2.hasNext()).isFalse();
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
} }
@Test public void multipleProxiesMultipleInetAddressesMultipleConfigurations() throws Exception { @Test public void multipleProxiesMultipleInetAddressesMultipleConfigurations() throws Exception {
@ -316,7 +313,7 @@ public final class RouteSelectorTest {
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort); assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
dns.assertRequests(proxyAHost); dns.assertRequests(proxyAHost);
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort); assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort);
assertFalse(selection1.hasNext()); assertThat(selection1.hasNext()).isFalse();
// Proxy B // Proxy B
dns.set(proxyBHost, dns.allocate(2)); dns.set(proxyBHost, dns.allocate(2));
@ -324,10 +321,10 @@ public final class RouteSelectorTest {
assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort); assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort);
dns.assertRequests(proxyBHost); dns.assertRequests(proxyBHost);
assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 1), proxyBPort); assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 1), proxyBPort);
assertFalse(selection2.hasNext()); assertThat(selection2.hasNext()).isFalse();
// No more proxies to attempt. // No more proxies to attempt.
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
} }
@Test public void failedRouteWithSingleProxy() throws Exception { @Test public void failedRouteWithSingleProxy() throws Exception {
@ -343,7 +340,7 @@ public final class RouteSelectorTest {
List<Route> regularRoutes = selection1.getAll(); List<Route> regularRoutes = selection1.getAll();
// Check that we do indeed have more than one route. // Check that we do indeed have more than one route.
assertEquals(numberOfAddresses, regularRoutes.size()); assertThat(regularRoutes.size()).isEqualTo(numberOfAddresses);
// Add first regular route as failed. // Add first regular route as failed.
routeDatabase.failed(regularRoutes.get(0)); routeDatabase.failed(regularRoutes.get(0));
// Reset selector // Reset selector
@ -351,15 +348,15 @@ public final class RouteSelectorTest {
// The first selection prioritizes the non-failed routes. // The first selection prioritizes the non-failed routes.
RouteSelector.Selection selection2 = routeSelector.next(); RouteSelector.Selection selection2 = routeSelector.next();
assertEquals(regularRoutes.get(1), selection2.next()); assertThat(selection2.next()).isEqualTo(regularRoutes.get(1));
assertFalse(selection2.hasNext()); assertThat(selection2.hasNext()).isFalse();
// The second selection will contain all failed routes. // The second selection will contain all failed routes.
RouteSelector.Selection selection3 = routeSelector.next(); RouteSelector.Selection selection3 = routeSelector.next();
assertEquals(regularRoutes.get(0), selection3.next()); assertThat(selection3.next()).isEqualTo(regularRoutes.get(0));
assertFalse(selection3.hasNext()); assertThat(selection3.hasNext()).isFalse();
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
} }
@Test public void failedRouteWithMultipleProxies() throws IOException { @Test public void failedRouteWithMultipleProxies() throws IOException {
@ -385,15 +382,15 @@ public final class RouteSelectorTest {
RouteSelector.Selection selection2 = routeSelector.next(); RouteSelector.Selection selection2 = routeSelector.next();
dns.assertRequests(proxyAHost, proxyBHost); dns.assertRequests(proxyAHost, proxyBHost);
assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort); assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort);
assertFalse(selection2.hasNext()); assertThat(selection2.hasNext()).isFalse();
// Confirm the last selection contains the postponed route from ProxyA. // Confirm the last selection contains the postponed route from ProxyA.
RouteSelector.Selection selection3 = routeSelector.next(); RouteSelector.Selection selection3 = routeSelector.next();
dns.assertRequests(); dns.assertRequests();
assertRoute(selection3.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort); assertRoute(selection3.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
assertFalse(selection3.hasNext()); assertThat(selection3.hasNext()).isFalse();
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
} }
@Test public void queryForAllSelectedRoutes() throws IOException { @Test public void queryForAllSelectedRoutes() throws IOException {
@ -409,42 +406,42 @@ public final class RouteSelectorTest {
assertRoute(routes.get(0), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort); assertRoute(routes.get(0), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
assertRoute(routes.get(1), address, NO_PROXY, dns.lookup(uriHost, 1), uriPort); assertRoute(routes.get(1), address, NO_PROXY, dns.lookup(uriHost, 1), uriPort);
assertSame(routes.get(0), selection.next()); assertThat(selection.next()).isSameAs(routes.get(0));
assertSame(routes.get(1), selection.next()); assertThat(selection.next()).isSameAs(routes.get(1));
assertFalse(selection.hasNext()); assertThat(selection.hasNext()).isFalse();
assertFalse(routeSelector.hasNext()); assertThat(routeSelector.hasNext()).isFalse();
} }
@Test public void getHostString() throws Exception { @Test public void getHostString() throws Exception {
// Name proxy specification. // Name proxy specification.
InetSocketAddress socketAddress = InetSocketAddress.createUnresolved("host", 1234); InetSocketAddress socketAddress = InetSocketAddress.createUnresolved("host", 1234);
assertEquals("host", RouteSelector.getHostString(socketAddress)); assertThat(RouteSelector.getHostString(socketAddress)).isEqualTo("host");
socketAddress = InetSocketAddress.createUnresolved("127.0.0.1", 1234); socketAddress = InetSocketAddress.createUnresolved("127.0.0.1", 1234);
assertEquals("127.0.0.1", RouteSelector.getHostString(socketAddress)); assertThat(RouteSelector.getHostString(socketAddress)).isEqualTo("127.0.0.1");
// InetAddress proxy specification. // InetAddress proxy specification.
socketAddress = new InetSocketAddress(InetAddress.getByName("localhost"), 1234); socketAddress = new InetSocketAddress(InetAddress.getByName("localhost"), 1234);
assertEquals("127.0.0.1", RouteSelector.getHostString(socketAddress)); assertThat(RouteSelector.getHostString(socketAddress)).isEqualTo("127.0.0.1");
socketAddress = new InetSocketAddress( socketAddress = new InetSocketAddress(
InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 1234); InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 1234);
assertEquals("127.0.0.1", RouteSelector.getHostString(socketAddress)); assertThat(RouteSelector.getHostString(socketAddress)).isEqualTo("127.0.0.1");
socketAddress = new InetSocketAddress( socketAddress = new InetSocketAddress(
InetAddress.getByAddress("foobar", new byte[] {127, 0, 0, 1}), 1234); InetAddress.getByAddress("foobar", new byte[] {127, 0, 0, 1}), 1234);
assertEquals("127.0.0.1", RouteSelector.getHostString(socketAddress)); assertThat(RouteSelector.getHostString(socketAddress)).isEqualTo("127.0.0.1");
} }
@Test public void routeToString() throws Exception { @Test public void routeToString() throws Exception {
Route route = new Route(httpAddress(), Proxy.NO_PROXY, Route route = new Route(httpAddress(), Proxy.NO_PROXY,
InetSocketAddress.createUnresolved("host", 1234)); InetSocketAddress.createUnresolved("host", 1234));
assertEquals("Route{host:1234}", route.toString()); assertThat(route.toString()).isEqualTo("Route{host:1234}");
} }
private void assertRoute(Route route, Address address, Proxy proxy, InetAddress socketAddress, private void assertRoute(Route route, Address address, Proxy proxy, InetAddress socketAddress,
int socketPort) { int socketPort) {
assertEquals(address, route.address()); assertThat(route.address()).isEqualTo(address);
assertEquals(proxy, route.proxy()); assertThat(route.proxy()).isEqualTo(proxy);
assertEquals(socketAddress, route.socketAddress().getAddress()); assertThat(route.socketAddress().getAddress()).isEqualTo(socketAddress);
assertEquals(socketPort, route.socketAddress().getPort()); assertThat(route.socketAddress().getPort()).isEqualTo(socketPort);
} }
/** Returns an address that's without an SSL socket factory or hostname verifier. */ /** Returns an address that's without an SSL socket factory or hostname verifier. */

View File

@ -21,8 +21,7 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
public class HttpDateTest { public class HttpDateTest {
@ -43,48 +42,51 @@ public class HttpDateTest {
@Test public void parseStandardFormats() throws Exception { @Test public void parseStandardFormats() throws Exception {
// RFC 822, updated by RFC 1123 with GMT. // RFC 822, updated by RFC 1123 with GMT.
assertEquals(0L, HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT").getTime()); assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT").getTime()).isEqualTo(0L);
assertEquals(1402057830000L, HttpDate.parse("Fri, 06 Jun 2014 12:30:30 GMT").getTime()); assertThat(HttpDate.parse("Fri, 06 Jun 2014 12:30:30 GMT").getTime()).isEqualTo(1402057830000L);
// RFC 850, obsoleted by RFC 1036 with GMT. // RFC 850, obsoleted by RFC 1036 with GMT.
assertEquals(0L, HttpDate.parse("Thursday, 01-Jan-70 00:00:00 GMT").getTime()); assertThat(HttpDate.parse("Thursday, 01-Jan-70 00:00:00 GMT").getTime()).isEqualTo(0L);
assertEquals(1402057830000L, HttpDate.parse("Friday, 06-Jun-14 12:30:30 GMT").getTime()); assertThat(HttpDate.parse("Friday, 06-Jun-14 12:30:30 GMT").getTime()).isEqualTo(1402057830000L);
// ANSI C's asctime(): should use GMT, not platform default. // ANSI C's asctime(): should use GMT, not platform default.
assertEquals(0L, HttpDate.parse("Thu Jan 1 00:00:00 1970").getTime()); assertThat(HttpDate.parse("Thu Jan 1 00:00:00 1970").getTime()).isEqualTo(0L);
assertEquals(1402057830000L, HttpDate.parse("Fri Jun 6 12:30:30 2014").getTime()); assertThat(HttpDate.parse("Fri Jun 6 12:30:30 2014").getTime()).isEqualTo(1402057830000L);
} }
@Test public void format() throws Exception { @Test public void format() throws Exception {
assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", HttpDate.format(new Date(0))); assertThat(HttpDate.format(new Date(0))).isEqualTo("Thu, 01 Jan 1970 00:00:00 GMT");
assertEquals("Fri, 06 Jun 2014 12:30:30 GMT", HttpDate.format(new Date(1402057830000L))); assertThat(HttpDate.format(new Date(1402057830000L))).isEqualTo(
"Fri, 06 Jun 2014 12:30:30 GMT");
} }
@Test public void parseNonStandardStrings() throws Exception { @Test public void parseNonStandardStrings() throws Exception {
// RFC 822, updated by RFC 1123 with any TZ // RFC 822, updated by RFC 1123 with any TZ
assertEquals(3600000L, HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT-01:00").getTime()); assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT-01:00").getTime()).isEqualTo(3600000L);
assertEquals(28800000L, HttpDate.parse("Thu, 01 Jan 1970 00:00:00 PST").getTime()); assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00:00 PST").getTime()).isEqualTo(28800000L);
// Ignore trailing junk // Ignore trailing junk
assertEquals(0L, HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT JUNK").getTime()); assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT JUNK").getTime()).isEqualTo(0L);
// Missing timezones treated as bad. // Missing timezones treated as bad.
assertNull(HttpDate.parse("Thu, 01 Jan 1970 00:00:00")); assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00:00")).isNull();
// Missing seconds treated as bad. // Missing seconds treated as bad.
assertNull(HttpDate.parse("Thu, 01 Jan 1970 00:00 GMT")); assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00 GMT")).isNull();
// Extra spaces treated as bad. // Extra spaces treated as bad.
assertNull(HttpDate.parse("Thu, 01 Jan 1970 00:00 GMT")); assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00 GMT")).isNull();
// Missing leading zero treated as bad. // Missing leading zero treated as bad.
assertNull(HttpDate.parse("Thu, 1 Jan 1970 00:00 GMT")); assertThat(HttpDate.parse("Thu, 1 Jan 1970 00:00 GMT")).isNull();
// RFC 850, obsoleted by RFC 1036 with any TZ. // RFC 850, obsoleted by RFC 1036 with any TZ.
assertEquals(3600000L, HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 GMT-01:00").getTime()); assertThat(HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 GMT-01:00").getTime()).isEqualTo(
assertEquals(28800000L, HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 PST").getTime()); 3600000L);
assertThat(HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 PST").getTime()).isEqualTo(28800000L);
// Ignore trailing junk // Ignore trailing junk
assertEquals(28800000L, HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 PST JUNK").getTime()); assertThat(HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 PST JUNK").getTime()).isEqualTo(
28800000L);
// ANSI C's asctime() format // ANSI C's asctime() format
// This format ignores the timezone entirely even if it is present and uses GMT. // This format ignores the timezone entirely even if it is present and uses GMT.
assertEquals(1402057830000L, HttpDate.parse("Fri Jun 6 12:30:30 2014 PST").getTime()); assertThat(HttpDate.parse("Fri Jun 6 12:30:30 2014 PST").getTime()).isEqualTo(1402057830000L);
// Ignore trailing junk. // Ignore trailing junk.
assertEquals(1402057830000L, HttpDate.parse("Fri Jun 6 12:30:30 2014 JUNK").getTime()); assertThat(HttpDate.parse("Fri Jun 6 12:30:30 2014 JUNK").getTime()).isEqualTo(1402057830000L);
} }
} }

View File

@ -26,7 +26,7 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import okhttp3.internal.Util; import okhttp3.internal.Util;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public final class RecordingProxySelector extends ProxySelector { public final class RecordingProxySelector extends ProxySelector {
public final List<Proxy> proxies = new ArrayList<>(); public final List<Proxy> proxies = new ArrayList<>();
@ -39,7 +39,7 @@ public final class RecordingProxySelector extends ProxySelector {
} }
public void assertRequests(URI... expectedUris) { public void assertRequests(URI... expectedUris) {
assertEquals(Arrays.asList(expectedUris), requestedUris); assertThat(requestedUris).isEqualTo(Arrays.asList(expectedUris));
requestedUris.clear(); requestedUris.clear();
} }

View File

@ -20,7 +20,7 @@ import java.net.ProtocolException;
import okhttp3.Protocol; import okhttp3.Protocol;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class StatusLineTest { public final class StatusLineTest {
@ -29,18 +29,18 @@ public final class StatusLineTest {
int version = 1; int version = 1;
int code = 200; int code = 200;
StatusLine statusLine = StatusLine.parse("HTTP/1." + version + " " + code + " " + message); StatusLine statusLine = StatusLine.parse("HTTP/1." + version + " " + code + " " + message);
assertEquals(message, statusLine.message); assertThat(statusLine.message).isEqualTo(message);
assertEquals(Protocol.HTTP_1_1, statusLine.protocol); assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1);
assertEquals(code, statusLine.code); assertThat(statusLine.code).isEqualTo(code);
} }
@Test public void emptyMessage() throws IOException { @Test public void emptyMessage() throws IOException {
int version = 1; int version = 1;
int code = 503; int code = 503;
StatusLine statusLine = StatusLine.parse("HTTP/1." + version + " " + code + " "); StatusLine statusLine = StatusLine.parse("HTTP/1." + version + " " + code + " ");
assertEquals("", statusLine.message); assertThat(statusLine.message).isEqualTo("");
assertEquals(Protocol.HTTP_1_1, statusLine.protocol); assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1);
assertEquals(code, statusLine.code); assertThat(statusLine.code).isEqualTo(code);
} }
/** /**
@ -51,17 +51,17 @@ public final class StatusLineTest {
int version = 1; int version = 1;
int code = 503; int code = 503;
StatusLine statusLine = StatusLine.parse("HTTP/1." + version + " " + code); StatusLine statusLine = StatusLine.parse("HTTP/1." + version + " " + code);
assertEquals("", statusLine.message); assertThat(statusLine.message).isEqualTo("");
assertEquals(Protocol.HTTP_1_1, statusLine.protocol); assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1);
assertEquals(code, statusLine.code); assertThat(statusLine.code).isEqualTo(code);
} }
// https://github.com/square/okhttp/issues/386 // https://github.com/square/okhttp/issues/386
@Test public void shoutcast() throws IOException { @Test public void shoutcast() throws IOException {
StatusLine statusLine = StatusLine.parse("ICY 200 OK"); StatusLine statusLine = StatusLine.parse("ICY 200 OK");
assertEquals("OK", statusLine.message); assertThat(statusLine.message).isEqualTo("OK");
assertEquals(Protocol.HTTP_1_0, statusLine.protocol); assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_0);
assertEquals(200, statusLine.code); assertThat(statusLine.code).isEqualTo(200);
} }
@Test public void missingProtocol() throws IOException { @Test public void missingProtocol() throws IOException {

View File

@ -32,56 +32,56 @@ import static okhttp3.internal.http2.Http2.TYPE_PING;
import static okhttp3.internal.http2.Http2.TYPE_PUSH_PROMISE; import static okhttp3.internal.http2.Http2.TYPE_PUSH_PROMISE;
import static okhttp3.internal.http2.Http2.TYPE_SETTINGS; import static okhttp3.internal.http2.Http2.TYPE_SETTINGS;
import static okhttp3.internal.http2.Http2.frameLog; import static okhttp3.internal.http2.Http2.frameLog;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public final class FrameLogTest { public final class FrameLogTest {
/** Real stream traffic applied to the log format. */ /** Real stream traffic applied to the log format. */
@Test public void exampleStream() { @Test public void exampleStream() {
assertEquals(">> 0x00000000 5 SETTINGS ", assertThat(frameLog(false, 0, 5, TYPE_SETTINGS, FLAG_NONE)).isEqualTo(
frameLog(false, 0, 5, TYPE_SETTINGS, FLAG_NONE)); ">> 0x00000000 5 SETTINGS ");
assertEquals(">> 0x00000003 100 HEADERS END_HEADERS", assertThat(frameLog(false, 3, 100, TYPE_HEADERS, FLAG_END_HEADERS)).isEqualTo(
frameLog(false, 3, 100, TYPE_HEADERS, FLAG_END_HEADERS)); ">> 0x00000003 100 HEADERS END_HEADERS");
assertEquals(">> 0x00000003 0 DATA END_STREAM", assertThat(frameLog(false, 3, 0, TYPE_DATA, FLAG_END_STREAM)).isEqualTo(
frameLog(false, 3, 0, TYPE_DATA, FLAG_END_STREAM)); ">> 0x00000003 0 DATA END_STREAM");
assertEquals("<< 0x00000000 15 SETTINGS ", assertThat(frameLog(true, 0, 15, TYPE_SETTINGS, FLAG_NONE)).isEqualTo(
frameLog(true, 0, 15, TYPE_SETTINGS, FLAG_NONE)); "<< 0x00000000 15 SETTINGS ");
assertEquals(">> 0x00000000 0 SETTINGS ACK", assertThat(frameLog(false, 0, 0, TYPE_SETTINGS, FLAG_ACK)).isEqualTo(
frameLog(false, 0, 0, TYPE_SETTINGS, FLAG_ACK)); ">> 0x00000000 0 SETTINGS ACK");
assertEquals("<< 0x00000000 0 SETTINGS ACK", assertThat(frameLog(true, 0, 0, TYPE_SETTINGS, FLAG_ACK)).isEqualTo(
frameLog(true, 0, 0, TYPE_SETTINGS, FLAG_ACK)); "<< 0x00000000 0 SETTINGS ACK");
assertEquals("<< 0x00000003 22 HEADERS END_HEADERS", assertThat(frameLog(true, 3, 22, TYPE_HEADERS, FLAG_END_HEADERS)).isEqualTo(
frameLog(true, 3, 22, TYPE_HEADERS, FLAG_END_HEADERS)); "<< 0x00000003 22 HEADERS END_HEADERS");
assertEquals("<< 0x00000003 226 DATA END_STREAM", assertThat(frameLog(true, 3, 226, TYPE_DATA, FLAG_END_STREAM)).isEqualTo(
frameLog(true, 3, 226, TYPE_DATA, FLAG_END_STREAM)); "<< 0x00000003 226 DATA END_STREAM");
assertEquals(">> 0x00000000 8 GOAWAY ", assertThat(frameLog(false, 0, 8, TYPE_GOAWAY, FLAG_NONE)).isEqualTo(
frameLog(false, 0, 8, TYPE_GOAWAY, FLAG_NONE)); ">> 0x00000000 8 GOAWAY ");
} }
@Test public void flagOverlapOn0x1() { @Test public void flagOverlapOn0x1() {
assertEquals("<< 0x00000000 0 SETTINGS ACK", assertThat(frameLog(true, 0, 0, TYPE_SETTINGS, (byte) 0x1)).isEqualTo(
frameLog(true, 0, 0, TYPE_SETTINGS, (byte) 0x1)); "<< 0x00000000 0 SETTINGS ACK");
assertEquals("<< 0x00000000 8 PING ACK", assertThat(frameLog(true, 0, 8, TYPE_PING, (byte) 0x1)).isEqualTo(
frameLog(true, 0, 8, TYPE_PING, (byte) 0x1)); "<< 0x00000000 8 PING ACK");
assertEquals("<< 0x00000003 0 HEADERS END_STREAM", assertThat(frameLog(true, 3, 0, TYPE_HEADERS, (byte) 0x1)).isEqualTo(
frameLog(true, 3, 0, TYPE_HEADERS, (byte) 0x1)); "<< 0x00000003 0 HEADERS END_STREAM");
assertEquals("<< 0x00000003 0 DATA END_STREAM", assertThat(frameLog(true, 3, 0, TYPE_DATA, (byte) 0x1)).isEqualTo(
frameLog(true, 3, 0, TYPE_DATA, (byte) 0x1)); "<< 0x00000003 0 DATA END_STREAM");
} }
@Test public void flagOverlapOn0x4() { @Test public void flagOverlapOn0x4() {
assertEquals("<< 0x00000003 10000 HEADERS END_HEADERS", assertThat(frameLog(true, 3, 10000, TYPE_HEADERS, (byte) 0x4)).isEqualTo(
frameLog(true, 3, 10000, TYPE_HEADERS, (byte) 0x4)); "<< 0x00000003 10000 HEADERS END_HEADERS");
assertEquals("<< 0x00000003 10000 CONTINUATION END_HEADERS", assertThat(frameLog(true, 3, 10000, TYPE_CONTINUATION, (byte) 0x4)).isEqualTo(
frameLog(true, 3, 10000, TYPE_CONTINUATION, (byte) 0x4)); "<< 0x00000003 10000 CONTINUATION END_HEADERS");
assertEquals("<< 0x00000004 10000 PUSH_PROMISE END_PUSH_PROMISE", assertThat(frameLog(true, 4, 10000, TYPE_PUSH_PROMISE, (byte) 0x4)).isEqualTo(
frameLog(true, 4, 10000, TYPE_PUSH_PROMISE, (byte) 0x4)); "<< 0x00000004 10000 PUSH_PROMISE END_PUSH_PROMISE");
} }
@Test public void flagOverlapOn0x20() { @Test public void flagOverlapOn0x20() {
assertEquals("<< 0x00000003 10000 HEADERS PRIORITY", assertThat(frameLog(true, 3, 10000, TYPE_HEADERS, (byte) 0x20)).isEqualTo(
frameLog(true, 3, 10000, TYPE_HEADERS, (byte) 0x20)); "<< 0x00000003 10000 HEADERS PRIORITY");
assertEquals("<< 0x00000003 10000 DATA COMPRESSED", assertThat(frameLog(true, 3, 10000, TYPE_DATA, (byte) 0x20)).isEqualTo(
frameLog(true, 3, 10000, TYPE_DATA, (byte) 0x20)); "<< 0x00000003 10000 DATA COMPRESSED");
} }
/** /**
@ -92,7 +92,7 @@ public final class FrameLogTest {
List<String> formattedFlags = new ArrayList<>(0x40); // Highest valid flag is 0x20. List<String> formattedFlags = new ArrayList<>(0x40); // Highest valid flag is 0x20.
for (byte i = 0; i < 0x40; i++) formattedFlags.add(Http2.formatFlags(TYPE_HEADERS, i)); for (byte i = 0; i < 0x40; i++) formattedFlags.add(Http2.formatFlags(TYPE_HEADERS, i));
assertEquals(Arrays.asList( assertThat(formattedFlags).isEqualTo(Arrays.asList(
"", "",
"END_STREAM", "END_STREAM",
"00000010", "00000010",
@ -157,6 +157,6 @@ public final class FrameLogTest {
"00111101", "00111101",
"00111110", "00111110",
"00111111" "00111111"
), formattedFlags); ));
} }
} }

View File

@ -25,8 +25,7 @@ import org.junit.Test;
import static okhttp3.TestUtil.headerEntries; import static okhttp3.TestUtil.headerEntries;
import static okio.ByteString.decodeHex; import static okio.ByteString.decodeHex;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class HpackTest { public final class HpackTest {
@ -55,9 +54,9 @@ public final class HpackTest {
bytesIn.writeAll(bytesOut); bytesIn.writeAll(bytesOut);
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(0, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(0);
assertEquals(headerBlock, hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerBlock);
} }
/** /**
@ -75,9 +74,10 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(0, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(0);
assertEquals(headerEntries("custom-key", "custom-header"), hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(
headerEntries("custom-key", "custom-header"));
} }
/** Oldest entries are evicted to support newer ones. */ /** Oldest entries are evicted to support newer ones. */
@ -115,8 +115,8 @@ public final class HpackTest {
Hpack.Writer writer = new Hpack.Writer(110, false, bytesOut); Hpack.Writer writer = new Hpack.Writer(110, false, bytesOut);
writer.writeHeaders(headerBlock); writer.writeHeaders(headerBlock);
assertEquals(bytesIn, bytesOut); assertThat(bytesOut).isEqualTo(bytesIn);
assertEquals(2, writer.headerCount); assertThat(writer.headerCount).isEqualTo(2);
int tableLength = writer.dynamicTable.length; int tableLength = writer.dynamicTable.length;
Header entry = writer.dynamicTable[tableLength - 1]; Header entry = writer.dynamicTable[tableLength - 1];
@ -160,7 +160,7 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(2, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(2);
Header entry1 = hpackReader.dynamicTable[readerHeaderTableLength() - 1]; Header entry1 = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
checkEntry(entry1, "custom-bar", "custom-header", 55); checkEntry(entry1, "custom-bar", "custom-header", 55);
@ -170,13 +170,13 @@ public final class HpackTest {
// Once a header field is decoded and added to the reconstructed header // Once a header field is decoded and added to the reconstructed header
// list, it cannot be removed from it. Hence, foo is here. // list, it cannot be removed from it. Hence, foo is here.
assertEquals(headerBlock, hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerBlock);
// Simulate receiving a small dynamic table size update, that implies eviction. // Simulate receiving a small dynamic table size update, that implies eviction.
bytesIn.writeByte(0x3F); // Dynamic table size update (size = 55). bytesIn.writeByte(0x3F); // Dynamic table size update (size = 55).
bytesIn.writeByte(0x18); bytesIn.writeByte(0x18);
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(1, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(1);
} }
/** Header table backing array is initially 8 long, let's ensure it grows. */ /** Header table backing array is initially 8 long, let's ensure it grows. */
@ -198,7 +198,7 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(256, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(256);
} }
@Test public void huffmanDecodingSupported() throws IOException { @Test public void huffmanDecodingSupported() throws IOException {
@ -210,8 +210,8 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(1, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(1);
assertEquals(52, hpackReader.dynamicTableByteCount); assertThat(hpackReader.dynamicTableByteCount).isEqualTo(52);
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1]; Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
checkEntry(entry, ":path", "www.example.com", 52); checkEntry(entry, ":path", "www.example.com", 52);
@ -230,13 +230,14 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(1, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(1);
assertEquals(55, hpackReader.dynamicTableByteCount); assertThat(hpackReader.dynamicTableByteCount).isEqualTo(55);
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1]; Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
checkEntry(entry, "custom-key", "custom-header", 55); checkEntry(entry, "custom-key", "custom-header", 55);
assertEquals(headerEntries("custom-key", "custom-header"), hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(
headerEntries("custom-key", "custom-header"));
} }
/** /**
@ -251,13 +252,13 @@ public final class HpackTest {
bytesIn.writeUtf8("/sample/path"); bytesIn.writeUtf8("/sample/path");
hpackWriter.writeHeaders(headerBlock); hpackWriter.writeHeaders(headerBlock);
assertEquals(bytesIn, bytesOut); assertThat(bytesOut).isEqualTo(bytesIn);
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(0, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(0);
assertEquals(headerBlock, hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerBlock);
} }
@Test public void literalHeaderFieldWithoutIndexingNewName() throws IOException { @Test public void literalHeaderFieldWithoutIndexingNewName() throws IOException {
@ -272,9 +273,9 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(0, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(0);
assertEquals(headerBlock, hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerBlock);
} }
@Test public void literalHeaderFieldNeverIndexedIndexedName() throws IOException { @Test public void literalHeaderFieldNeverIndexedIndexedName() throws IOException {
@ -285,9 +286,10 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(0, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(0);
assertEquals(headerEntries(":path", "/sample/path"), hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(
headerEntries(":path", "/sample/path"));
} }
@Test public void literalHeaderFieldNeverIndexedNewName() throws IOException { @Test public void literalHeaderFieldNeverIndexedNewName() throws IOException {
@ -302,9 +304,9 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(0, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(0);
assertEquals(headerBlock, hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerBlock);
} }
@Test public void literalHeaderFieldWithIncrementalIndexingIndexedName() throws IOException { @Test public void literalHeaderFieldWithIncrementalIndexingIndexedName() throws IOException {
@ -316,9 +318,9 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(1, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(1);
assertEquals(headerBlock, hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerBlock);
} }
@Test public void literalHeaderFieldWithIncrementalIndexingNewName() throws IOException { @Test public void literalHeaderFieldWithIncrementalIndexingNewName() throws IOException {
@ -332,18 +334,18 @@ public final class HpackTest {
bytesIn.writeUtf8("custom-header"); bytesIn.writeUtf8("custom-header");
hpackWriter.writeHeaders(headerBlock); hpackWriter.writeHeaders(headerBlock);
assertEquals(bytesIn, bytesOut); assertThat(bytesOut).isEqualTo(bytesIn);
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
Header entry = hpackWriter.dynamicTable[hpackWriter.dynamicTable.length - 1]; Header entry = hpackWriter.dynamicTable[hpackWriter.dynamicTable.length - 1];
checkEntry(entry, "custom-key", "custom-header", 55); checkEntry(entry, "custom-key", "custom-header", 55);
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(1, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(1);
assertEquals(headerBlock, hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerBlock);
} }
@Test public void theSameHeaderAfterOneIncrementalIndexed() throws IOException { @Test public void theSameHeaderAfterOneIncrementalIndexed() throws IOException {
@ -362,18 +364,18 @@ public final class HpackTest {
bytesIn.writeByte(0xbe); // Indexed name and value (idx = 63) bytesIn.writeByte(0xbe); // Indexed name and value (idx = 63)
hpackWriter.writeHeaders(headerBlock); hpackWriter.writeHeaders(headerBlock);
assertEquals(bytesIn, bytesOut); assertThat(bytesOut).isEqualTo(bytesIn);
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
Header entry = hpackWriter.dynamicTable[hpackWriter.dynamicTable.length - 1]; Header entry = hpackWriter.dynamicTable[hpackWriter.dynamicTable.length - 1];
checkEntry(entry, "custom-key", "custom-header", 55); checkEntry(entry, "custom-key", "custom-header", 55);
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(1, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(1);
assertEquals(headerBlock, hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerBlock);
} }
@Test public void staticHeaderIsNotCopiedIntoTheIndexedTable() throws IOException { @Test public void staticHeaderIsNotCopiedIntoTheIndexedTable() throws IOException {
@ -382,12 +384,13 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(0, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(0);
assertEquals(0, hpackReader.dynamicTableByteCount); assertThat(hpackReader.dynamicTableByteCount).isEqualTo(0);
assertNull(hpackReader.dynamicTable[readerHeaderTableLength() - 1]); assertThat(hpackReader.dynamicTable[readerHeaderTableLength() - 1]).isNull();
assertEquals(headerEntries(":method", "GET"), hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(
headerEntries(":method", "GET"));
} }
// Example taken from twitter/hpack DecoderTest.testUnusedIndex // Example taken from twitter/hpack DecoderTest.testUnusedIndex
@ -398,7 +401,7 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("index == 0", e.getMessage()); assertThat(e.getMessage()).isEqualTo("index == 0");
} }
} }
@ -410,7 +413,7 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("Header index too large 127", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Header index too large 127");
} }
} }
@ -423,7 +426,7 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("Header index too large -2147483521", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Header index too large -2147483521");
} }
} }
@ -432,14 +435,14 @@ public final class HpackTest {
bytesIn.writeByte(0x20); bytesIn.writeByte(0x20);
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(0, hpackReader.maxDynamicTableByteCount()); assertThat(hpackReader.maxDynamicTableByteCount()).isEqualTo(0);
bytesIn.writeByte(0x3f); // encode size 4096 bytesIn.writeByte(0x3f); // encode size 4096
bytesIn.writeByte(0xe1); bytesIn.writeByte(0xe1);
bytesIn.writeByte(0x1f); bytesIn.writeByte(0x1f);
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(4096, hpackReader.maxDynamicTableByteCount()); assertThat(hpackReader.maxDynamicTableByteCount()).isEqualTo(4096);
} }
// Example taken from twitter/hpack DecoderTest.testIllegalHeaderTableSizeUpdate // Example taken from twitter/hpack DecoderTest.testIllegalHeaderTableSizeUpdate
@ -452,7 +455,7 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("Invalid dynamic table size update 4097", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Invalid dynamic table size update 4097");
} }
} }
@ -465,7 +468,7 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("Invalid dynamic table size update -2147483648", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Invalid dynamic table size update -2147483648");
} }
} }
@ -480,9 +483,10 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
// Not buffered in header table. // Not buffered in header table.
assertEquals(0, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(0);
assertEquals(headerEntries(":method", "GET"), hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(
headerEntries(":method", "GET"));
} }
@Test public void readLiteralHeaderWithIncrementalIndexingStaticName() throws IOException { @Test public void readLiteralHeaderWithIncrementalIndexingStaticName() throws IOException {
@ -493,7 +497,8 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals(Arrays.asList(new Header("www-authenticate", "Basic")), hpackReader.getAndResetHeaderList()); assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(
Arrays.asList(new Header("www-authenticate", "Basic")));
} }
@Test public void readLiteralHeaderWithIncrementalIndexingDynamicName() throws IOException { @Test public void readLiteralHeaderWithIncrementalIndexingDynamicName() throws IOException {
@ -509,9 +514,8 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertEquals( assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(
Arrays.asList(new Header("custom-foo", "Basic"), new Header("custom-foo", "Basic2")), Arrays.asList(new Header("custom-foo", "Basic"), new Header("custom-foo", "Basic2")));
hpackReader.getAndResetHeaderList());
} }
/** /**
@ -548,7 +552,7 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("Header index too large 78", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Header index too large 78");
} }
} }
@ -566,21 +570,21 @@ public final class HpackTest {
} }
private void checkReadFirstRequestWithoutHuffman() { private void checkReadFirstRequestWithoutHuffman() {
assertEquals(1, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(1);
// [ 1] (s = 57) :authority: www.example.com // [ 1] (s = 57) :authority: www.example.com
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1]; Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
checkEntry(entry, ":authority", "www.example.com", 57); checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 57 // Table size: 57
assertEquals(57, hpackReader.dynamicTableByteCount); assertThat(hpackReader.dynamicTableByteCount).isEqualTo(57);
// Decoded header list: // Decoded header list:
assertEquals(headerEntries( assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET", ":method", "GET",
":scheme", "http", ":scheme", "http",
":path", "/", ":path", "/",
":authority", "www.example.com"), hpackReader.getAndResetHeaderList()); ":authority", "www.example.com"));
} }
private void secondRequestWithoutHuffman() { private void secondRequestWithoutHuffman() {
@ -599,7 +603,7 @@ public final class HpackTest {
} }
private void checkReadSecondRequestWithoutHuffman() { private void checkReadSecondRequestWithoutHuffman() {
assertEquals(2, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(2);
// [ 1] (s = 53) cache-control: no-cache // [ 1] (s = 53) cache-control: no-cache
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 2]; Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 2];
@ -610,15 +614,15 @@ public final class HpackTest {
checkEntry(entry, ":authority", "www.example.com", 57); checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 110 // Table size: 110
assertEquals(110, hpackReader.dynamicTableByteCount); assertThat(hpackReader.dynamicTableByteCount).isEqualTo(110);
// Decoded header list: // Decoded header list:
assertEquals(headerEntries( assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET", ":method", "GET",
":scheme", "http", ":scheme", "http",
":path", "/", ":path", "/",
":authority", "www.example.com", ":authority", "www.example.com",
"cache-control", "no-cache"), hpackReader.getAndResetHeaderList()); "cache-control", "no-cache"));
} }
private void thirdRequestWithoutHuffman() { private void thirdRequestWithoutHuffman() {
@ -638,7 +642,7 @@ public final class HpackTest {
} }
private void checkReadThirdRequestWithoutHuffman() { private void checkReadThirdRequestWithoutHuffman() {
assertEquals(3, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(3);
// [ 1] (s = 54) custom-key: custom-value // [ 1] (s = 54) custom-key: custom-value
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 3]; Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 3];
@ -653,15 +657,15 @@ public final class HpackTest {
checkEntry(entry, ":authority", "www.example.com", 57); checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 164 // Table size: 164
assertEquals(164, hpackReader.dynamicTableByteCount); assertThat(hpackReader.dynamicTableByteCount).isEqualTo(164);
// Decoded header list: // Decoded header list:
assertEquals(headerEntries( assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET", ":method", "GET",
":scheme", "https", ":scheme", "https",
":path", "/index.html", ":path", "/index.html",
":authority", "www.example.com", ":authority", "www.example.com",
"custom-key", "custom-value"), hpackReader.getAndResetHeaderList()); "custom-key", "custom-value"));
} }
/** /**
@ -696,21 +700,21 @@ public final class HpackTest {
} }
private void checkReadFirstRequestWithHuffman() { private void checkReadFirstRequestWithHuffman() {
assertEquals(1, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(1);
// [ 1] (s = 57) :authority: www.example.com // [ 1] (s = 57) :authority: www.example.com
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1]; Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
checkEntry(entry, ":authority", "www.example.com", 57); checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 57 // Table size: 57
assertEquals(57, hpackReader.dynamicTableByteCount); assertThat(hpackReader.dynamicTableByteCount).isEqualTo(57);
// Decoded header list: // Decoded header list:
assertEquals(headerEntries( assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET", ":method", "GET",
":scheme", "http", ":scheme", "http",
":path", "/", ":path", "/",
":authority", "www.example.com"), hpackReader.getAndResetHeaderList()); ":authority", "www.example.com"));
} }
private void secondRequestWithHuffman() { private void secondRequestWithHuffman() {
@ -730,7 +734,7 @@ public final class HpackTest {
} }
private void checkReadSecondRequestWithHuffman() { private void checkReadSecondRequestWithHuffman() {
assertEquals(2, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(2);
// [ 1] (s = 53) cache-control: no-cache // [ 1] (s = 53) cache-control: no-cache
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 2]; Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 2];
@ -741,15 +745,15 @@ public final class HpackTest {
checkEntry(entry, ":authority", "www.example.com", 57); checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 110 // Table size: 110
assertEquals(110, hpackReader.dynamicTableByteCount); assertThat(hpackReader.dynamicTableByteCount).isEqualTo(110);
// Decoded header list: // Decoded header list:
assertEquals(headerEntries( assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET", ":method", "GET",
":scheme", "http", ":scheme", "http",
":path", "/", ":path", "/",
":authority", "www.example.com", ":authority", "www.example.com",
"cache-control", "no-cache"), hpackReader.getAndResetHeaderList()); "cache-control", "no-cache"));
} }
private void thirdRequestWithHuffman() { private void thirdRequestWithHuffman() {
@ -771,7 +775,7 @@ public final class HpackTest {
} }
private void checkReadThirdRequestWithHuffman() { private void checkReadThirdRequestWithHuffman() {
assertEquals(3, hpackReader.headerCount); assertThat(hpackReader.headerCount).isEqualTo(3);
// [ 1] (s = 54) custom-key: custom-value // [ 1] (s = 54) custom-key: custom-value
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 3]; Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 3];
@ -786,24 +790,24 @@ public final class HpackTest {
checkEntry(entry, ":authority", "www.example.com", 57); checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 164 // Table size: 164
assertEquals(164, hpackReader.dynamicTableByteCount); assertThat(hpackReader.dynamicTableByteCount).isEqualTo(164);
// Decoded header list: // Decoded header list:
assertEquals(headerEntries( assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET", ":method", "GET",
":scheme", "https", ":scheme", "https",
":path", "/index.html", ":path", "/index.html",
":authority", "www.example.com", ":authority", "www.example.com",
"custom-key", "custom-value"), hpackReader.getAndResetHeaderList()); "custom-key", "custom-value"));
} }
@Test public void readSingleByteInt() throws IOException { @Test public void readSingleByteInt() throws IOException {
assertEquals(10, newReader(byteStream()).readInt(10, 31)); assertThat(newReader(byteStream()).readInt(10, 31)).isEqualTo(10);
assertEquals(10, newReader(byteStream()).readInt(0xe0 | 10, 31)); assertThat(newReader(byteStream()).readInt(0xe0 | 10, 31)).isEqualTo(10);
} }
@Test public void readMultibyteInt() throws IOException { @Test public void readMultibyteInt() throws IOException {
assertEquals(1337, newReader(byteStream(154, 10)).readInt(31, 31)); assertThat(newReader(byteStream(154, 10)).readInt(31, 31)).isEqualTo(1337);
} }
@Test public void writeSingleByteInt() throws IOException { @Test public void writeSingleByteInt() throws IOException {
@ -823,26 +827,26 @@ public final class HpackTest {
@Test public void max31BitValue() throws IOException { @Test public void max31BitValue() throws IOException {
hpackWriter.writeInt(0x7fffffff, 31, 0); hpackWriter.writeInt(0x7fffffff, 31, 0);
assertBytes(31, 224, 255, 255, 255, 7); assertBytes(31, 224, 255, 255, 255, 7);
assertEquals(0x7fffffff, assertThat(newReader(byteStream(224, 255, 255, 255, 7)).readInt(31, 31)).isEqualTo(
newReader(byteStream(224, 255, 255, 255, 7)).readInt(31, 31)); (long) 0x7fffffff);
} }
@Test public void prefixMask() throws IOException { @Test public void prefixMask() throws IOException {
hpackWriter.writeInt(31, 31, 0); hpackWriter.writeInt(31, 31, 0);
assertBytes(31, 0); assertBytes(31, 0);
assertEquals(31, newReader(byteStream(0)).readInt(31, 31)); assertThat(newReader(byteStream(0)).readInt(31, 31)).isEqualTo(31);
} }
@Test public void prefixMaskMinusOne() throws IOException { @Test public void prefixMaskMinusOne() throws IOException {
hpackWriter.writeInt(30, 31, 0); hpackWriter.writeInt(30, 31, 0);
assertBytes(30); assertBytes(30);
assertEquals(31, newReader(byteStream(0)).readInt(31, 31)); assertThat(newReader(byteStream(0)).readInt(31, 31)).isEqualTo(31);
} }
@Test public void zero() throws IOException { @Test public void zero() throws IOException {
hpackWriter.writeInt(0, 31, 0); hpackWriter.writeInt(0, 31, 0);
assertBytes(0); assertBytes(0);
assertEquals(0, newReader(byteStream()).readInt(0, 31)); assertThat(newReader(byteStream()).readInt(0, 31)).isEqualTo(0);
} }
@Test public void lowercaseHeaderNameBeforeEmit() throws IOException { @Test public void lowercaseHeaderNameBeforeEmit() throws IOException {
@ -855,14 +859,15 @@ public final class HpackTest {
newReader(byteStream(0, 3, 'F', 'o', 'o', 3, 'B', 'a', 'R')).readHeaders(); newReader(byteStream(0, 3, 'F', 'o', 'o', 3, 'B', 'a', 'R')).readHeaders();
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("PROTOCOL_ERROR response malformed: mixed case name: Foo", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"PROTOCOL_ERROR response malformed: mixed case name: Foo");
} }
} }
@Test public void emptyHeaderName() throws IOException { @Test public void emptyHeaderName() throws IOException {
hpackWriter.writeByteString(ByteString.encodeUtf8("")); hpackWriter.writeByteString(ByteString.encodeUtf8(""));
assertBytes(0); assertBytes(0);
assertEquals(ByteString.EMPTY, newReader(byteStream(0)).readByteString()); assertThat(newReader(byteStream(0)).readByteString()).isEqualTo(ByteString.EMPTY);
} }
@Test public void emitsDynamicTableSizeUpdate() throws IOException { @Test public void emitsDynamicTableSizeUpdate() throws IOException {
@ -931,13 +936,13 @@ public final class HpackTest {
"custom-key1", "custom-header", "custom-key1", "custom-header",
"custom-key2", "custom-header"); "custom-key2", "custom-header");
hpackWriter.writeHeaders(headerBlock); hpackWriter.writeHeaders(headerBlock);
assertEquals(2, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(2);
hpackWriter.setHeaderTableSizeSetting(56); hpackWriter.setHeaderTableSizeSetting(56);
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
hpackWriter.setHeaderTableSizeSetting(0); hpackWriter.setHeaderTableSizeSetting(0);
assertEquals(0, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(0);
} }
@Test public void noEvictionOnDynamicTableSizeIncrease() throws IOException { @Test public void noEvictionOnDynamicTableSizeIncrease() throws IOException {
@ -946,15 +951,15 @@ public final class HpackTest {
"custom-key1", "custom-header", "custom-key1", "custom-header",
"custom-key2", "custom-header"); "custom-key2", "custom-header");
hpackWriter.writeHeaders(headerBlock); hpackWriter.writeHeaders(headerBlock);
assertEquals(2, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(2);
hpackWriter.setHeaderTableSizeSetting(8192); hpackWriter.setHeaderTableSizeSetting(8192);
assertEquals(2, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(2);
} }
@Test public void dynamicTableSizeHasAnUpperBound() { @Test public void dynamicTableSizeHasAnUpperBound() {
hpackWriter.setHeaderTableSizeSetting(1048576); hpackWriter.setHeaderTableSizeSetting(1048576);
assertEquals(16384, hpackWriter.maxDynamicTableByteCount); assertThat(hpackWriter.maxDynamicTableByteCount).isEqualTo(16384);
} }
@Test public void huffmanEncode() throws IOException { @Test public void huffmanEncode() throws IOException {
@ -973,33 +978,33 @@ public final class HpackTest {
.readByteString(); .readByteString();
ByteString actual = bytesOut.readByteString(); ByteString actual = bytesOut.readByteString();
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test public void staticTableIndexedHeaders() throws IOException { @Test public void staticTableIndexedHeaders() throws IOException {
hpackWriter.writeHeaders(headerEntries(":method", "GET")); hpackWriter.writeHeaders(headerEntries(":method", "GET"));
assertBytes(0x82); assertBytes(0x82);
assertEquals(0, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":method", "POST")); hpackWriter.writeHeaders(headerEntries(":method", "POST"));
assertBytes(0x83); assertBytes(0x83);
assertEquals(0, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":path", "/")); hpackWriter.writeHeaders(headerEntries(":path", "/"));
assertBytes(0x84); assertBytes(0x84);
assertEquals(0, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":path", "/index.html")); hpackWriter.writeHeaders(headerEntries(":path", "/index.html"));
assertBytes(0x85); assertBytes(0x85);
assertEquals(0, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":scheme", "http")); hpackWriter.writeHeaders(headerEntries(":scheme", "http"));
assertBytes(0x86); assertBytes(0x86);
assertEquals(0, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":scheme", "https")); hpackWriter.writeHeaders(headerEntries(":scheme", "https"));
assertBytes(0x87); assertBytes(0x87);
assertEquals(0, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(0);
} }
@Test public void dynamicTableIndexedHeader() throws IOException { @Test public void dynamicTableIndexedHeader() throws IOException {
@ -1007,64 +1012,64 @@ public final class HpackTest {
assertBytes(0x40, assertBytes(0x40,
10, 'c', 'u', 's', 't', 'o', 'm', '-', 'k', 'e', 'y', 10, 'c', 'u', 's', 't', 'o', 'm', '-', 'k', 'e', 'y',
13, 'c', 'u', 's', 't', 'o', 'm', '-', 'h', 'e', 'a', 'd', 'e', 'r'); 13, 'c', 'u', 's', 't', 'o', 'm', '-', 'h', 'e', 'a', 'd', 'e', 'r');
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
hpackWriter.writeHeaders(headerEntries("custom-key", "custom-header")); hpackWriter.writeHeaders(headerEntries("custom-key", "custom-header"));
assertBytes(0xbe); assertBytes(0xbe);
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
} }
@Test public void doNotIndexPseudoHeaders() throws IOException { @Test public void doNotIndexPseudoHeaders() throws IOException {
hpackWriter.writeHeaders(headerEntries(":method", "PUT")); hpackWriter.writeHeaders(headerEntries(":method", "PUT"));
assertBytes(0x02, 3, 'P', 'U', 'T'); assertBytes(0x02, 3, 'P', 'U', 'T');
assertEquals(0, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":path", "/okhttp")); hpackWriter.writeHeaders(headerEntries(":path", "/okhttp"));
assertBytes(0x04, 7, '/', 'o', 'k', 'h', 't', 't', 'p'); assertBytes(0x04, 7, '/', 'o', 'k', 'h', 't', 't', 'p');
assertEquals(0, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(0);
} }
@Test public void incrementalIndexingWithAuthorityPseudoHeader() throws IOException { @Test public void incrementalIndexingWithAuthorityPseudoHeader() throws IOException {
hpackWriter.writeHeaders(headerEntries(":authority", "foo.com")); hpackWriter.writeHeaders(headerEntries(":authority", "foo.com"));
assertBytes(0x41, 7, 'f', 'o', 'o', '.', 'c', 'o', 'm'); assertBytes(0x41, 7, 'f', 'o', 'o', '.', 'c', 'o', 'm');
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
hpackWriter.writeHeaders(headerEntries(":authority", "foo.com")); hpackWriter.writeHeaders(headerEntries(":authority", "foo.com"));
assertBytes(0xbe); assertBytes(0xbe);
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
// If the :authority header somehow changes, it should be re-added to the dynamic table. // If the :authority header somehow changes, it should be re-added to the dynamic table.
hpackWriter.writeHeaders(headerEntries(":authority", "bar.com")); hpackWriter.writeHeaders(headerEntries(":authority", "bar.com"));
assertBytes(0x41, 7, 'b', 'a', 'r', '.', 'c', 'o', 'm'); assertBytes(0x41, 7, 'b', 'a', 'r', '.', 'c', 'o', 'm');
assertEquals(2, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(2);
hpackWriter.writeHeaders(headerEntries(":authority", "bar.com")); hpackWriter.writeHeaders(headerEntries(":authority", "bar.com"));
assertBytes(0xbe); assertBytes(0xbe);
assertEquals(2, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(2);
} }
@Test public void incrementalIndexingWithStaticTableIndexedName() throws IOException { @Test public void incrementalIndexingWithStaticTableIndexedName() throws IOException {
hpackWriter.writeHeaders(headerEntries("accept-encoding", "gzip")); hpackWriter.writeHeaders(headerEntries("accept-encoding", "gzip"));
assertBytes(0x50, 4, 'g', 'z', 'i', 'p'); assertBytes(0x50, 4, 'g', 'z', 'i', 'p');
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
hpackWriter.writeHeaders(headerEntries("accept-encoding", "gzip")); hpackWriter.writeHeaders(headerEntries("accept-encoding", "gzip"));
assertBytes(0xbe); assertBytes(0xbe);
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
} }
@Test public void incrementalIndexingWithDynamcTableIndexedName() throws IOException { @Test public void incrementalIndexingWithDynamcTableIndexedName() throws IOException {
hpackWriter.writeHeaders(headerEntries("foo", "bar")); hpackWriter.writeHeaders(headerEntries("foo", "bar"));
assertBytes(0x40, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r'); assertBytes(0x40, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r');
assertEquals(1, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(1);
hpackWriter.writeHeaders(headerEntries("foo", "bar1")); hpackWriter.writeHeaders(headerEntries("foo", "bar1"));
assertBytes(0x7e, 4, 'b', 'a', 'r', '1'); assertBytes(0x7e, 4, 'b', 'a', 'r', '1');
assertEquals(2, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(2);
hpackWriter.writeHeaders(headerEntries("foo", "bar1")); hpackWriter.writeHeaders(headerEntries("foo", "bar1"));
assertBytes(0xbe); assertBytes(0xbe);
assertEquals(2, hpackWriter.headerCount); assertThat(hpackWriter.headerCount).isEqualTo(2);
} }
private Hpack.Reader newReader(Buffer source) { private Hpack.Reader newReader(Buffer source) {
@ -1076,15 +1081,15 @@ public final class HpackTest {
} }
private void checkEntry(Header entry, String name, String value, int size) { private void checkEntry(Header entry, String name, String value, int size) {
assertEquals(name, entry.name.utf8()); assertThat(entry.name.utf8()).isEqualTo(name);
assertEquals(value, entry.value.utf8()); assertThat(entry.value.utf8()).isEqualTo(value);
assertEquals(size, entry.hpackSize); assertThat(entry.hpackSize).isEqualTo(size);
} }
private void assertBytes(int... bytes) throws IOException { private void assertBytes(int... bytes) throws IOException {
ByteString expected = intArrayToByteArray(bytes); ByteString expected = intArrayToByteArray(bytes);
ByteString actual = bytesOut.readByteString(); ByteString actual = bytesOut.readByteString();
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
private ByteString intArrayToByteArray(int[] bytes) { private ByteString intArrayToByteArray(int[] bytes) {

View File

@ -35,9 +35,7 @@ import static okhttp3.internal.http2.Http2.FLAG_END_STREAM;
import static okhttp3.internal.http2.Http2.FLAG_NONE; import static okhttp3.internal.http2.Http2.FLAG_NONE;
import static okhttp3.internal.http2.Http2.FLAG_PADDED; import static okhttp3.internal.http2.Http2.FLAG_PADDED;
import static okhttp3.internal.http2.Http2.FLAG_PRIORITY; import static okhttp3.internal.http2.Http2.FLAG_PRIORITY;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class Http2Test { public final class Http2Test {
@ -65,15 +63,16 @@ public final class Http2Test {
frame.writeInt(expectedStreamId & 0x7fffffff); frame.writeInt(expectedStreamId & 0x7fffffff);
frame.writeAll(headerBytes); frame.writeAll(headerBytes);
assertEquals(frame, sendHeaderFrames(true, sentHeaders)); // Check writer sends the same bytes. // Check writer sends the same bytes.
assertThat(sendHeaderFrames(true, sentHeaders)).isEqualTo(frame);
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void headers(boolean inFinished, int streamId, @Override public void headers(boolean inFinished, int streamId,
int associatedStreamId, List<Header> headerBlock) { int associatedStreamId, List<Header> headerBlock) {
assertTrue(inFinished); assertThat(inFinished).isTrue();
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(-1, associatedStreamId); assertThat(associatedStreamId).isEqualTo(-1);
assertEquals(sentHeaders, headerBlock); assertThat(headerBlock).isEqualTo(sentHeaders);
} }
}); });
} }
@ -93,17 +92,17 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void priority(int streamId, int streamDependency, int weight, @Override public void priority(int streamId, int streamDependency, int weight,
boolean exclusive) { boolean exclusive) {
assertEquals(0, streamDependency); assertThat(streamDependency).isEqualTo(0);
assertEquals(256, weight); assertThat(weight).isEqualTo(256);
assertFalse(exclusive); assertThat(exclusive).isFalse();
} }
@Override public void headers(boolean inFinished, int streamId, @Override public void headers(boolean inFinished, int streamId,
int associatedStreamId, List<Header> nameValueBlock) { int associatedStreamId, List<Header> nameValueBlock) {
assertFalse(inFinished); assertThat(inFinished).isFalse();
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(-1, associatedStreamId); assertThat(associatedStreamId).isEqualTo(-1);
assertEquals(sentHeaders, nameValueBlock); assertThat(nameValueBlock).isEqualTo(sentHeaders);
} }
}); });
} }
@ -128,16 +127,17 @@ public final class Http2Test {
frame.writeInt(expectedStreamId & 0x7fffffff); frame.writeInt(expectedStreamId & 0x7fffffff);
frame.writeAll(headerBlock); frame.writeAll(headerBlock);
assertEquals(frame, sendHeaderFrames(false, sentHeaders)); // Check writer sends the same bytes. // Check writer sends the same bytes.
assertThat(sendHeaderFrames(false, sentHeaders)).isEqualTo(frame);
// Reading the above frames should result in a concatenated headerBlock. // Reading the above frames should result in a concatenated headerBlock.
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void headers(boolean inFinished, int streamId, @Override public void headers(boolean inFinished, int streamId,
int associatedStreamId, List<Header> headerBlock) { int associatedStreamId, List<Header> headerBlock) {
assertFalse(inFinished); assertThat(inFinished).isFalse();
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(-1, associatedStreamId); assertThat(associatedStreamId).isEqualTo(-1);
assertEquals(sentHeaders, headerBlock); assertThat(headerBlock).isEqualTo(sentHeaders);
} }
}); });
} }
@ -161,14 +161,15 @@ public final class Http2Test {
frame.writeInt(expectedPromisedStreamId & 0x7fffffff); frame.writeInt(expectedPromisedStreamId & 0x7fffffff);
frame.writeAll(headerBytes); frame.writeAll(headerBytes);
assertEquals(frame, sendPushPromiseFrames(expectedPromisedStreamId, pushPromise)); assertThat(sendPushPromiseFrames(expectedPromisedStreamId, pushPromise)).isEqualTo(
frame);
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override @Override
public void pushPromise(int streamId, int promisedStreamId, List<Header> headerBlock) { public void pushPromise(int streamId, int promisedStreamId, List<Header> headerBlock) {
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(expectedPromisedStreamId, promisedStreamId); assertThat(promisedStreamId).isEqualTo(expectedPromisedStreamId);
assertEquals(pushPromise, headerBlock); assertThat(headerBlock).isEqualTo(pushPromise);
} }
}); });
} }
@ -196,15 +197,16 @@ public final class Http2Test {
frame.writeInt(expectedStreamId & 0x7fffffff); frame.writeInt(expectedStreamId & 0x7fffffff);
frame.writeAll(headerBlock); frame.writeAll(headerBlock);
assertEquals(frame, sendPushPromiseFrames(expectedPromisedStreamId, pushPromise)); assertThat(sendPushPromiseFrames(expectedPromisedStreamId, pushPromise)).isEqualTo(
frame);
// Reading the above frames should result in a concatenated headerBlock. // Reading the above frames should result in a concatenated headerBlock.
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override @Override
public void pushPromise(int streamId, int promisedStreamId, List<Header> headerBlock) { public void pushPromise(int streamId, int promisedStreamId, List<Header> headerBlock) {
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(expectedPromisedStreamId, promisedStreamId); assertThat(promisedStreamId).isEqualTo(expectedPromisedStreamId);
assertEquals(pushPromise, headerBlock); assertThat(headerBlock).isEqualTo(pushPromise);
} }
}); });
} }
@ -218,8 +220,8 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void rstStream(int streamId, ErrorCode errorCode) { @Override public void rstStream(int streamId, ErrorCode errorCode) {
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(ErrorCode.PROTOCOL_ERROR, errorCode); assertThat(errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR);
} }
}); });
} }
@ -238,9 +240,10 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void settings(boolean clearPrevious, Settings settings) { @Override public void settings(boolean clearPrevious, Settings settings) {
assertFalse(clearPrevious); // No clearPrevious in HTTP/2. // No clearPrevious in HTTP/2.
assertEquals(reducedTableSizeBytes, settings.getHeaderTableSize()); assertThat(clearPrevious).isFalse();
assertFalse(settings.getEnablePush(true)); assertThat(settings.getHeaderTableSize()).isEqualTo(reducedTableSizeBytes);
assertThat(settings.getEnablePush(true)).isFalse();
} }
}); });
} }
@ -257,7 +260,7 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler()); reader.nextFrame(false, new BaseTestHandler());
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1", e.getMessage()); assertThat(e.getMessage()).isEqualTo("PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1");
} }
} }
@ -275,7 +278,7 @@ public final class Http2Test {
settingValue.set(settings.get(7)); settingValue.set(settings.get(7));
} }
}); });
assertEquals(settingValue.intValue(), 1); assertThat(1).isEqualTo(settingValue.intValue());
} }
@Test public void readSettingsFrameExperimentalId() throws IOException { @Test public void readSettingsFrameExperimentalId() throws IOException {
@ -305,7 +308,8 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler()); reader.nextFrame(false, new BaseTestHandler());
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("PROTOCOL_ERROR SETTINGS_INITIAL_WINDOW_SIZE > 2^31 - 1", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"PROTOCOL_ERROR SETTINGS_INITIAL_WINDOW_SIZE > 2^31 - 1");
} }
} }
@ -321,7 +325,8 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler()); reader.nextFrame(false, new BaseTestHandler());
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: -2147483648", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: -2147483648");
} }
} }
@ -337,7 +342,7 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler()); reader.nextFrame(false, new BaseTestHandler());
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16383", e.getMessage()); assertThat(e.getMessage()).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16383");
} }
} }
@ -353,7 +358,8 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler()); reader.nextFrame(false, new BaseTestHandler());
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16777216", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16777216");
} }
} }
@ -369,13 +375,13 @@ public final class Http2Test {
frame.writeInt(expectedPayload2); frame.writeInt(expectedPayload2);
// Check writer sends the same bytes. // Check writer sends the same bytes.
assertEquals(frame, sendPingFrame(true, expectedPayload1, expectedPayload2)); assertThat(sendPingFrame(true, expectedPayload1, expectedPayload2)).isEqualTo(frame);
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void ping(boolean ack, int payload1, int payload2) { @Override public void ping(boolean ack, int payload1, int payload2) {
assertTrue(ack); assertThat(ack).isTrue();
assertEquals(expectedPayload1, payload1); assertThat(payload1).isEqualTo(expectedPayload1);
assertEquals(expectedPayload2, payload2); assertThat(payload2).isEqualTo(expectedPayload2);
} }
}); });
} }
@ -391,17 +397,17 @@ public final class Http2Test {
frame.write(expectedData); frame.write(expectedData);
// Check writer sends the same bytes. // Check writer sends the same bytes.
assertEquals(frame, sendDataFrame(new Buffer().write(expectedData))); assertThat(sendDataFrame(new Buffer().write(expectedData))).isEqualTo(frame);
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void data(boolean inFinished, int streamId, BufferedSource source, @Override public void data(boolean inFinished, int streamId, BufferedSource source,
int length) throws IOException { int length) throws IOException {
assertFalse(inFinished); assertThat(inFinished).isFalse();
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(Http2.INITIAL_MAX_FRAME_SIZE, length); assertThat(length).isEqualTo(Http2.INITIAL_MAX_FRAME_SIZE);
ByteString data = source.readByteString(length); ByteString data = source.readByteString(length);
for (byte b : data.toByteArray()) { for (byte b : data.toByteArray()) {
assertEquals(2, b); assertThat(b).isEqualTo((byte) 2);
} }
} }
}); });
@ -420,7 +426,7 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler()); reader.nextFrame(false, new BaseTestHandler());
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("PROTOCOL_ERROR: TYPE_DATA streamId == 0", e.getMessage()); assertThat(e.getMessage()).isEqualTo("PROTOCOL_ERROR: TYPE_DATA streamId == 0");
} }
} }
@ -441,8 +447,8 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler()); reader.nextFrame(false, new BaseTestHandler());
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA", assertThat(e.getMessage()).isEqualTo(
e.getMessage()); "PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA");
} }
} }
@ -464,7 +470,8 @@ public final class Http2Test {
frame.write(padding); frame.write(padding);
reader.nextFrame(false, assertData()); reader.nextFrame(false, assertData());
assertTrue(frame.exhausted()); // Padding was skipped. // Padding was skipped.
assertThat(frame.exhausted()).isTrue();
} }
@Test public void readPaddedDataFrameZeroPadding() throws IOException { @Test public void readPaddedDataFrameZeroPadding() throws IOException {
@ -497,7 +504,8 @@ public final class Http2Test {
frame.write(padding); frame.write(padding);
reader.nextFrame(false, assertHeaderBlock()); reader.nextFrame(false, assertHeaderBlock());
assertTrue(frame.exhausted()); // Padding was skipped. // Padding was skipped.
assertThat(frame.exhausted()).isTrue();
} }
@Test public void readPaddedHeadersFrameZeroPadding() throws IOException { @Test public void readPaddedHeadersFrameZeroPadding() throws IOException {
@ -538,7 +546,7 @@ public final class Http2Test {
frame.writeAll(headerBlock); frame.writeAll(headerBlock);
reader.nextFrame(false, assertHeaderBlock()); reader.nextFrame(false, assertHeaderBlock());
assertTrue(frame.exhausted()); assertThat(frame.exhausted()).isTrue();
} }
@Test public void tooLargeDataFrame() throws IOException { @Test public void tooLargeDataFrame() throws IOException {
@ -546,7 +554,7 @@ public final class Http2Test {
sendDataFrame(new Buffer().write(new byte[0x1000000])); sendDataFrame(new Buffer().write(new byte[0x1000000]));
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("FRAME_SIZE_ERROR length > 16384: 16777216", e.getMessage()); assertThat(e.getMessage()).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216");
} }
} }
@ -560,12 +568,12 @@ public final class Http2Test {
frame.writeInt((int) expectedWindowSizeIncrement); frame.writeInt((int) expectedWindowSizeIncrement);
// Check writer sends the same bytes. // Check writer sends the same bytes.
assertEquals(frame, windowUpdate(expectedWindowSizeIncrement)); assertThat(windowUpdate(expectedWindowSizeIncrement)).isEqualTo(frame);
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void windowUpdate(int streamId, long windowSizeIncrement) { @Override public void windowUpdate(int streamId, long windowSizeIncrement) {
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(expectedWindowSizeIncrement, windowSizeIncrement); assertThat(windowSizeIncrement).isEqualTo(expectedWindowSizeIncrement);
} }
}); });
} }
@ -575,15 +583,15 @@ public final class Http2Test {
windowUpdate(0); windowUpdate(0);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 0", assertThat(e.getMessage()).isEqualTo(
e.getMessage()); "windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 0");
} }
try { try {
windowUpdate(0x80000000L); windowUpdate(0x80000000L);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 2147483648", assertThat(e.getMessage()).isEqualTo(
e.getMessage()); "windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 2147483648");
} }
} }
@ -598,14 +606,15 @@ public final class Http2Test {
frame.writeInt(expectedError.httpCode); frame.writeInt(expectedError.httpCode);
// Check writer sends the same bytes. // Check writer sends the same bytes.
assertEquals(frame, sendGoAway(expectedStreamId, expectedError, Util.EMPTY_BYTE_ARRAY)); assertThat(sendGoAway(expectedStreamId, expectedError, Util.EMPTY_BYTE_ARRAY)).isEqualTo(
frame);
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void goAway( @Override public void goAway(
int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) { int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
assertEquals(expectedStreamId, lastGoodStreamId); assertThat(lastGoodStreamId).isEqualTo(expectedStreamId);
assertEquals(expectedError, errorCode); assertThat(errorCode).isEqualTo(expectedError);
assertEquals(0, debugData.size()); assertThat(debugData.size()).isEqualTo(0);
} }
}); });
} }
@ -624,14 +633,14 @@ public final class Http2Test {
frame.write(expectedData.toByteArray()); frame.write(expectedData.toByteArray());
// Check writer sends the same bytes. // Check writer sends the same bytes.
assertEquals(frame, sendGoAway(0, expectedError, expectedData.toByteArray())); assertThat(sendGoAway(0, expectedError, expectedData.toByteArray())).isEqualTo(frame);
reader.nextFrame(false, new BaseTestHandler() { reader.nextFrame(false, new BaseTestHandler() {
@Override public void goAway( @Override public void goAway(
int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) { int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
assertEquals(0, lastGoodStreamId); assertThat(lastGoodStreamId).isEqualTo(0);
assertEquals(expectedError, errorCode); assertThat(errorCode).isEqualTo(expectedError);
assertEquals(expectedData, debugData); assertThat(debugData).isEqualTo(expectedData);
} }
}); });
} }
@ -644,7 +653,7 @@ public final class Http2Test {
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// TODO: real max is based on settings between 16384 and 16777215 // TODO: real max is based on settings between 16384 and 16777215
assertEquals("FRAME_SIZE_ERROR length > 16384: 16777216", e.getMessage()); assertThat(e.getMessage()).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216");
} }
} }
@ -655,7 +664,7 @@ public final class Http2Test {
writer.applyAndAckSettings(new Settings().set(Settings.MAX_FRAME_SIZE, newMaxFrameSize)); writer.applyAndAckSettings(new Settings().set(Settings.MAX_FRAME_SIZE, newMaxFrameSize));
assertEquals(newMaxFrameSize, writer.maxDataLength()); assertThat(writer.maxDataLength()).isEqualTo(newMaxFrameSize);
writer.frameHeader(0, newMaxFrameSize, Http2.TYPE_DATA, FLAG_NONE); writer.frameHeader(0, newMaxFrameSize, Http2.TYPE_DATA, FLAG_NONE);
} }
@ -668,7 +677,7 @@ public final class Http2Test {
writer.frameHeader(streamId, Http2.INITIAL_MAX_FRAME_SIZE, Http2.TYPE_DATA, FLAG_NONE); writer.frameHeader(streamId, Http2.INITIAL_MAX_FRAME_SIZE, Http2.TYPE_DATA, FLAG_NONE);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("reserved bit set: -2147483645", e.getMessage()); assertThat(e.getMessage()).isEqualTo("reserved bit set: -2147483645");
} }
} }
@ -720,10 +729,10 @@ public final class Http2Test {
return new BaseTestHandler() { return new BaseTestHandler() {
@Override public void headers(boolean inFinished, int streamId, @Override public void headers(boolean inFinished, int streamId,
int associatedStreamId, List<Header> headerBlock) { int associatedStreamId, List<Header> headerBlock) {
assertFalse(inFinished); assertThat(inFinished).isFalse();
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(-1, associatedStreamId); assertThat(associatedStreamId).isEqualTo(-1);
assertEquals(headerEntries("foo", "barrr", "baz", "qux"), headerBlock); assertThat(headerBlock).isEqualTo(headerEntries("foo", "barrr", "baz", "qux"));
} }
}; };
} }
@ -732,12 +741,12 @@ public final class Http2Test {
return new BaseTestHandler() { return new BaseTestHandler() {
@Override public void data(boolean inFinished, int streamId, BufferedSource source, @Override public void data(boolean inFinished, int streamId, BufferedSource source,
int length) throws IOException { int length) throws IOException {
assertFalse(inFinished); assertThat(inFinished).isFalse();
assertEquals(expectedStreamId, streamId); assertThat(streamId).isEqualTo(expectedStreamId);
assertEquals(1123, length); assertThat(length).isEqualTo(1123);
ByteString data = source.readByteString(length); ByteString data = source.readByteString(length);
for (byte b : data.toByteArray()) { for (byte b : data.toByteArray()) {
assertEquals(2, b); assertThat(b).isEqualTo((byte) 2);
} }
} }
}; };

View File

@ -65,6 +65,7 @@ import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.GzipSink; import okio.GzipSink;
import okio.Okio; import okio.Okio;
import org.assertj.core.api.Assertions;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
@ -80,11 +81,9 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.assertj.core.data.Offset.offset;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
@ -163,15 +162,16 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABCDE", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
assertEquals("", response.message()); Assertions.assertThat(response.message()).isEqualTo("");
assertEquals(protocol, response.protocol()); Assertions.assertThat(response.protocol()).isEqualTo(protocol);
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request.getRequestLine()); Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1");
assertEquals(scheme, request.getHeader(":scheme")); Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme);
assertEquals(server.getHostName() + ":" + server.getPort(), request.getHeader(":authority")); Assertions.assertThat(request.getHeader(":authority")).isEqualTo(
(server.getHostName() + ":" + server.getPort()));
} }
@Test public void emptyResponse() throws IOException { @Test public void emptyResponse() throws IOException {
@ -182,7 +182,7 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(-1, response.body().byteStream().read()); Assertions.assertThat(response.body().byteStream().read()).isEqualTo(-1);
response.body().close(); response.body().close();
} }
@ -205,12 +205,12 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABCDE", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("POST /foo HTTP/1.1", request.getRequestLine()); Assertions.assertThat(request.getRequestLine()).isEqualTo("POST /foo HTTP/1.1");
assertArrayEquals(postBytes, request.getBody().readByteArray()); assertArrayEquals(postBytes, request.getBody().readByteArray());
assertNull(request.getHeader("Content-Length")); Assertions.assertThat(request.getHeader("Content-Length")).isNull();
} }
@Test public void userSuppliedContentLengthHeader() throws Exception { @Test public void userSuppliedContentLengthHeader() throws Exception {
@ -236,12 +236,13 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABCDE", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("POST /foo HTTP/1.1", request.getRequestLine()); Assertions.assertThat(request.getRequestLine()).isEqualTo("POST /foo HTTP/1.1");
assertArrayEquals(postBytes, request.getBody().readByteArray()); assertArrayEquals(postBytes, request.getBody().readByteArray());
assertEquals(postBytes.length, Integer.parseInt(request.getHeader("Content-Length"))); Assertions.assertThat(Integer.parseInt(request.getHeader("Content-Length"))).isEqualTo(
(long) postBytes.length);
} }
@Test public void closeAfterFlush() throws Exception { @Test public void closeAfterFlush() throws Exception {
@ -269,12 +270,13 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABCDE", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("POST /foo HTTP/1.1", request.getRequestLine()); Assertions.assertThat(request.getRequestLine()).isEqualTo("POST /foo HTTP/1.1");
assertArrayEquals(postBytes, request.getBody().readByteArray()); assertArrayEquals(postBytes, request.getBody().readByteArray());
assertEquals(postBytes.length, Integer.parseInt(request.getHeader("Content-Length"))); Assertions.assertThat(Integer.parseInt(request.getHeader("Content-Length"))).isEqualTo(
(long) postBytes.length);
} }
@Test public void connectionReuse() throws Exception { @Test public void connectionReuse() throws Exception {
@ -290,12 +292,12 @@ public final class HttpOverHttp2Test {
Response response1 = call1.execute(); Response response1 = call1.execute();
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("ABC", response1.body().source().readUtf8(3)); Assertions.assertThat(response1.body().source().readUtf8(3)).isEqualTo("ABC");
assertEquals("GHI", response2.body().source().readUtf8(3)); Assertions.assertThat(response2.body().source().readUtf8(3)).isEqualTo("GHI");
assertEquals("DEF", response1.body().source().readUtf8(3)); Assertions.assertThat(response1.body().source().readUtf8(3)).isEqualTo("DEF");
assertEquals("JKL", response2.body().source().readUtf8(3)); Assertions.assertThat(response2.body().source().readUtf8(3)).isEqualTo("JKL");
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(1, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
response1.close(); response1.close();
response2.close(); response2.close();
@ -317,14 +319,14 @@ public final class HttpOverHttp2Test {
// Cancel the call and discard what we've buffered for the response body. This should free up // Cancel the call and discard what we've buffered for the response body. This should free up
// the connection flow-control window so new requests can proceed. // the connection flow-control window so new requests can proceed.
call1.cancel(); call1.cancel();
assertFalse("Call should not have completed successfully.", Assertions.assertThat(Util.discard(response1.body().source(), 1, TimeUnit.SECONDS)).overridingErrorMessage(
Util.discard(response1.body().source(), 1, TimeUnit.SECONDS)); "Call should not have completed successfully.").isFalse();
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("abc", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("abc");
} }
/** Wait for the client to receive {@code dataLength} DATA frames. */ /** Wait for the client to receive {@code dataLength} DATA frames. */
@ -361,7 +363,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("abc", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("abc");
} }
@Test public void concurrentRequestWithEmptyFlowControlWindow() throws Exception { @Test public void concurrentRequestWithEmptyFlowControlWindow() throws Exception {
@ -377,9 +379,10 @@ public final class HttpOverHttp2Test {
waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE); waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE);
assertEquals(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE, response1.body().contentLength()); Assertions.assertThat(response1.body().contentLength()).isEqualTo(
(long) Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE);
int read = response1.body().source().read(new byte[8192]); int read = response1.body().source().read(new byte[8192]);
assertEquals(8192, read); Assertions.assertThat(read).isEqualTo(8192);
// Make a second call that should transmit the response headers. The response body won't be // Make a second call that should transmit the response headers. The response body won't be
// transmitted until the flow-control window is updated from the first request. // transmitted until the flow-control window is updated from the first request.
@ -387,13 +390,13 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals(200, response2.code()); Assertions.assertThat(response2.code()).isEqualTo(200);
// Close the response body. This should discard the buffered data and update the connection // Close the response body. This should discard the buffered data and update the connection
// flow-control window. // flow-control window.
response1.close(); response1.close();
assertEquals("abc", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("abc");
} }
/** https://github.com/square/okhttp/issues/373 */ /** https://github.com/square/okhttp/issues/373 */
@ -406,8 +409,8 @@ public final class HttpOverHttp2Test {
executor.execute(new AsyncRequest("/r1", countDownLatch)); executor.execute(new AsyncRequest("/r1", countDownLatch));
executor.execute(new AsyncRequest("/r2", countDownLatch)); executor.execute(new AsyncRequest("/r2", countDownLatch));
countDownLatch.await(); countDownLatch.await();
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(1, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void gzippedResponseBody() throws Exception { @Test public void gzippedResponseBody() throws Exception {
@ -420,7 +423,7 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABCABCABC", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABCABCABC");
} }
@Test public void authenticate() throws Exception { @Test public void authenticate() throws Exception {
@ -440,13 +443,13 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("Successful auth!", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("Successful auth!");
RecordedRequest denied = server.takeRequest(); RecordedRequest denied = server.takeRequest();
assertNull(denied.getHeader("Authorization")); Assertions.assertThat(denied.getHeader("Authorization")).isNull();
RecordedRequest accepted = server.takeRequest(); RecordedRequest accepted = server.takeRequest();
assertEquals("GET / HTTP/1.1", accepted.getRequestLine()); Assertions.assertThat(accepted.getRequestLine()).isEqualTo("GET / HTTP/1.1");
assertEquals(credential, accepted.getHeader("Authorization")); Assertions.assertThat(accepted.getHeader("Authorization")).isEqualTo(credential);
} }
@Test public void redirect() throws Exception { @Test public void redirect() throws Exception {
@ -460,12 +463,12 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("This is the new location!", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("This is the new location!");
RecordedRequest request1 = server.takeRequest(); RecordedRequest request1 = server.takeRequest();
assertEquals("/", request1.getPath()); Assertions.assertThat(request1.getPath()).isEqualTo("/");
RecordedRequest request2 = server.takeRequest(); RecordedRequest request2 = server.takeRequest();
assertEquals("/foo", request2.getPath()); Assertions.assertThat(request2.getPath()).isEqualTo("/foo");
} }
@Test public void readAfterLastByte() throws Exception { @Test public void readAfterLastByte() throws Exception {
@ -477,11 +480,11 @@ public final class HttpOverHttp2Test {
Response response = call.execute(); Response response = call.execute();
InputStream in = response.body().byteStream(); InputStream in = response.body().byteStream();
assertEquals('A', in.read()); Assertions.assertThat(in.read()).isEqualTo('A');
assertEquals('B', in.read()); Assertions.assertThat(in.read()).isEqualTo('B');
assertEquals('C', in.read()); Assertions.assertThat(in.read()).isEqualTo('C');
assertEquals(-1, in.read()); Assertions.assertThat(in.read()).isEqualTo(-1);
assertEquals(-1, in.read()); Assertions.assertThat(in.read()).isEqualTo(-1);
in.close(); in.close();
} }
@ -502,7 +505,7 @@ public final class HttpOverHttp2Test {
call1.execute(); call1.execute();
fail("Should have timed out!"); fail("Should have timed out!");
} catch (SocketTimeoutException expected) { } catch (SocketTimeoutException expected) {
assertEquals("timeout", expected.getMessage()); Assertions.assertThat(expected.getMessage()).isEqualTo("timeout");
} }
// Confirm that a subsequent request on the same connection is not impacted. // Confirm that a subsequent request on the same connection is not impacted.
@ -510,11 +513,11 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("A", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("A");
// Confirm that the connection was reused. // Confirm that the connection was reused.
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(1, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
/** /**
@ -537,7 +540,7 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals(new String(body), response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo(new String(body));
} }
/** /**
@ -567,7 +570,7 @@ public final class HttpOverHttp2Test {
response1.body().string(); response1.body().string();
fail("Should have timed out!"); fail("Should have timed out!");
} catch (SocketTimeoutException expected) { } catch (SocketTimeoutException expected) {
assertEquals("timeout", expected.getMessage()); Assertions.assertThat(expected.getMessage()).isEqualTo("timeout");
} }
// Confirm that a subsequent request on the same connection is not impacted. // Confirm that a subsequent request on the same connection is not impacted.
@ -575,11 +578,11 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals(body, response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo(body);
// Confirm that the connection was reused. // Confirm that the connection was reused.
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(1, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void connectionTimeout() throws Exception { @Test public void connectionTimeout() throws Exception {
@ -604,7 +607,7 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals("A", response1.body().string()); Assertions.assertThat(response1.body().string()).isEqualTo("A");
try { try {
call2.execute(); call2.execute();
@ -613,8 +616,8 @@ public final class HttpOverHttp2Test {
} }
// Confirm that the connection was reused. // Confirm that the connection was reused.
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(1, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void responsesAreCached() throws IOException { @Test public void responsesAreCached() throws IOException {
@ -631,26 +634,26 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals("A", response1.body().string()); Assertions.assertThat(response1.body().string()).isEqualTo("A");
assertEquals(1, cache.requestCount()); Assertions.assertThat(cache.requestCount()).isEqualTo(1);
assertEquals(1, cache.networkCount()); Assertions.assertThat(cache.networkCount()).isEqualTo(1);
assertEquals(0, cache.hitCount()); Assertions.assertThat(cache.hitCount()).isEqualTo(0);
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("A", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("A");
Call call3 = client.newCall(new Request.Builder() Call call3 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response3 = call3.execute(); Response response3 = call3.execute();
assertEquals("A", response3.body().string()); Assertions.assertThat(response3.body().string()).isEqualTo("A");
assertEquals(3, cache.requestCount()); Assertions.assertThat(cache.requestCount()).isEqualTo(3);
assertEquals(1, cache.networkCount()); Assertions.assertThat(cache.networkCount()).isEqualTo(1);
assertEquals(2, cache.hitCount()); Assertions.assertThat(cache.hitCount()).isEqualTo(2);
} }
@Test public void conditionalCache() throws IOException { @Test public void conditionalCache() throws IOException {
@ -668,21 +671,21 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals("A", response1.body().string()); Assertions.assertThat(response1.body().string()).isEqualTo("A");
assertEquals(1, cache.requestCount()); Assertions.assertThat(cache.requestCount()).isEqualTo(1);
assertEquals(1, cache.networkCount()); Assertions.assertThat(cache.networkCount()).isEqualTo(1);
assertEquals(0, cache.hitCount()); Assertions.assertThat(cache.hitCount()).isEqualTo(0);
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("A", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("A");
assertEquals(2, cache.requestCount()); Assertions.assertThat(cache.requestCount()).isEqualTo(2);
assertEquals(2, cache.networkCount()); Assertions.assertThat(cache.networkCount()).isEqualTo(2);
assertEquals(1, cache.hitCount()); Assertions.assertThat(cache.hitCount()).isEqualTo(1);
} }
@Test public void responseCachedWithoutConsumingFullBody() throws IOException { @Test public void responseCachedWithoutConsumingFullBody() throws IOException {
@ -701,14 +704,14 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals("AB", response1.body().source().readUtf8(2)); Assertions.assertThat(response1.body().source().readUtf8(2)).isEqualTo("AB");
response1.body().close(); response1.body().close();
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("ABCD", response2.body().source().readUtf8()); Assertions.assertThat(response2.body().source().readUtf8()).isEqualTo("ABCD");
response2.body().close(); response2.body().close();
} }
@ -729,10 +732,10 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("a=b", request.getHeader("Cookie")); Assertions.assertThat(request.getHeader("Cookie")).isEqualTo("a=b");
} }
@Test public void receiveResponseCookies() throws Exception { @Test public void receiveResponseCookies() throws Exception {
@ -748,7 +751,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("");
cookieJar.assertResponseCookies("a=b; path=/"); cookieJar.assertResponseCookies("a=b; path=/");
} }
@ -767,13 +770,13 @@ public final class HttpOverHttp2Test {
call1.cancel(); call1.cancel();
// That connection is pooled, and it works. // That connection is pooled, and it works.
assertEquals(1, client.connectionPool().connectionCount()); Assertions.assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("def", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("def");
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Clean up the connection. // Clean up the connection.
response.close(); response.close();
@ -790,10 +793,12 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("abc", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("abc");
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. // New connection.
assertEquals(1, server.takeRequest().getSequenceNumber()); // Reused connection. Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Reused connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void recoverFromOneInternalErrorRequiresNewConnection() throws Exception { @Test public void recoverFromOneInternalErrorRequiresNewConnection() throws Exception {
@ -811,10 +816,12 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("abc", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("abc");
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. // New connection.
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void recoverFromMultipleRefusedStreamsRequiresNewConnection() throws Exception { @Test public void recoverFromMultipleRefusedStreamsRequiresNewConnection() throws Exception {
@ -835,11 +842,14 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("abc", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("abc");
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. // New connection.
assertEquals(1, server.takeRequest().getSequenceNumber()); // Reused connection. Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. // Reused connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
// New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void recoverFromCancelReusesConnection() throws Exception { @Test public void recoverFromCancelReusesConnection() throws Exception {
@ -860,8 +870,8 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("def", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("def");
assertEquals(1, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void recoverFromMultipleCancelReusesConnection() throws Exception { @Test public void recoverFromMultipleCancelReusesConnection() throws Exception {
@ -886,8 +896,8 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ghi", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ghi");
assertEquals(2, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2);
} }
/** Make a call and canceling it as soon as it's accepted by the server. */ /** Make a call and canceling it as soon as it's accepted by the server. */
@ -904,7 +914,8 @@ public final class HttpOverHttp2Test {
@Override public void onResponse(Call call1, Response response) { @Override public void onResponse(Call call1, Response response) {
} }
}); });
assertEquals(expectedSequenceNumber, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(
(long) expectedSequenceNumber);
call.cancel(); call.cancel();
latch.await(); latch.await();
} }
@ -935,7 +946,7 @@ public final class HttpOverHttp2Test {
call.execute(); call.execute();
fail(); fail();
} catch (StreamResetException expected) { } catch (StreamResetException expected) {
assertEquals(errorCode, expected.errorCode); Assertions.assertThat(expected.errorCode).isEqualTo(errorCode);
} }
} }
@ -985,24 +996,24 @@ public final class HttpOverHttp2Test {
.build(); .build();
blockingAuthClient.newCall(request).enqueue(callback); blockingAuthClient.newCall(request).enqueue(callback);
String response1 = responses.take(); String response1 = responses.take();
assertEquals("", response1); Assertions.assertThat(response1).isEqualTo("");
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Now make the second request which will restrict the first HTTP/2 connection from creating new // Now make the second request which will restrict the first HTTP/2 connection from creating new
// streams. // streams.
client.newCall(request).enqueue(callback); client.newCall(request).enqueue(callback);
String response2 = responses.take(); String response2 = responses.take();
assertEquals("DEF", response2); Assertions.assertThat(response2).isEqualTo("DEF");
assertEquals(1, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Let the first request proceed. It should discard the the held HTTP/2 connection and get a new // Let the first request proceed. It should discard the the held HTTP/2 connection and get a new
// one. // one.
latch.countDown(); latch.countDown();
String response3 = responses.take(); String response3 = responses.take();
assertEquals("ABC", response3); Assertions.assertThat(response3).isEqualTo("ABC");
assertEquals(1, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
assertEquals(2, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2);
} }
@Test public void nonAsciiResponseHeader() throws Exception { @Test public void nonAsciiResponseHeader() throws Exception {
@ -1016,8 +1027,8 @@ public final class HttpOverHttp2Test {
Response response = call.execute(); Response response = call.execute();
response.close(); response.close();
assertEquals("α", response.header("Alpha")); Assertions.assertThat(response.header("Alpha")).isEqualTo("α");
assertEquals("Beta", response.header("β")); Assertions.assertThat(response.header("β")).isEqualTo("Beta");
} }
@Test public void serverSendsPushPromise_GET() throws Exception { @Test public void serverSendsPushPromise_GET() throws Exception {
@ -1033,18 +1044,20 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABCDE", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
assertEquals("", response.message()); Assertions.assertThat(response.message()).isEqualTo("");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request.getRequestLine()); Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1");
assertEquals(scheme, request.getHeader(":scheme")); Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme);
assertEquals(server.getHostName() + ":" + server.getPort(), request.getHeader(":authority")); Assertions.assertThat(request.getHeader(":authority")).isEqualTo(
(server.getHostName() + ":" + server.getPort()));
RecordedRequest pushedRequest = server.takeRequest(); RecordedRequest pushedRequest = server.takeRequest();
assertEquals("GET /foo/bar HTTP/1.1", pushedRequest.getRequestLine()); Assertions.assertThat(pushedRequest.getRequestLine()).isEqualTo(
assertEquals("bar", pushedRequest.getHeader("foo")); "GET /foo/bar HTTP/1.1");
Assertions.assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar");
} }
@Test public void serverSendsPushPromise_HEAD() throws Exception { @Test public void serverSendsPushPromise_HEAD() throws Exception {
@ -1059,18 +1072,20 @@ public final class HttpOverHttp2Test {
.url(server.url("/foo")) .url(server.url("/foo"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABCDE", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
assertEquals(200, response.code()); Assertions.assertThat(response.code()).isEqualTo(200);
assertEquals("", response.message()); Assertions.assertThat(response.message()).isEqualTo("");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request.getRequestLine()); Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1");
assertEquals(scheme, request.getHeader(":scheme")); Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme);
assertEquals(server.getHostName() + ":" + server.getPort(), request.getHeader(":authority")); Assertions.assertThat(request.getHeader(":authority")).isEqualTo(
(server.getHostName() + ":" + server.getPort()));
RecordedRequest pushedRequest = server.takeRequest(); RecordedRequest pushedRequest = server.takeRequest();
assertEquals("HEAD /foo/bar HTTP/1.1", pushedRequest.getRequestLine()); Assertions.assertThat(pushedRequest.getRequestLine()).isEqualTo(
assertEquals("bar", pushedRequest.getHeader("foo")); "HEAD /foo/bar HTTP/1.1");
Assertions.assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar");
} }
@Test public void noDataFramesSentWithNullRequestBody() throws Exception { @Test public void noDataFramesSentWithNullRequestBody() throws Exception {
@ -1082,9 +1097,9 @@ public final class HttpOverHttp2Test {
.method("DELETE", null) .method("DELETE", null)
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABC", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABC");
assertEquals(protocol, response.protocol()); Assertions.assertThat(response.protocol()).isEqualTo(protocol);
List<String> logs = http2Handler.takeAll(); List<String> logs = http2Handler.takeAll();
@ -1100,9 +1115,9 @@ public final class HttpOverHttp2Test {
.method("DELETE", Util.EMPTY_REQUEST) .method("DELETE", Util.EMPTY_REQUEST)
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABC", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABC");
assertEquals(protocol, response.protocol()); Assertions.assertThat(response.protocol()).isEqualTo(protocol);
List<String> logs = http2Handler.takeAll(); List<String> logs = http2Handler.takeAll();
@ -1125,16 +1140,20 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABC", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABC");
assertEquals(protocol, response.protocol()); Assertions.assertThat(response.protocol()).isEqualTo(protocol);
// Confirm a single ping was sent and received, and its reply was sent and received. // Confirm a single ping was sent and received, and its reply was sent and received.
List<String> logs = http2Handler.takeAll(); List<String> logs = http2Handler.takeAll();
assertEquals(1, countFrames(logs, "FINE: >> 0x00000000 8 PING ")); Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo(
assertEquals(1, countFrames(logs, "FINE: << 0x00000000 8 PING ")); (long) 1);
assertEquals(1, countFrames(logs, "FINE: >> 0x00000000 8 PING ACK")); Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ")).isEqualTo(
assertEquals(1, countFrames(logs, "FINE: << 0x00000000 8 PING ACK")); (long) 1);
Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ACK")).isEqualTo(
(long) 1);
Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo(
(long) 1);
} }
@Test public void missingPongsFailsConnection() throws Exception { @Test public void missingPongsFailsConnection() throws Exception {
@ -1157,16 +1176,20 @@ public final class HttpOverHttp2Test {
call.execute(); call.execute();
fail(); fail();
} catch (StreamResetException expected) { } catch (StreamResetException expected) {
assertEquals("stream was reset: PROTOCOL_ERROR", expected.getMessage()); Assertions.assertThat(expected.getMessage()).isEqualTo(
"stream was reset: PROTOCOL_ERROR");
} }
long elapsedUntilFailure = System.nanoTime() - executeAtNanos; long elapsedUntilFailure = System.nanoTime() - executeAtNanos;
assertEquals(1000, TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure), 250d); Assertions.assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo(
(double) 1000, offset(250d));
// Confirm a single ping was sent but not acknowledged. // Confirm a single ping was sent but not acknowledged.
List<String> logs = http2Handler.takeAll(); List<String> logs = http2Handler.takeAll();
assertEquals(1, countFrames(logs, "FINE: >> 0x00000000 8 PING ")); Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo(
assertEquals(0, countFrames(logs, "FINE: << 0x00000000 8 PING ACK")); (long) 1);
Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo(
(long) 0);
} }
private String firstFrame(List<String> logs, String type) { private String firstFrame(List<String> logs, String type) {
@ -1203,7 +1226,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("");
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setBody("ABC")); .setBody("ABC"));
@ -1227,13 +1250,17 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response3 = call3.execute(); Response response3 = call3.execute();
assertEquals("ABC", response1.body().string()); Assertions.assertThat(response1.body().string()).isEqualTo("ABC");
assertEquals("DEF", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("DEF");
assertEquals("GHI", response3.body().string()); Assertions.assertThat(response3.body().string()).isEqualTo("GHI");
assertEquals(0, server.takeRequest().getSequenceNumber()); // Settings connection. // Settings connection.
assertEquals(1, server.takeRequest().getSequenceNumber()); // Reuse settings connection. Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(2, server.takeRequest().getSequenceNumber()); // Reuse settings connection. // Reuse settings connection.
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection! Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
// Reuse settings connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2);
// New connection!
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void connectionNotReusedAfterShutdown() throws Exception { @Test public void connectionNotReusedAfterShutdown() throws Exception {
@ -1247,15 +1274,15 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals("ABC", response1.body().string()); Assertions.assertThat(response1.body().string()).isEqualTo("ABC");
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("DEF", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("DEF");
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
/** /**
@ -1282,7 +1309,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("ABC", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("ABC");
// Wait until the GOAWAY has been processed. // Wait until the GOAWAY has been processed.
RealConnection connection = (RealConnection) chain.connection(); RealConnection connection = (RealConnection) chain.connection();
while (connection.isHealthy(false)) ; while (connection.isHealthy(false)) ;
@ -1296,10 +1323,10 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("DEF", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("DEF");
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(0, server.takeRequest().getSequenceNumber()); Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void responseHeadersAfterGoaway() throws Exception { @Test public void responseHeadersAfterGoaway() throws Exception {
@ -1322,9 +1349,9 @@ public final class HttpOverHttp2Test {
client.newCall(new Request.Builder().url(server.url("/")).build()).enqueue(callback); client.newCall(new Request.Builder().url(server.url("/")).build()).enqueue(callback);
client.newCall(new Request.Builder().url(server.url("/")).build()).enqueue(callback); client.newCall(new Request.Builder().url(server.url("/")).build()).enqueue(callback);
assertEquals("DEF", bodies.poll(2, SECONDS)); Assertions.assertThat(bodies.poll(2, SECONDS)).isEqualTo("DEF");
assertEquals("ABC", bodies.poll(2, SECONDS)); Assertions.assertThat(bodies.poll(2, SECONDS)).isEqualTo("ABC");
assertEquals(2, server.getRequestCount()); Assertions.assertThat(server.getRequestCount()).isEqualTo(2);
} }
/** /**
@ -1366,7 +1393,7 @@ public final class HttpOverHttp2Test {
.url("https://android.com/call2") .url("https://android.com/call2")
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("call2 response", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("call2 response");
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -1392,27 +1419,27 @@ public final class HttpOverHttp2Test {
.url("https://android.com/call1") .url("https://android.com/call1")
.build()); .build());
Response response2 = call1.execute(); Response response2 = call1.execute();
assertEquals("call1 response", response2.body().string()); Assertions.assertThat(response2.body().string()).isEqualTo("call1 response");
RecordedRequest call1Connect = server.takeRequest(); RecordedRequest call1Connect = server.takeRequest();
assertEquals("CONNECT", call1Connect.getMethod()); Assertions.assertThat(call1Connect.getMethod()).isEqualTo("CONNECT");
assertEquals(0, call1Connect.getSequenceNumber()); Assertions.assertThat(call1Connect.getSequenceNumber()).isEqualTo(0);
RecordedRequest call2Connect = server.takeRequest(); RecordedRequest call2Connect = server.takeRequest();
assertEquals("CONNECT", call2Connect.getMethod()); Assertions.assertThat(call2Connect.getMethod()).isEqualTo("CONNECT");
assertEquals(0, call2Connect.getSequenceNumber()); Assertions.assertThat(call2Connect.getSequenceNumber()).isEqualTo(0);
RecordedRequest call2Get = server.takeRequest(); RecordedRequest call2Get = server.takeRequest();
assertEquals("GET", call2Get.getMethod()); Assertions.assertThat(call2Get.getMethod()).isEqualTo("GET");
assertEquals("/call2", call2Get.getPath()); Assertions.assertThat(call2Get.getPath()).isEqualTo("/call2");
assertEquals(0, call2Get.getSequenceNumber()); Assertions.assertThat(call2Get.getSequenceNumber()).isEqualTo(0);
RecordedRequest call1Get = server.takeRequest(); RecordedRequest call1Get = server.takeRequest();
assertEquals("GET", call1Get.getMethod()); Assertions.assertThat(call1Get.getMethod()).isEqualTo("GET");
assertEquals("/call1", call1Get.getPath()); Assertions.assertThat(call1Get.getPath()).isEqualTo("/call1");
assertEquals(1, call1Get.getSequenceNumber()); Assertions.assertThat(call1Get.getSequenceNumber()).isEqualTo(1);
assertEquals(1, client.connectionPool().connectionCount()); Assertions.assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
} }
/** https://github.com/square/okhttp/issues/3103 */ /** https://github.com/square/okhttp/issues/3103 */
@ -1435,10 +1462,11 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("");
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertEquals("privateobject.com", recordedRequest.getHeader(":authority")); Assertions.assertThat(recordedRequest.getHeader(":authority")).isEqualTo(
"privateobject.com");
} }
private Buffer gzip(String bytes) throws IOException { private Buffer gzip(String bytes) throws IOException {
@ -1464,7 +1492,7 @@ public final class HttpOverHttp2Test {
.url(server.url(path)) .url(server.url(path))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
assertEquals("A", response.body().string()); Assertions.assertThat(response.body().string()).isEqualTo("A");
countDownLatch.countDown(); countDownLatch.countDown();
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@ -21,8 +21,8 @@ import okio.Buffer;
import okio.ByteString; import okio.ByteString;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/** Original version of this class was lifted from {@code com.twitter.hpack.HuffmanTest}. */ /** Original version of this class was lifted from {@code com.twitter.hpack.HuffmanTest}. */
public final class HuffmanTest { public final class HuffmanTest {
@ -41,7 +41,7 @@ public final class HuffmanTest {
private void assertRoundTrip(ByteString data) throws IOException { private void assertRoundTrip(ByteString data) throws IOException {
Buffer buffer = new Buffer(); Buffer buffer = new Buffer();
Huffman.get().encode(data, buffer); Huffman.get().encode(data, buffer);
assertEquals(buffer.size(), Huffman.get().encodedLength(data)); assertThat(Huffman.get().encodedLength(data)).isEqualTo(buffer.size());
byte[] decodedBytes = Huffman.get().decode(buffer.readByteArray()); byte[] decodedBytes = Huffman.get().decode(buffer.readByteArray());
assertArrayEquals(data.toByteArray(), decodedBytes); assertArrayEquals(data.toByteArray(), decodedBytes);

View File

@ -19,43 +19,41 @@ import org.junit.Test;
import static okhttp3.internal.http2.Settings.DEFAULT_INITIAL_WINDOW_SIZE; import static okhttp3.internal.http2.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
import static okhttp3.internal.http2.Settings.MAX_CONCURRENT_STREAMS; import static okhttp3.internal.http2.Settings.MAX_CONCURRENT_STREAMS;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public final class SettingsTest { public final class SettingsTest {
@Test public void unsetField() { @Test public void unsetField() {
Settings settings = new Settings(); Settings settings = new Settings();
assertEquals(-3, settings.getMaxConcurrentStreams(-3)); assertThat(settings.getMaxConcurrentStreams(-3)).isEqualTo(-3);
} }
@Test public void setFields() { @Test public void setFields() {
Settings settings = new Settings(); Settings settings = new Settings();
settings.set(Settings.HEADER_TABLE_SIZE, 8096); settings.set(Settings.HEADER_TABLE_SIZE, 8096);
assertEquals(8096, settings.getHeaderTableSize()); assertThat(settings.getHeaderTableSize()).isEqualTo(8096);
assertTrue(settings.getEnablePush(true)); assertThat(settings.getEnablePush(true)).isTrue();
settings.set(Settings.ENABLE_PUSH, 1); settings.set(Settings.ENABLE_PUSH, 1);
assertTrue(settings.getEnablePush(false)); assertThat(settings.getEnablePush(false)).isTrue();
settings.clear(); settings.clear();
assertEquals(-3, settings.getMaxConcurrentStreams(-3)); assertThat(settings.getMaxConcurrentStreams(-3)).isEqualTo(-3);
settings.set(MAX_CONCURRENT_STREAMS, 75); settings.set(MAX_CONCURRENT_STREAMS, 75);
assertEquals(75, settings.getMaxConcurrentStreams(-3)); assertThat(settings.getMaxConcurrentStreams(-3)).isEqualTo(75);
settings.clear(); settings.clear();
assertEquals(16384, settings.getMaxFrameSize(16384)); assertThat(settings.getMaxFrameSize(16384)).isEqualTo(16384);
settings.set(Settings.MAX_FRAME_SIZE, 16777215); settings.set(Settings.MAX_FRAME_SIZE, 16777215);
assertEquals(16777215, settings.getMaxFrameSize(16384)); assertThat(settings.getMaxFrameSize(16384)).isEqualTo(16777215);
assertEquals(-1, settings.getMaxHeaderListSize(-1)); assertThat(settings.getMaxHeaderListSize(-1)).isEqualTo(-1);
settings.set(Settings.MAX_HEADER_LIST_SIZE, 16777215); settings.set(Settings.MAX_HEADER_LIST_SIZE, 16777215);
assertEquals(16777215, settings.getMaxHeaderListSize(-1)); assertThat(settings.getMaxHeaderListSize(-1)).isEqualTo(16777215);
assertEquals(DEFAULT_INITIAL_WINDOW_SIZE, assertThat(settings.getInitialWindowSize()).isEqualTo(DEFAULT_INITIAL_WINDOW_SIZE);
settings.getInitialWindowSize());
settings.set(Settings.INITIAL_WINDOW_SIZE, 108); settings.set(Settings.INITIAL_WINDOW_SIZE, 108);
assertEquals(108, settings.getInitialWindowSize()); assertThat(settings.getInitialWindowSize()).isEqualTo(108);
} }
@Test public void merge() { @Test public void merge() {
@ -70,9 +68,9 @@ public final class SettingsTest {
b.set(Settings.MAX_CONCURRENT_STREAMS, 60000); b.set(Settings.MAX_CONCURRENT_STREAMS, 60000);
a.merge(b); a.merge(b);
assertEquals(10000, a.getHeaderTableSize()); assertThat(a.getHeaderTableSize()).isEqualTo(10000);
assertEquals(40000, a.getMaxHeaderListSize(-1)); assertThat(a.getMaxHeaderListSize(-1)).isEqualTo(40000);
assertEquals(50000, a.getInitialWindowSize()); assertThat(a.getInitialWindowSize()).isEqualTo(50000);
assertEquals(60000, a.getMaxConcurrentStreams(-1)); assertThat(a.getMaxConcurrentStreams(-1)).isEqualTo(60000);
} }
} }

View File

@ -18,7 +18,7 @@ package okhttp3.internal.platform;
import org.junit.Test; import org.junit.Test;
import static okhttp3.internal.platform.PlatformTest.getPlatform; import static okhttp3.internal.platform.PlatformTest.getPlatform;
import static org.junit.Assert.assertNotNull; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
public class Jdk8WithJettyBootPlatformTest { public class Jdk8WithJettyBootPlatformTest {
@ -26,6 +26,6 @@ public class Jdk8WithJettyBootPlatformTest {
public void testBuildsWithJettyBoot() { public void testBuildsWithJettyBoot() {
assumeTrue(getPlatform().equals("jdk-with-jetty-boot")); assumeTrue(getPlatform().equals("jdk-with-jetty-boot"));
assertNotNull(Jdk8WithJettyBootPlatform.buildIfSupported()); assertThat(Jdk8WithJettyBootPlatform.buildIfSupported()).isNotNull();
} }
} }

View File

@ -18,8 +18,7 @@ package okhttp3.internal.platform;
import org.junit.Test; import org.junit.Test;
import static okhttp3.internal.platform.PlatformTest.getPlatform; import static okhttp3.internal.platform.PlatformTest.getPlatform;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
public class Jdk9PlatformTest { public class Jdk9PlatformTest {
@ -27,7 +26,7 @@ public class Jdk9PlatformTest {
public void buildsWhenJdk9() { public void buildsWhenJdk9() {
assumeTrue(getPlatform().equals("jdk9")); assumeTrue(getPlatform().equals("jdk9"));
assertNotNull(Jdk9Platform.buildIfSupported()); assertThat(Jdk9Platform.buildIfSupported()).isNotNull();
} }
@Test @Test
@ -36,12 +35,12 @@ public class Jdk9PlatformTest {
Jdk9Platform platform = Jdk9Platform.buildIfSupported(); Jdk9Platform platform = Jdk9Platform.buildIfSupported();
assertEquals("getApplicationProtocol", platform.getProtocolMethod.getName()); assertThat(platform.getProtocolMethod.getName()).isEqualTo("getApplicationProtocol");
assertEquals("setApplicationProtocols", platform.setProtocolMethod.getName()); assertThat(platform.setProtocolMethod.getName()).isEqualTo("setApplicationProtocols");
} }
@Test @Test
public void testToStringIsClassname() { public void testToStringIsClassname() {
assertEquals("Jdk9Platform", new Jdk9Platform(null, null).toString()); assertThat(new Jdk9Platform(null, null).toString()).isEqualTo("Jdk9Platform");
} }
} }

View File

@ -17,7 +17,7 @@ package okhttp3.internal.platform;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
public class PlatformTest { public class PlatformTest {
@Test public void alwaysBuilds() { @Test public void alwaysBuilds() {
@ -26,7 +26,7 @@ public class PlatformTest {
/** Guard against the default value changing by accident. */ /** Guard against the default value changing by accident. */
@Test public void defaultPrefix() { @Test public void defaultPrefix() {
assertEquals("OkHttp", new Platform().getPrefix()); assertThat(new Platform().getPrefix()).isEqualTo("OkHttp");
} }
public static String getPlatform() { public static String getPlatform() {
@ -39,6 +39,6 @@ public class PlatformTest {
@Test @Test
public void testToStringIsClassname() { public void testToStringIsClassname() {
assertEquals("Platform", new Platform().toString()); assertThat(new Platform().toString()).isEqualTo("Platform");
} }
} }

View File

@ -25,9 +25,7 @@ import okio.Okio;
import org.junit.Test; import org.junit.Test;
import static okhttp3.internal.publicsuffix.PublicSuffixDatabase.PUBLIC_SUFFIX_RESOURCE; import static okhttp3.internal.publicsuffix.PublicSuffixDatabase.PUBLIC_SUFFIX_RESOURCE;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class PublicSuffixDatabaseTest { public final class PublicSuffixDatabaseTest {
@ -40,12 +38,14 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("square.com\n"); .writeUtf8("square.com\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), new byte[]{}); publicSuffixDatabase.setListBytes(buffer.readByteArray(), new byte[]{});
assertEquals("example.com", publicSuffixDatabase.getEffectiveTldPlusOne("example.com")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("example.com")).isEqualTo(
assertEquals("example.com", publicSuffixDatabase.getEffectiveTldPlusOne("foo.example.com")); "example.com");
assertEquals("bar.square.com", assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.example.com")).isEqualTo(
publicSuffixDatabase.getEffectiveTldPlusOne("foo.bar.square.com")); "example.com");
assertEquals("foo.my.square.com", assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.bar.square.com")).isEqualTo(
publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.com")); "bar.square.com");
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.com")).isEqualTo(
"foo.my.square.com");
} }
@Test public void wildcardMatch() { @Test public void wildcardMatch() {
@ -55,11 +55,11 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("example.com\n"); .writeUtf8("example.com\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), new byte[]{}); publicSuffixDatabase.setListBytes(buffer.readByteArray(), new byte[]{});
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("my.square.com")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("my.square.com")).isNull();
assertEquals("foo.my.square.com", assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.com")).isEqualTo(
publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.com")); "foo.my.square.com");
assertEquals("foo.my.square.com", assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("bar.foo.my.square.com")).isEqualTo(
publicSuffixDatabase.getEffectiveTldPlusOne("bar.foo.my.square.com")); "foo.my.square.com");
} }
@Test public void boundarySearches() { @Test public void boundarySearches() {
@ -69,10 +69,10 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("fff\n"); .writeUtf8("fff\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), new byte[]{}); publicSuffixDatabase.setListBytes(buffer.readByteArray(), new byte[]{});
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("aaa")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("aaa")).isNull();
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("ggg")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("ggg")).isNull();
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("ccc")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("ccc")).isNull();
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("eee")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("eee")).isNull();
} }
@Test public void exceptionRule() { @Test public void exceptionRule() {
@ -85,9 +85,11 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("square.com\n"); .writeUtf8("square.com\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), exception.readByteArray()); publicSuffixDatabase.setListBytes(buffer.readByteArray(), exception.readByteArray());
assertEquals("my.square.jp", publicSuffixDatabase.getEffectiveTldPlusOne("my.square.jp")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("my.square.jp")).isEqualTo(
assertEquals("my.square.jp", publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.jp")); "my.square.jp");
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("my1.square.jp")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.jp")).isEqualTo(
"my.square.jp");
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("my1.square.jp")).isNull();
} }
@Test public void noEffectiveTldPlusOne() { @Test public void noEffectiveTldPlusOne() {
@ -100,8 +102,8 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("square.com\n"); .writeUtf8("square.com\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), exception.readByteArray()); publicSuffixDatabase.setListBytes(buffer.readByteArray(), exception.readByteArray());
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("example.com")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("example.com")).isNull();
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("foo.square.jp")); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.square.jp")).isNull();
} }
@Test public void allPublicSuffixes() throws IOException { @Test public void allPublicSuffixes() throws IOException {
@ -119,10 +121,10 @@ public final class PublicSuffixDatabaseTest {
// A wildcard rule, let's replace the wildcard with a value. // A wildcard rule, let's replace the wildcard with a value.
publicSuffix = publicSuffix.replaceAll("\\*", "square"); publicSuffix = publicSuffix.replaceAll("\\*", "square");
} }
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne(publicSuffix)); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(publicSuffix)).isNull();
String test = "foobar." + publicSuffix; String test = "foobar." + publicSuffix;
assertEquals(test, publicSuffixDatabase.getEffectiveTldPlusOne(test)); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(test)).isEqualTo(test);
} }
} }
@ -140,10 +142,11 @@ public final class PublicSuffixDatabaseTest {
while (!buffer.exhausted()) { while (!buffer.exhausted()) {
String exception = buffer.readUtf8LineStrict(); String exception = buffer.readUtf8LineStrict();
assertEquals(exception, publicSuffixDatabase.getEffectiveTldPlusOne(exception)); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(exception)).isEqualTo(
exception);
String test = "foobar." + exception; String test = "foobar." + exception;
assertEquals(exception, publicSuffixDatabase.getEffectiveTldPlusOne(test)); assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(test)).isEqualTo(exception);
} }
} }
@ -151,9 +154,9 @@ public final class PublicSuffixDatabaseTest {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
try { try {
String result = publicSuffixDatabase.getEffectiveTldPlusOne("squareup.com"); String result = publicSuffixDatabase.getEffectiveTldPlusOne("squareup.com");
assertEquals("squareup.com", result); assertThat(result).isEqualTo("squareup.com");
} finally { } finally {
assertTrue(Thread.interrupted()); assertThat(Thread.interrupted()).isTrue();
} }
} }
@ -276,9 +279,9 @@ public final class PublicSuffixDatabaseTest {
String result = publicSuffixDatabase.getEffectiveTldPlusOne(canonicalDomain); String result = publicSuffixDatabase.getEffectiveTldPlusOne(canonicalDomain);
if (registrablePart == null) { if (registrablePart == null) {
assertNull(result); assertThat(result).isNull();
} else { } else {
assertEquals(Util.canonicalizeHost(registrablePart), result); assertThat(result).isEqualTo(Util.canonicalizeHost(registrablePart));
} }
} }
} }

View File

@ -47,8 +47,7 @@ import static okhttp3.internal.platform.PlatformTest.getJvmSpecVersion;
import static okhttp3.internal.platform.PlatformTest.getPlatform; import static okhttp3.internal.platform.PlatformTest.getPlatform;
import static okhttp3.tls.internal.TlsUtil.newKeyManager; import static okhttp3.tls.internal.TlsUtil.newKeyManager;
import static okhttp3.tls.internal.TlsUtil.newTrustManager; import static okhttp3.tls.internal.TlsUtil.newTrustManager;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeFalse;
@ -102,7 +101,7 @@ public final class CertificatePinnerChainValidationTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals("abc", response1.body().string()); assertThat(response1.body().string()).isEqualTo("abc");
// Confirm that a second request also succeeds. This should detect caching problems. // Confirm that a second request also succeeds. This should detect caching problems.
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
@ -112,7 +111,7 @@ public final class CertificatePinnerChainValidationTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("def", response2.body().string()); assertThat(response2.body().string()).isEqualTo("def");
} }
/** The pinner should accept an intermediate from the server's chain. */ /** The pinner should accept an intermediate from the server's chain. */
@ -162,7 +161,7 @@ public final class CertificatePinnerChainValidationTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
assertEquals("abc", response1.body().string()); assertThat(response1.body().string()).isEqualTo("abc");
response1.close(); response1.close();
// Force a fresh connection for the next request. // Force a fresh connection for the next request.
@ -176,7 +175,7 @@ public final class CertificatePinnerChainValidationTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
assertEquals("def", response2.body().string()); assertThat(response2.body().string()).isEqualTo("def");
response2.close(); response2.close();
} }
@ -251,7 +250,7 @@ public final class CertificatePinnerChainValidationTest {
} catch (SSLPeerUnverifiedException expected) { } catch (SSLPeerUnverifiedException expected) {
// Certificate pinning fails! // Certificate pinning fails!
String message = expected.getMessage(); String message = expected.getMessage();
assertTrue(message, message.startsWith("Certificate pinning failure!")); assertThat(message).startsWith("Certificate pinning failure!");
} }
} }
@ -326,11 +325,11 @@ public final class CertificatePinnerChainValidationTest {
} catch (SSLHandshakeException expected) { } catch (SSLHandshakeException expected) {
// On Android, the handshake fails before the certificate pinner runs. // On Android, the handshake fails before the certificate pinner runs.
String message = expected.getMessage(); String message = expected.getMessage();
assertTrue(message, message.contains("Could not validate certificate")); assertThat(message).contains("Could not validate certificate");
} catch (SSLPeerUnverifiedException expected) { } catch (SSLPeerUnverifiedException expected) {
// On OpenJDK, the handshake succeeds but the certificate pinner fails. // On OpenJDK, the handshake succeeds but the certificate pinner fails.
String message = expected.getMessage(); String message = expected.getMessage();
assertTrue(message, message.startsWith("Certificate pinning failure!")); assertThat(message).startsWith("Certificate pinning failure!");
} }
} }

View File

@ -47,8 +47,7 @@ import static okhttp3.internal.platform.PlatformTest.getJvmSpecVersion;
import static okhttp3.internal.platform.PlatformTest.getPlatform; import static okhttp3.internal.platform.PlatformTest.getPlatform;
import static okhttp3.tls.internal.TlsUtil.newKeyManager; import static okhttp3.tls.internal.TlsUtil.newKeyManager;
import static okhttp3.tls.internal.TlsUtil.newTrustManager; import static okhttp3.tls.internal.TlsUtil.newTrustManager;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeFalse;
@ -118,9 +117,11 @@ public final class ClientAuthTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal()); assertThat(response.handshake().peerPrincipal()).isEqualTo(
assertEquals(new X500Principal("CN=Jethro Willis"), response.handshake().localPrincipal()); new X500Principal("CN=Local Host"));
assertEquals("abc", response.body().string()); assertThat(response.handshake().localPrincipal()).isEqualTo(
new X500Principal("CN=Jethro Willis"));
assertThat(response.body().string()).isEqualTo("abc");
} }
@Test public void clientAuthForNeeds() throws Exception { @Test public void clientAuthForNeeds() throws Exception {
@ -134,9 +135,11 @@ public final class ClientAuthTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal()); assertThat(response.handshake().peerPrincipal()).isEqualTo(
assertEquals(new X500Principal("CN=Jethro Willis"), response.handshake().localPrincipal()); new X500Principal("CN=Local Host"));
assertEquals("abc", response.body().string()); assertThat(response.handshake().localPrincipal()).isEqualTo(
new X500Principal("CN=Jethro Willis"));
assertThat(response.body().string()).isEqualTo("abc");
} }
@Test public void clientAuthSkippedForNone() throws Exception { @Test public void clientAuthSkippedForNone() throws Exception {
@ -150,9 +153,10 @@ public final class ClientAuthTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal()); assertThat(response.handshake().peerPrincipal()).isEqualTo(
assertNull(response.handshake().localPrincipal()); new X500Principal("CN=Local Host"));
assertEquals("abc", response.body().string()); assertThat(response.handshake().localPrincipal()).isNull();
assertThat(response.body().string()).isEqualTo("abc");
} }
@Test public void missingClientAuthSkippedForWantsOnly() throws Exception { @Test public void missingClientAuthSkippedForWantsOnly() throws Exception {
@ -166,9 +170,10 @@ public final class ClientAuthTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal()); assertThat(response.handshake().peerPrincipal()).isEqualTo(
assertNull(response.handshake().localPrincipal()); new X500Principal("CN=Local Host"));
assertEquals("abc", response.body().string()); assertThat(response.handshake().localPrincipal()).isNull();
assertThat(response.body().string()).isEqualTo("abc");
} }
@Test public void missingClientAuthFailsForNeeds() throws Exception { @Test public void missingClientAuthFailsForNeeds() throws Exception {
@ -191,9 +196,9 @@ public final class ClientAuthTest {
} catch (SSLHandshakeException expected) { } catch (SSLHandshakeException expected) {
} catch (SSLException expected) { } catch (SSLException expected) {
String jvmVersion = System.getProperty("java.specification.version"); String jvmVersion = System.getProperty("java.specification.version");
assertEquals("11", jvmVersion); assertThat(jvmVersion).isEqualTo("11");
} catch (SocketException expected) { } catch (SocketException expected) {
assertEquals("jdk9", getPlatform()); assertThat(getPlatform()).isEqualTo("jdk9");
} }
} }
@ -247,9 +252,9 @@ public final class ClientAuthTest {
} catch (SSLException expected) { } catch (SSLException expected) {
// javax.net.ssl.SSLException: readRecord // javax.net.ssl.SSLException: readRecord
String jvmVersion = System.getProperty("java.specification.version"); String jvmVersion = System.getProperty("java.specification.version");
assertEquals("11", jvmVersion); assertThat(jvmVersion).isEqualTo("11");
} catch (SocketException expected) { } catch (SocketException expected) {
assertEquals("jdk9", getPlatform()); assertThat(getPlatform()).isEqualTo("jdk9");
} }
} }

View File

@ -20,7 +20,7 @@ import javax.security.auth.x500.X500Principal;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class DistinguishedNameParserTest { public final class DistinguishedNameParserTest {
@ -120,7 +120,8 @@ public final class DistinguishedNameParserTest {
private void assertCn(String expected, String dn) { private void assertCn(String expected, String dn) {
X500Principal principal = new X500Principal(dn); X500Principal principal = new X500Principal(dn);
DistinguishedNameParser parser = new DistinguishedNameParser(principal); DistinguishedNameParser parser = new DistinguishedNameParser(principal);
assertEquals(dn, expected, parser.findMostSpecific("cn")); assertThat(parser.findMostSpecific("cn")).overridingErrorMessage(dn).isEqualTo(
expected);
} }
private void expectExceptionInPrincipal(String dn) { private void expectExceptionInPrincipal(String dn) {

View File

@ -29,9 +29,7 @@ import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for our hostname verifier. Most of these tests are from AOSP, which itself includes tests * Tests for our hostname verifier. Most of these tests are from AOSP, which itself includes tests
@ -42,7 +40,7 @@ public final class HostnameVerifierTest {
@Test public void verify() throws Exception { @Test public void verify() throws Exception {
FakeSSLSession session = new FakeSSLSession(); FakeSSLSession session = new FakeSSLSession();
assertFalse(verifier.verify("localhost", session)); assertThat(verifier.verify("localhost", session)).isFalse();
} }
@Test public void verifyCn() throws Exception { @Test public void verifyCn() throws Exception {
@ -73,9 +71,9 @@ public final class HostnameVerifierTest {
+ "HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx\n" + "HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx\n"
+ "SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S\n" + "SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n");
assertFalse(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isFalse();
assertFalse(verifier.verify("a.foo.com", session)); assertThat(verifier.verify("a.foo.com", session)).isFalse();
assertFalse(verifier.verify("bar.com", session)); assertThat(verifier.verify("bar.com", session)).isFalse();
} }
@Test public void verifyNonAsciiCn() throws Exception { @Test public void verifyNonAsciiCn() throws Exception {
@ -106,8 +104,8 @@ public final class HostnameVerifierTest {
+ "9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae\n" + "9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae\n"
+ "UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA=\n" + "UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA=\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n");
assertFalse(verifier.verify("\u82b1\u5b50.co.jp", session)); assertThat(verifier.verify("\u82b1\u5b50.co.jp", session)).isFalse();
assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session)); assertThat(verifier.verify("a.\u82b1\u5b50.co.jp", session)).isFalse();
} }
@Test public void verifySubjectAlt() throws Exception { @Test public void verifySubjectAlt() throws Exception {
@ -139,10 +137,10 @@ public final class HostnameVerifierTest {
+ "2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr\n" + "2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr\n"
+ "VbWx/uETImUu+NZg22ewEw==\n" + "VbWx/uETImUu+NZg22ewEw==\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n");
assertFalse(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isFalse();
assertFalse(verifier.verify("a.foo.com", session)); assertThat(verifier.verify("a.foo.com", session)).isFalse();
assertTrue(verifier.verify("bar.com", session)); assertThat(verifier.verify("bar.com", session)).isTrue();
assertFalse(verifier.verify("a.bar.com", session)); assertThat(verifier.verify("a.bar.com", session)).isFalse();
} }
/** /**
@ -180,8 +178,8 @@ public final class HostnameVerifierTest {
+ "sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt\n" + "sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt\n"
+ "j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+\n" + "j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n");
assertTrue(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isTrue();
assertFalse(verifier.verify("a.foo.com", session)); assertThat(verifier.verify("a.foo.com", session)).isFalse();
// these checks test alternative subjects. The test data contains an // these checks test alternative subjects. The test data contains an
// alternative subject starting with a japanese kanji character. This is // alternative subject starting with a japanese kanji character. This is
// not supported by Android because the underlying implementation from // not supported by Android because the underlying implementation from
@ -220,10 +218,10 @@ public final class HostnameVerifierTest {
+ "qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo\n" + "qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo\n"
+ "n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg==\n" + "n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg==\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n");
assertTrue(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isTrue();
assertFalse(verifier.verify("a.foo.com", session)); assertThat(verifier.verify("a.foo.com", session)).isFalse();
assertTrue(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isTrue();
assertFalse(verifier.verify("a.foo.com", session)); assertThat(verifier.verify("a.foo.com", session)).isFalse();
} }
@Test public void verifyMultipleCn() throws Exception { @Test public void verifyMultipleCn() throws Exception {
@ -255,12 +253,12 @@ public final class HostnameVerifierTest {
+ "SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI\n" + "SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI\n"
+ "VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE=\n" + "VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE=\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n");
assertFalse(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isFalse();
assertFalse(verifier.verify("a.foo.com", session)); assertThat(verifier.verify("a.foo.com", session)).isFalse();
assertFalse(verifier.verify("bar.com", session)); assertThat(verifier.verify("bar.com", session)).isFalse();
assertFalse(verifier.verify("a.bar.com", session)); assertThat(verifier.verify("a.bar.com", session)).isFalse();
assertFalse(verifier.verify("\u82b1\u5b50.co.jp", session)); assertThat(verifier.verify("\u82b1\u5b50.co.jp", session)).isFalse();
assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session)); assertThat(verifier.verify("a.\u82b1\u5b50.co.jp", session)).isFalse();
} }
@Test public void verifyWilcardCn() throws Exception { @Test public void verifyWilcardCn() throws Exception {
@ -291,10 +289,10 @@ public final class HostnameVerifierTest {
+ "G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e\n" + "G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e\n"
+ "l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n" + "l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n");
assertFalse(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isFalse();
assertFalse(verifier.verify("www.foo.com", session)); assertThat(verifier.verify("www.foo.com", session)).isFalse();
assertFalse(verifier.verify("\u82b1\u5b50.foo.com", session)); assertThat(verifier.verify("\u82b1\u5b50.foo.com", session)).isFalse();
assertFalse(verifier.verify("a.b.foo.com", session)); assertThat(verifier.verify("a.b.foo.com", session)).isFalse();
} }
@Test public void verifyWilcardCnOnTld() throws Exception { @Test public void verifyWilcardCnOnTld() throws Exception {
@ -326,8 +324,8 @@ public final class HostnameVerifierTest {
+ "UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF\n" + "UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF\n"
+ "EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM\n" + "EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n");
assertFalse(verifier.verify("foo.co.jp", session)); assertThat(verifier.verify("foo.co.jp", session)).isFalse();
assertFalse(verifier.verify("\u82b1\u5b50.co.jp", session)); assertThat(verifier.verify("\u82b1\u5b50.co.jp", session)).isFalse();
} }
/** /**
@ -366,10 +364,10 @@ public final class HostnameVerifierTest {
+ "pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3\n" + "pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n");
// try the foo.com variations // try the foo.com variations
assertTrue(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isTrue();
assertTrue(verifier.verify("www.foo.com", session)); assertThat(verifier.verify("www.foo.com", session)).isTrue();
assertTrue(verifier.verify("\u82b1\u5b50.foo.com", session)); assertThat(verifier.verify("\u82b1\u5b50.foo.com", session)).isTrue();
assertFalse(verifier.verify("a.b.foo.com", session)); assertThat(verifier.verify("a.b.foo.com", session)).isFalse();
// these checks test alternative subjects. The test data contains an // these checks test alternative subjects. The test data contains an
// alternative subject starting with a japanese kanji character. This is // alternative subject starting with a japanese kanji character. This is
// not supported by Android because the underlying implementation from // not supported by Android because the underlying implementation from
@ -405,15 +403,16 @@ public final class HostnameVerifierTest {
+ "DCzOCv9Ma6Lv5o5jcYWVxvBSTsnt22hsJpWD1K7iY9lbkLwl0ivn73pG2evsAn9G\n" + "DCzOCv9Ma6Lv5o5jcYWVxvBSTsnt22hsJpWD1K7iY9lbkLwl0ivn73pG2evsAn9G\n"
+ "X8YKH52fnHsCrhSD\n" + "X8YKH52fnHsCrhSD\n"
+ "-----END CERTIFICATE-----"); + "-----END CERTIFICATE-----");
assertEquals(new X500Principal("CN=localhost"), certificate.getSubjectX500Principal()); assertThat(certificate.getSubjectX500Principal()).isEqualTo(
new X500Principal("CN=localhost"));
FakeSSLSession session = new FakeSSLSession(certificate); FakeSSLSession session = new FakeSSLSession(certificate);
assertTrue(verifier.verify("localhost", session)); assertThat(verifier.verify("localhost", session)).isTrue();
assertTrue(verifier.verify("localhost.localdomain", session)); assertThat(verifier.verify("localhost.localdomain", session)).isTrue();
assertFalse(verifier.verify("local.host", session)); assertThat(verifier.verify("local.host", session)).isFalse();
assertTrue(verifier.verify("127.0.0.1", session)); assertThat(verifier.verify("127.0.0.1", session)).isTrue();
assertFalse(verifier.verify("127.0.0.2", session)); assertThat(verifier.verify("127.0.0.2", session)).isFalse();
} }
@Test public void wildcardsCannotMatchIpAddresses() throws Exception { @Test public void wildcardsCannotMatchIpAddresses() throws Exception {
@ -430,7 +429,7 @@ public final class HostnameVerifierTest {
+ "BQUAA0EAk9i88xdjWoewqvE+iMC9tD2obMchgFDaHH0ogxxiRaIKeEly3g0uGxIt\n" + "BQUAA0EAk9i88xdjWoewqvE+iMC9tD2obMchgFDaHH0ogxxiRaIKeEly3g0uGxIt\n"
+ "fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ==\n" + "fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ==\n"
+ "-----END CERTIFICATE-----"); + "-----END CERTIFICATE-----");
assertFalse(verifier.verify("127.0.0.1", session)); assertThat(verifier.verify("127.0.0.1", session)).isFalse();
} }
/** /**
@ -452,7 +451,7 @@ public final class HostnameVerifierTest {
+ "U6LFxmZr31lFyis2/T68PpjAppc0DpNQuA2m/Y7oTHBDi55Fw6HVHCw3lucuWZ5d\n" + "U6LFxmZr31lFyis2/T68PpjAppc0DpNQuA2m/Y7oTHBDi55Fw6HVHCw3lucuWZ5d\n"
+ "qUYo4ES548JdpQtcLrW2sA==\n" + "qUYo4ES548JdpQtcLrW2sA==\n"
+ "-----END CERTIFICATE-----"); + "-----END CERTIFICATE-----");
assertFalse(verifier.verify("google.com", session)); assertThat(verifier.verify("google.com", session)).isFalse();
} }
@Test public void subjectAltName() throws Exception { @Test public void subjectAltName() throws Exception {
@ -478,11 +477,11 @@ public final class HostnameVerifierTest {
+ "DQYJKoZIhvcNAQEFBQADQQBXpZZPOY2Dy1lGG81JTr8L4or9jpKacD7n51eS8iqI\n" + "DQYJKoZIhvcNAQEFBQADQQBXpZZPOY2Dy1lGG81JTr8L4or9jpKacD7n51eS8iqI\n"
+ "oTznPNuXHU5bFN0AAGX2ij47f/EahqTpo5RdS95P4sVm\n" + "oTznPNuXHU5bFN0AAGX2ij47f/EahqTpo5RdS95P4sVm\n"
+ "-----END CERTIFICATE-----"); + "-----END CERTIFICATE-----");
assertFalse(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isFalse();
assertTrue(verifier.verify("bar.com", session)); assertThat(verifier.verify("bar.com", session)).isTrue();
assertTrue(verifier.verify("baz.com", session)); assertThat(verifier.verify("baz.com", session)).isTrue();
assertFalse(verifier.verify("a.foo.com", session)); assertThat(verifier.verify("a.foo.com", session)).isFalse();
assertFalse(verifier.verify("quux.com", session)); assertThat(verifier.verify("quux.com", session)).isFalse();
} }
@Test public void subjectAltNameWithWildcard() throws Exception { @Test public void subjectAltNameWithWildcard() throws Exception {
@ -508,39 +507,39 @@ public final class HostnameVerifierTest {
+ "bTANBgkqhkiG9w0BAQUFAANBAB8yrSl8zqy07i0SNYx2B/FnvQY734pxioaqFWfO\n" + "bTANBgkqhkiG9w0BAQUFAANBAB8yrSl8zqy07i0SNYx2B/FnvQY734pxioaqFWfO\n"
+ "Bqo1ZZl/9aPHEWIwBrxYNVB0SGu/kkbt/vxqOjzzrkXukmI=\n" + "Bqo1ZZl/9aPHEWIwBrxYNVB0SGu/kkbt/vxqOjzzrkXukmI=\n"
+ "-----END CERTIFICATE-----"); + "-----END CERTIFICATE-----");
assertFalse(verifier.verify("foo.com", session)); assertThat(verifier.verify("foo.com", session)).isFalse();
assertTrue(verifier.verify("bar.com", session)); assertThat(verifier.verify("bar.com", session)).isTrue();
assertTrue(verifier.verify("a.baz.com", session)); assertThat(verifier.verify("a.baz.com", session)).isTrue();
assertFalse(verifier.verify("baz.com", session)); assertThat(verifier.verify("baz.com", session)).isFalse();
assertFalse(verifier.verify("a.foo.com", session)); assertThat(verifier.verify("a.foo.com", session)).isFalse();
assertFalse(verifier.verify("a.bar.com", session)); assertThat(verifier.verify("a.bar.com", session)).isFalse();
assertFalse(verifier.verify("quux.com", session)); assertThat(verifier.verify("quux.com", session)).isFalse();
} }
@Test public void verifyAsIpAddress() { @Test public void verifyAsIpAddress() {
// IPv4 // IPv4
assertTrue(Util.verifyAsIpAddress("127.0.0.1")); assertThat(Util.verifyAsIpAddress("127.0.0.1")).isTrue();
assertTrue(Util.verifyAsIpAddress("1.2.3.4")); assertThat(Util.verifyAsIpAddress("1.2.3.4")).isTrue();
// IPv6 // IPv6
assertTrue(Util.verifyAsIpAddress("::1")); assertThat(Util.verifyAsIpAddress("::1")).isTrue();
assertTrue(Util.verifyAsIpAddress("2001:db8::1")); assertThat(Util.verifyAsIpAddress("2001:db8::1")).isTrue();
assertTrue(Util.verifyAsIpAddress("::192.168.0.1")); assertThat(Util.verifyAsIpAddress("::192.168.0.1")).isTrue();
assertTrue(Util.verifyAsIpAddress("::ffff:192.168.0.1")); assertThat(Util.verifyAsIpAddress("::ffff:192.168.0.1")).isTrue();
assertTrue(Util.verifyAsIpAddress("FEDC:BA98:7654:3210:FEDC:BA98:7654:3210")); assertThat(Util.verifyAsIpAddress("FEDC:BA98:7654:3210:FEDC:BA98:7654:3210")).isTrue();
assertTrue(Util.verifyAsIpAddress("1080:0:0:0:8:800:200C:417A")); assertThat(Util.verifyAsIpAddress("1080:0:0:0:8:800:200C:417A")).isTrue();
assertTrue(Util.verifyAsIpAddress("1080::8:800:200C:417A")); assertThat(Util.verifyAsIpAddress("1080::8:800:200C:417A")).isTrue();
assertTrue(Util.verifyAsIpAddress("FF01::101")); assertThat(Util.verifyAsIpAddress("FF01::101")).isTrue();
assertTrue(Util.verifyAsIpAddress("0:0:0:0:0:0:13.1.68.3")); assertThat(Util.verifyAsIpAddress("0:0:0:0:0:0:13.1.68.3")).isTrue();
assertTrue(Util.verifyAsIpAddress("0:0:0:0:0:FFFF:129.144.52.38")); assertThat(Util.verifyAsIpAddress("0:0:0:0:0:FFFF:129.144.52.38")).isTrue();
assertTrue(Util.verifyAsIpAddress("::13.1.68.3")); assertThat(Util.verifyAsIpAddress("::13.1.68.3")).isTrue();
assertTrue(Util.verifyAsIpAddress("::FFFF:129.144.52.38")); assertThat(Util.verifyAsIpAddress("::FFFF:129.144.52.38")).isTrue();
// Hostnames // Hostnames
assertFalse(Util.verifyAsIpAddress("go")); assertThat(Util.verifyAsIpAddress("go")).isFalse();
assertFalse(Util.verifyAsIpAddress("localhost")); assertThat(Util.verifyAsIpAddress("localhost")).isFalse();
assertFalse(Util.verifyAsIpAddress("squareup.com")); assertThat(Util.verifyAsIpAddress("squareup.com")).isFalse();
assertFalse(Util.verifyAsIpAddress("www.nintendo.co.jp")); assertThat(Util.verifyAsIpAddress("www.nintendo.co.jp")).isFalse();
} }
private X509Certificate certificate(String certificate) throws Exception { private X509Certificate certificate(String certificate) throws Exception {

View File

@ -32,9 +32,8 @@ import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse; import static org.assertj.core.data.Offset.offset;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class RealWebSocketTest { public final class RealWebSocketTest {
@ -65,10 +64,11 @@ public final class RealWebSocketTest {
@Test public void close() throws IOException { @Test public void close() throws IOException {
client.webSocket.close(1000, "Hello!"); client.webSocket.close(1000, "Hello!");
assertFalse(server.processNextFrame()); // This will trigger a close response. // This will trigger a close response.
assertThat(server.processNextFrame()).isFalse();
server.listener.assertClosing(1000, "Hello!"); server.listener.assertClosing(1000, "Hello!");
server.webSocket.close(1000, "Goodbye!"); server.webSocket.close(1000, "Goodbye!");
assertFalse(client.processNextFrame()); assertThat(client.processNextFrame()).isFalse();
client.listener.assertClosing(1000, "Goodbye!"); client.listener.assertClosing(1000, "Goodbye!");
server.listener.assertClosed(1000, "Hello!"); server.listener.assertClosed(1000, "Hello!");
client.listener.assertClosed(1000, "Goodbye!"); client.listener.assertClosed(1000, "Goodbye!");
@ -77,8 +77,8 @@ public final class RealWebSocketTest {
@Test public void clientCloseThenMethodsReturnFalse() throws IOException { @Test public void clientCloseThenMethodsReturnFalse() throws IOException {
client.webSocket.close(1000, "Hello!"); client.webSocket.close(1000, "Hello!");
assertFalse(client.webSocket.close(1000, "Hello!")); assertThat(client.webSocket.close(1000, "Hello!")).isFalse();
assertFalse(client.webSocket.send("Hello!")); assertThat(client.webSocket.send("Hello!")).isFalse();
} }
@Test public void clientCloseWith0Fails() throws IOException { @Test public void clientCloseWith0Fails() throws IOException {
@ -86,7 +86,7 @@ public final class RealWebSocketTest {
client.webSocket.close(0, null); client.webSocket.close(0, null);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals(expected.getMessage(), "Code must be in range [1000,5000): 0"); assertThat("Code must be in range [1000,5000): 0").isEqualTo(expected.getMessage());
} }
} }
@ -95,18 +95,18 @@ public final class RealWebSocketTest {
client.webSocket.pong(ByteString.encodeUtf8("Ping!")); client.webSocket.pong(ByteString.encodeUtf8("Ping!"));
client.listener.assertFailure(IOException.class, "source is closed"); client.listener.assertFailure(IOException.class, "source is closed");
assertFalse(client.webSocket.send("Hello!")); assertThat(client.webSocket.send("Hello!")).isFalse();
} }
@Test public void socketClosedDuringMessageKillsWebSocket() throws IOException { @Test public void socketClosedDuringMessageKillsWebSocket() throws IOException {
client2Server.source().close(); client2Server.source().close();
assertTrue(client.webSocket.send("Hello!")); assertThat(client.webSocket.send("Hello!")).isTrue();
client.listener.assertFailure(IOException.class, "source is closed"); client.listener.assertFailure(IOException.class, "source is closed");
// A failed write prevents further use of the WebSocket instance. // A failed write prevents further use of the WebSocket instance.
assertFalse(client.webSocket.send("Hello!")); assertThat(client.webSocket.send("Hello!")).isFalse();
assertFalse(client.webSocket.pong(ByteString.encodeUtf8("Ping!"))); assertThat(client.webSocket.pong(ByteString.encodeUtf8("Ping!"))).isFalse();
} }
@Test public void serverCloseThenWritingPingSucceeds() throws IOException { @Test public void serverCloseThenWritingPingSucceeds() throws IOException {
@ -114,7 +114,7 @@ public final class RealWebSocketTest {
client.processNextFrame(); client.processNextFrame();
client.listener.assertClosing(1000, "Hello!"); client.listener.assertClosing(1000, "Hello!");
assertTrue(client.webSocket.pong(ByteString.encodeUtf8("Pong?"))); assertThat(client.webSocket.pong(ByteString.encodeUtf8("Pong?"))).isTrue();
} }
@Test public void clientCanWriteMessagesAfterServerClose() throws IOException { @Test public void clientCanWriteMessagesAfterServerClose() throws IOException {
@ -122,7 +122,7 @@ public final class RealWebSocketTest {
client.processNextFrame(); client.processNextFrame();
client.listener.assertClosing(1000, "Hello!"); client.listener.assertClosing(1000, "Hello!");
assertTrue(client.webSocket.send("Hi!")); assertThat(client.webSocket.send("Hi!")).isTrue();
server.processNextFrame(); server.processNextFrame();
server.listener.assertTextMessage("Hi!"); server.listener.assertTextMessage("Hi!");
} }
@ -131,7 +131,7 @@ public final class RealWebSocketTest {
server.webSocket.close(1000, "Hello!"); server.webSocket.close(1000, "Hello!");
client.processNextFrame(); client.processNextFrame();
client.listener.assertClosing(1000, "Hello!"); client.listener.assertClosing(1000, "Hello!");
assertTrue(client.webSocket.close(1000, "Bye!")); assertThat(client.webSocket.close(1000, "Bye!")).isTrue();
} }
@Test public void emptyCloseInitiatesShutdown() throws IOException { @Test public void emptyCloseInitiatesShutdown() throws IOException {
@ -139,7 +139,7 @@ public final class RealWebSocketTest {
client.processNextFrame(); client.processNextFrame();
client.listener.assertClosing(1005, ""); client.listener.assertClosing(1005, "");
assertTrue(client.webSocket.close(1000, "Bye!")); assertThat(client.webSocket.close(1000, "Bye!")).isTrue();
server.processNextFrame(); server.processNextFrame();
server.listener.assertClosing(1000, "Bye!"); server.listener.assertClosing(1000, "Bye!");
@ -148,13 +148,13 @@ public final class RealWebSocketTest {
@Test public void clientCloseClosesConnection() throws IOException { @Test public void clientCloseClosesConnection() throws IOException {
client.webSocket.close(1000, "Hello!"); client.webSocket.close(1000, "Hello!");
assertFalse(client.closed); assertThat(client.closed).isFalse();
server.processNextFrame(); // Read client closing, send server close. server.processNextFrame(); // Read client closing, send server close.
server.listener.assertClosing(1000, "Hello!"); server.listener.assertClosing(1000, "Hello!");
server.webSocket.close(1000, "Goodbye!"); server.webSocket.close(1000, "Goodbye!");
client.processNextFrame(); // Read server closing, close connection. client.processNextFrame(); // Read server closing, close connection.
assertTrue(client.closed); assertThat(client.closed).isTrue();
client.listener.assertClosing(1000, "Goodbye!"); client.listener.assertClosing(1000, "Goodbye!");
// Server and client both finished closing, connection is closed. // Server and client both finished closing, connection is closed.
@ -166,7 +166,7 @@ public final class RealWebSocketTest {
server.webSocket.close(1000, "Hello!"); server.webSocket.close(1000, "Hello!");
client.processNextFrame(); // Read server close, send client close, close connection. client.processNextFrame(); // Read server close, send client close, close connection.
assertFalse(client.closed); assertThat(client.closed).isFalse();
client.listener.assertClosing(1000, "Hello!"); client.listener.assertClosing(1000, "Hello!");
client.webSocket.close(1000, "Hello!"); client.webSocket.close(1000, "Hello!");
@ -182,7 +182,7 @@ public final class RealWebSocketTest {
server.webSocket.close(1000, "Hello!"); server.webSocket.close(1000, "Hello!");
client.processNextFrame(); // Read close, close connection close. client.processNextFrame(); // Read close, close connection close.
assertFalse(client.closed); assertThat(client.closed).isFalse();
client.webSocket.close(1000, "Hi!"); client.webSocket.close(1000, "Hi!");
server.processNextFrame(); server.processNextFrame();
@ -191,7 +191,7 @@ public final class RealWebSocketTest {
client.listener.assertClosed(1000, "Hello!"); client.listener.assertClosed(1000, "Hello!");
server.listener.assertClosed(1000, "Hi!"); server.listener.assertClosed(1000, "Hi!");
client.webSocket.awaitTermination(5, TimeUnit.SECONDS); client.webSocket.awaitTermination(5, TimeUnit.SECONDS);
assertTrue(client.closed); assertThat(client.closed).isTrue();
server.listener.assertExhausted(); // Client should not have sent second close. server.listener.assertExhausted(); // Client should not have sent second close.
client.listener.assertExhausted(); // Server should not have sent second close. client.listener.assertExhausted(); // Server should not have sent second close.
@ -200,9 +200,9 @@ public final class RealWebSocketTest {
@Test public void serverCloseBreaksReadMessageLoop() throws IOException { @Test public void serverCloseBreaksReadMessageLoop() throws IOException {
server.webSocket.send("Hello!"); server.webSocket.send("Hello!");
server.webSocket.close(1000, "Bye!"); server.webSocket.close(1000, "Bye!");
assertTrue(client.processNextFrame()); assertThat(client.processNextFrame()).isTrue();
client.listener.assertTextMessage("Hello!"); client.listener.assertTextMessage("Hello!");
assertFalse(client.processNextFrame()); assertThat(client.processNextFrame()).isFalse();
client.listener.assertClosing(1000, "Bye!"); client.listener.assertClosing(1000, "Bye!");
} }
@ -210,7 +210,7 @@ public final class RealWebSocketTest {
server.sink.write(ByteString.decodeHex("0a00")).emit(); // Invalid non-final ping frame. server.sink.write(ByteString.decodeHex("0a00")).emit(); // Invalid non-final ping frame.
client.processNextFrame(); // Detects error, send close, close connection. client.processNextFrame(); // Detects error, send close, close connection.
assertTrue(client.closed); assertThat(client.closed).isTrue();
client.listener.assertFailure(ProtocolException.class, "Control frames must be final."); client.listener.assertFailure(ProtocolException.class, "Control frames must be final.");
server.processNextFrame(); server.processNextFrame();
@ -220,13 +220,14 @@ public final class RealWebSocketTest {
@Test public void protocolErrorInCloseResponseClosesConnection() throws IOException { @Test public void protocolErrorInCloseResponseClosesConnection() throws IOException {
client.webSocket.close(1000, "Hello"); client.webSocket.close(1000, "Hello");
server.processNextFrame(); server.processNextFrame();
assertFalse(client.closed); // Not closed until close reply is received. // Not closed until close reply is received.
assertThat(client.closed).isFalse();
// Manually write an invalid masked close frame. // Manually write an invalid masked close frame.
server.sink.write(ByteString.decodeHex("888760b420bb635c68de0cd84f")).emit(); server.sink.write(ByteString.decodeHex("888760b420bb635c68de0cd84f")).emit();
client.processNextFrame();// Detects error, disconnects immediately since close already sent. client.processNextFrame();// Detects error, disconnects immediately since close already sent.
assertTrue(client.closed); assertThat(client.closed).isTrue();
client.listener.assertFailure( client.listener.assertFailure(
ProtocolException.class, "Server-sent frames must not be masked."); ProtocolException.class, "Server-sent frames must not be masked.");
@ -238,11 +239,12 @@ public final class RealWebSocketTest {
client.webSocket.close(1000, "Hello!"); client.webSocket.close(1000, "Hello!");
server.processNextFrame(); server.processNextFrame();
assertFalse(client.closed); // Not closed until close reply is received. // Not closed until close reply is received.
assertThat(client.closed).isFalse();
server.sink.write(ByteString.decodeHex("0a00")).emit(); // Invalid non-final ping frame. server.sink.write(ByteString.decodeHex("0a00")).emit(); // Invalid non-final ping frame.
client.processNextFrame(); // Detects error, disconnects immediately since close already sent. client.processNextFrame(); // Detects error, disconnects immediately since close already sent.
assertTrue(client.closed); assertThat(client.closed).isTrue();
client.listener.assertFailure(ProtocolException.class, "Control frames must be final."); client.listener.assertFailure(ProtocolException.class, "Control frames must be final.");
server.listener.assertClosing(1000, "Hello!"); server.listener.assertClosing(1000, "Hello!");
@ -269,7 +271,7 @@ public final class RealWebSocketTest {
client.webSocket.close(1000, "Bye!"); client.webSocket.close(1000, "Bye!");
client.listener.assertFailure(IOException.class, "failure"); client.listener.assertFailure(IOException.class, "failure");
assertTrue(client.closed); assertThat(client.closed).isTrue();
} }
@Ignore // TODO(jwilson): come up with a way to test unchecked exceptions on the writer thread. @Ignore // TODO(jwilson): come up with a way to test unchecked exceptions on the writer thread.
@ -292,17 +294,20 @@ public final class RealWebSocketTest {
server.processNextFrame(); // Ping. server.processNextFrame(); // Ping.
client.processNextFrame(); // Pong. client.processNextFrame(); // Pong.
long elapsedUntilPing1 = System.nanoTime() - startNanos; long elapsedUntilPing1 = System.nanoTime() - startNanos;
assertEquals(500, TimeUnit.NANOSECONDS.toMillis(elapsedUntilPing1), 250d); assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilPing1)).isCloseTo((double) 500, offset(
250d));
server.processNextFrame(); // Ping. server.processNextFrame(); // Ping.
client.processNextFrame(); // Pong. client.processNextFrame(); // Pong.
long elapsedUntilPing2 = System.nanoTime() - startNanos; long elapsedUntilPing2 = System.nanoTime() - startNanos;
assertEquals(1000, TimeUnit.NANOSECONDS.toMillis(elapsedUntilPing2), 250d); assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilPing2)).isCloseTo((double) 1000, offset(
250d));
server.processNextFrame(); // Ping. server.processNextFrame(); // Ping.
client.processNextFrame(); // Pong. client.processNextFrame(); // Pong.
long elapsedUntilPing3 = System.nanoTime() - startNanos; long elapsedUntilPing3 = System.nanoTime() - startNanos;
assertEquals(1500, TimeUnit.NANOSECONDS.toMillis(elapsedUntilPing3), 250d); assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilPing3)).isCloseTo((double) 1500, offset(
250d));
} }
@Test public void unacknowledgedPingFailsConnection() throws IOException { @Test public void unacknowledgedPingFailsConnection() throws IOException {
@ -313,7 +318,8 @@ public final class RealWebSocketTest {
client.listener.assertFailure(SocketTimeoutException.class, client.listener.assertFailure(SocketTimeoutException.class,
"sent ping but didn't receive pong within 500ms (after 0 successful ping/pongs)"); "sent ping but didn't receive pong within 500ms (after 0 successful ping/pongs)");
long elapsedUntilFailure = System.nanoTime() - startNanos; long elapsedUntilFailure = System.nanoTime() - startNanos;
assertEquals(1000, TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure), 250d); assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo((double) 1000, offset(
250d));
} }
@Test public void unexpectedPongsDoNotInterfereWithFailureDetection() throws IOException { @Test public void unexpectedPongsDoNotInterfereWithFailureDetection() throws IOException {
@ -332,14 +338,16 @@ public final class RealWebSocketTest {
server.processNextFrame(); // Ping. server.processNextFrame(); // Ping.
client.processNextFrame(); // Pong. client.processNextFrame(); // Pong.
long elapsedUntilPing = System.nanoTime() - startNanos; long elapsedUntilPing = System.nanoTime() - startNanos;
assertEquals(500, TimeUnit.NANOSECONDS.toMillis(elapsedUntilPing), 250d); assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilPing)).isCloseTo((double) 500, offset(
250d));
// After 1000ms the client will attempt a ping 2, but we don't process it. That'll cause the // After 1000ms the client will attempt a ping 2, but we don't process it. That'll cause the
// client to fail at 1500ms when it's time to send ping 3 because pong 2 hasn't been received. // client to fail at 1500ms when it's time to send ping 3 because pong 2 hasn't been received.
client.listener.assertFailure(SocketTimeoutException.class, client.listener.assertFailure(SocketTimeoutException.class,
"sent ping but didn't receive pong within 500ms (after 1 successful ping/pongs)"); "sent ping but didn't receive pong within 500ms (after 1 successful ping/pongs)");
long elapsedUntilFailure = System.nanoTime() - startNanos; long elapsedUntilFailure = System.nanoTime() - startNanos;
assertEquals(1500, TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure), 250d); assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo((double) 1500, offset(
250d));
} }
/** One peer's streams, listener, and web socket in the test. */ /** One peer's streams, listener, and web socket in the test. */

View File

@ -54,11 +54,8 @@ import static okhttp3.TestUtil.defaultClient;
import static okhttp3.TestUtil.ensureAllConnectionsReleased; import static okhttp3.TestUtil.ensureAllConnectionsReleased;
import static okhttp3.TestUtil.repeat; import static okhttp3.TestUtil.repeat;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse; import static org.assertj.core.data.Offset.offset;
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 static org.junit.Assert.fail;
public final class WebSocketHttpTest { public final class WebSocketHttpTest {
@ -73,7 +70,8 @@ public final class WebSocketHttpTest {
.readTimeout(500, TimeUnit.MILLISECONDS) .readTimeout(500, TimeUnit.MILLISECONDS)
.addInterceptor(chain -> { .addInterceptor(chain -> {
Response response = chain.proceed(chain.request()); Response response = chain.proceed(chain.request());
assertNotNull(response.body()); // Ensure application interceptors never see a null body. // Ensure application interceptors never see a null body.
assertThat(response.body()).isNotNull();
return response; return response;
}) })
.build(); .build();
@ -120,7 +118,7 @@ public final class WebSocketHttpTest {
webSocket.send((String) null); webSocket.send((String) null);
fail(); fail();
} catch (NullPointerException e) { } catch (NullPointerException e) {
assertEquals("text == null", e.getMessage()); assertThat(e.getMessage()).isEqualTo("text == null");
} }
closeWebSockets(webSocket, server); closeWebSockets(webSocket, server);
@ -136,7 +134,7 @@ public final class WebSocketHttpTest {
webSocket.send((ByteString) null); webSocket.send((ByteString) null);
fail(); fail();
} catch (NullPointerException e) { } catch (NullPointerException e) {
assertEquals("bytes == null", e.getMessage()); assertThat(e.getMessage()).isEqualTo("bytes == null");
} }
closeWebSockets(webSocket, server); closeWebSockets(webSocket, server);
@ -189,7 +187,7 @@ public final class WebSocketHttpTest {
newWebSocket(); newWebSocket();
assertEquals("", logs.take()); assertThat(logs.take()).isEqualTo("");
logger.removeHandler(logs); logger.removeHandler(logs);
} }
@ -372,10 +370,10 @@ public final class WebSocketHttpTest {
client = client.newBuilder() client = client.newBuilder()
.addInterceptor(chain -> { .addInterceptor(chain -> {
assertNull(chain.request().body()); assertThat(chain.request().body()).isNull();
Response response = chain.proceed(chain.request()); Response response = chain.proceed(chain.request());
assertEquals("Upgrade", response.header("Connection")); assertThat(response.header("Connection")).isEqualTo("Upgrade");
assertTrue(response.body().source().exhausted()); assertThat(response.body().source().exhausted()).isTrue();
interceptedCount.incrementAndGet(); interceptedCount.incrementAndGet();
return response; return response;
}) })
@ -385,7 +383,7 @@ public final class WebSocketHttpTest {
WebSocket webSocket = newWebSocket(); WebSocket webSocket = newWebSocket();
clientListener.assertOpen(); clientListener.assertOpen();
assertEquals(1, interceptedCount.get()); assertThat(interceptedCount.get()).isEqualTo(1);
webSocket.close(1000, null); webSocket.close(1000, null);
WebSocket server = serverListener.assertOpen(); WebSocket server = serverListener.assertOpen();
@ -425,8 +423,9 @@ public final class WebSocketHttpTest {
messageCount++; messageCount++;
long queueSize = webSocket.queueSize(); long queueSize = webSocket.queueSize();
assertTrue(queueSize >= 0 && queueSize <= messageCount * message.size()); assertThat(queueSize >= 0 && queueSize <= messageCount * message.size()).isTrue();
assertTrue(messageCount < 32); // Expect to fail before enqueueing 32 MiB. // Expect to fail before enqueueing 32 MiB.
assertThat(messageCount < 32).isTrue();
} }
// Confirm all sent messages were received, followed by a client-initiated close. // Confirm all sent messages were received, followed by a client-initiated close.
@ -475,7 +474,7 @@ public final class WebSocketHttpTest {
webSocket.close(1000, reason); webSocket.close(1000, reason);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals("reason.size() > 123: " + reason, expected.getMessage()); assertThat(expected.getMessage()).isEqualTo(("reason.size() > 123: " + reason));
} }
webSocket.close(1000, null); webSocket.close(1000, null);
@ -525,7 +524,7 @@ public final class WebSocketHttpTest {
WebSocket webSocket = newWebSocket(); WebSocket webSocket = newWebSocket();
clientListener.assertFailure(SocketTimeoutException.class, "timeout", "Read timed out"); clientListener.assertFailure(SocketTimeoutException.class, "timeout", "Read timed out");
assertFalse(webSocket.close(1000, null)); assertThat(webSocket.close(1000, null)).isFalse();
} }
/** /**
@ -547,7 +546,7 @@ public final class WebSocketHttpTest {
clientListener.assertOpen(); clientListener.assertOpen();
clientListener.assertFailure(SocketTimeoutException.class, "timeout", "Read timed out"); clientListener.assertFailure(SocketTimeoutException.class, "timeout", "Read timed out");
assertFalse(webSocket.close(1000, null)); assertThat(webSocket.close(1000, null)).isFalse();
} }
@Test public void readTimeoutDoesNotApplyAcrossFrames() throws Exception { @Test public void readTimeoutDoesNotApplyAcrossFrames() throws Exception {
@ -583,16 +582,17 @@ public final class WebSocketHttpTest {
} }
long elapsedUntilPong3 = System.nanoTime() - startNanos; long elapsedUntilPong3 = System.nanoTime() - startNanos;
assertEquals(1500, TimeUnit.NANOSECONDS.toMillis(elapsedUntilPong3), 250d); assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilPong3)).isCloseTo((double) 1500, offset(
250d));
// The client pinged the server 3 times, and it has ponged back 3 times. // The client pinged the server 3 times, and it has ponged back 3 times.
assertEquals(3, webSocket.sentPingCount()); assertThat(webSocket.sentPingCount()).isEqualTo(3);
assertEquals(3, server.receivedPingCount()); assertThat(server.receivedPingCount()).isEqualTo(3);
assertEquals(3, webSocket.receivedPongCount()); assertThat(webSocket.receivedPongCount()).isEqualTo(3);
// The server has never pinged the client. // The server has never pinged the client.
assertEquals(0, server.receivedPongCount()); assertThat(server.receivedPongCount()).isEqualTo(0);
assertEquals(0, webSocket.receivedPingCount()); assertThat(webSocket.receivedPingCount()).isEqualTo(0);
closeWebSockets(webSocket, server); closeWebSockets(webSocket, server);
} }
@ -607,12 +607,12 @@ public final class WebSocketHttpTest {
Thread.sleep(1000); Thread.sleep(1000);
// No pings and no pongs. // No pings and no pongs.
assertEquals(0, webSocket.sentPingCount()); assertThat(webSocket.sentPingCount()).isEqualTo(0);
assertEquals(0, webSocket.receivedPingCount()); assertThat(webSocket.receivedPingCount()).isEqualTo(0);
assertEquals(0, webSocket.receivedPongCount()); assertThat(webSocket.receivedPongCount()).isEqualTo(0);
assertEquals(0, server.sentPingCount()); assertThat(server.sentPingCount()).isEqualTo(0);
assertEquals(0, server.receivedPingCount()); assertThat(server.receivedPingCount()).isEqualTo(0);
assertEquals(0, server.receivedPongCount()); assertThat(server.receivedPongCount()).isEqualTo(0);
closeWebSockets(webSocket, server); closeWebSockets(webSocket, server);
} }
@ -647,7 +647,8 @@ public final class WebSocketHttpTest {
latch.countDown(); latch.countDown();
long elapsedUntilFailure = System.nanoTime() - openAtNanos; long elapsedUntilFailure = System.nanoTime() - openAtNanos;
assertEquals(1000, TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure), 250d); assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo((double) 1000, offset(
250d));
} }
/** https://github.com/square/okhttp/issues/2788 */ /** https://github.com/square/okhttp/issues/2788 */
@ -666,7 +667,8 @@ public final class WebSocketHttpTest {
// Confirm that the hard cancel occurred after 500 ms. // Confirm that the hard cancel occurred after 500 ms.
clientListener.assertFailure(); clientListener.assertFailure();
long elapsedUntilFailure = System.nanoTime() - closeAtNanos; long elapsedUntilFailure = System.nanoTime() - closeAtNanos;
assertEquals(500, TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure), 250d); assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo((double) 500, offset(
250d));
// Close the server and confirm it saw what we expected. // Close the server and confirm it saw what we expected.
server.close(1000, null); server.close(1000, null);
@ -697,7 +699,7 @@ public final class WebSocketHttpTest {
clientListener.assertClosed(1000, ""); clientListener.assertClosed(1000, "");
serverListener.assertClosed(1000, ""); serverListener.assertClosed(1000, "");
assertEquals(Collections.emptyList(), listener.recordedEventTypes()); assertThat(listener.recordedEventTypes()).isEmpty();
} }
@Test public void callTimeoutAppliesToSetup() throws Exception { @Test public void callTimeoutAppliesToSetup() throws Exception {
@ -759,8 +761,8 @@ public final class WebSocketHttpTest {
Response response = client.newCall(regularRequest).execute(); Response response = client.newCall(regularRequest).execute();
response.close(); response.close();
assertEquals(0, webServer.takeRequest().getSequenceNumber()); assertThat(webServer.takeRequest().getSequenceNumber()).isEqualTo(0);
assertEquals(1, webServer.takeRequest().getSequenceNumber()); assertThat(webServer.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
private MockResponse upgradeResponse(RecordedRequest request) { private MockResponse upgradeResponse(RecordedRequest request) {

View File

@ -26,8 +26,7 @@ import okio.ByteString;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class WebSocketReaderTest { public final class WebSocketReaderTest {
@ -49,7 +48,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Control frames must be final.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Control frames must be final.");
} }
} }
@ -59,7 +58,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Reserved flags are unsupported.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Reserved flags are unsupported.");
} }
data.clear(); data.clear();
data.write(ByteString.decodeHex("aa00")); // Empty ping, flag 2 set. data.write(ByteString.decodeHex("aa00")); // Empty ping, flag 2 set.
@ -67,7 +66,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Reserved flags are unsupported.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Reserved flags are unsupported.");
} }
data.clear(); data.clear();
data.write(ByteString.decodeHex("ca00")); // Empty ping, flag 3 set. data.write(ByteString.decodeHex("ca00")); // Empty ping, flag 3 set.
@ -75,7 +74,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Reserved flags are unsupported.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Reserved flags are unsupported.");
} }
} }
@ -85,7 +84,7 @@ public final class WebSocketReaderTest {
serverReader.processNextFrame(); serverReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Client-sent frames must be masked.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Client-sent frames must be masked.");
} }
} }
@ -95,7 +94,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Server-sent frames must not be masked.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Server-sent frames must not be masked.");
} }
} }
@ -105,7 +104,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Control frame must be less than 125B.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Control frame must be less than 125B.");
} }
} }
@ -139,7 +138,8 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Frame length 0x8000000000000000 > 0x7FFFFFFFFFFFFFFF", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"Frame length 0x8000000000000000 > 0x7FFFFFFFFFFFFFFF");
} }
} }
@ -233,7 +233,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Expected continuation opcode. Got: 2", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Expected continuation opcode. Got: 2");
} }
} }
@ -261,7 +261,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Malformed close payload length of 1.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Malformed close payload length of 1.");
} }
} }
@ -284,14 +284,14 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Code must be in range [1000,5000): 1", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Code must be in range [1000,5000): 1");
} }
data.write(ByteString.decodeHex("88021388")); // Close with code 5000 data.write(ByteString.decodeHex("88021388")); // Close with code 5000
try { try {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
assertEquals("Code must be in range [1000,5000): 5000", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Code must be in range [1000,5000): 5000");
} }
} }
@ -310,10 +310,11 @@ public final class WebSocketReaderTest {
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
String message = e.getMessage(); String message = e.getMessage();
assertTrue(message, Pattern.matches("Code \\d+ is reserved and may not be used.", message)); assertThat(Pattern.matches("Code \\d+ is reserved and may not be used.", message)).overridingErrorMessage(
message).isTrue();
} }
} }
assertEquals(1991, count); assertThat(count).isEqualTo(1991);
} }
private byte[] binaryData(int length) { private byte[] binaryData(int length) {

View File

@ -28,10 +28,7 @@ import okhttp3.WebSocketListener;
import okhttp3.internal.platform.Platform; import okhttp3.internal.platform.Platform;
import okio.ByteString; import okio.ByteString;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public final class WebSocketRecorder extends WebSocketListener { public final class WebSocketRecorder extends WebSocketListener {
private final String name; private final String name;
@ -135,36 +132,36 @@ public final class WebSocketRecorder extends WebSocketListener {
public void assertTextMessage(String payload) { public void assertTextMessage(String payload) {
Object actual = nextEvent(); Object actual = nextEvent();
assertEquals(new Message(payload), actual); assertThat(actual).isEqualTo(new Message(payload));
} }
public void assertBinaryMessage(ByteString payload) { public void assertBinaryMessage(ByteString payload) {
Object actual = nextEvent(); Object actual = nextEvent();
assertEquals(new Message(payload), actual); assertThat(actual).isEqualTo(new Message(payload));
} }
public void assertPing(ByteString payload) { public void assertPing(ByteString payload) {
Object actual = nextEvent(); Object actual = nextEvent();
assertEquals(new Ping(payload), actual); assertThat(actual).isEqualTo(new Ping(payload));
} }
public void assertPong(ByteString payload) { public void assertPong(ByteString payload) {
Object actual = nextEvent(); Object actual = nextEvent();
assertEquals(new Pong(payload), actual); assertThat(actual).isEqualTo(new Pong(payload));
} }
public void assertClosing(int code, String reason) { public void assertClosing(int code, String reason) {
Object actual = nextEvent(); Object actual = nextEvent();
assertEquals(new Closing(code, reason), actual); assertThat(actual).isEqualTo(new Closing(code, reason));
} }
public void assertClosed(int code, String reason) { public void assertClosed(int code, String reason) {
Object actual = nextEvent(); Object actual = nextEvent();
assertEquals(new Closed(code, reason), actual); assertThat(actual).isEqualTo(new Closed(code, reason));
} }
public void assertExhausted() { public void assertExhausted() {
assertTrue("Remaining events: " + events, events.isEmpty()); assertThat(events.isEmpty()).overridingErrorMessage("Remaining events: " + events).isTrue();
} }
public WebSocket assertOpen() { public WebSocket assertOpen() {
@ -181,8 +178,8 @@ public final class WebSocketRecorder extends WebSocketListener {
throw new AssertionError("Expected Failure but was " + event); throw new AssertionError("Expected Failure but was " + event);
} }
Failure failure = (Failure) event; Failure failure = (Failure) event;
assertNull(failure.response); assertThat(failure.response).isNull();
assertSame(t, failure.t); assertThat(failure.t).isSameAs(t);
} }
public void assertFailure(Class<? extends IOException> cls, String... messages) { public void assertFailure(Class<? extends IOException> cls, String... messages) {
@ -191,10 +188,11 @@ public final class WebSocketRecorder extends WebSocketListener {
throw new AssertionError("Expected Failure but was " + event); throw new AssertionError("Expected Failure but was " + event);
} }
Failure failure = (Failure) event; Failure failure = (Failure) event;
assertNull(failure.response); assertThat(failure.response).isNull();
assertEquals(cls, failure.t.getClass()); assertThat(failure.t.getClass()).isEqualTo(cls);
if (messages.length > 0) { if (messages.length > 0) {
assertTrue(failure.t.getMessage(), Arrays.asList(messages).contains(failure.t.getMessage())); assertThat(Arrays.asList(messages).contains(failure.t.getMessage())).overridingErrorMessage(
failure.t.getMessage()).isTrue();
} }
} }
@ -212,12 +210,12 @@ public final class WebSocketRecorder extends WebSocketListener {
throw new AssertionError("Expected Failure but was " + event); throw new AssertionError("Expected Failure but was " + event);
} }
Failure failure = (Failure) event; Failure failure = (Failure) event;
assertEquals(code, failure.response.code()); assertThat(failure.response.code()).isEqualTo(code);
if (body != null) { if (body != null) {
assertEquals(body, failure.responseBody); assertThat(failure.responseBody).isEqualTo(body);
} }
assertEquals(cls, failure.t.getClass()); assertThat(failure.t.getClass()).isEqualTo(cls);
assertEquals(message, failure.t.getMessage()); assertThat(failure.t.getMessage()).isEqualTo(message);
} }
/** Expose this recorder as a frame callback and shim in "ping" events. */ /** Expose this recorder as a frame callback and shim in "ping" events. */

View File

@ -35,8 +35,7 @@ import static okhttp3.internal.ws.WebSocketProtocol.OPCODE_BINARY;
import static okhttp3.internal.ws.WebSocketProtocol.OPCODE_TEXT; import static okhttp3.internal.ws.WebSocketProtocol.OPCODE_TEXT;
import static okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_BYTE_MAX; import static okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_BYTE_MAX;
import static okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_SHORT_MAX; import static okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_SHORT_MAX;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class WebSocketWriterTest { public final class WebSocketWriterTest {
@ -50,7 +49,8 @@ public final class WebSocketWriterTest {
@Rule public final TestRule noDataLeftBehind = (base, description) -> new Statement() { @Rule public final TestRule noDataLeftBehind = (base, description) -> new Statement() {
@Override public void evaluate() throws Throwable { @Override public void evaluate() throws Throwable {
base.evaluate(); base.evaluate();
assertEquals("Data not empty", "", data.readByteString().hex()); assertThat(data.readByteString().hex()).overridingErrorMessage("Data not empty").isEqualTo(
"");
} }
}; };
@ -82,7 +82,7 @@ public final class WebSocketWriterTest {
assertData("8105"); assertData("8105");
assertData(bytes); assertData(bytes);
assertTrue(data.exhausted()); assertThat(data.exhausted()).isTrue();
} }
@Test public void serverLargeBufferedPayloadWrittenAsOneFrame() throws IOException { @Test public void serverLargeBufferedPayloadWrittenAsOneFrame() throws IOException {
@ -97,7 +97,7 @@ public final class WebSocketWriterTest {
assertData("817e"); assertData("817e");
assertData(Util.format("%04x", length)); assertData(Util.format("%04x", length));
assertData(bytes); assertData(bytes);
assertTrue(data.exhausted()); assertThat(data.exhausted()).isTrue();
} }
@Test public void serverLargeNonBufferedPayloadWrittenAsMultipleFrames() throws IOException { @Test public void serverLargeNonBufferedPayloadWrittenAsMultipleFrames() throws IOException {
@ -125,7 +125,7 @@ public final class WebSocketWriterTest {
assertData(bytes.readByteArray(24_576)); assertData(bytes.readByteArray(24_576));
assertData("807e06a0"); assertData("807e06a0");
assertData(bytes.readByteArray(1_696)); assertData(bytes.readByteArray(1_696));
assertTrue(data.exhausted()); assertThat(data.exhausted()).isTrue();
} }
@Test public void closeFlushes() throws IOException { @Test public void closeFlushes() throws IOException {
@ -150,7 +150,7 @@ public final class WebSocketWriterTest {
sink.write(payload, payload.size()); sink.write(payload, payload.size());
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
assertEquals("closed", e.getMessage()); assertThat(e.getMessage()).isEqualTo("closed");
} }
} }
@ -288,7 +288,7 @@ public final class WebSocketWriterTest {
clientWriter.writeClose(98724976, ByteString.encodeUtf8("Hello")); clientWriter.writeClose(98724976, ByteString.encodeUtf8("Hello"));
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Code must be in range [1000,5000): 98724976", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Code must be in range [1000,5000): 98724976");
} }
} }
@ -297,7 +297,7 @@ public final class WebSocketWriterTest {
clientWriter.writeClose(1005, ByteString.encodeUtf8("Hello")); clientWriter.writeClose(1005, ByteString.encodeUtf8("Hello"));
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Code 1005 is reserved and may not be used.", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Code 1005 is reserved and may not be used.");
} }
} }
@ -346,7 +346,8 @@ public final class WebSocketWriterTest {
serverWriter.writePing(ByteString.of(binaryData(1000))); serverWriter.writePing(ByteString.of(binaryData(1000)));
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Payload size must be less than or equal to 125", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"Payload size must be less than or equal to 125");
} }
} }
@ -355,7 +356,8 @@ public final class WebSocketWriterTest {
serverWriter.writePong(ByteString.of(binaryData(1000))); serverWriter.writePong(ByteString.of(binaryData(1000)));
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Payload size must be less than or equal to 125", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"Payload size must be less than or equal to 125");
} }
} }
@ -365,7 +367,8 @@ public final class WebSocketWriterTest {
serverWriter.writeClose(1000, longReason); serverWriter.writeClose(1000, longReason);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Payload size must be less than or equal to 125", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"Payload size must be less than or equal to 125");
} }
} }
@ -375,7 +378,8 @@ public final class WebSocketWriterTest {
clientWriter.newMessageSink(OPCODE_TEXT, -1); clientWriter.newMessageSink(OPCODE_TEXT, -1);
fail(); fail();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
assertEquals("Another message writer is active. Did you call close()?", e.getMessage()); assertThat(e.getMessage()).isEqualTo(
"Another message writer is active. Did you call close()?");
} }
} }
@ -385,7 +389,7 @@ public final class WebSocketWriterTest {
private void assertData(ByteString expected) throws EOFException { private void assertData(ByteString expected) throws EOFException {
ByteString actual = data.readByteString(expected.size()); ByteString actual = data.readByteString(expected.size());
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
private void assertData(byte[] data) throws IOException { private void assertData(byte[] data) throws IOException {
@ -394,7 +398,8 @@ public final class WebSocketWriterTest {
int count = Math.min(byteCount, data.length - i); int count = Math.min(byteCount, data.length - i);
Buffer expectedChunk = new Buffer(); Buffer expectedChunk = new Buffer();
expectedChunk.write(data, i, count); expectedChunk.write(data, i, count);
assertEquals("At " + i, expectedChunk.readByteString(), this.data.readByteString(count)); assertThat(this.data.readByteString(count)).overridingErrorMessage("At " + i).isEqualTo(
expectedChunk.readByteString());
} }
} }

View File

@ -39,6 +39,11 @@
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -38,8 +38,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static okhttp3.internal.Util.closeQuietly; import static okhttp3.internal.Util.closeQuietly;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public final class HandshakeCertificatesTest { public final class HandshakeCertificatesTest {
private ExecutorService executorService; private ExecutorService executorService;
@ -92,17 +91,16 @@ public final class HandshakeCertificatesTest {
Future<Handshake> clientHandshakeFuture = doClientHandshake(client, serverAddress); Future<Handshake> clientHandshakeFuture = doClientHandshake(client, serverAddress);
Handshake serverHandshake = serverHandshakeFuture.get(); Handshake serverHandshake = serverHandshakeFuture.get();
assertEquals(serverHandshake.peerCertificates(), assertThat(Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate())).isEqualTo(
Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate())); serverHandshake.peerCertificates());
assertEquals(serverHandshake.localCertificates(), assertThat(Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate())).isEqualTo(
Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate())); serverHandshake.localCertificates());
Handshake clientHandshake = clientHandshakeFuture.get(); Handshake clientHandshake = clientHandshakeFuture.get();
assertEquals(clientHandshake.peerCertificates(), assertThat(Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate())).isEqualTo(
Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate())); clientHandshake.peerCertificates());
assertEquals(clientHandshake.localCertificates(), assertThat(Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate())).isEqualTo(
Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate())); clientHandshake.localCertificates());
} }
@Test public void keyManager() { @Test public void keyManager() {
@ -122,8 +120,8 @@ public final class HandshakeCertificatesTest {
.build(); .build();
assertPrivateKeysEquals(certificate.keyPair().getPrivate(), assertPrivateKeysEquals(certificate.keyPair().getPrivate(),
handshakeCertificates.keyManager().getPrivateKey("private")); handshakeCertificates.keyManager().getPrivateKey("private"));
assertEquals(Arrays.asList(certificate.certificate(), intermediate.certificate()), assertThat(Arrays.asList(handshakeCertificates.keyManager().getCertificateChain("private"))).isEqualTo(
Arrays.asList(handshakeCertificates.keyManager().getCertificateChain("private"))); Arrays.asList(certificate.certificate(), intermediate.certificate()));
} }
@Test public void platformTrustedCertificates() { @Test public void platformTrustedCertificates() {
@ -137,7 +135,7 @@ public final class HandshakeCertificatesTest {
names.add(name.substring(0, name.indexOf(" "))); names.add(name.substring(0, name.indexOf(" ")));
} }
// It's safe to assume all platforms will have a major Internet certificate issuer. // It's safe to assume all platforms will have a major Internet certificate issuer.
assertTrue(names.toString(), names.contains("CN=Entrust")); assertThat(names.contains("CN=Entrust")).overridingErrorMessage(names.toString()).isTrue();
} }
private InetSocketAddress startTlsServer() throws IOException { private InetSocketAddress startTlsServer() throws IOException {
@ -186,6 +184,7 @@ public final class HandshakeCertificatesTest {
} }
private void assertPrivateKeysEquals(PrivateKey expected, PrivateKey actual) { private void assertPrivateKeysEquals(PrivateKey expected, PrivateKey actual) {
assertEquals(ByteString.of(expected.getEncoded()), ByteString.of(actual.getEncoded())); assertThat(ByteString.of(actual.getEncoded())).isEqualTo(
ByteString.of(expected.getEncoded()));
} }
} }

View File

@ -31,9 +31,8 @@ import okio.ByteString;
import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralName;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull; import static org.assertj.core.data.Offset.offset;
import static org.junit.Assert.assertTrue;
public final class HeldCertificateTest { public final class HeldCertificateTest {
@Test public void defaultCertificate() throws CertificateParsingException { @Test public void defaultCertificate() throws CertificateParsingException {
@ -41,17 +40,18 @@ public final class HeldCertificateTest {
HeldCertificate heldCertificate = new HeldCertificate.Builder().build(); HeldCertificate heldCertificate = new HeldCertificate.Builder().build();
X509Certificate certificate = heldCertificate.certificate(); X509Certificate certificate = heldCertificate.certificate();
assertEquals("self-signed", assertThat(certificate.getSubjectX500Principal().getName()).overridingErrorMessage(
certificate.getIssuerX500Principal().getName(), "self-signed").isEqualTo(certificate.getIssuerX500Principal().getName());
certificate.getSubjectX500Principal().getName()); assertThat(certificate.getIssuerX500Principal().getName().matches("CN=[0-9a-f-]{36}")).isTrue();
assertTrue(certificate.getIssuerX500Principal().getName().matches("CN=[0-9a-f-]{36}")); assertThat(certificate.getSerialNumber()).isEqualTo(BigInteger.ONE);
assertEquals(BigInteger.ONE, certificate.getSerialNumber()); assertThat(certificate.getSubjectAlternativeNames()).isNull();
assertNull(certificate.getSubjectAlternativeNames());
double deltaMillis = 1000.0; double deltaMillis = 1000.0;
long durationMillis = TimeUnit.MINUTES.toMillis(60 * 24); long durationMillis = TimeUnit.MINUTES.toMillis(60 * 24);
assertEquals((double) now, certificate.getNotBefore().getTime(), deltaMillis); assertThat((double) certificate.getNotBefore().getTime()).isCloseTo(
assertEquals((double) now + durationMillis, certificate.getNotAfter().getTime(), deltaMillis); (double) now, offset(deltaMillis));
assertThat((double) certificate.getNotAfter().getTime()).isCloseTo(
(double) now + durationMillis, offset(deltaMillis));
} }
@Test public void customInterval() { @Test public void customInterval() {
@ -60,8 +60,8 @@ public final class HeldCertificateTest {
.validityInterval(5_000L, 10_000L) .validityInterval(5_000L, 10_000L)
.build(); .build();
X509Certificate certificate = heldCertificate.certificate(); X509Certificate certificate = heldCertificate.certificate();
assertEquals(5_000L, certificate.getNotBefore().getTime()); assertThat(certificate.getNotBefore().getTime()).isEqualTo(5_000L);
assertEquals(10_000L, certificate.getNotAfter().getTime()); assertThat(certificate.getNotAfter().getTime()).isEqualTo(10_000L);
} }
@Test public void customDuration() { @Test public void customDuration() {
@ -74,8 +74,10 @@ public final class HeldCertificateTest {
double deltaMillis = 1000.0; double deltaMillis = 1000.0;
long durationMillis = 5_000L; long durationMillis = 5_000L;
assertEquals((double) now, certificate.getNotBefore().getTime(), deltaMillis); assertThat((double) certificate.getNotBefore().getTime()).isCloseTo(
assertEquals((double) now + durationMillis, certificate.getNotAfter().getTime(), deltaMillis); (double) now, offset(deltaMillis));
assertThat((double) certificate.getNotAfter().getTime()).isCloseTo(
(double) now + durationMillis, offset(deltaMillis));
} }
@Test public void subjectAlternativeNames() throws CertificateParsingException { @Test public void subjectAlternativeNames() throws CertificateParsingException {
@ -87,9 +89,9 @@ public final class HeldCertificateTest {
X509Certificate certificate = heldCertificate.certificate(); X509Certificate certificate = heldCertificate.certificate();
List<List<?>> subjectAlternativeNames = new ArrayList<>( List<List<?>> subjectAlternativeNames = new ArrayList<>(
certificate.getSubjectAlternativeNames()); certificate.getSubjectAlternativeNames());
assertEquals(subjectAlternativeNames, Arrays.asList( assertThat(Arrays.asList(
Arrays.asList(GeneralName.iPAddress, "1.1.1.1"), Arrays.asList(GeneralName.iPAddress, "1.1.1.1"),
Arrays.asList(GeneralName.dNSName, "cash.app"))); Arrays.asList(GeneralName.dNSName, "cash.app"))).isEqualTo(subjectAlternativeNames);
} }
@Test public void commonName() { @Test public void commonName() {
@ -98,7 +100,7 @@ public final class HeldCertificateTest {
.build(); .build();
X509Certificate certificate = heldCertificate.certificate(); X509Certificate certificate = heldCertificate.certificate();
assertEquals("CN=cash.app", certificate.getSubjectX500Principal().getName()); assertThat(certificate.getSubjectX500Principal().getName()).isEqualTo("CN=cash.app");
} }
@Test public void organizationalUnit() { @Test public void organizationalUnit() {
@ -108,7 +110,8 @@ public final class HeldCertificateTest {
.build(); .build();
X509Certificate certificate = heldCertificate.certificate(); X509Certificate certificate = heldCertificate.certificate();
assertEquals("CN=cash.app,OU=cash", certificate.getSubjectX500Principal().getName()); assertThat(certificate.getSubjectX500Principal().getName()).isEqualTo(
"CN=cash.app,OU=cash");
} }
/** Confirm golden values of encoded PEMs. */ /** Confirm golden values of encoded PEMs. */
@ -142,7 +145,7 @@ public final class HeldCertificateTest {
.rsa2048() .rsa2048()
.build(); .build();
assertEquals(heldCertificate.certificatePem(), "" assertThat((""
+ "-----BEGIN CERTIFICATE-----\n" + "-----BEGIN CERTIFICATE-----\n"
+ "MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\n" + "MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\n"
+ "LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT\n" + "LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT\n"
@ -153,9 +156,9 @@ public final class HeldCertificateTest {
+ "UVwKh5Ry7es3OxtY3IgQunPUoLc0Gw71gl9Z+7t2FJ5VkcI5gWfutmdxZ2bDXCI8\n" + "UVwKh5Ry7es3OxtY3IgQunPUoLc0Gw71gl9Z+7t2FJ5VkcI5gWfutmdxZ2bDXCI8\n"
+ "8V0vxo1pHXnbBrnxhS/Z3TBerw8RyQqcaWOdp+pBXyIWmR+jHk9cHZCqQveTIBsY\n" + "8V0vxo1pHXnbBrnxhS/Z3TBerw8RyQqcaWOdp+pBXyIWmR+jHk9cHZCqQveTIBsY\n"
+ "jaA9VEhgdaVhxBsT2qzUNDsXlOzGsliznDfoqETb\n" + "jaA9VEhgdaVhxBsT2qzUNDsXlOzGsliznDfoqETb\n"
+ "-----END CERTIFICATE-----\n"); + "-----END CERTIFICATE-----\n")).isEqualTo(heldCertificate.certificatePem());
assertEquals(heldCertificate.privateKeyPkcs1Pem(), "" assertThat((""
+ "-----BEGIN RSA PRIVATE KEY-----\n" + "-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIICWwIBAAKBgQCApFHhtrLan28q+oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1w\n" + "MIICWwIBAAKBgQCApFHhtrLan28q+oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1w\n"
+ "J4YEoUCjDlPOtpht7XLbUmBnbIzN89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274w\n" + "J4YEoUCjDlPOtpht7XLbUmBnbIzN89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274w\n"
@ -170,9 +173,9 @@ public final class HeldCertificateTest {
+ "xs/h8kq5HE+woNdjPzZHVEJ2Xt46/PKbf/iBjcKJnOlrf5ieH3FjjU5BjHHzmX39\n" + "xs/h8kq5HE+woNdjPzZHVEJ2Xt46/PKbf/iBjcKJnOlrf5ieH3FjjU5BjHHzmX39\n"
+ "TUHjVwwGeveNVwrCFQJAEjoNNj5VRy4nVO5iBOubMDDOf0TYUuGhY3s/zMMRTTh2\n" + "TUHjVwwGeveNVwrCFQJAEjoNNj5VRy4nVO5iBOubMDDOf0TYUuGhY3s/zMMRTTh2\n"
+ "sXPVYAsGD1wizrXX+wFaL3chtF1oG1Fx/jcsSsG6BA==\n" + "sXPVYAsGD1wizrXX+wFaL3chtF1oG1Fx/jcsSsG6BA==\n"
+ "-----END RSA PRIVATE KEY-----\n"); + "-----END RSA PRIVATE KEY-----\n")).isEqualTo(heldCertificate.privateKeyPkcs1Pem());
assertEquals(heldCertificate.privateKeyPkcs8Pem(), "" assertThat((""
+ "-----BEGIN PRIVATE KEY-----\n" + "-----BEGIN PRIVATE KEY-----\n"
+ "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAICkUeG2stqfbyr6\n" + "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAICkUeG2stqfbyr6\n"
+ "gyiVm5pN9YEDRXlowi+rfYGyWhC7ouW9fXAnhgShQKMOU862mG3tcttSYGdsjM3z\n" + "gyiVm5pN9YEDRXlowi+rfYGyWhC7ouW9fXAnhgShQKMOU862mG3tcttSYGdsjM3z\n"
@ -188,7 +191,7 @@ public final class HeldCertificateTest {
+ "8pt/+IGNwomc6Wt/mJ4fcWONTkGMcfOZff1NQeNXDAZ6941XCsIVAkASOg02PlVH\n" + "8pt/+IGNwomc6Wt/mJ4fcWONTkGMcfOZff1NQeNXDAZ6941XCsIVAkASOg02PlVH\n"
+ "LidU7mIE65swMM5/RNhS4aFjez/MwxFNOHaxc9VgCwYPXCLOtdf7AVovdyG0XWgb\n" + "LidU7mIE65swMM5/RNhS4aFjez/MwxFNOHaxc9VgCwYPXCLOtdf7AVovdyG0XWgb\n"
+ "UXH+NyxKwboE\n" + "UXH+NyxKwboE\n"
+ "-----END PRIVATE KEY-----\n"); + "-----END PRIVATE KEY-----\n")).isEqualTo(heldCertificate.privateKeyPkcs8Pem());
} }
@Test public void ecdsaSignedByRsa() { @Test public void ecdsaSignedByRsa() {
@ -202,8 +205,8 @@ public final class HeldCertificateTest {
.signedBy(root) .signedBy(root)
.build(); .build();
assertEquals("SHA256WITHRSA", root.certificate().getSigAlgName()); assertThat(root.certificate().getSigAlgName()).isEqualTo("SHA256WITHRSA");
assertEquals("SHA256WITHRSA", leaf.certificate().getSigAlgName()); assertThat(leaf.certificate().getSigAlgName()).isEqualTo("SHA256WITHRSA");
} }
@Test public void rsaSignedByEcdsa() { @Test public void rsaSignedByEcdsa() {
@ -217,7 +220,7 @@ public final class HeldCertificateTest {
.signedBy(root) .signedBy(root)
.build(); .build();
assertEquals("SHA256WITHECDSA", root.certificate().getSigAlgName()); assertThat(root.certificate().getSigAlgName()).isEqualTo("SHA256WITHECDSA");
assertEquals("SHA256WITHECDSA", leaf.certificate().getSigAlgName()); assertThat(leaf.certificate().getSigAlgName()).isEqualTo("SHA256WITHECDSA");
} }
} }

View File

@ -53,6 +53,11 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -26,6 +26,7 @@
<module>okhttp-testing-support</module> <module>okhttp-testing-support</module>
<module>okhttp-tls</module> <module>okhttp-tls</module>
<module>okhttp-urlconnection</module> <module>okhttp-urlconnection</module>
<module>okhttp-hpacktests</module>
<module>okhttp-logging-interceptor</module> <module>okhttp-logging-interceptor</module>
@ -53,6 +54,7 @@
<!-- Test Dependencies --> <!-- Test Dependencies -->
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<assertj.version>3.11.0</assertj.version>
<!-- platform test mode --> <!-- platform test mode -->
<okhttp.platform>platform</okhttp.platform> <okhttp.platform>platform</okhttp.platform>
@ -130,6 +132,11 @@
<artifactId>conscrypt-openjdk-uber</artifactId> <artifactId>conscrypt-openjdk-uber</artifactId>
<version>${conscrypt.version}</version> <version>${conscrypt.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>