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>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

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

View File

@ -26,7 +26,7 @@ import okhttp3.internal.Util;
import okio.Buffer;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
public class RecordedRequestTest {
Headers headers = Util.EMPTY_HEADERS;
@ -76,7 +76,7 @@ public class RecordedRequestTest {
RecordedRequest request = new RecordedRequest("GET / HTTP/1.1", headers,
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 {
@ -86,7 +86,7 @@ public class RecordedRequestTest {
RecordedRequest request = new RecordedRequest("GET / HTTP/1.1", headers,
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 {
@ -96,6 +96,6 @@ public class RecordedRequestTest {
RecordedRequest request = new RecordedRequest("GET / HTTP/1.1", headers,
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>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -24,7 +24,7 @@ import okhttp3.internal.http2.hpackjson.HpackJsonUtil;
import okhttp3.internal.http2.hpackjson.Story;
import okio.Buffer;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
/**
@ -83,7 +83,8 @@ public class HpackDecodeTestBase {
*/
private static void assertSetEquals(
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() {

View File

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

View File

@ -38,17 +38,13 @@ import okhttp3.tls.HandshakeCertificates;
import okio.Buffer;
import okio.BufferedSink;
import okio.ByteString;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.assertj.core.api.Assertions.assertThat;
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.Assume.assumeThat;
@ -91,11 +87,11 @@ public final class HttpLoggingInterceptorTest {
@Test public void levelGetter() {
// The default is NONE.
Assert.assertEquals(Level.NONE, applicationInterceptor.getLevel());
assertThat(applicationInterceptor.getLevel()).isEqualTo(Level.NONE);
for (Level level : Level.values()) {
applicationInterceptor.setLevel(level);
assertEquals(level, applicationInterceptor.getLevel());
assertThat(applicationInterceptor.getLevel()).isEqualTo(level);
}
}
@ -104,13 +100,13 @@ public final class HttpLoggingInterceptorTest {
applicationInterceptor.setLevel(null);
fail();
} 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() {
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();
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();
networkLogs
@ -649,13 +646,13 @@ public final class HttpLoggingInterceptorTest {
}
@Test public void isPlaintext() {
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer()));
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("abc")));
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("new\r\nlines")));
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("white\t space")));
assertTrue(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0x80)));
assertFalse(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0x00)));
assertFalse(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0xc0)));
assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer())).isTrue();
assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("abc"))).isTrue();
assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("new\r\nlines"))).isTrue();
assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeUtf8("white\t space"))).isTrue();
assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0x80))).isTrue();
assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0x00))).isFalse();
assertThat(HttpLoggingInterceptor.isPlaintext(new Buffer().writeByte(0xc0))).isFalse();
}
@Test public void responseBodyIsBinary() throws IOException {
@ -827,7 +824,7 @@ public final class HttpLoggingInterceptorTest {
Response response = client.newCall(request).execute();
assumeThat(response.protocol(), equalTo(Protocol.HTTP_2));
assertEquals("Hello response!", response.body().string());
assertThat(response.body().string()).isEqualTo("Hello response!");
applicationLogs
.assertLogEqual("--> POST " + url)
@ -849,22 +846,23 @@ public final class HttpLoggingInterceptorTest {
private int index;
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++);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
return this;
}
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++);
assertTrue("<" + actual + "> did not match pattern <" + pattern + ">",
Pattern.matches(pattern, actual));
assertThat(Pattern.matches(pattern, actual)).overridingErrorMessage(
"<" + actual + "> did not match pattern <" + pattern + ">").isTrue();
return this;
}
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) {

View File

@ -35,7 +35,7 @@ import static java.util.Arrays.asList;
import static okhttp3.Protocol.HTTP_1_1;
import static okhttp3.Protocol.HTTP_2;
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;
public final class LoggingEventListenerTest {
@ -67,7 +67,7 @@ public final class LoggingEventListenerTest {
public void get() throws Exception {
server.enqueue(new MockResponse().setBody("Hello!").setHeader("Content-Type", PLAIN));
Response response = client.newCall(request().build()).execute();
assertNotNull(response.body());
assertThat(response.body()).isNotNull();
response.body().bytes();
logRecorder
@ -136,7 +136,7 @@ public final class LoggingEventListenerTest {
server.enqueue(new MockResponse());
Response response = client.newCall(request().build()).execute();
assertNotNull(response.body());
assertThat(response.body()).isNotNull();
response.body().bytes();
logRecorder

View File

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

View File

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

View File

@ -25,9 +25,7 @@ import okhttp3.Response;
import okhttp3.internal.platform.Platform;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
public final class EventSourceRecorder extends EventSourceListener {
private final BlockingQueue<Object> events = new LinkedBlockingDeque<>();
@ -67,12 +65,12 @@ public final class EventSourceRecorder extends EventSourceListener {
}
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) {
Object actual = nextEvent();
assertEquals(new Event(id, type, data), actual);
assertThat(actual).isEqualTo(new Event(id, type, data));
}
public EventSource assertOpen() {
@ -96,9 +94,9 @@ public final class EventSourceRecorder extends EventSourceListener {
throw new AssertionError("Expected Failure but was " + event);
}
if (message != null) {
assertEquals(message, ((Failure) event).t.getMessage());
assertThat(((Failure) event).t.getMessage()).isEqualTo(message);
} 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.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
public final class ServerSentEventIteratorTest {
/** Either {@link Event} or {@link Long} items for events and retry changes, respectively. */
private final Deque<Object> callbacks = new ArrayDeque<>();
@After public void after() {
assertTrue("Unconsumed events: " + callbacks, callbacks.isEmpty());
assertThat(callbacks.isEmpty()).overridingErrorMessage("Unconsumed events: " + callbacks).isTrue();
}
@Test public void multiline() throws IOException {
@ -40,7 +39,7 @@ public final class ServerSentEventIteratorTest {
+ "data: +2\n"
+ "data: 10\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 {
@ -49,7 +48,7 @@ public final class ServerSentEventIteratorTest {
+ "data: +2\r"
+ "data: 10\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 {
@ -58,7 +57,7 @@ public final class ServerSentEventIteratorTest {
+ "data: +2\r\n"
+ "data: 10\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 {
@ -72,9 +71,9 @@ public final class ServerSentEventIteratorTest {
+ "event: add\n"
+ "data: 113411\n"
+ "\n");
assertEquals(new Event(null, "add", "73857293"), callbacks.remove());
assertEquals(new Event(null, "remove", "2153"), callbacks.remove());
assertEquals(new Event(null, "add", "113411"), callbacks.remove());
assertThat(callbacks.remove()).isEqualTo(new Event(null, "add", "73857293"));
assertThat(callbacks.remove()).isEqualTo(new Event(null, "remove", "2153"));
assertThat(callbacks.remove()).isEqualTo(new Event(null, "add", "113411"));
}
@Test public void commentsIgnored() throws IOException {
@ -84,7 +83,7 @@ public final class ServerSentEventIteratorTest {
+ "data: first event\n"
+ "id: 1\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 {
@ -97,9 +96,9 @@ public final class ServerSentEventIteratorTest {
+ "\n"
+ "data: third event\n"
+ "\n");
assertEquals(new Event("1", null, "first event"), callbacks.remove());
assertEquals(new Event(null, null, "second event"), callbacks.remove());
assertEquals(new Event(null, null, "third event"), callbacks.remove());
assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "first event"));
assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "second event"));
assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "third event"));
}
@Test public void nakedFieldNames() throws IOException {
@ -110,8 +109,8 @@ public final class ServerSentEventIteratorTest {
+ "data\n"
+ "\n"
+ "data:\n");
assertEquals(new Event(null, null, ""), callbacks.remove());
assertEquals(new Event(null, null, "\n"), callbacks.remove());
assertThat(callbacks.remove()).isEqualTo(new Event(null, null, ""));
assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "\n"));
}
@Test public void colonSpaceOptional() throws IOException {
@ -120,15 +119,15 @@ public final class ServerSentEventIteratorTest {
+ "\n"
+ "data: test\n"
+ "\n");
assertEquals(new Event(null, null, "test"), callbacks.remove());
assertEquals(new Event(null, null, "test"), callbacks.remove());
assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "test"));
assertThat(callbacks.remove()).isEqualTo(new Event(null, null, "test"));
}
@Test public void leadingWhitespace() throws IOException {
consumeEvents(""
+ "data: test\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 {
@ -141,9 +140,9 @@ public final class ServerSentEventIteratorTest {
+ "id: 2\n"
+ "data: third event\n"
+ "\n");
assertEquals(new Event("1", null, "first event"), callbacks.remove());
assertEquals(new Event("1", null, "second event"), callbacks.remove());
assertEquals(new Event("2", null, "third event"), callbacks.remove());
assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "first event"));
assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "second event"));
assertThat(callbacks.remove()).isEqualTo(new Event("2", null, "third event"));
}
@Test public void idIgnoredFromEmptyEvent() throws IOException {
@ -155,8 +154,8 @@ public final class ServerSentEventIteratorTest {
+ "\n"
+ "data: second event\n"
+ "\n");
assertEquals(new Event("1", null, "first event"), callbacks.remove());
assertEquals(new Event("1", null, "second event"), callbacks.remove());
assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "first event"));
assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "second event"));
}
@Test public void retry() throws IOException {
@ -166,8 +165,8 @@ public final class ServerSentEventIteratorTest {
+ "data: first event\n"
+ "id: 1\n"
+ "\n");
assertEquals(22L, callbacks.remove());
assertEquals(new Event("1", null, "first event"), callbacks.remove());
assertThat(callbacks.remove()).isEqualTo(22L);
assertThat(callbacks.remove()).isEqualTo(new Event("1", null, "first event"));
}
@Test public void retryInvalidFormatIgnored() throws IOException {
@ -176,7 +175,7 @@ public final class ServerSentEventIteratorTest {
+ "\n"
+ "retry: hey"
+ "\n");
assertEquals(22L, callbacks.remove());
assertThat(callbacks.remove()).isEqualTo(22L);
}
private void consumeEvents(String source) throws IOException {
@ -191,6 +190,7 @@ public final class ServerSentEventIteratorTest {
Buffer buffer = new Buffer().writeUtf8(source);
ServerSentEventReader reader = new ServerSentEventReader(buffer, callback);
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>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</dependency>
</dependencies>
<build>

View File

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

View File

@ -22,7 +22,7 @@ import java.util.Collections;
import java.util.Deque;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
public final class RecordingCookieJar implements CookieJar {
private final Deque<List<Cookie>> requestCookies = new ArrayDeque<>();
@ -42,7 +42,7 @@ public final class RecordingCookieJar implements CookieJar {
for (Cookie cookie : actualCookies) {
actualCookieStrings.add(cookie.toString());
}
assertEquals(Arrays.asList(cookies), actualCookieStrings);
assertThat(actualCookieStrings).containsExactly(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 okhttp3.internal.http2.Header;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
public final class TestUtil {
public static final InetSocketAddress UNREACHABLE_ADDRESS
@ -88,6 +88,6 @@ public final class TestUtil {
public static void ensureAllConnectionsReleased(OkHttpClient client) {
client.connectionPool().evictAll();
assertEquals(0, client.connectionPool().idleConnectionCount());
assertThat(client.connectionPool().idleConnectionCount()).isEqualTo(0);
}
}

View File

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

View File

@ -22,8 +22,7 @@ import okhttp3.internal.Util;
import okhttp3.internal.http.RecordingProxySelector;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.assertj.core.api.Assertions.assertThat;
public final class AddressTest {
private Dns dns = Dns.SYSTEM;
@ -38,8 +37,8 @@ public final class AddressTest {
authenticator, null, protocols, connectionSpecs, proxySelector);
Address b = new Address("square.com", 80, dns, socketFactory, null, null, null,
authenticator, null, protocols, connectionSpecs, proxySelector);
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
assertThat(b).isEqualTo(a);
assertThat(b.hashCode()).isEqualTo(a.hashCode());
}
@Test public void differentProxySelectorsAreDifferent() throws Exception {
@ -47,19 +46,20 @@ public final class AddressTest {
authenticator, null, protocols, connectionSpecs, new RecordingProxySelector());
Address b = new Address("square.com", 80, dns, socketFactory, null, null, null,
authenticator, null, protocols, connectionSpecs, new RecordingProxySelector());
assertNotEquals(a, b);
assertThat(b).isNotEqualTo(a);
}
@Test public void addressToString() throws Exception {
Address address = new Address("square.com", 80, dns, socketFactory, null, null, null,
authenticator, null, protocols, connectionSpecs, proxySelector);
assertEquals("Address{square.com:80, proxySelector=RecordingProxySelector}",
address.toString());
assertThat(address.toString()).isEqualTo(
"Address{square.com:80, proxySelector=RecordingProxySelector}");
}
@Test public void addressWithProxyToString() throws Exception {
Address address = new Address("square.com", 80, dns, socketFactory, null, null, null,
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 org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class CacheControlTest {
@Test public void emptyBuilderIsEmpty() throws Exception {
CacheControl cacheControl = new CacheControl.Builder().build();
assertEquals("", cacheControl.toString());
assertFalse(cacheControl.noCache());
assertFalse(cacheControl.noStore());
assertEquals(-1, cacheControl.maxAgeSeconds());
assertEquals(-1, cacheControl.sMaxAgeSeconds());
assertFalse(cacheControl.isPrivate());
assertFalse(cacheControl.isPublic());
assertFalse(cacheControl.mustRevalidate());
assertEquals(-1, cacheControl.maxStaleSeconds());
assertEquals(-1, cacheControl.minFreshSeconds());
assertFalse(cacheControl.onlyIfCached());
assertFalse(cacheControl.mustRevalidate());
assertThat(cacheControl.toString()).isEqualTo("");
assertThat(cacheControl.noCache()).isFalse();
assertThat(cacheControl.noStore()).isFalse();
assertThat(cacheControl.maxAgeSeconds()).isEqualTo(-1);
assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(-1);
assertThat(cacheControl.isPrivate()).isFalse();
assertThat(cacheControl.isPublic()).isFalse();
assertThat(cacheControl.mustRevalidate()).isFalse();
assertThat(cacheControl.maxStaleSeconds()).isEqualTo(-1);
assertThat(cacheControl.minFreshSeconds()).isEqualTo(-1);
assertThat(cacheControl.onlyIfCached()).isFalse();
assertThat(cacheControl.mustRevalidate()).isFalse();
}
@Test public void completeBuilder() throws Exception {
@ -53,38 +49,39 @@ public final class CacheControlTest {
.noTransform()
.immutable()
.build();
assertEquals("no-cache, no-store, max-age=1, max-stale=2, min-fresh=3, only-if-cached, "
+ "no-transform, immutable", cacheControl.toString());
assertTrue(cacheControl.noCache());
assertTrue(cacheControl.noStore());
assertEquals(1, cacheControl.maxAgeSeconds());
assertEquals(2, cacheControl.maxStaleSeconds());
assertEquals(3, cacheControl.minFreshSeconds());
assertTrue(cacheControl.onlyIfCached());
assertTrue(cacheControl.noTransform());
assertTrue(cacheControl.immutable());
assertThat(cacheControl.toString()).isEqualTo(
("no-cache, no-store, max-age=1, max-stale=2, min-fresh=3, only-if-cached, "
+ "no-transform, immutable"));
assertThat(cacheControl.noCache()).isTrue();
assertThat(cacheControl.noStore()).isTrue();
assertThat(cacheControl.maxAgeSeconds()).isEqualTo(1);
assertThat(cacheControl.maxStaleSeconds()).isEqualTo(2);
assertThat(cacheControl.minFreshSeconds()).isEqualTo(3);
assertThat(cacheControl.onlyIfCached()).isTrue();
assertThat(cacheControl.noTransform()).isTrue();
assertThat(cacheControl.immutable()).isTrue();
// These members are accessible to response headers only.
assertEquals(-1, cacheControl.sMaxAgeSeconds());
assertFalse(cacheControl.isPrivate());
assertFalse(cacheControl.isPublic());
assertFalse(cacheControl.mustRevalidate());
assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(-1);
assertThat(cacheControl.isPrivate()).isFalse();
assertThat(cacheControl.isPublic()).isFalse();
assertThat(cacheControl.mustRevalidate()).isFalse();
}
@Test public void parseEmpty() throws Exception {
CacheControl cacheControl = CacheControl.parse(
new Headers.Builder().set("Cache-Control", "").build());
assertEquals("", cacheControl.toString());
assertFalse(cacheControl.noCache());
assertFalse(cacheControl.noStore());
assertEquals(-1, cacheControl.maxAgeSeconds());
assertEquals(-1, cacheControl.sMaxAgeSeconds());
assertFalse(cacheControl.isPublic());
assertFalse(cacheControl.mustRevalidate());
assertEquals(-1, cacheControl.maxStaleSeconds());
assertEquals(-1, cacheControl.minFreshSeconds());
assertFalse(cacheControl.onlyIfCached());
assertFalse(cacheControl.mustRevalidate());
assertThat(cacheControl.toString()).isEqualTo("");
assertThat(cacheControl.noCache()).isFalse();
assertThat(cacheControl.noStore()).isFalse();
assertThat(cacheControl.maxAgeSeconds()).isEqualTo(-1);
assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(-1);
assertThat(cacheControl.isPublic()).isFalse();
assertThat(cacheControl.mustRevalidate()).isFalse();
assertThat(cacheControl.maxStaleSeconds()).isEqualTo(-1);
assertThat(cacheControl.minFreshSeconds()).isEqualTo(-1);
assertThat(cacheControl.onlyIfCached()).isFalse();
assertThat(cacheControl.mustRevalidate()).isFalse();
}
@Test public void parse() throws Exception {
@ -93,18 +90,18 @@ public final class CacheControlTest {
CacheControl cacheControl = CacheControl.parse(new Headers.Builder()
.set("Cache-Control", header)
.build());
assertTrue(cacheControl.noCache());
assertTrue(cacheControl.noStore());
assertEquals(1, cacheControl.maxAgeSeconds());
assertEquals(2, cacheControl.sMaxAgeSeconds());
assertTrue(cacheControl.isPrivate());
assertTrue(cacheControl.isPublic());
assertTrue(cacheControl.mustRevalidate());
assertEquals(3, cacheControl.maxStaleSeconds());
assertEquals(4, cacheControl.minFreshSeconds());
assertTrue(cacheControl.onlyIfCached());
assertTrue(cacheControl.noTransform());
assertEquals(header, cacheControl.toString());
assertThat(cacheControl.noCache()).isTrue();
assertThat(cacheControl.noStore()).isTrue();
assertThat(cacheControl.maxAgeSeconds()).isEqualTo(1);
assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(2);
assertThat(cacheControl.isPrivate()).isTrue();
assertThat(cacheControl.isPublic()).isTrue();
assertThat(cacheControl.mustRevalidate()).isTrue();
assertThat(cacheControl.maxStaleSeconds()).isEqualTo(3);
assertThat(cacheControl.minFreshSeconds()).isEqualTo(4);
assertThat(cacheControl.onlyIfCached()).isTrue();
assertThat(cacheControl.noTransform()).isTrue();
assertThat(cacheControl.toString()).isEqualTo(header);
}
@Test public void parseIgnoreCacheControlExtensions() throws Exception {
@ -113,26 +110,26 @@ public final class CacheControlTest {
CacheControl cacheControl = CacheControl.parse(new Headers.Builder()
.set("Cache-Control", header)
.build());
assertFalse(cacheControl.noCache());
assertFalse(cacheControl.noStore());
assertEquals(-1, cacheControl.maxAgeSeconds());
assertEquals(-1, cacheControl.sMaxAgeSeconds());
assertTrue(cacheControl.isPrivate());
assertFalse(cacheControl.isPublic());
assertFalse(cacheControl.mustRevalidate());
assertEquals(-1, cacheControl.maxStaleSeconds());
assertEquals(-1, cacheControl.minFreshSeconds());
assertFalse(cacheControl.onlyIfCached());
assertFalse(cacheControl.noTransform());
assertFalse(cacheControl.immutable());
assertEquals(header, cacheControl.toString());
assertThat(cacheControl.noCache()).isFalse();
assertThat(cacheControl.noStore()).isFalse();
assertThat(cacheControl.maxAgeSeconds()).isEqualTo(-1);
assertThat(cacheControl.sMaxAgeSeconds()).isEqualTo(-1);
assertThat(cacheControl.isPrivate()).isTrue();
assertThat(cacheControl.isPublic()).isFalse();
assertThat(cacheControl.mustRevalidate()).isFalse();
assertThat(cacheControl.maxStaleSeconds()).isEqualTo(-1);
assertThat(cacheControl.minFreshSeconds()).isEqualTo(-1);
assertThat(cacheControl.onlyIfCached()).isFalse();
assertThat(cacheControl.noTransform()).isFalse();
assertThat(cacheControl.immutable()).isFalse();
assertThat(cacheControl.toString()).isEqualTo(header);
}
@Test public void parseCacheControlAndPragmaAreCombined() {
Headers headers =
Headers.of("Cache-Control", "max-age=12", "Pragma", "must-revalidate", "Pragma", "public");
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.
@ -140,43 +137,43 @@ public final class CacheControlTest {
String value = new String("max-age=12");
Headers headers = Headers.of("Cache-Control", value);
CacheControl cacheControl = CacheControl.parse(headers);
assertSame(value, cacheControl.toString());
assertThat(cacheControl.toString()).isSameAs(value);
}
@Test public void parseCacheControlHeaderValueInvalidatedByPragma() {
Headers headers = Headers.of("Cache-Control", "max-age=12", "Pragma", "must-revalidate");
CacheControl cacheControl = CacheControl.parse(headers);
assertNull(cacheControl.headerValue);
assertThat(cacheControl.headerValue).isNull();
}
@Test public void parseCacheControlHeaderValueInvalidatedByTwoValues() {
Headers headers = Headers.of("Cache-Control", "max-age=12", "Cache-Control", "must-revalidate");
CacheControl cacheControl = CacheControl.parse(headers);
assertNull(cacheControl.headerValue);
assertThat(cacheControl.headerValue).isNull();
}
@Test public void parsePragmaHeaderValueIsNotRetained() {
Headers headers = Headers.of("Pragma", "must-revalidate");
CacheControl cacheControl = CacheControl.parse(headers);
assertNull(cacheControl.headerValue);
assertThat(cacheControl.headerValue).isNull();
}
@Test public void computedHeaderValueIsCached() {
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(2, TimeUnit.DAYS)
.build();
assertNull(cacheControl.headerValue);
assertEquals("max-age=172800", cacheControl.toString());
assertEquals("max-age=172800", cacheControl.headerValue);
assertThat(cacheControl.headerValue).isNull();
assertThat(cacheControl.toString()).isEqualTo("max-age=172800");
assertThat(cacheControl.headerValue).isEqualTo("max-age=172800");
cacheControl.headerValue = "Hi";
assertEquals("Hi", cacheControl.toString());
assertThat(cacheControl.toString()).isEqualTo("Hi");
}
@Test public void timeDurationTruncatedToMaxValue() throws Exception {
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(365 * 100, TimeUnit.DAYS) // Longer than Integer.MAX_VALUE seconds.
.build();
assertEquals(Integer.MAX_VALUE, cacheControl.maxAgeSeconds());
assertThat(cacheControl.maxAgeSeconds()).isEqualTo(Integer.MAX_VALUE);
}
@Test public void secondsMustBeNonNegative() throws Exception {
@ -192,6 +189,6 @@ public final class CacheControlTest {
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(4999, TimeUnit.MILLISECONDS)
.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 org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class CertificateChainCleanerTest {
@ -37,16 +37,14 @@ public final class CertificateChainCleanerTest {
HeldCertificate rootB = new HeldCertificate.Builder()
.serialNumber(2L)
.build();
assertEquals(
CertificateChainCleaner.get(rootA.certificate(), rootB.certificate()),
CertificateChainCleaner.get(rootB.certificate(), rootA.certificate()));
assertThat(CertificateChainCleaner.get(rootB.certificate(), rootA.certificate())).isEqualTo(
CertificateChainCleaner.get(rootA.certificate(), rootB.certificate()));
}
@Test public void equalsFromTrustManager() {
HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder().build();
X509TrustManager x509TrustManager = handshakeCertificates.trustManager();
assertEquals(
CertificateChainCleaner.get(x509TrustManager),
assertThat(CertificateChainCleaner.get(x509TrustManager)).isEqualTo(
CertificateChainCleaner.get(x509TrustManager));
}
@ -55,7 +53,7 @@ public final class CertificateChainCleanerTest {
.serialNumber(1L)
.build();
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() {
@ -85,7 +83,8 @@ public final class CertificateChainCleanerTest {
.build();
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 {
@ -102,8 +101,9 @@ public final class CertificateChainCleanerTest {
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(certB, certA, root),
cleaner.clean(list(certB, certA), "hostname")); // Root is added!
// Root is added!
assertThat(cleaner.clean(list(certB, certA), "hostname")).isEqualTo(
list(certB, certA, root));
}
@Test public void unorderedChainOfCertificatesWithRoot() throws Exception {
@ -124,8 +124,8 @@ public final class CertificateChainCleanerTest {
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(certC, certB, certA, root),
cleaner.clean(list(certC, certA, root, certB), "hostname"));
assertThat(cleaner.clean(list(certC, certA, root, certB), "hostname")).isEqualTo(
list(certC, certB, certA, root));
}
@Test public void unorderedChainOfCertificatesWithoutRoot() throws Exception {
@ -146,8 +146,8 @@ public final class CertificateChainCleanerTest {
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(certC, certB, certA, root),
cleaner.clean(list(certC, certA, certB), "hostname"));
assertThat(cleaner.clean(list(certC, certA, certB), "hostname")).isEqualTo(
list(certC, certB, certA, root));
}
@Test public void unrelatedCertificatesAreOmitted() throws Exception {
@ -167,8 +167,8 @@ public final class CertificateChainCleanerTest {
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate());
assertEquals(list(certB, certA, root),
cleaner.clean(list(certB, certUnnecessary, certA, root), "hostname"));
assertThat(cleaner.clean(list(certB, certUnnecessary, certA, root), "hostname")).isEqualTo(
list(certB, certA, root));
}
@Test public void chainGoesAllTheWayToSelfSignedRoot() throws Exception {
@ -190,12 +190,12 @@ public final class CertificateChainCleanerTest {
CertificateChainCleaner cleaner = CertificateChainCleaner.get(
selfSigned.certificate(), trusted.certificate());
assertEquals(list(certB, certA, trusted, selfSigned),
cleaner.clean(list(certB, certA), "hostname"));
assertEquals(list(certB, certA, trusted, selfSigned),
cleaner.clean(list(certB, certA, trusted), "hostname"));
assertEquals(list(certB, certA, trusted, selfSigned),
cleaner.clean(list(certB, certA, trusted, selfSigned), "hostname"));
assertThat(cleaner.clean(list(certB, certA), "hostname")).isEqualTo(
list(certB, certA, trusted, selfSigned));
assertThat(cleaner.clean(list(certB, certA, trusted), "hostname")).isEqualTo(
list(certB, certA, trusted, selfSigned));
assertThat(cleaner.clean(list(certB, certA, trusted, selfSigned), "hostname")).isEqualTo(
list(certB, certA, trusted, selfSigned));
}
@Test public void trustedRootNotSelfSigned() throws Exception {
@ -216,10 +216,10 @@ public final class CertificateChainCleanerTest {
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(trusted.certificate());
assertEquals(list(certificate, intermediateCa, trusted),
cleaner.clean(list(certificate, intermediateCa), "hostname"));
assertEquals(list(certificate, intermediateCa, trusted),
cleaner.clean(list(certificate, intermediateCa, trusted), "hostname"));
assertThat(cleaner.clean(list(certificate, intermediateCa), "hostname")).isEqualTo(
list(certificate, intermediateCa, trusted));
assertThat(cleaner.clean(list(certificate, intermediateCa, trusted), "hostname")).isEqualTo(
list(certificate, intermediateCa, trusted));
}
@Test public void chainMaxLength() throws Exception {
@ -231,8 +231,9 @@ public final class CertificateChainCleanerTest {
X509Certificate root = heldCertificates.get(heldCertificates.size() - 1).certificate();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root);
assertEquals(certificates, cleaner.clean(certificates, "hostname"));
assertEquals(certificates, cleaner.clean(certificates.subList(0, 9), "hostname"));
assertThat(cleaner.clean(certificates, "hostname")).isEqualTo(certificates);
assertThat(cleaner.clean(certificates.subList(0, 9), "hostname")).isEqualTo(
certificates);
}
@Test public void chainTooLong() {

View File

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

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_WITH_AES_128_CBC_SHA256;
import static okhttp3.CipherSuite.forJavaName;
import static org.assertj.core.api.Assertions.assertThat;
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;
public class CipherSuiteTest {
@ -38,18 +36,20 @@ public class CipherSuiteTest {
@Test public void hashCode_usesIdentityHashCode_legacyCase() {
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() {
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() {
assertSame(forJavaName("TestCipherSuite"), forJavaName("TestCipherSuite"));
assertSame(TLS_KRB5_WITH_DES_CBC_MD5,
forJavaName(TLS_KRB5_WITH_DES_CBC_MD5.javaName()));
assertThat(forJavaName("TestCipherSuite")).isSameAs(forJavaName("TestCipherSuite"));
assertThat(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...
CipherSuite cs = forJavaName(new String("FakeCipherSuite_instancesAreInterned"));
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() {
assertEquals(forJavaName("cipher"), forJavaName("cipher"));
assertNotEquals(forJavaName("cipherA"), forJavaName("cipherB"));
assertEquals(forJavaName("SSL_RSA_EXPORT_WITH_RC4_40_MD5"), TLS_RSA_EXPORT_WITH_RC4_40_MD5);
assertNotEquals(TLS_RSA_EXPORT_WITH_RC4_40_MD5, TLS_RSA_WITH_AES_128_CBC_SHA256);
assertThat(forJavaName("cipher")).isEqualTo(forJavaName("cipher"));
assertThat(forJavaName("cipherB")).isNotEqualTo(forJavaName("cipherA"));
assertThat(TLS_RSA_EXPORT_WITH_RC4_40_MD5).isEqualTo(
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() {
@ -77,16 +79,18 @@ public class CipherSuiteTest {
}
@Test public void javaName_examples() {
assertEquals("SSL_RSA_EXPORT_WITH_RC4_40_MD5", TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName());
assertEquals("TLS_RSA_WITH_AES_128_CBC_SHA256", TLS_RSA_WITH_AES_128_CBC_SHA256.javaName());
assertEquals("TestCipherSuite", forJavaName("TestCipherSuite").javaName());
assertThat(TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName()).isEqualTo(
"SSL_RSA_EXPORT_WITH_RC4_40_MD5");
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() {
assertEquals(TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName,
TLS_RSA_EXPORT_WITH_RC4_40_MD5.toString());
assertEquals(TLS_RSA_WITH_AES_128_CBC_SHA256.javaName,
TLS_RSA_WITH_AES_128_CBC_SHA256.toString());
assertThat(TLS_RSA_EXPORT_WITH_RC4_40_MD5.toString()).isEqualTo(
TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName);
assertThat(TLS_RSA_WITH_AES_128_CBC_SHA256.toString()).isEqualTo(
TLS_RSA_WITH_AES_128_CBC_SHA256.javaName);
}
/**
@ -98,15 +102,12 @@ public class CipherSuiteTest {
*/
@Test public void forJavaName_fromLegacyEnumName() {
// These would have been considered equal in OkHttp 3.3.1, but now aren't.
assertEquals(
forJavaName("TLS_RSA_EXPORT_WITH_RC4_40_MD5"),
forJavaName("SSL_RSA_EXPORT_WITH_RC4_40_MD5"));
assertEquals(
forJavaName("TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"),
forJavaName("SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"));
assertEquals(
forJavaName("TLS_FAKE_NEW_CIPHER"),
forJavaName("SSL_FAKE_NEW_CIPHER"));
assertThat(forJavaName("SSL_RSA_EXPORT_WITH_RC4_40_MD5")).isEqualTo(
forJavaName("TLS_RSA_EXPORT_WITH_RC4_40_MD5"));
assertThat(forJavaName("SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA")).isEqualTo(
forJavaName("TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"));
assertThat(forJavaName("SSL_FAKE_NEW_CIPHER")).isEqualTo(
forJavaName("TLS_FAKE_NEW_CIPHER"));
}
@Test public void applyIntersectionRetainsSslPrefixes() throws Exception {

View File

@ -34,7 +34,7 @@ import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class ConnectionCoalescingTest {
@ -104,7 +104,7 @@ public final class ConnectionCoalescingTest {
HttpUrl sanUrl = url.newBuilder().host("san.com").build();
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());
assertEquals(1, client.connectionPool().connectionCount());
assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
}
/** 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();
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. */
@ -193,7 +193,7 @@ public final class ConnectionCoalescingTest {
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. */
@ -233,7 +233,7 @@ public final class ConnectionCoalescingTest {
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)));
assert200Http2Response(execute(sanUrl), "san.com");
assertEquals(1, client.connectionPool().connectionCount());
assertEquals(1, connectCount.get());
assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
assertThat(connectCount.get()).isEqualTo(1);
}
/** Check that wildcard SANs are supported. */
@ -278,7 +278,7 @@ public final class ConnectionCoalescingTest {
HttpUrl sanUrl = url.newBuilder().host("www.wildcard.com").build();
assert200Http2Response(execute(sanUrl), "www.wildcard.com");
assertEquals(1, client.connectionPool().connectionCount());
assertThat(client.connectionPool().connectionCount()).isEqualTo(1);
}
/** Network interceptors check for changes to target. */
@ -295,7 +295,7 @@ public final class ConnectionCoalescingTest {
HttpUrl sanUrl = url.newBuilder().host("san.com").build();
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. */
@ -309,7 +309,7 @@ public final class ConnectionCoalescingTest {
assert200Http2Response(execute("https://messenger.com/robots.txt"), "messenger.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 {
@ -321,9 +321,9 @@ public final class ConnectionCoalescingTest {
}
private void assert200Http2Response(Response response, String expectedHost) {
assertEquals(200, response.code());
assertEquals(expectedHost, response.request().url().host());
assertEquals(Protocol.HTTP_2, response.protocol());
assertThat(response.code()).isEqualTo(200);
assertThat(response.request().url().host()).isEqualTo(expectedHost);
assertThat(response.protocol()).isEqualTo(Protocol.HTTP_2);
response.body().close();
}
}

View File

@ -31,7 +31,7 @@ import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
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;
public final class ConnectionReuseTest {
@ -132,9 +132,9 @@ public final class ConnectionReuseTest {
.url(server.url("/"))
.build();
Response response = client.newCall(request).execute();
assertEquals("b", response.body().string());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(1, server.takeRequest().getSequenceNumber());
assertThat(response.body().string()).isEqualTo("b");
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
@Test public void connectionsNotReusedWithRedirectIfDiscardingResponseIsSlow() throws Exception {
@ -152,9 +152,9 @@ public final class ConnectionReuseTest {
.url(server.url("/"))
.build();
Response response = client.newCall(request).execute();
assertEquals("b", response.body().string());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertThat(response.body().string()).isEqualTo("b");
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
}
@Test public void silentRetryWhenIdempotentRequestFailsOnReusedConnection() throws Exception {
@ -167,13 +167,13 @@ public final class ConnectionReuseTest {
.build();
Response responseA = client.newCall(request).execute();
assertEquals("a", responseA.body().string());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertThat(responseA.body().string()).isEqualTo("a");
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Response responseB = client.newCall(request).execute();
assertEquals("b", responseB.body().string());
assertEquals(1, server.takeRequest().getSequenceNumber());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertThat(responseB.body().string()).isEqualTo("b");
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
}
@Test public void staleConnectionNotReusedForNonIdempotentRequest() throws Exception {
@ -185,8 +185,8 @@ public final class ConnectionReuseTest {
.url(server.url("/"))
.build();
Response responseA = client.newCall(requestA).execute();
assertEquals("a", responseA.body().string());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertThat(responseA.body().string()).isEqualTo("a");
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Give the socket a chance to become stale.
Thread.sleep(250);
@ -196,8 +196,8 @@ public final class ConnectionReuseTest {
.post(RequestBody.create(MediaType.get("text/plain"), "b"))
.build();
Response responseB = client.newCall(requestB).execute();
assertEquals("b", responseB.body().string());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertThat(responseB.body().string()).isEqualTo("b");
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
}
@Test public void http2ConnectionsAreSharedBeforeResponseIsConsumed() throws Exception {
@ -212,8 +212,8 @@ public final class ConnectionReuseTest {
Response response2 = client.newCall(request).execute();
response1.body().string(); // Discard the response body.
response2.body().string(); // Discard the response body.
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(1, server.takeRequest().getSequenceNumber());
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
@Test public void connectionsAreEvicted() throws Exception {
@ -228,16 +228,16 @@ public final class ConnectionReuseTest {
.build();
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.
Thread.sleep(500);
Response response2 = client.newCall(request).execute();
assertEquals("b", response2.body().string());
assertThat(response2.body().string()).isEqualTo("b");
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
}
@Test public void connectionsAreNotReusedIfSslSocketFactoryChanges() throws Exception {
@ -287,8 +287,8 @@ public final class ConnectionReuseTest {
Response response2 = anotherClient.newCall(request).execute();
response2.body().close();
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
}
/**
@ -330,11 +330,12 @@ public final class ConnectionReuseTest {
.build();
Call call = client.newCall(request);
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());
assertEquals(0, server.takeRequest().getSequenceNumber()); // No connection reuse.
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// No connection reuse.
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
for (Response response : responsesNotClosed) {
Util.closeQuietly(response);
@ -364,7 +365,7 @@ public final class ConnectionReuseTest {
for (int i = 0; i < requests.length; i++) {
Response response = client.newCall(requests[i]).execute();
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) {
Response response = client.newCall(request).execute();
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 org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class ConnectionSpecTest {
@ -37,7 +34,7 @@ public final class ConnectionSpecTest {
.build();
fail();
} 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();
fail();
} 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 {
ConnectionSpec cleartextSpec = new ConnectionSpec.Builder(false).build();
assertFalse(cleartextSpec.isTls());
assertThat(cleartextSpec.isTls()).isFalse();
}
@Test public void tlsBuilder_explicitCiphers() throws Exception {
@ -63,9 +60,9 @@ public final class ConnectionSpecTest {
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(true)
.build();
assertEquals(Arrays.asList(CipherSuite.TLS_RSA_WITH_RC4_128_MD5), tlsSpec.cipherSuites());
assertEquals(Arrays.asList(TlsVersion.TLS_1_2), tlsSpec.tlsVersions());
assertTrue(tlsSpec.supportsTlsExtensions());
assertThat(tlsSpec.cipherSuites()).containsExactly(CipherSuite.TLS_RSA_WITH_RC4_128_MD5);
assertThat(tlsSpec.tlsVersions()).containsExactly(TlsVersion.TLS_1_2);
assertThat(tlsSpec.supportsTlsExtensions()).isTrue();
}
@Test public void tlsBuilder_defaultCiphers() throws Exception {
@ -73,9 +70,9 @@ public final class ConnectionSpecTest {
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(true)
.build();
assertNull(tlsSpec.cipherSuites());
assertEquals(Arrays.asList(TlsVersion.TLS_1_2), tlsSpec.tlsVersions());
assertTrue(tlsSpec.supportsTlsExtensions());
assertThat(tlsSpec.cipherSuites()).isNull();
assertThat(tlsSpec.tlsVersions()).containsExactly(TlsVersion.TLS_1_2);
assertThat(tlsSpec.supportsTlsExtensions()).isTrue();
}
@Test public void tls_defaultCiphers_noFallbackIndicator() throws Exception {
@ -94,16 +91,16 @@ public final class ConnectionSpecTest {
TlsVersion.TLS_1_1.javaName,
});
assertTrue(tlsSpec.isCompatible(socket));
assertThat(tlsSpec.isCompatible(socket)).isTrue();
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(
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName);
assertEquals(expectedCipherSet, expectedCipherSet);
assertThat(expectedCipherSet).isEqualTo(expectedCipherSet);
}
@Test public void tls_defaultCiphers_withFallbackIndicator() throws Exception {
@ -122,10 +119,10 @@ public final class ConnectionSpecTest {
TlsVersion.TLS_1_1.javaName,
});
assertTrue(tlsSpec.isCompatible(socket));
assertThat(tlsSpec.isCompatible(socket)).isTrue();
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(
@ -134,7 +131,7 @@ public final class ConnectionSpecTest {
if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) {
expectedCipherSet.add("TLS_FALLBACK_SCSV");
}
assertEquals(expectedCipherSet, expectedCipherSet);
assertThat(expectedCipherSet).isEqualTo(expectedCipherSet);
}
@Test public void tls_explicitCiphers() throws Exception {
@ -154,16 +151,16 @@ public final class ConnectionSpecTest {
TlsVersion.TLS_1_1.javaName,
});
assertTrue(tlsSpec.isCompatible(socket));
assertThat(tlsSpec.isCompatible(socket)).isTrue();
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);
if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) {
expectedCipherSet.add("TLS_FALLBACK_SCSV");
}
assertEquals(expectedCipherSet, expectedCipherSet);
assertThat(expectedCipherSet).isEqualTo(expectedCipherSet);
}
@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_MD5.javaName,
});
assertTrue(tlsSpec.isCompatible(socket));
assertThat(tlsSpec.isCompatible(socket)).isTrue();
socket.setEnabledCipherSuites(new String[] {
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName,
});
assertFalse(tlsSpec.isCompatible(socket));
assertThat(tlsSpec.isCompatible(socket)).isFalse();
}
@Test public void allEnabledCipherSuites() throws Exception {
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledCipherSuites()
.build();
assertNull(tlsSpec.cipherSuites());
assertThat(tlsSpec.cipherSuites()).isNull();
SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
sslSocket.setEnabledCipherSuites(new String[] {
@ -213,17 +210,16 @@ public final class ConnectionSpecTest {
});
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_MD5.javaName),
Arrays.asList(sslSocket.getEnabledCipherSuites()));
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName);
}
@Test public void allEnabledTlsVersions() throws Exception {
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledTlsVersions()
.build();
assertNull(tlsSpec.tlsVersions());
assertThat(tlsSpec.tlsVersions()).isNull();
SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
sslSocket.setEnabledProtocols(new String[] {
@ -232,8 +228,8 @@ public final class ConnectionSpecTest {
});
tlsSpec.apply(sslSocket, false);
assertEquals(Arrays.asList(TlsVersion.SSL_3_0.javaName(), TlsVersion.TLS_1_1.javaName()),
Arrays.asList(sslSocket.getEnabledProtocols()));
assertThat(Arrays.asList(sslSocket.getEnabledProtocols())).containsExactly(
TlsVersion.SSL_3_0.javaName(), TlsVersion.TLS_1_1.javaName());
}
@Test public void tls_missingTlsVersion() throws Exception {
@ -250,10 +246,10 @@ public final class ConnectionSpecTest {
socket.setEnabledProtocols(
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});
assertFalse(tlsSpec.isCompatible(socket));
assertThat(tlsSpec.isCompatible(socket)).isFalse();
}
@Test public void equalsAndHashCode() throws Exception {
@ -265,18 +261,18 @@ public final class ConnectionSpecTest {
.build();
Set<Object> set = new CopyOnWriteArraySet<>();
assertTrue(set.add(ConnectionSpec.MODERN_TLS));
assertTrue(set.add(ConnectionSpec.COMPATIBLE_TLS));
assertTrue(set.add(ConnectionSpec.CLEARTEXT));
assertTrue(set.add(allTlsVersions));
assertTrue(set.add(allCipherSuites));
assertThat(set.add(ConnectionSpec.MODERN_TLS)).isTrue();
assertThat(set.add(ConnectionSpec.COMPATIBLE_TLS)).isTrue();
assertThat(set.add(ConnectionSpec.CLEARTEXT)).isTrue();
assertThat(set.add(allTlsVersions)).isTrue();
assertThat(set.add(allCipherSuites)).isTrue();
assertTrue(set.remove(ConnectionSpec.MODERN_TLS));
assertTrue(set.remove(ConnectionSpec.COMPATIBLE_TLS));
assertTrue(set.remove(ConnectionSpec.CLEARTEXT));
assertTrue(set.remove(allTlsVersions));
assertTrue(set.remove(allCipherSuites));
assertTrue(set.isEmpty());
assertThat(set.remove(ConnectionSpec.MODERN_TLS)).isTrue();
assertThat(set.remove(ConnectionSpec.COMPATIBLE_TLS)).isTrue();
assertThat(set.remove(ConnectionSpec.CLEARTEXT)).isTrue();
assertThat(set.remove(allTlsVersions)).isTrue();
assertThat(set.remove(allCipherSuites)).isTrue();
assertThat(set.isEmpty()).isTrue();
}
@Test public void allEnabledToString() throws Exception {
@ -284,8 +280,9 @@ public final class ConnectionSpecTest {
.allEnabledTlsVersions()
.allEnabledCipherSuites()
.build();
assertEquals("ConnectionSpec(cipherSuites=[all enabled], tlsVersions=[all enabled], "
+ "supportsTlsExtensions=true)", connectionSpec.toString());
assertThat(connectionSpec.toString()).isEqualTo(
("ConnectionSpec(cipherSuites=[all enabled], tlsVersions=[all enabled], "
+ "supportsTlsExtensions=true)"));
}
@Test public void simpleToString() throws Exception {
@ -293,8 +290,9 @@ public final class ConnectionSpecTest {
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)
.build();
assertEquals("ConnectionSpec(cipherSuites=[SSL_RSA_WITH_RC4_128_MD5], tlsVersions=[TLS_1_2], "
+ "supportsTlsExtensions=true)", connectionSpec.toString());
assertThat(connectionSpec.toString()).isEqualTo(
("ConnectionSpec(cipherSuites=[SSL_RSA_WITH_RC4_128_MD5], tlsVersions=[TLS_1_2], "
+ "supportsTlsExtensions=true)"));
}
@SafeVarargs

View File

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

View File

@ -25,12 +25,7 @@ import okhttp3.internal.Util;
import okhttp3.internal.http.HttpDate;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
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.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class CookieTest {
@ -38,263 +33,264 @@ public final class CookieTest {
@Test public void simpleCookie() throws Exception {
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 {
assertNull(Cookie.parse(url, "foo"));
assertNull(Cookie.parse(url, "foo; Path=/"));
assertThat(Cookie.parse(url, "foo")).isNull();
assertThat(Cookie.parse(url, "foo; Path=/")).isNull();
}
@Test public void emptyName() throws Exception {
assertNull(Cookie.parse(url, "=b"));
assertNull(Cookie.parse(url, " =b"));
assertNull(Cookie.parse(url, "\r\t \n=b"));
assertThat(Cookie.parse(url, "=b")).isNull();
assertThat(Cookie.parse(url, " =b")).isNull();
assertThat(Cookie.parse(url, "\r\t \n=b")).isNull();
}
@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 {
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 {
assertEquals("a", Cookie.parse(url, " a=b").name());
assertEquals("a", Cookie.parse(url, "a =b").name());
assertEquals("a", Cookie.parse(url, "\r\t \na\n\t \n=b").name());
assertThat(Cookie.parse(url, " a=b").name()).isEqualTo("a");
assertThat(Cookie.parse(url, "a =b").name()).isEqualTo("a");
assertThat(Cookie.parse(url, "\r\t \na\n\t \n=b").name()).isEqualTo("a");
}
@Test public void emptyValue() throws Exception {
assertEquals("", Cookie.parse(url, "a=").value());
assertEquals("", Cookie.parse(url, "a= ").value());
assertEquals("", Cookie.parse(url, "a=\r\t \n").value());
assertThat(Cookie.parse(url, "a=").value()).isEqualTo("");
assertThat(Cookie.parse(url, "a= ").value()).isEqualTo("");
assertThat(Cookie.parse(url, "a=\r\t \n").value()).isEqualTo("");
}
@Test public void trimLeadingAndTrailingWhitespaceFromValue() throws Exception {
assertEquals("", Cookie.parse(url, "a= ").value());
assertEquals("b", Cookie.parse(url, "a= b").value());
assertEquals("b", Cookie.parse(url, "a=b ").value());
assertEquals("b", Cookie.parse(url, "a=\r\t \nb\n\t \n").value());
assertThat(Cookie.parse(url, "a= ").value()).isEqualTo("");
assertThat(Cookie.parse(url, "a= b").value()).isEqualTo("b");
assertThat(Cookie.parse(url, "a=b ").value()).isEqualTo("b");
assertThat(Cookie.parse(url, "a=\r\t \nb\n\t \n").value()).isEqualTo("b");
}
@Test public void invalidCharacters() throws Exception {
assertNull(Cookie.parse(url, "a\u0000b=cd"));
assertNull(Cookie.parse(url, "ab=c\u0000d"));
assertNull(Cookie.parse(url, "a\u0001b=cd"));
assertNull(Cookie.parse(url, "ab=c\u0001d"));
assertNull(Cookie.parse(url, "a\u0009b=cd"));
assertNull(Cookie.parse(url, "ab=c\u0009d"));
assertNull(Cookie.parse(url, "a\u001fb=cd"));
assertNull(Cookie.parse(url, "ab=c\u001fd"));
assertNull(Cookie.parse(url, "a\u007fb=cd"));
assertNull(Cookie.parse(url, "ab=c\u007fd"));
assertNull(Cookie.parse(url, "a\u0080b=cd"));
assertNull(Cookie.parse(url, "ab=c\u0080d"));
assertNull(Cookie.parse(url, "a\u00ffb=cd"));
assertNull(Cookie.parse(url, "ab=c\u00ffd"));
assertThat(Cookie.parse(url, "a\u0000b=cd")).isNull();
assertThat(Cookie.parse(url, "ab=c\u0000d")).isNull();
assertThat(Cookie.parse(url, "a\u0001b=cd")).isNull();
assertThat(Cookie.parse(url, "ab=c\u0001d")).isNull();
assertThat(Cookie.parse(url, "a\u0009b=cd")).isNull();
assertThat(Cookie.parse(url, "ab=c\u0009d")).isNull();
assertThat(Cookie.parse(url, "a\u001fb=cd")).isNull();
assertThat(Cookie.parse(url, "ab=c\u001fd")).isNull();
assertThat(Cookie.parse(url, "a\u007fb=cd")).isNull();
assertThat(Cookie.parse(url, "ab=c\u007fd")).isNull();
assertThat(Cookie.parse(url, "a\u0080b=cd")).isNull();
assertThat(Cookie.parse(url, "ab=c\u0080d")).isNull();
assertThat(Cookie.parse(url, "a\u00ffb=cd")).isNull();
assertThat(Cookie.parse(url, "ab=c\u00ffd")).isNull();
}
@Test public void maxAge() throws Exception {
assertEquals(51000L,
Cookie.parse(50000L, url, "a=b; Max-Age=1").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854724").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854725").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854726").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=1").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=2").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=3").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(50000L, url, "a=b; Max-Age=10000000000000000000").expiresAt());
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=1").expiresAt()).isEqualTo(51000L);
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854724").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854725").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=9223372036854726").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=1").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=2").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(9223372036854773807L, url, "a=b; Max-Age=3").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=10000000000000000000").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
}
@Test public void maxAgeNonPositive() throws Exception {
assertEquals(Long.MIN_VALUE,
Cookie.parse(50000L, url, "a=b; Max-Age=-1").expiresAt());
assertEquals(Long.MIN_VALUE,
Cookie.parse(50000L, url, "a=b; Max-Age=0").expiresAt());
assertEquals(Long.MIN_VALUE,
Cookie.parse(50000L, url, "a=b; Max-Age=-9223372036854775808").expiresAt());
assertEquals(Long.MIN_VALUE,
Cookie.parse(50000L, url, "a=b; Max-Age=-9223372036854775809").expiresAt());
assertEquals(Long.MIN_VALUE,
Cookie.parse(50000L, url, "a=b; Max-Age=-10000000000000000000").expiresAt());
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=-1").expiresAt()).isEqualTo(Long.MIN_VALUE);
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=0").expiresAt()).isEqualTo(Long.MIN_VALUE);
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=-9223372036854775808").expiresAt()).isEqualTo(
Long.MIN_VALUE);
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=-9223372036854775809").expiresAt()).isEqualTo(
Long.MIN_VALUE);
assertThat(Cookie.parse(50000L, url, "a=b; Max-Age=-10000000000000000000").expiresAt()).isEqualTo(
Long.MIN_VALUE);
}
@Test public void domainAndPath() throws Exception {
Cookie cookie = Cookie.parse(url, "SID=31d4d96e407aad42; Path=/; Domain=example.com");
assertEquals("example.com", cookie.domain());
assertEquals("/", cookie.path());
assertFalse(cookie.hostOnly());
assertEquals("SID=31d4d96e407aad42; domain=example.com; path=/", cookie.toString());
assertThat(cookie.domain()).isEqualTo("example.com");
assertThat(cookie.path()).isEqualTo("/");
assertThat(cookie.hostOnly()).isFalse();
assertThat(cookie.toString()).isEqualTo(
"SID=31d4d96e407aad42; domain=example.com; path=/");
}
@Test public void secureAndHttpOnly() throws Exception {
Cookie cookie = Cookie.parse(url, "SID=31d4d96e407aad42; Path=/; Secure; HttpOnly");
assertTrue(cookie.secure());
assertTrue(cookie.httpOnly());
assertEquals("SID=31d4d96e407aad42; path=/; secure; httponly", cookie.toString());
assertThat(cookie.secure()).isTrue();
assertThat(cookie.httpOnly()).isTrue();
assertThat(cookie.toString()).isEqualTo(
"SID=31d4d96e407aad42; path=/; secure; httponly");
}
@Test public void expiresDate() throws Exception {
assertEquals(date("1970-01-01T00:00:00.000+0000"), new Date(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:00 GMT").expiresAt()));
assertEquals(date("2021-06-09T10:18:14.000+0000"), new Date(
Cookie.parse(url, "a=b; Expires=Wed, 09 Jun 2021 10:18:14 GMT").expiresAt()));
assertEquals(date("1994-11-06T08:49:37.000+0000"), new Date(
Cookie.parse(url, "a=b; Expires=Sun, 06 Nov 1994 08:49:37 GMT").expiresAt()));
assertThat(new Date(
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:00 GMT").expiresAt())).isEqualTo(
date("1970-01-01T00:00:00.000+0000"));
assertThat(new Date(
Cookie.parse(url, "a=b; Expires=Wed, 09 Jun 2021 10:18:14 GMT").expiresAt())).isEqualTo(
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 {
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 70 00:00:00 GMT").expiresAt());
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=Thu, 01 January 1970 00:00:00 GMT").expiresAt());
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=Thu, 01 Janucember 1970 00:00:00 GMT").expiresAt());
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=Thu, 1 Jan 1970 00:00:00 GMT").expiresAt());
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 0:00:00 GMT").expiresAt());
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:0:00 GMT").expiresAt());
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:0 GMT").expiresAt());
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=00:00:00 Thu, 01 Jan 1970 GMT").expiresAt());
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=00:00:00 1970 Jan 01").expiresAt());
assertEquals(0L,
Cookie.parse(url, "a=b; Expires=00:00:00 1970 Jan 1").expiresAt());
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 70 00:00:00 GMT").expiresAt()).isEqualTo(
0L);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 January 1970 00:00:00 GMT").expiresAt()).isEqualTo(
0L);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Janucember 1970 00:00:00 GMT").expiresAt()).isEqualTo(
0L);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 1 Jan 1970 00:00:00 GMT").expiresAt()).isEqualTo(
0L);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 0:00:00 GMT").expiresAt()).isEqualTo(
0L);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:0:00 GMT").expiresAt()).isEqualTo(
0L);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:0 GMT").expiresAt()).isEqualTo(
0L);
assertThat(Cookie.parse(url, "a=b; Expires=00:00:00 Thu, 01 Jan 1970 GMT").expiresAt()).isEqualTo(
0L);
assertThat(Cookie.parse(url, "a=b; Expires=00:00:00 1970 Jan 01").expiresAt()).isEqualTo(0L);
assertThat(Cookie.parse(url, "a=b; Expires=00:00:00 1970 Jan 1").expiresAt()).isEqualTo(0L);
}
@Test public void invalidYear() throws Exception {
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1600 00:00:00 GMT").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 19999 00:00:00 GMT").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 00:00:00 GMT").expiresAt());
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1600 00:00:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 19999 00:00:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 00:00:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
}
@Test public void invalidMonth() throws Exception {
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 01 Foo 1970 00:00:00 GMT").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 01 Foocember 1970 00:00:00 GMT").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 01 1970 00:00:00 GMT").expiresAt());
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Foo 1970 00:00:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Foocember 1970 00:00:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 1970 00:00:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
}
@Test public void invalidDayOfMonth() throws Exception {
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 32 Jan 1970 00:00:00 GMT").expiresAt());
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, Jan 1970 00:00:00 GMT").expiresAt());
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 32 Jan 1970 00:00:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
assertThat(Cookie.parse(url, "a=b; Expires=Thu, Jan 1970 00:00:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
}
@Test public void invalidHour() throws Exception {
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 24:00:00 GMT").expiresAt());
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 24:00:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
}
@Test public void invalidMinute() throws Exception {
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:60:00 GMT").expiresAt());
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:60:00 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
}
@Test public void invalidSecond() throws Exception {
assertEquals(HttpDate.MAX_DATE,
Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:60 GMT").expiresAt());
assertThat(Cookie.parse(url, "a=b; Expires=Thu, 01 Jan 1970 00:00:60 GMT").expiresAt()).isEqualTo(
HttpDate.MAX_DATE);
}
@Test public void domainMatches() throws Exception {
Cookie cookie = Cookie.parse(url, "a=b; domain=example.com");
assertTrue(cookie.matches(HttpUrl.get("http://example.com")));
assertTrue(cookie.matches(HttpUrl.get("http://www.example.com")));
assertFalse(cookie.matches(HttpUrl.get("http://square.com")));
assertThat(cookie.matches(HttpUrl.get("http://example.com"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://www.example.com"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://square.com"))).isFalse();
}
/** If no domain is present, match only the origin domain. */
@Test public void domainMatchesNoDomain() throws Exception {
Cookie cookie = Cookie.parse(url, "a=b");
assertTrue(cookie.matches(HttpUrl.get("http://example.com")));
assertFalse(cookie.matches(HttpUrl.get("http://www.example.com")));
assertFalse(cookie.matches(HttpUrl.get("http://square.com")));
assertThat(cookie.matches(HttpUrl.get("http://example.com"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://www.example.com"))).isFalse();
assertThat(cookie.matches(HttpUrl.get("http://square.com"))).isFalse();
}
/** Ignore an optional leading `.` in the domain. */
@Test public void domainMatchesIgnoresLeadingDot() throws Exception {
Cookie cookie = Cookie.parse(url, "a=b; domain=.example.com");
assertTrue(cookie.matches(HttpUrl.get("http://example.com")));
assertTrue(cookie.matches(HttpUrl.get("http://www.example.com")));
assertFalse(cookie.matches(HttpUrl.get("http://square.com")));
assertThat(cookie.matches(HttpUrl.get("http://example.com"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://www.example.com"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://square.com"))).isFalse();
}
/** Ignore the entire attribute if the domain ends with `.`. */
@Test public void domainIgnoredWithTrailingDot() throws Exception {
Cookie cookie = Cookie.parse(url, "a=b; domain=example.com.");
assertTrue(cookie.matches(HttpUrl.get("http://example.com")));
assertFalse(cookie.matches(HttpUrl.get("http://www.example.com")));
assertFalse(cookie.matches(HttpUrl.get("http://square.com")));
assertThat(cookie.matches(HttpUrl.get("http://example.com"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://www.example.com"))).isFalse();
assertThat(cookie.matches(HttpUrl.get("http://square.com"))).isFalse();
}
@Test public void idnDomainMatches() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://☃.net/"), "a=b; domain=☃.net");
assertTrue(cookie.matches(HttpUrl.get("http://☃.net/")));
assertTrue(cookie.matches(HttpUrl.get("http://xn--n3h.net/")));
assertTrue(cookie.matches(HttpUrl.get("http://www.☃.net/")));
assertTrue(cookie.matches(HttpUrl.get("http://www.xn--n3h.net/")));
assertThat(cookie.matches(HttpUrl.get("http://☃.net/"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://xn--n3h.net/"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://www.☃.net/"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://www.xn--n3h.net/"))).isTrue();
}
@Test public void punycodeDomainMatches() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://xn--n3h.net/"), "a=b; domain=xn--n3h.net");
assertTrue(cookie.matches(HttpUrl.get("http://☃.net/")));
assertTrue(cookie.matches(HttpUrl.get("http://xn--n3h.net/")));
assertTrue(cookie.matches(HttpUrl.get("http://www.☃.net/")));
assertTrue(cookie.matches(HttpUrl.get("http://www.xn--n3h.net/")));
assertThat(cookie.matches(HttpUrl.get("http://☃.net/"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://xn--n3h.net/"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://www.☃.net/"))).isTrue();
assertThat(cookie.matches(HttpUrl.get("http://www.xn--n3h.net/"))).isTrue();
}
@Test public void domainMatchesIpAddress() throws Exception {
HttpUrl urlWithIp = HttpUrl.get("http://123.45.234.56/");
assertNull(Cookie.parse(urlWithIp, "a=b; domain=234.56"));
assertEquals("123.45.234.56", Cookie.parse(urlWithIp, "a=b; domain=123.45.234.56").domain());
assertThat(Cookie.parse(urlWithIp, "a=b; domain=234.56")).isNull();
assertThat(Cookie.parse(urlWithIp, "a=b; domain=123.45.234.56").domain()).isEqualTo(
"123.45.234.56");
}
@Test public void domainMatchesIpv6Address() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://[::1]/"), "a=b; domain=::1");
assertEquals("::1", cookie.domain());
assertTrue(cookie.matches(HttpUrl.get("http://[::1]/")));
assertThat(cookie.domain()).isEqualTo("::1");
assertThat(cookie.matches(HttpUrl.get("http://[::1]/"))).isTrue();
}
@Test public void domainMatchesIpv6AddressWithCompression() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://[0001:0000::]/"), "a=b; domain=0001:0000::");
assertEquals("1::", cookie.domain());
assertTrue(cookie.matches(HttpUrl.get("http://[1::]/")));
assertThat(cookie.domain()).isEqualTo("1::");
assertThat(cookie.matches(HttpUrl.get("http://[1::]/"))).isTrue();
}
@Test public void domainMatchesIpv6AddressWithIpv4Suffix() throws Exception {
Cookie cookie = Cookie.parse(
HttpUrl.get("http://[::1:ffff:ffff]/"), "a=b; domain=::1:255.255.255.255");
assertEquals("::1:ffff:ffff", cookie.domain());
assertTrue(cookie.matches(HttpUrl.get("http://[::1:ffff:ffff]/")));
assertThat(cookie.domain()).isEqualTo("::1:ffff:ffff");
assertThat(cookie.matches(HttpUrl.get("http://[::1:ffff:ffff]/"))).isTrue();
}
@Test public void ipv6AddressDoesntMatch() throws Exception {
Cookie cookie = Cookie.parse(HttpUrl.get("http://[::1]/"), "a=b; domain=::2");
assertNull(cookie);
assertThat(cookie).isNull();
}
@Test public void ipv6AddressMalformed() throws Exception {
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() {
HttpUrl ascii = HttpUrl.get("https://foo1.foo.bar.elb.amazonaws.com");
assertNotNull(Cookie.parse(ascii, "a=b; domain=foo.bar.elb.amazonaws.com"));
assertNull(Cookie.parse(ascii, "a=b; domain=bar.elb.amazonaws.com"));
assertNull(Cookie.parse(ascii, "a=b; domain=com"));
assertThat(Cookie.parse(ascii, "a=b; domain=foo.bar.elb.amazonaws.com")).isNotNull();
assertThat(Cookie.parse(ascii, "a=b; domain=bar.elb.amazonaws.com")).isNull();
assertThat(Cookie.parse(ascii, "a=b; domain=com")).isNull();
HttpUrl unicode = HttpUrl.get("https://長.長.長崎.jp");
assertNotNull(Cookie.parse(unicode, "a=b; domain=長.長崎.jp"));
assertNull(Cookie.parse(unicode, "a=b; domain=長崎.jp"));
assertThat(Cookie.parse(unicode, "a=b; domain=長.長崎.jp")).isNotNull();
assertThat(Cookie.parse(unicode, "a=b; domain=長崎.jp")).isNull();
HttpUrl punycode = HttpUrl.get("https://xn--ue5a.xn--ue5a.xn--8ltr62k.jp");
assertNotNull(Cookie.parse(punycode, "a=b; domain=xn--ue5a.xn--8ltr62k.jp"));
assertNull(Cookie.parse(punycode, "a=b; domain=xn--8ltr62k.jp"));
assertThat(Cookie.parse(punycode, "a=b; domain=xn--ue5a.xn--8ltr62k.jp")).isNotNull();
assertThat(Cookie.parse(punycode, "a=b; domain=xn--8ltr62k.jp")).isNull();
}
@Test public void hostOnly() throws Exception {
assertTrue(Cookie.parse(url, "a=b").hostOnly());
assertFalse(Cookie.parse(url, "a=b; domain=example.com").hostOnly());
assertThat(Cookie.parse(url, "a=b").hostOnly()).isTrue();
assertThat(Cookie.parse(url, "a=b; domain=example.com").hostOnly()).isFalse();
}
@Test public void defaultPath() throws Exception {
assertEquals("/foo", Cookie.parse(HttpUrl.get("http://example.com/foo/bar"), "a=b").path());
assertEquals("/foo", Cookie.parse(HttpUrl.get("http://example.com/foo/"), "a=b").path());
assertEquals("/", Cookie.parse(HttpUrl.get("http://example.com/foo"), "a=b").path());
assertEquals("/", Cookie.parse(HttpUrl.get("http://example.com/"), "a=b").path());
assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/bar"), "a=b").path()).isEqualTo(
"/foo");
assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/"), "a=b").path()).isEqualTo(
"/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 {
assertEquals("/foo", Cookie.parse(HttpUrl.get("http://example.com/foo/bar"),
"a=b; path=quux").path());
assertEquals("/foo", Cookie.parse(HttpUrl.get("http://example.com/foo/bar"),
"a=b; path=").path());
assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/bar"),
"a=b; path=quux").path()).isEqualTo("/foo");
assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/bar"),
"a=b; path=").path()).isEqualTo("/foo");
}
@Test public void pathAttributeDoesntNeedToMatch() throws Exception {
assertEquals("/quux", Cookie.parse(HttpUrl.get("http://example.com/"),
"a=b; path=/quux").path());
assertEquals("/quux", Cookie.parse(HttpUrl.get("http://example.com/foo/bar"),
"a=b; path=/quux").path());
assertThat(Cookie.parse(HttpUrl.get("http://example.com/"),
"a=b; path=/quux").path()).isEqualTo("/quux");
assertThat(Cookie.parse(HttpUrl.get("http://example.com/foo/bar"),
"a=b; path=/quux").path()).isEqualTo("/quux");
}
@Test public void httpOnly() throws Exception {
assertFalse(Cookie.parse(url, "a=b").httpOnly());
assertTrue(Cookie.parse(url, "a=b; HttpOnly").httpOnly());
assertThat(Cookie.parse(url, "a=b").httpOnly()).isFalse();
assertThat(Cookie.parse(url, "a=b; HttpOnly").httpOnly()).isTrue();
}
@Test public void secure() throws Exception {
assertFalse(Cookie.parse(url, "a=b").secure());
assertTrue(Cookie.parse(url, "a=b; Secure").secure());
assertThat(Cookie.parse(url, "a=b").secure()).isFalse();
assertThat(Cookie.parse(url, "a=b; Secure").secure()).isTrue();
}
@Test public void maxAgeTakesPrecedenceOverExpires() throws Exception {
// Max-Age = 1, Expires = 2. In either order.
assertEquals(1000L, Cookie.parse(
0L, url, "a=b; Max-Age=1; Expires=Thu, 01 Jan 1970 00:00:02 GMT").expiresAt());
assertEquals(1000L, Cookie.parse(
0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:02 GMT; Max-Age=1").expiresAt());
assertThat(Cookie.parse(
0L, url, "a=b; Max-Age=1; Expires=Thu, 01 Jan 1970 00:00:02 GMT").expiresAt()).isEqualTo(
1000L);
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.
assertEquals(2000L, Cookie.parse(
0L, url, "a=b; Max-Age=2; Expires=Thu, 01 Jan 1970 00:00:01 GMT").expiresAt());
assertEquals(2000L, Cookie.parse(
0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=2").expiresAt());
assertThat(Cookie.parse(
0L, url, "a=b; Max-Age=2; Expires=Thu, 01 Jan 1970 00:00:01 GMT").expiresAt()).isEqualTo(
2000L);
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. */
@Test public void lastMaxAgeWins() throws Exception {
assertEquals(3000L, Cookie.parse(
0L, url, "a=b; Max-Age=2; Max-Age=4; Max-Age=1; Max-Age=3").expiresAt());
assertThat(Cookie.parse(
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. */
@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:04 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 {
assertFalse(Cookie.parse(0L, url, "a=b").persistent());
assertTrue(Cookie.parse(0L, url, "a=b; Max-Age=1").persistent());
assertTrue(Cookie.parse(0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT").persistent());
assertThat(Cookie.parse(0L, url, "a=b").persistent()).isFalse();
assertThat(Cookie.parse(0L, url, "a=b; Max-Age=1").persistent()).isTrue();
assertThat(Cookie.parse(0L, url, "a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT").persistent()).isTrue();
}
@Test public void parseAll() throws Exception {
@ -393,9 +397,9 @@ public final class CookieTest {
.add("Set-Cookie: c=d")
.build();
List<Cookie> cookies = Cookie.parseAll(url, headers);
assertEquals(2, cookies.size());
assertEquals("a=b; path=/", cookies.get(0).toString());
assertEquals("c=d; path=/", cookies.get(1).toString());
assertThat(cookies.size()).isEqualTo(2);
assertThat(cookies.get(0).toString()).isEqualTo("a=b; path=/");
assertThat(cookies.get(1).toString()).isEqualTo("c=d; path=/");
}
@Test public void builder() throws Exception {
@ -404,15 +408,15 @@ public final class CookieTest {
.value("b")
.domain("example.com")
.build();
assertEquals("a", cookie.name());
assertEquals("b", cookie.value());
assertEquals(HttpDate.MAX_DATE, cookie.expiresAt());
assertEquals("example.com", cookie.domain());
assertEquals("/", cookie.path());
assertFalse(cookie.secure());
assertFalse(cookie.httpOnly());
assertFalse(cookie.persistent());
assertFalse(cookie.hostOnly());
assertThat(cookie.name()).isEqualTo("a");
assertThat(cookie.value()).isEqualTo("b");
assertThat(cookie.expiresAt()).isEqualTo(HttpDate.MAX_DATE);
assertThat(cookie.domain()).isEqualTo("example.com");
assertThat(cookie.path()).isEqualTo("/");
assertThat(cookie.secure()).isFalse();
assertThat(cookie.httpOnly()).isFalse();
assertThat(cookie.persistent()).isFalse();
assertThat(cookie.hostOnly()).isFalse();
}
@Test public void builderNameValidation() throws Exception {
@ -448,7 +452,8 @@ public final class CookieTest {
.hostOnlyDomain("example.com")
.expiresAt(Long.MAX_VALUE)
.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 {
@ -458,7 +463,8 @@ public final class CookieTest {
.hostOnlyDomain("example.com")
.expiresAt(date("1970-01-01T00:00:01.000+0000").getTime())
.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 {
@ -468,7 +474,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com")
.expiresAt(date("1970-01-01T00:00:00.000+0000").getTime())
.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 {
@ -490,8 +496,8 @@ public final class CookieTest {
.value("b")
.hostOnlyDomain("squareup.com")
.build();
assertEquals("squareup.com", cookie.domain());
assertTrue(cookie.hostOnly());
assertThat(cookie.domain()).isEqualTo("squareup.com");
assertThat(cookie.hostOnly()).isTrue();
}
@Test public void builderPath() throws Exception {
@ -501,7 +507,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com")
.path("/foo")
.build();
assertEquals("/foo", cookie.path());
assertThat(cookie.path()).isEqualTo("/foo");
}
@Test public void builderPathValidation() throws Exception {
@ -524,7 +530,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com")
.secure()
.build();
assertTrue(cookie.secure());
assertThat(cookie.secure()).isTrue();
}
@Test public void builderHttpOnly() throws Exception {
@ -534,7 +540,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com")
.httpOnly()
.build();
assertTrue(cookie.httpOnly());
assertThat(cookie.httpOnly()).isTrue();
}
@Test public void builderIpv6() throws Exception {
@ -543,7 +549,7 @@ public final class CookieTest {
.value("b")
.domain("0:0:0:0:0:0:0:1")
.build();
assertEquals("::1", cookie.domain());
assertThat(cookie.domain()).isEqualTo("::1");
}
@Test public void equalsAndHashCode() throws Exception {
@ -561,14 +567,14 @@ public final class CookieTest {
for (String stringB : cookieStrings) {
Cookie cookieB = Cookie.parse(0, url, stringB);
if (Objects.equals(stringA, stringB)) {
assertEquals(cookieA.hashCode(), cookieB.hashCode());
assertEquals(cookieA, cookieB);
assertThat(cookieB.hashCode()).isEqualTo(cookieA.hashCode());
assertThat(cookieB).isEqualTo(cookieA);
} else {
assertNotEquals(cookieA.hashCode(), cookieB.hashCode());
assertNotEquals(cookieA, cookieB);
assertThat(cookieB.hashCode()).isNotEqualTo((long) cookieA.hashCode());
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 static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.Offset.offset;
import static org.junit.Assert.fail;
/** Derived from Android's CookiesTest. */
@ -65,17 +63,17 @@ public class CookiesTest {
get(urlWithIpAddress);
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
assertEquals(1, cookies.size());
assertThat(cookies.size()).isEqualTo(1);
HttpCookie cookie = cookies.get(0);
assertEquals("a", cookie.getName());
assertEquals("android", cookie.getValue());
assertNull(cookie.getComment());
assertNull(cookie.getCommentURL());
assertFalse(cookie.getDiscard());
assertTrue(cookie.getMaxAge() > 100000000000L);
assertEquals("/path", cookie.getPath());
assertTrue(cookie.getSecure());
assertEquals(0, cookie.getVersion());
assertThat(cookie.getName()).isEqualTo("a");
assertThat(cookie.getValue()).isEqualTo("android");
assertThat(cookie.getComment()).isNull();
assertThat(cookie.getCommentURL()).isNull();
assertThat(cookie.getDiscard()).isFalse();
assertThat(cookie.getMaxAge() > 100000000000L).isTrue();
assertThat(cookie.getPath()).isEqualTo("/path");
assertThat(cookie.getSecure()).isTrue();
assertThat(cookie.getVersion()).isEqualTo(0);
}
@Test public void testRfc2109Response() throws Exception {
@ -97,15 +95,16 @@ public class CookiesTest {
get(urlWithIpAddress);
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
assertEquals(1, cookies.size());
assertThat(cookies.size()).isEqualTo(1);
HttpCookie cookie = cookies.get(0);
assertEquals("a", cookie.getName());
assertEquals("android", cookie.getValue());
assertNull(cookie.getCommentURL());
assertFalse(cookie.getDiscard());
assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding!
assertEquals("/path", cookie.getPath());
assertTrue(cookie.getSecure());
assertThat(cookie.getName()).isEqualTo("a");
assertThat(cookie.getValue()).isEqualTo("android");
assertThat(cookie.getCommentURL()).isNull();
assertThat(cookie.getDiscard()).isFalse();
// Converting to a fixed date can cause rounding!
assertThat((double) cookie.getMaxAge()).isCloseTo(60.0, offset(1.0));
assertThat(cookie.getPath()).isEqualTo("/path");
assertThat(cookie.getSecure()).isTrue();
}
@Test public void testQuotedAttributeValues() throws Exception {
@ -130,13 +129,14 @@ public class CookiesTest {
get(urlWithIpAddress);
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
assertEquals(1, cookies.size());
assertThat(cookies.size()).isEqualTo(1);
HttpCookie cookie = cookies.get(0);
assertEquals("a", cookie.getName());
assertEquals("android", cookie.getValue());
assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding!
assertEquals("/path", cookie.getPath());
assertTrue(cookie.getSecure());
assertThat(cookie.getName()).isEqualTo("a");
assertThat(cookie.getValue()).isEqualTo("android");
// Converting to a fixed date can cause rounding!
assertThat((double) cookie.getMaxAge()).isCloseTo(60.0, offset(1.0));
assertThat(cookie.getPath()).isEqualTo("/path");
assertThat(cookie.getSecure()).isTrue();
}
@Test public void testSendingCookiesFromStore() throws Exception {
@ -161,7 +161,7 @@ public class CookiesTest {
get(serverUrl);
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 {
@ -189,7 +189,7 @@ public class CookiesTest {
get(serverUrl);
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 {
@ -207,11 +207,11 @@ public class CookiesTest {
get(urlWithIpAddress(server, "/"));
RecordedRequest request1 = server.takeRequest();
assertNull(request1.getHeader("Cookie"));
assertThat(request1.getHeader("Cookie")).isNull();
get(urlWithIpAddress(server, "/"));
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 {
@ -241,7 +241,7 @@ public class CookiesTest {
get(redirectSourceUrl);
RecordedRequest request = redirectSource.takeRequest();
assertEquals("c=cookie", request.getHeader("Cookie"));
assertThat(request.getHeader("Cookie")).isEqualTo("c=cookie");
for (String header : redirectTarget.takeRequest().getHeaders().names()) {
if (header.startsWith("Cookie")) {
@ -270,9 +270,9 @@ public class CookiesTest {
get(server.url("/"));
RecordedRequest request = server.takeRequest();
assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
assertNull(request.getHeader("Cookie2"));
assertNull(request.getHeader("Quux"));
assertThat(request.getHeader("Cookie")).isEqualTo("Bar=bar; Baz=baz");
assertThat(request.getHeader("Cookie2")).isNull();
assertThat(request.getHeader("Quux")).isNull();
}
@Test public void acceptOriginalServerMatchesSubdomain() throws Exception {
@ -283,9 +283,9 @@ public class CookiesTest {
cookieJar.saveFromResponse(url, Arrays.asList(
Cookie.parse(url, "a=android; Domain=squareup.com")));
List<Cookie> actualCookies = cookieJar.loadForRequest(url);
assertEquals(1, actualCookies.size());
assertEquals("a", actualCookies.get(0).name());
assertEquals("android", actualCookies.get(0).value());
assertThat(actualCookies.size()).isEqualTo(1);
assertThat(actualCookies.get(0).name()).isEqualTo("a");
assertThat(actualCookies.get(0).value()).isEqualTo("android");
}
@Test public void acceptOriginalServerMatchesRfc2965Dot() throws Exception {
@ -296,9 +296,9 @@ public class CookiesTest {
cookieJar.saveFromResponse(url, Arrays.asList(
Cookie.parse(url, "a=android; Domain=.squareup.com")));
List<Cookie> actualCookies = cookieJar.loadForRequest(url);
assertEquals(1, actualCookies.size());
assertEquals("a", actualCookies.get(0).name());
assertEquals("android", actualCookies.get(0).value());
assertThat(actualCookies.size()).isEqualTo(1);
assertThat(actualCookies.get(0).name()).isEqualTo("a");
assertThat(actualCookies.get(0).value()).isEqualTo("android");
}
@Test public void acceptOriginalServerMatchesExactly() throws Exception {
@ -309,9 +309,9 @@ public class CookiesTest {
cookieJar.saveFromResponse(url, Arrays.asList(
Cookie.parse(url, "a=android; Domain=squareup.com")));
List<Cookie> actualCookies = cookieJar.loadForRequest(url);
assertEquals(1, actualCookies.size());
assertEquals("a", actualCookies.get(0).name());
assertEquals("android", actualCookies.get(0).value());
assertThat(actualCookies.size()).isEqualTo(1);
assertThat(actualCookies.get(0).name()).isEqualTo("a");
assertThat(actualCookies.get(0).value()).isEqualTo("android");
}
@Test public void acceptOriginalServerDoesNotMatchDifferentServer() throws Exception {
@ -324,7 +324,7 @@ public class CookiesTest {
HttpUrl url2 = HttpUrl.get("https://www.squareup.com/");
List<Cookie> actualCookies = cookieJar.loadForRequest(url2);
assertEquals(Collections.<Cookie>emptyList(), actualCookies);
assertThat(actualCookies).isEmpty();
}
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.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
@ -20,9 +19,7 @@ import org.junit.Rule;
import org.junit.Test;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class DispatcherTest {
@ -176,10 +173,10 @@ public final class DispatcherTest {
a3.enqueue(callback);
a4.enqueue(callback);
a5.enqueue(callback);
assertEquals(3, dispatcher.runningCallsCount());
assertEquals(2, dispatcher.queuedCallsCount());
assertEquals(set(a1, a2, a3), set(dispatcher.runningCalls()));
assertEquals(set(a4, a5), set(dispatcher.queuedCalls()));
assertThat(dispatcher.runningCallsCount()).isEqualTo(3);
assertThat(dispatcher.queuedCallsCount()).isEqualTo(2);
assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2, a3));
assertThat(set(dispatcher.queuedCalls())).isEqualTo(set(a4, a5));
}
@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.
ready.await();
assertEquals(2, dispatcher.runningCallsCount());
assertEquals(0, dispatcher.queuedCallsCount());
assertEquals(set(a1, a2), set(dispatcher.runningCalls()));
assertEquals(Collections.emptyList(), dispatcher.queuedCalls());
assertThat(dispatcher.runningCallsCount()).isEqualTo(2);
assertThat(dispatcher.queuedCallsCount()).isEqualTo(0);
assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2));
assertThat(dispatcher.queuedCalls()).isEmpty();
// Cancel some calls. That doesn't impact running or queued.
a2.cancel();
a3.cancel();
assertEquals(set(a1, a2), set(dispatcher.runningCalls()));
assertEquals(Collections.emptyList(), dispatcher.queuedCalls());
assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2));
assertThat(dispatcher.queuedCalls()).isEmpty();
// Let the calls finish.
waiting.countDown();
@ -223,22 +220,22 @@ public final class DispatcherTest {
t2.join();
// Now we should have 0 running calls and 0 queued calls.
assertEquals(0, dispatcher.runningCallsCount());
assertEquals(0, dispatcher.queuedCallsCount());
assertEquals(Collections.emptyList(), dispatcher.runningCalls());
assertEquals(Collections.emptyList(), dispatcher.queuedCalls());
assertThat(dispatcher.runningCallsCount()).isEqualTo(0);
assertThat(dispatcher.queuedCallsCount()).isEqualTo(0);
assertThat(dispatcher.runningCalls()).isEmpty();
assertThat(dispatcher.queuedCalls()).isEmpty();
assertTrue(a1.isExecuted());
assertFalse(a1.isCanceled());
assertThat(a1.isExecuted()).isTrue();
assertThat(a1.isCanceled()).isFalse();
assertTrue(a2.isExecuted());
assertTrue(a2.isCanceled());
assertThat(a2.isExecuted()).isTrue();
assertThat(a2.isCanceled()).isTrue();
assertFalse(a3.isExecuted());
assertTrue(a3.isCanceled());
assertThat(a3.isExecuted()).isFalse();
assertThat(a3.isCanceled()).isTrue();
assertFalse(a4.isExecuted());
assertFalse(a4.isCanceled());
assertThat(a4.isExecuted()).isFalse();
assertThat(a4.isCanceled()).isFalse();
}
@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/2")).enqueue(callback);
executor.finishJob("http://a/1");
assertFalse(idle.get());
assertThat(idle.get()).isFalse();
CountDownLatch ready = 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")));
ready.await(5, SECONDS);
executor.finishJob("http://a/2");
assertFalse(idle.get());
assertThat(idle.get()).isFalse();
proceed.countDown();
t1.join();
assertTrue(idle.get());
assertThat(idle.get()).isTrue();
}
@Test public void executionRejectedImmediately() throws Exception {
@ -279,7 +276,7 @@ public final class DispatcherTest {
executor.shutdown();
client.newCall(request).enqueue(callback);
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 {
@ -292,8 +289,8 @@ public final class DispatcherTest {
dispatcher.setMaxRequests(2); // Trigger promotion.
callback.await(request2.url()).assertFailure(InterruptedIOException.class);
assertEquals(Arrays.asList("CallStart", "CallStart", "CallFailed"),
listener.recordedEventTypes());
assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallStart",
"CallFailed");
}
@Test public void executionRejectedAfterMaxRequestsPerHostChange() throws Exception {
@ -305,8 +302,8 @@ public final class DispatcherTest {
client.newCall(request2).enqueue(callback);
dispatcher.setMaxRequestsPerHost(2); // Trigger promotion.
callback.await(request2.url()).assertFailure(InterruptedIOException.class);
assertEquals(Arrays.asList("CallStart", "CallStart", "CallFailed"),
listener.recordedEventTypes());
assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallStart",
"CallFailed");
}
@Test public void executionRejectedAfterPrecedingCallFinishes() throws Exception {
@ -318,8 +315,8 @@ public final class DispatcherTest {
client.newCall(request2).enqueue(callback);
executor.finishJob("http://a/1"); // Trigger promotion.
callback.await(request2.url()).assertFailure(InterruptedIOException.class);
assertEquals(Arrays.asList("CallStart", "CallStart", "CallFailed"),
listener.recordedEventTypes());
assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallStart",
"CallFailed");
}
@SafeVarargs
@ -357,7 +354,7 @@ public final class DispatcherTest {
for (AsyncCall call : calls) {
actualUrls.add(call.request().url().toString());
}
assertEquals(Arrays.asList(expectedUrls), actualUrls);
assertThat(actualUrls).containsExactly(expectedUrls);
}
public void finishJob(String url) {

View File

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

View File

@ -52,6 +52,7 @@ import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.HandshakeCertificates;
import okio.Buffer;
import okio.BufferedSink;
import org.assertj.core.api.Assertions;
import org.hamcrest.BaseMatcher;
import org.hamcrest.CoreMatchers;
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.either;
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.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeThat;
@ -110,15 +105,15 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
assertEquals("abc", response.body().string());
Assertions.assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.body().string()).isEqualTo("abc");
response.body().close();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test public void successfulCallEventSequenceForEnqueue() throws Exception {
@ -149,7 +144,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test public void failedCallEventSequence() {
@ -171,7 +166,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseFailed", "ConnectionReleased",
"CallFailed");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test public void failedDribbledCallEventSequence() throws IOException {
@ -200,9 +195,10 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseFailed", "ConnectionReleased", "CallFailed");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
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() {
@ -214,11 +210,11 @@ public final class EventListenerTest {
call.execute();
fail();
} catch (IOException expected) {
assertEquals("Canceled", expected.getMessage());
Assertions.assertThat(expected.getMessage()).isEqualTo("Canceled");
}
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 {
@ -226,7 +222,7 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().string();
response.body().close();
@ -237,7 +233,7 @@ public final class EventListenerTest {
"RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd",
"ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test public void secondCallEventSequence() throws IOException {
@ -262,7 +258,7 @@ public final class EventListenerTest {
"RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd",
"ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
private void assertBytesReadWritten(RecordingEventListener listener,
@ -273,31 +269,32 @@ public final class EventListenerTest {
RequestHeadersEnd responseHeadersEnd = listener.removeUpToEvent(RequestHeadersEnd.class);
assertThat("request header length", responseHeadersEnd.headerLength, requestHeaderLength);
} else {
assertFalse("Found RequestHeadersEnd",
listener.recordedEventTypes().contains("RequestHeadersEnd"));
Assertions.assertThat(listener.recordedEventTypes().contains("RequestHeadersEnd")).overridingErrorMessage(
"Found RequestHeadersEnd").isFalse();
}
if (requestBodyBytes != null) {
RequestBodyEnd responseBodyEnd = listener.removeUpToEvent(RequestBodyEnd.class);
assertThat("request body bytes", responseBodyEnd.bytesWritten, requestBodyBytes);
} else {
assertFalse("Found RequestBodyEnd", listener.recordedEventTypes().contains("RequestBodyEnd"));
Assertions.assertThat(listener.recordedEventTypes().contains("RequestBodyEnd")).overridingErrorMessage(
"Found RequestBodyEnd").isFalse();
}
if (responseHeaderLength != null) {
ResponseHeadersEnd responseHeadersEnd = listener.removeUpToEvent(ResponseHeadersEnd.class);
assertThat("response header length", responseHeadersEnd.headerLength, responseHeaderLength);
} else {
assertFalse("Found ResponseHeadersEnd",
listener.recordedEventTypes().contains("ResponseHeadersEnd"));
Assertions.assertThat(listener.recordedEventTypes().contains("ResponseHeadersEnd")).overridingErrorMessage(
"Found ResponseHeadersEnd").isFalse();
}
if (responseBodyBytes != null) {
ResponseBodyEnd responseBodyEnd = listener.removeUpToEvent(ResponseBodyEnd.class);
assertThat("response body bytes", responseBodyEnd.bytesRead, responseBodyBytes);
} else {
assertFalse("Found ResponseBodyEnd",
listener.recordedEventTypes().contains("ResponseBodyEnd"));
Assertions.assertThat(listener.recordedEventTypes().contains("ResponseBodyEnd")).overridingErrorMessage(
"Found ResponseBodyEnd").isFalse();
}
}
@ -391,17 +388,17 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
DnsStart dnsStart = listener.removeUpToEvent(DnsStart.class);
assertSame(call, dnsStart.call);
assertEquals(server.getHostName(), dnsStart.domainName);
Assertions.assertThat(dnsStart.call).isSameAs(call);
Assertions.assertThat(dnsStart.domainName).isEqualTo(server.getHostName());
DnsEnd dnsEnd = listener.removeUpToEvent(DnsEnd.class);
assertSame(call, dnsEnd.call);
assertEquals(server.getHostName(), dnsEnd.domainName);
assertEquals(1, dnsEnd.inetAddressList.size());
Assertions.assertThat(dnsEnd.call).isSameAs(call);
Assertions.assertThat(dnsEnd.domainName).isEqualTo(server.getHostName());
Assertions.assertThat(dnsEnd.inetAddressList.size()).isEqualTo(1);
}
@Test public void noDnsLookupOnPooledConnection() throws IOException {
@ -413,7 +410,7 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response1 = call1.execute();
assertEquals(200, response1.code());
Assertions.assertThat(response1.code()).isEqualTo(200);
response1.body().close();
listener.clearAllEvents();
@ -422,12 +419,12 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals(200, response2.code());
Assertions.assertThat(response2.code()).isEqualTo(200);
response2.body().close();
List<String> recordedEvents = listener.recordedEventTypes();
assertFalse(recordedEvents.contains("DnsStart"));
assertFalse(recordedEvents.contains("DnsEnd"));
Assertions.assertThat(recordedEvents.contains("DnsStart")).isFalse();
Assertions.assertThat(recordedEvents.contains("DnsEnd")).isFalse();
}
@Test public void multipleDnsLookupsForSingleCall() throws IOException {
@ -448,7 +445,7 @@ public final class EventListenerTest {
.url("http://fakeurl:" + server.getPort())
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
listener.removeUpToEvent(DnsStart.class);
@ -473,8 +470,9 @@ public final class EventListenerTest {
listener.removeUpToEvent(DnsStart.class);
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertSame(call, callFailed.call);
assertTrue(callFailed.ioe instanceof UnknownHostException);
Assertions.assertThat(callFailed.call).isSameAs(call);
boolean condition = callFailed.ioe instanceof UnknownHostException;
Assertions.assertThat(condition).isTrue();
}
@Test public void emptyDnsLookup() {
@ -495,8 +493,9 @@ public final class EventListenerTest {
listener.removeUpToEvent(DnsStart.class);
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertSame(call, callFailed.call);
assertTrue(callFailed.ioe instanceof UnknownHostException);
Assertions.assertThat(callFailed.call).isSameAs(call);
boolean condition = callFailed.ioe instanceof UnknownHostException;
Assertions.assertThat(condition).isTrue();
}
@Test public void successfulConnect() throws IOException {
@ -506,21 +505,21 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
InetAddress address = client.dns().lookup(server.getHostName()).get(0);
InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
assertSame(call, connectStart.call);
assertEquals(expectedAddress, connectStart.inetSocketAddress);
assertEquals(Proxy.NO_PROXY, connectStart.proxy);
Assertions.assertThat(connectStart.call).isSameAs(call);
Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY);
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
assertSame(call, connectEnd.call);
assertEquals(expectedAddress, connectEnd.inetSocketAddress);
assertEquals(Protocol.HTTP_1_1, connectEnd.protocol);
Assertions.assertThat(connectEnd.call).isSameAs(call);
Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1);
}
@Test public void failedConnect() throws UnknownHostException {
@ -541,15 +540,15 @@ public final class EventListenerTest {
InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
assertSame(call, connectStart.call);
assertEquals(expectedAddress, connectStart.inetSocketAddress);
assertEquals(Proxy.NO_PROXY, connectStart.proxy);
Assertions.assertThat(connectStart.call).isSameAs(call);
Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY);
ConnectFailed connectFailed = listener.removeUpToEvent(ConnectFailed.class);
assertSame(call, connectFailed.call);
assertEquals(expectedAddress, connectFailed.inetSocketAddress);
assertNull(connectFailed.protocol);
assertNotNull(connectFailed.ioe);
Assertions.assertThat(connectFailed.call).isSameAs(call);
Assertions.assertThat(connectFailed.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectFailed.protocol).isNull();
Assertions.assertThat(connectFailed.ioe).isNotNull();
}
@Test public void multipleConnectsForSingleCall() throws IOException {
@ -566,7 +565,7 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
listener.removeUpToEvent(ConnectStart.class);
@ -586,21 +585,21 @@ public final class EventListenerTest {
.url("http://www.fakeurl")
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
InetAddress address = client.dns().lookup(server.getHostName()).get(0);
InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
assertSame(call, connectStart.call);
assertEquals(expectedAddress, connectStart.inetSocketAddress);
assertEquals(server.toProxyAddress(), connectStart.proxy);
Assertions.assertThat(connectStart.call).isSameAs(call);
Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectStart.proxy).isEqualTo(server.toProxyAddress());
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
assertSame(call, connectEnd.call);
assertEquals(expectedAddress, connectEnd.inetSocketAddress);
assertEquals(Protocol.HTTP_1_1, connectEnd.protocol);
Assertions.assertThat(connectEnd.call).isSameAs(call);
Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1);
}
@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())
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
InetSocketAddress expectedAddress = InetSocketAddress.createUnresolved(
SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
assertSame(call, connectStart.call);
assertEquals(expectedAddress, connectStart.inetSocketAddress);
assertEquals(proxy, connectStart.proxy);
Assertions.assertThat(connectStart.call).isSameAs(call);
Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectStart.proxy).isEqualTo(proxy);
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
assertSame(call, connectEnd.call);
assertEquals(expectedAddress, connectEnd.inetSocketAddress);
assertEquals(Protocol.HTTP_1_1, connectEnd.protocol);
Assertions.assertThat(connectEnd.call).isSameAs(call);
Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1);
}
@Test public void authenticatingTunnelProxyConnect() throws IOException {
@ -654,13 +653,13 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
listener.removeUpToEvent(ConnectStart.class);
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
assertNull(connectEnd.protocol);
Assertions.assertThat(connectEnd.protocol).isNull();
listener.removeUpToEvent(ConnectStart.class);
listener.removeUpToEvent(ConnectEnd.class);
@ -674,15 +673,15 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class);
assertSame(call, secureStart.call);
Assertions.assertThat(secureStart.call).isSameAs(call);
SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class);
assertSame(call, secureEnd.call);
assertNotNull(secureEnd.handshake);
Assertions.assertThat(secureEnd.call).isSameAs(call);
Assertions.assertThat(secureEnd.handshake).isNotNull();
}
@Test public void failedSecureConnect() {
@ -700,11 +699,11 @@ public final class EventListenerTest {
}
SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class);
assertSame(call, secureStart.call);
Assertions.assertThat(secureStart.call).isSameAs(call);
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertSame(call, callFailed.call);
assertNotNull(callFailed.ioe);
Assertions.assertThat(callFailed.call).isSameAs(call);
Assertions.assertThat(callFailed.ioe).isNotNull();
}
@Test public void secureConnectWithTunnel() throws IOException {
@ -721,15 +720,15 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class);
assertSame(call, secureStart.call);
Assertions.assertThat(secureStart.call).isSameAs(call);
SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class);
assertSame(call, secureEnd.call);
assertNotNull(secureEnd.handshake);
Assertions.assertThat(secureEnd.call).isSameAs(call);
Assertions.assertThat(secureEnd.handshake).isNotNull();
}
@Test public void multipleSecureConnectsForSingleCall() throws IOException {
@ -746,7 +745,7 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
listener.removeUpToEvent(SecureConnectStart.class);
@ -770,7 +769,7 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response1 = call1.execute();
assertEquals(200, response1.code());
Assertions.assertThat(response1.code()).isEqualTo(200);
response1.body().close();
listener.clearAllEvents();
@ -779,12 +778,12 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals(200, response2.code());
Assertions.assertThat(response2.code()).isEqualTo(200);
response2.body().close();
List<String> recordedEvents = listener.recordedEventTypes();
assertFalse(recordedEvents.contains("SecureConnectStart"));
assertFalse(recordedEvents.contains("SecureConnectEnd"));
Assertions.assertThat(recordedEvents.contains("SecureConnectStart")).isFalse();
Assertions.assertThat(recordedEvents.contains("SecureConnectEnd")).isFalse();
}
@Test public void successfulConnectionFound() throws IOException {
@ -794,12 +793,12 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
Assertions.assertThat(response.code()).isEqualTo(200);
response.body().close();
ConnectionAcquired connectionAcquired = listener.removeUpToEvent(ConnectionAcquired.class);
assertSame(call, connectionAcquired.call);
assertNotNull(connectionAcquired.connection);
Assertions.assertThat(connectionAcquired.call).isSameAs(call);
Assertions.assertThat(connectionAcquired.connection).isNotNull();
}
@Test public void noConnectionFoundOnFollowUp() throws IOException {
@ -813,12 +812,12 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("ABC", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("ABC");
listener.removeUpToEvent(ConnectionAcquired.class);
List<String> remainingEvents = listener.recordedEventTypes();
assertFalse(remainingEvents.contains("ConnectionAcquired"));
Assertions.assertThat(remainingEvents.contains("ConnectionAcquired")).isFalse();
}
@Test public void pooledConnectionFound() throws IOException {
@ -830,7 +829,7 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response1 = call1.execute();
assertEquals(200, response1.code());
Assertions.assertThat(response1.code()).isEqualTo(200);
response1.body().close();
ConnectionAcquired connectionAcquired1 = listener.removeUpToEvent(ConnectionAcquired.class);
@ -840,11 +839,12 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals(200, response2.code());
Assertions.assertThat(response2.code()).isEqualTo(200);
response2.body().close();
ConnectionAcquired connectionAcquired2 = listener.removeUpToEvent(ConnectionAcquired.class);
assertSame(connectionAcquired1.connection, connectionAcquired2.connection);
Assertions.assertThat(connectionAcquired2.connection).isSameAs(
connectionAcquired1.connection);
}
@Test public void multipleConnectionsFoundForSingleCall() throws IOException {
@ -859,7 +859,7 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("ABC", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("ABC");
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
assumeThat(response, matchesProtocol(Protocol.HTTP_2));
}
assertEquals(expectedProtocol, response.protocol());
Assertions.assertThat(response.protocol()).isEqualTo(expectedProtocol);
try {
response.body.string();
fail();
@ -904,7 +904,7 @@ public final class EventListenerTest {
}
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertNotNull(callFailed.ioe);
Assertions.assertThat(callFailed.ioe).isNotNull();
}
@Test public void emptyResponseBody() throws IOException {
@ -923,7 +923,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test public void emptyResponseBodyConnectionClose() throws IOException {
@ -941,7 +941,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test public void responseBodyClosedClosedWithoutReadingAllData() throws IOException {
@ -960,7 +960,7 @@ public final class EventListenerTest {
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test public void requestBodyFailHttp1OverHttps() throws IOException {
@ -1012,7 +1012,7 @@ public final class EventListenerTest {
}
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
assertNotNull(callFailed.ioe);
Assertions.assertThat(callFailed.ioe).isNotNull();
}
@Test public void requestBodyMultipleFailuresReportedOnlyOnce() {
@ -1055,7 +1055,7 @@ public final class EventListenerTest {
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart",
"ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd",
"RequestBodyStart", "RequestFailed", "ConnectionReleased", "CallFailed");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test public void requestBodySuccessHttp1OverHttps() throws IOException {
@ -1108,15 +1108,15 @@ public final class EventListenerTest {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals(200, response.code());
assertEquals("abc", response.body().string());
Assertions.assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.body().string()).isEqualTo("abc");
response.body().close();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
private void requestBodySuccess(RequestBody body, Matcher<Long> requestBodyBytes,
@ -1128,7 +1128,7 @@ public final class EventListenerTest {
.post(body)
.build());
Response response = call.execute();
assertEquals("World!", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("World!");
assertBytesReadWritten(listener, any(Long.class), requestBodyBytes, responseHeaderLength,
equalTo(6L));
@ -1159,7 +1159,7 @@ public final class EventListenerTest {
"ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased",
"CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test
@ -1181,7 +1181,7 @@ public final class EventListenerTest {
"ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased",
"CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
}
@Test public void applicationInterceptorProceedsMultipleTimes() throws Exception {
@ -1191,7 +1191,7 @@ public final class EventListenerTest {
client = client.newBuilder()
.addInterceptor(chain -> {
try (Response a = chain.proceed(chain.request())) {
assertEquals("a", a.body().string());
Assertions.assertThat(a.body().string()).isEqualTo("a");
}
return chain.proceed(chain.request());
})
@ -1199,7 +1199,7 @@ public final class EventListenerTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute();
assertEquals("b", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("b");
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
@ -1207,10 +1207,10 @@ public final class EventListenerTest {
"ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased",
"CallEnd");
assertEquals(expectedEvents, listener.recordedEventTypes());
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(1, server.takeRequest().getSequenceNumber());
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
@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());
Response response = call.execute();
assertEquals("a", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("a");
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. */
@ -1250,6 +1250,6 @@ public final class EventListenerTest {
"ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd",
"ResponseHeadersStart", "RequestBodyStart", "RequestBodyEnd", "ResponseHeadersEnd",
"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 java.nio.charset.Charset;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
public final class FormBodyTest {
@Test public void urlEncoding() throws Exception {
@ -30,32 +30,33 @@ public final class FormBodyTest {
.add("%25", "%25")
.build();
assertEquals(3, body.size());
assertThat(body.size()).isEqualTo(3);
assertEquals("a%2B%3D%26%20b", body.encodedName(0));
assertEquals("space%2C%20the", body.encodedName(1));
assertEquals("%2525", body.encodedName(2));
assertThat(body.encodedName(0)).isEqualTo("a%2B%3D%26%20b");
assertThat(body.encodedName(1)).isEqualTo("space%2C%20the");
assertThat(body.encodedName(2)).isEqualTo("%2525");
assertEquals("a+=& b", body.name(0));
assertEquals("space, the", body.name(1));
assertEquals("%25", body.name(2));
assertThat(body.name(0)).isEqualTo("a+=& b");
assertThat(body.name(1)).isEqualTo("space, the");
assertThat(body.name(2)).isEqualTo("%25");
assertEquals("c%2B%3D%26%20d", body.encodedValue(0));
assertEquals("final%20frontier", body.encodedValue(1));
assertEquals("%2525", body.encodedValue(2));
assertThat(body.encodedValue(0)).isEqualTo("c%2B%3D%26%20d");
assertThat(body.encodedValue(1)).isEqualTo("final%20frontier");
assertThat(body.encodedValue(2)).isEqualTo("%2525");
assertEquals("c+=& d", body.value(0));
assertEquals("final frontier", body.value(1));
assertEquals("%25", body.value(2));
assertThat(body.value(0)).isEqualTo("c+=& d");
assertThat(body.value(1)).isEqualTo("final frontier");
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";
assertEquals(expected.length(), body.contentLength());
assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer out = new Buffer();
body.writeTo(out);
assertEquals(expected, out.readUtf8());
assertThat(out.readUtf8()).isEqualTo(expected);
}
@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";
Buffer out = new Buffer();
body.writeTo(out);
assertEquals(expected, out.readUtf8());
assertThat(out.readUtf8()).isEqualTo(expected);
}
@Test public void encodedPair() throws Exception {
@ -77,11 +78,11 @@ public final class FormBodyTest {
.build();
String expected = "sim=ple";
assertEquals(expected.length(), body.contentLength());
assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer buffer = new Buffer();
body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8());
assertThat(buffer.readUtf8()).isEqualTo(expected);
}
@Test public void encodeMultiplePairs() throws Exception {
@ -92,99 +93,103 @@ public final class FormBodyTest {
.build();
String expected = "sim=ple&hey=there&help=me";
assertEquals(expected.length(), body.contentLength());
assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer buffer = new Buffer();
body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8());
assertThat(buffer.readUtf8()).isEqualTo(expected);
}
@Test public void buildEmptyForm() throws Exception {
FormBody body = new FormBody.Builder().build();
String expected = "";
assertEquals(expected.length(), body.contentLength());
assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer buffer = new Buffer();
body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8());
assertThat(buffer.readUtf8()).isEqualTo(expected);
}
@Test public void characterEncoding() throws Exception {
assertEquals("%00", formEncode(0)); // Browsers convert '\u0000' to '%EF%BF%BD'.
assertEquals("%01", formEncode(1));
assertEquals("%02", formEncode(2));
assertEquals("%03", formEncode(3));
assertEquals("%04", formEncode(4));
assertEquals("%05", formEncode(5));
assertEquals("%06", formEncode(6));
assertEquals("%07", formEncode(7));
assertEquals("%08", formEncode(8));
assertEquals("%09", formEncode(9));
assertEquals("%0A", formEncode(10)); // Browsers convert '\n' to '\r\n'
assertEquals("%0B", formEncode(11));
assertEquals("%0C", formEncode(12));
assertEquals("%0D", formEncode(13)); // Browsers convert '\r' to '\r\n'
assertEquals("%0E", formEncode(14));
assertEquals("%0F", formEncode(15));
assertEquals("%10", formEncode(16));
assertEquals("%11", formEncode(17));
assertEquals("%12", formEncode(18));
assertEquals("%13", formEncode(19));
assertEquals("%14", formEncode(20));
assertEquals("%15", formEncode(21));
assertEquals("%16", formEncode(22));
assertEquals("%17", formEncode(23));
assertEquals("%18", formEncode(24));
assertEquals("%19", formEncode(25));
assertEquals("%1A", formEncode(26));
assertEquals("%1B", formEncode(27));
assertEquals("%1C", formEncode(28));
assertEquals("%1D", formEncode(29));
assertEquals("%1E", formEncode(30));
assertEquals("%1F", formEncode(31));
assertEquals("%20", formEncode(32)); // Browsers use '+' for space.
assertEquals("%21", formEncode(33));
assertEquals("%22", formEncode(34));
assertEquals("%23", formEncode(35));
assertEquals("%24", formEncode(36));
assertEquals("%25", formEncode(37));
assertEquals("%26", formEncode(38));
assertEquals("%27", formEncode(39));
assertEquals("%28", formEncode(40));
assertEquals("%29", formEncode(41));
assertEquals("*", formEncode(42));
assertEquals("%2B", formEncode(43));
assertEquals("%2C", formEncode(44));
assertEquals("-", formEncode(45));
assertEquals(".", formEncode(46));
assertEquals("%2F", formEncode(47));
assertEquals("0", formEncode(48));
assertEquals("9", formEncode(57));
assertEquals("%3A", formEncode(58));
assertEquals("%3B", formEncode(59));
assertEquals("%3C", formEncode(60));
assertEquals("%3D", formEncode(61));
assertEquals("%3E", formEncode(62));
assertEquals("%3F", formEncode(63));
assertEquals("%40", formEncode(64));
assertEquals("A", formEncode(65));
assertEquals("Z", formEncode(90));
assertEquals("%5B", formEncode(91));
assertEquals("%5C", formEncode(92));
assertEquals("%5D", formEncode(93));
assertEquals("%5E", formEncode(94));
assertEquals("_", formEncode(95));
assertEquals("%60", formEncode(96));
assertEquals("a", formEncode(97));
assertEquals("z", formEncode(122));
assertEquals("%7B", formEncode(123));
assertEquals("%7C", formEncode(124));
assertEquals("%7D", formEncode(125));
assertEquals("%7E", formEncode(126));
assertEquals("%7F", formEncode(127));
assertEquals("%C2%80", formEncode(128));
assertEquals("%C3%BF", formEncode(255));
// Browsers convert '\u0000' to '%EF%BF%BD'.
assertThat(formEncode(0)).isEqualTo("%00");
assertThat(formEncode(1)).isEqualTo("%01");
assertThat(formEncode(2)).isEqualTo("%02");
assertThat(formEncode(3)).isEqualTo("%03");
assertThat(formEncode(4)).isEqualTo("%04");
assertThat(formEncode(5)).isEqualTo("%05");
assertThat(formEncode(6)).isEqualTo("%06");
assertThat(formEncode(7)).isEqualTo("%07");
assertThat(formEncode(8)).isEqualTo("%08");
assertThat(formEncode(9)).isEqualTo("%09");
// Browsers convert '\n' to '\r\n'
assertThat(formEncode(10)).isEqualTo("%0A");
assertThat(formEncode(11)).isEqualTo("%0B");
assertThat(formEncode(12)).isEqualTo("%0C");
// Browsers convert '\r' to '\r\n'
assertThat(formEncode(13)).isEqualTo("%0D");
assertThat(formEncode(14)).isEqualTo("%0E");
assertThat(formEncode(15)).isEqualTo("%0F");
assertThat(formEncode(16)).isEqualTo("%10");
assertThat(formEncode(17)).isEqualTo("%11");
assertThat(formEncode(18)).isEqualTo("%12");
assertThat(formEncode(19)).isEqualTo("%13");
assertThat(formEncode(20)).isEqualTo("%14");
assertThat(formEncode(21)).isEqualTo("%15");
assertThat(formEncode(22)).isEqualTo("%16");
assertThat(formEncode(23)).isEqualTo("%17");
assertThat(formEncode(24)).isEqualTo("%18");
assertThat(formEncode(25)).isEqualTo("%19");
assertThat(formEncode(26)).isEqualTo("%1A");
assertThat(formEncode(27)).isEqualTo("%1B");
assertThat(formEncode(28)).isEqualTo("%1C");
assertThat(formEncode(29)).isEqualTo("%1D");
assertThat(formEncode(30)).isEqualTo("%1E");
assertThat(formEncode(31)).isEqualTo("%1F");
// Browsers use '+' for space.
assertThat(formEncode(32)).isEqualTo("%20");
assertThat(formEncode(33)).isEqualTo("%21");
assertThat(formEncode(34)).isEqualTo("%22");
assertThat(formEncode(35)).isEqualTo("%23");
assertThat(formEncode(36)).isEqualTo("%24");
assertThat(formEncode(37)).isEqualTo("%25");
assertThat(formEncode(38)).isEqualTo("%26");
assertThat(formEncode(39)).isEqualTo("%27");
assertThat(formEncode(40)).isEqualTo("%28");
assertThat(formEncode(41)).isEqualTo("%29");
assertThat(formEncode(42)).isEqualTo("*");
assertThat(formEncode(43)).isEqualTo("%2B");
assertThat(formEncode(44)).isEqualTo("%2C");
assertThat(formEncode(45)).isEqualTo("-");
assertThat(formEncode(46)).isEqualTo(".");
assertThat(formEncode(47)).isEqualTo("%2F");
assertThat(formEncode(48)).isEqualTo("0");
assertThat(formEncode(57)).isEqualTo("9");
assertThat(formEncode(58)).isEqualTo("%3A");
assertThat(formEncode(59)).isEqualTo("%3B");
assertThat(formEncode(60)).isEqualTo("%3C");
assertThat(formEncode(61)).isEqualTo("%3D");
assertThat(formEncode(62)).isEqualTo("%3E");
assertThat(formEncode(63)).isEqualTo("%3F");
assertThat(formEncode(64)).isEqualTo("%40");
assertThat(formEncode(65)).isEqualTo("A");
assertThat(formEncode(90)).isEqualTo("Z");
assertThat(formEncode(91)).isEqualTo("%5B");
assertThat(formEncode(92)).isEqualTo("%5C");
assertThat(formEncode(93)).isEqualTo("%5D");
assertThat(formEncode(94)).isEqualTo("%5E");
assertThat(formEncode(95)).isEqualTo("_");
assertThat(formEncode(96)).isEqualTo("%60");
assertThat(formEncode(97)).isEqualTo("a");
assertThat(formEncode(122)).isEqualTo("z");
assertThat(formEncode(123)).isEqualTo("%7B");
assertThat(formEncode(124)).isEqualTo("%7C");
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 {
@ -204,10 +209,10 @@ public final class FormBodyTest {
.build();
String expected = "name=Nicol%E1s";
assertEquals(expected.length(), body.contentLength());
assertThat(body.contentLength()).isEqualTo(expected.length());
Buffer out = new Buffer();
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.singletonMap;
import static okhttp3.TestUtil.headerEntries;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class HeadersTest {
@ -54,9 +52,9 @@ public final class HeadersTest {
Request request = new Request.Builder().url("http://square.com/").build();
Response response = Http2ExchangeCodec.readHttp2HeadersList(headerBlock, Protocol.HTTP_2).request(request).build();
Headers headers = response.headers();
assertEquals(1, headers.size());
assertEquals(":version", headers.name(0));
assertEquals("HTTP/1.1", headers.value(0));
assertThat(headers.size()).isEqualTo(1);
assertThat(headers.name(0)).isEqualTo(":version");
assertThat(headers.value(0)).isEqualTo("HTTP/1.1");
}
@Test public void http2HeadersListDropsForbiddenHeadersHttp2() {
@ -72,7 +70,7 @@ public final class HeadersTest {
":path", "/",
":authority", "square.com",
":scheme", "http");
assertEquals(expected, Http2ExchangeCodec.http2HeadersList(request));
assertThat(Http2ExchangeCodec.http2HeadersList(request)).isEqualTo(expected);
}
@Test public void http2HeadersListDontDropTeIfTrailersHttp2() {
@ -85,13 +83,13 @@ public final class HeadersTest {
":path", "/",
":scheme", "http",
"te", "trailers");
assertEquals(expected, Http2ExchangeCodec.http2HeadersList(request));
assertThat(Http2ExchangeCodec.http2HeadersList(request)).isEqualTo(expected);
}
@Test public void ofTrims() {
Headers headers = Headers.of("\t User-Agent \n", " \r OkHttp ");
assertEquals("User-Agent", headers.name(0));
assertEquals("OkHttp", headers.value(0));
assertThat(headers.name(0)).isEqualTo("User-Agent");
assertThat(headers.value(0)).isEqualTo("OkHttp");
}
@Test public void addParsing() {
@ -103,10 +101,10 @@ public final class HeadersTest {
.add("ping: pong ") // Value whitespace is trimmed.
.add("kit:kat") // Space after colon is not required.
.build();
assertEquals(Arrays.asList("bar", "baz", "bak"), headers.values("foo"));
assertEquals(Arrays.asList("value"), headers.values("key"));
assertEquals(Arrays.asList("pong"), headers.values("ping"));
assertEquals(Arrays.asList("kat"), headers.values("kit"));
assertThat(headers.values("foo")).isEqualTo(Arrays.asList("bar", "baz", "bak"));
assertThat(headers.values("key")).isEqualTo(Arrays.asList("value"));
assertThat(headers.values("ping")).isEqualTo(Arrays.asList("pong"));
assertThat(headers.values("kit")).isEqualTo(Arrays.asList("kat"));
}
@Test public void addThrowsOnEmptyName() {
@ -145,8 +143,8 @@ public final class HeadersTest {
.build();
fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 1 in header name: héader1",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
"Unexpected char 0xe9 at 1 in header name: héader1");
}
}
@ -154,7 +152,7 @@ public final class HeadersTest {
Headers headers = new Headers.Builder()
.addUnsafeNonAscii("header1", "valué1")
.build();
assertEquals("header1: valué1\n", headers.toString());
assertThat(headers.toString()).isEqualTo("header1: valué1\n");
}
@Test public void ofThrowsOddNumberOfHeaders() {
@ -183,7 +181,7 @@ public final class HeadersTest {
@Test public void ofAcceptsEmptyValue() {
Headers headers = Headers.of("User-Agent", "");
assertEquals("", headers.value(0));
assertThat(headers.value(0)).isEqualTo("");
}
@Test public void ofMakesDefensiveCopy() {
@ -193,7 +191,7 @@ public final class HeadersTest {
};
Headers headers = Headers.of(namesAndValues);
namesAndValues[1] = "Chrome";
assertEquals("OkHttp", headers.value(0));
assertThat(headers.value(0)).isEqualTo("OkHttp");
}
@Test public void ofRejectsNullChar() {
@ -230,17 +228,17 @@ public final class HeadersTest {
@Test public void ofMapAcceptsEmptyValue() {
Headers headers = Headers.of(singletonMap("User-Agent", ""));
assertEquals("", headers.value(0));
assertThat(headers.value(0)).isEqualTo("");
}
@Test public void ofMapTrimsKey() {
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() {
Headers headers = Headers.of(singletonMap("User-Agent", " OkHttp "));
assertEquals("OkHttp", headers.value(0));
assertThat(headers.value(0)).isEqualTo("OkHttp");
}
@Test public void ofMapMakesDefensiveCopy() {
@ -249,7 +247,7 @@ public final class HeadersTest {
Headers headers = Headers.of(namesAndValues);
namesAndValues.put("User-Agent", "Chrome");
assertEquals("OkHttp", headers.value(0));
assertThat(headers.value(0)).isEqualTo("OkHttp");
}
@Test public void ofMapRejectsNullCharInName() {
@ -274,8 +272,8 @@ public final class HeadersTest {
"cache-control", "no-store",
"user-agent", "OkHttp");
Map<String, List<String>> headerMap = headers.toMultimap();
assertEquals(2, headerMap.get("cache-control").size());
assertEquals(1, headerMap.get("user-agent").size());
assertThat(headerMap.get("cache-control").size()).isEqualTo(2);
assertThat(headerMap.get("user-agent").size()).isEqualTo(1);
}
@Test public void toMultimapUsesCanonicalCase() {
@ -284,8 +282,8 @@ public final class HeadersTest {
"Cache-Control", "no-cache",
"User-Agent", "OkHttp");
Map<String, List<String>> headerMap = headers.toMultimap();
assertEquals(2, headerMap.get("cache-control").size());
assertEquals(1, headerMap.get("user-agent").size());
assertThat(headerMap.get("cache-control").size()).isEqualTo(2);
assertThat(headerMap.get("user-agent").size()).isEqualTo(1);
}
@Test public void toMultimapAllowsCaseInsensitiveGet() {
@ -293,8 +291,8 @@ public final class HeadersTest {
"cache-control", "no-store",
"Cache-Control", "no-cache");
Map<String, List<String>> headerMap = headers.toMultimap();
assertEquals(2, headerMap.get("cache-control").size());
assertEquals(2, headerMap.get("Cache-Control").size());
assertThat(headerMap.get("cache-control").size()).isEqualTo(2);
assertThat(headerMap.get("Cache-Control").size()).isEqualTo(2);
}
@Test public void nameIndexesAreStrict() {
@ -304,8 +302,8 @@ public final class HeadersTest {
fail();
} catch (IndexOutOfBoundsException expected) {
}
assertEquals("a", headers.name(0));
assertEquals("c", headers.name(1));
assertThat(headers.name(0)).isEqualTo("a");
assertThat(headers.name(1)).isEqualTo("c");
try {
headers.name(2);
fail();
@ -320,8 +318,8 @@ public final class HeadersTest {
fail();
} catch (IndexOutOfBoundsException expected) {
}
assertEquals("b", headers.value(0));
assertEquals("d", headers.value(1));
assertThat(headers.value(0)).isEqualTo("b");
assertThat(headers.value(1)).isEqualTo("d");
try {
headers.value(2);
fail();
@ -334,8 +332,8 @@ public final class HeadersTest {
new Headers.Builder().add("héader1", "value1");
fail("Should have complained about invalid name");
} catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 1 in header name: héader1",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
"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");
fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 4 in header1 value: valué1",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
"Unexpected char 0xe9 at 4 in header1 value: valué1");
}
}
@ -354,8 +352,8 @@ public final class HeadersTest {
Headers.of("héader1", "value1");
fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 1 in header name: héader1",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
"Unexpected char 0xe9 at 1 in header name: héader1");
}
}
@ -364,8 +362,8 @@ public final class HeadersTest {
Headers.of("header1", "valué1");
fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 4 in header1 value: valué1",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
"Unexpected char 0xe9 at 4 in header1 value: valué1");
}
}
@ -374,8 +372,8 @@ public final class HeadersTest {
Headers.of(singletonMap("héader1", "value1"));
fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 1 in header name: héader1",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
"Unexpected char 0xe9 at 1 in header name: héader1");
}
}
@ -384,8 +382,8 @@ public final class HeadersTest {
Headers.of(singletonMap("header1", "valué1"));
fail("Should have complained about invalid value");
} catch (IllegalArgumentException expected) {
assertEquals("Unexpected char 0xe9 at 4 in header1 value: valué1",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
"Unexpected char 0xe9 at 4 in header1 value: valué1");
}
}
@ -398,8 +396,8 @@ public final class HeadersTest {
.add("Connection", "close")
.add("Transfer-Encoding", "chunked")
.build();
assertEquals(headers1, headers2);
assertEquals(headers1.hashCode(), headers2.hashCode());
assertThat(headers2).isEqualTo(headers1);
assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode());
}
@Test public void headersNotEquals() {
@ -411,8 +409,8 @@ public final class HeadersTest {
.add("Connection", "keep-alive")
.add("Transfer-Encoding", "chunked")
.build();
assertNotEquals(headers1, headers2);
assertNotEquals(headers1.hashCode(), headers2.hashCode());
assertThat(headers2).isNotEqualTo(headers1);
assertThat(headers2.hashCode()).isNotEqualTo((long) headers1.hashCode());
}
@Test public void headersToString() {
@ -420,7 +418,7 @@ public final class HeadersTest {
.add("A", "a")
.add("B", "bb")
.build();
assertEquals("A: a\nB: bb\n", headers.toString());
assertThat(headers.toString()).isEqualTo("A: a\nB: bb\n");
}
@Test public void headersAddAll() {
@ -434,7 +432,7 @@ public final class HeadersTest {
.addAll(sourceHeaders)
.add("C", "c")
.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. */
@ -444,15 +442,15 @@ public final class HeadersTest {
+ "jdflkasdf\", qop=\"auth\", stale=\"FALSE\"")
.build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("Digest", challenges.get(0).scheme());
assertEquals("myrealm", challenges.get(0).realm());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams());
assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
}
@Test public void testDigestChallengeWithDifferentlyOrderedAuthParams() {
@ -461,15 +459,15 @@ public final class HeadersTest {
+ "dfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"")
.build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("Digest", challenges.get(0).scheme());
assertEquals("myrealm", challenges.get(0).realm());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams());
assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
}
@Test public void testDigestChallengeWithDifferentlyOrderedAuthParams2() {
@ -478,15 +476,15 @@ public final class HeadersTest {
+ "asdf\", realm=\"myrealm\", stale=\"FALSE\"")
.build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("Digest", challenges.get(0).scheme());
assertEquals("myrealm", challenges.get(0).realm());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams());
assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
}
@Test public void testDigestChallengeWithMissingRealm() {
@ -495,15 +493,15 @@ public final class HeadersTest {
+ "rlaskdfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"")
.build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("Digest", challenges.get(0).scheme());
assertNull(challenges.get(0).realm());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertThat(challenges.get(0).realm()).isNull();
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("underrealm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams());
assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
}
@Test public void testDigestChallengeWithAdditionalSpaces() {
@ -512,15 +510,15 @@ public final class HeadersTest {
+ "askdfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"")
.build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("Digest", challenges.get(0).scheme());
assertEquals("myrealm", challenges.get(0).realm());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams());
assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
}
@Test public void testDigestChallengeWithAdditionalSpacesBeforeFirstAuthParam() {
@ -529,15 +527,15 @@ public final class HeadersTest {
+ "aksjdflkasdf\", qop=\"auth\", stale=\"FALSE\"")
.build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("Digest", challenges.get(0).scheme());
assertEquals("myrealm", challenges.get(0).realm());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams());
assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
}
@Test public void testDigestChallengeWithCamelCasedNames() {
@ -546,15 +544,15 @@ public final class HeadersTest {
+ "dfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"")
.build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("DiGeSt", challenges.get(0).scheme());
assertEquals("myrealm", challenges.get(0).realm());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("DiGeSt");
assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams());
assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
}
@Test public void testDigestChallengeWithCamelCasedNames2() {
@ -564,25 +562,25 @@ public final class HeadersTest {
+ "jdflkasdf\", qop=\"auth\", stale=\"FALSE\"")
.build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("DIgEsT", challenges.get(0).scheme());
assertEquals("myrealm", challenges.get(0).realm());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("DIgEsT");
assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("nonce", "fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf");
expectedAuthParams.put("qop", "auth");
expectedAuthParams.put("stale", "FALSE");
assertEquals(expectedAuthParams, challenges.get(0).authParams());
assertThat(challenges.get(0).authParams()).isEqualTo(expectedAuthParams);
}
@Test public void testDigestChallengeWithTokenFormOfAuthParam() {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest realm=myrealm").build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("Digest", challenges.get(0).scheme());
assertEquals("myrealm", challenges.get(0).realm());
assertEquals(singletonMap("realm", "myrealm"), challenges.get(0).authParams());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertThat(challenges.get(0).realm()).isEqualTo("myrealm");
assertThat(challenges.get(0).authParams()).isEqualTo(singletonMap("realm", "myrealm"));
}
@Test public void testDigestChallengeWithoutAuthParams() {
@ -590,18 +588,18 @@ public final class HeadersTest {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest").build();
List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
assertEquals(1, challenges.size());
assertEquals("Digest", challenges.get(0).scheme());
assertNull(challenges.get(0).realm());
assertEquals(emptyMap(), challenges.get(0).authParams());
assertThat(challenges.size()).isEqualTo(1);
assertThat(challenges.get(0).scheme()).isEqualTo("Digest");
assertThat(challenges.get(0).realm()).isNull();
assertThat(challenges.get(0).authParams()).isEqualTo(emptyMap());
}
@Test public void basicChallenge() {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate: Basic realm=\"protected area\"")
.build();
assertEquals(singletonList(new Challenge("Basic", singletonMap("realm", "protected area"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
singletonList(new Challenge("Basic", singletonMap("realm", "protected area"))));
}
@Test public void basicChallengeWithCharset() {
@ -611,8 +609,8 @@ public final class HeadersTest {
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "protected area");
expectedAuthParams.put("charset", "UTF-8");
assertEquals(singletonList(new Challenge("Basic", expectedAuthParams)),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
singletonList(new Challenge("Basic", expectedAuthParams)));
}
@Test public void basicChallengeWithUnexpectedCharset() {
@ -623,74 +621,69 @@ public final class HeadersTest {
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "protected area");
expectedAuthParams.put("charset", "US-ASCII");
assertEquals(singletonList(new Challenge("Basic", expectedAuthParams)),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
singletonList(new Challenge("Basic", expectedAuthParams)));
}
@Test public void separatorsBeforeFirstChallenge() {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate", " , , Basic realm=myrealm")
.build();
assertEquals(singletonList(new Challenge("Basic", singletonMap("realm", "myrealm"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
singletonList(new Challenge("Basic", singletonMap("realm", "myrealm"))));
}
@Test public void spacesAroundKeyValueSeparator() {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Basic realm = \"myrealm\"")
.build();
assertEquals(singletonList(new Challenge("Basic", singletonMap("realm", "myrealm"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
singletonList(new Challenge("Basic", singletonMap("realm", "myrealm"))));
}
@Test public void multipleChallengesInOneHeader() {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Basic realm = \"myrealm\",Digest")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Basic", singletonMap("realm", "myrealm")),
new Challenge("Digest", Collections.emptyMap())),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Digest", Collections.emptyMap())));
}
@Test public void multipleChallengesWithSameSchemeButDifferentRealmInOneHeader() {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Basic realm = \"myrealm\",Basic realm=myotherrealm")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Basic", singletonMap("realm", "myrealm")),
new Challenge("Basic", singletonMap("realm", "myotherrealm"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Basic", singletonMap("realm", "myotherrealm"))));
}
@Test public void separatorsBeforeFirstAuthParam() {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest, Basic ,,realm=\"myrealm\"")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Basic", singletonMap("realm", "myrealm"))));
}
@Test public void onlyCommaBetweenChallenges() {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest,Basic realm=\"myrealm\"")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Basic", singletonMap("realm", "myrealm"))));
}
@Test public void multipleSeparatorsBetweenChallenges() {
Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest,,,, Basic ,,realm=\"myrealm\"")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Basic", singletonMap("realm", "myrealm"))));
}
@Test public void unknownAuthParams() {
@ -701,10 +694,9 @@ public final class HeadersTest {
Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("foo", "bar");
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", expectedAuthParams)),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Basic", expectedAuthParams)));
}
@Test public void escapedCharactersInQuotedString() {
@ -712,10 +704,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\"r\\ealm\"")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "my\\\"realm"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Basic", singletonMap("realm", "my\\\"realm"))));
}
@Test public void commaInQuotedStringAndBeforeFirstChallenge() {
@ -723,10 +714,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", ",Digest,,,, Basic ,,,realm=\"my, realm,\"")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "my, realm,"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Basic", singletonMap("realm", "my, realm,"))));
}
@Test public void unescapedDoubleQuoteInQuotedStringWithEvenNumberOfBackslashesInFront() {
@ -734,9 +724,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\\\"r\\ealm\"")
.build();
assertEquals(Arrays.asList(
new Challenge("Digest", Collections.emptyMap())),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap())));
}
@Test public void unescapedDoubleQuoteInQuotedString() {
@ -744,9 +733,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\"realm\"")
.build();
assertEquals(Arrays.asList(
new Challenge("Digest", Collections.emptyMap())),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap())));
}
@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")
.build();
assertEquals(Arrays.asList(
new Challenge("Digest", Collections.emptyMap())),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap())));
}
@Test public void token68InsteadOfAuthParams() {
@ -765,9 +752,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Other abc==")
.build();
assertEquals(singletonList(
new Challenge("Other", singletonMap(null, "abc=="))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
singletonList(
new Challenge("Other", singletonMap(null, "abc=="))));
}
@Test public void token68AndAuthParams() {
@ -775,9 +762,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Other abc==, realm=myrealm")
.build();
assertEquals(Arrays.asList(
new Challenge("Other", singletonMap(null, "abc=="))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Other", singletonMap(null, "abc=="))));
}
@Test public void repeatedAuthParamKey() {
@ -785,7 +771,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Other realm=myotherrealm, realm=myrealm")
.build();
assertEquals(emptyList(), HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(
emptyList());
}
@Test public void multipleAuthenticateHeaders() {
@ -794,10 +781,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Basic realm=myrealm")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Basic", singletonMap("realm", "myrealm"))));
}
@Test public void multipleAuthenticateHeadersInDifferentOrder() {
@ -806,10 +792,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Basic", singletonMap("realm", "myrealm")),
new Challenge("Digest", Collections.emptyMap())),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Digest", Collections.emptyMap())));
}
@Test public void multipleBasicAuthenticateHeaders() {
@ -818,23 +803,22 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Basic realm=myotherrealm")
.build();
assertEquals(Arrays.asList(
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList(
new Challenge("Basic", singletonMap("realm", "myrealm")),
new Challenge("Basic", singletonMap("realm", "myotherrealm"))),
HttpHeaders.parseChallenges(headers, "WWW-Authenticate"));
new Challenge("Basic", singletonMap("realm", "myotherrealm"))));
}
@Test public void byteCount() {
assertEquals(0L, Util.EMPTY_HEADERS.byteCount());
assertEquals(10L, new Headers.Builder()
assertThat(Util.EMPTY_HEADERS.byteCount()).isEqualTo(0L);
assertThat(new Headers.Builder()
.add("abc", "def")
.build()
.byteCount());
assertEquals(20L, new Headers.Builder()
.byteCount()).isEqualTo(10L);
assertThat(new Headers.Builder()
.add("abc", "def")
.add("ghi", "jkl")
.build()
.byteCount());
.byteCount()).isEqualTo(20L);
}
@Test public void addDate() {
@ -842,8 +826,8 @@ public final class HeadersTest {
Headers headers = new Headers.Builder()
.add("testDate", expected)
.build();
assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", headers.get("testDate"));
assertEquals(new Date(0L), headers.getDate("testDate"));
assertThat(headers.get("testDate")).isEqualTo("Thu, 01 Jan 1970 00:00:00 GMT");
assertThat(headers.getDate("testDate")).isEqualTo(new Date(0L));
}
@Test public void addDateNull() {
@ -853,7 +837,7 @@ public final class HeadersTest {
.build();
fail();
} 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()
.add("Test-Instant", expected)
.build();
assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", headers.get("Test-Instant"));
assertEquals(expected, headers.getInstant("Test-Instant"));
assertThat(headers.get("Test-Instant")).isEqualTo("Thu, 01 Jan 1970 00:00:00 GMT");
assertThat(headers.getInstant("Test-Instant")).isEqualTo(expected);
}
@Test public void addInstantNull() {
@ -873,7 +857,7 @@ public final class HeadersTest {
.build();
fail();
} 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))
.set("testDate", expected)
.build();
assertEquals("Thu, 01 Jan 1970 00:00:01 GMT", headers.get("testDate"));
assertEquals(expected, headers.getDate("testDate"));
assertThat(headers.get("testDate")).isEqualTo("Thu, 01 Jan 1970 00:00:01 GMT");
assertThat(headers.getDate("testDate")).isEqualTo(expected);
}
@Test public void setDateNull() {
@ -894,7 +878,7 @@ public final class HeadersTest {
.build();
fail();
} 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))
.set("Test-Instant", expected)
.build();
assertEquals("Thu, 01 Jan 1970 00:00:01 GMT", headers.get("Test-Instant"));
assertEquals(expected, headers.getInstant("Test-Instant"));
assertThat(headers.get("Test-Instant")).isEqualTo("Thu, 01 Jan 1970 00:00:01 GMT");
assertThat(headers.getInstant("Test-Instant")).isEqualTo(expected);
}
@Test public void setInstantNull() {
@ -915,7 +899,7 @@ public final class HeadersTest {
.build();
fail();
} 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.Test;
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.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class InterceptorTest {
@ -77,7 +72,7 @@ public final class InterceptorTest {
.build();
Response response = client.newCall(request).execute();
assertSame(interceptorResponse, response);
assertThat(response).isSameAs(interceptorResponse);
}
@Test public void networkInterceptorsCannotShortCircuitResponses() throws Exception {
@ -102,8 +97,8 @@ public final class InterceptorTest {
client.newCall(request).execute();
fail();
} catch (IllegalStateException expected) {
assertEquals("network interceptor " + interceptor + " must call proceed() exactly once",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
("network interceptor " + interceptor + " must call proceed() exactly once"));
}
}
@ -127,8 +122,8 @@ public final class InterceptorTest {
client.newCall(request).execute();
fail();
} catch (IllegalStateException expected) {
assertEquals("network interceptor " + interceptor + " must call proceed() exactly once",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
("network interceptor " + interceptor + " must call proceed() exactly once"));
}
}
@ -155,8 +150,8 @@ public final class InterceptorTest {
client.newCall(request).execute();
fail();
} catch (IllegalStateException expected) {
assertEquals("network interceptor " + interceptor + " must retain the same host and port",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
("network interceptor " + interceptor + " must retain the same host and port"));
}
}
@ -165,7 +160,7 @@ public final class InterceptorTest {
Interceptor interceptor = chain -> {
Connection connection = chain.connection();
assertNotNull(connection);
assertThat(connection).isNotNull();
return chain.proceed(chain.request());
};
client = client.newBuilder()
@ -186,14 +181,14 @@ public final class InterceptorTest {
Interceptor interceptor = chain -> {
// The network request has everything: User-Agent, Host, Accept-Encoding.
Request networkRequest = chain.request();
assertNotNull(networkRequest.header("User-Agent"));
assertEquals(server.getHostName() + ":" + server.getPort(),
networkRequest.header("Host"));
assertNotNull(networkRequest.header("Accept-Encoding"));
assertThat(networkRequest.header("User-Agent")).isNotNull();
assertThat(networkRequest.header("Host")).isEqualTo(
(server.getHostName() + ":" + server.getPort()));
assertThat(networkRequest.header("Accept-Encoding")).isNotNull();
// The network response also has everything, including the raw gzipped content.
Response networkResponse = chain.proceed(networkRequest);
assertEquals("gzip", networkResponse.header("Content-Encoding"));
assertThat(networkResponse.header("Content-Encoding")).isEqualTo("gzip");
return networkResponse;
};
client = client.newBuilder()
@ -205,14 +200,14 @@ public final class InterceptorTest {
.build();
// No extra headers in the application's request.
assertNull(request.header("User-Agent"));
assertNull(request.header("Host"));
assertNull(request.header("Accept-Encoding"));
assertThat(request.header("User-Agent")).isNull();
assertThat(request.header("Host")).isNull();
assertThat(request.header("Accept-Encoding")).isNull();
// No extra headers in the application's response.
Response response = client.newCall(request).execute();
assertNull(request.header("Content-Encoding"));
assertEquals("abcabcabc", response.body().string());
assertThat(request.header("Content-Encoding")).isNull();
assertThat(response.body().string()).isEqualTo("abcabcabc");
}
@Test public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception {
@ -240,8 +235,8 @@ public final class InterceptorTest {
client.newCall(request).execute();
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("POST", recordedRequest.getMethod());
assertEquals("abc", recordedRequest.getBody().readUtf8());
assertThat(recordedRequest.getMethod()).isEqualTo("POST");
assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("abc");
}
@Test public void applicationInterceptorsRewriteRequestToServer() throws Exception {
@ -272,10 +267,10 @@ public final class InterceptorTest {
client.newCall(request).execute();
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("ABC", recordedRequest.getBody().readUtf8());
assertEquals("foo", recordedRequest.getHeader("Original-Header"));
assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted"));
assertEquals("POST", recordedRequest.getMethod());
assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("ABC");
assertThat(recordedRequest.getHeader("Original-Header")).isEqualTo("foo");
assertThat(recordedRequest.getHeader("OkHttp-Intercepted")).isEqualTo("yep");
assertThat(recordedRequest.getMethod()).isEqualTo("POST");
}
@Test public void applicationInterceptorsRewriteResponseFromServer() throws Exception {
@ -304,9 +299,9 @@ public final class InterceptorTest {
.build();
Response response = client.newCall(request).execute();
assertEquals("ABC", response.body().string());
assertEquals("yep", response.header("OkHttp-Intercepted"));
assertEquals("foo", response.header("Original-Header"));
assertThat(response.body().string()).isEqualTo("ABC");
assertThat(response.header("OkHttp-Intercepted")).isEqualTo("yep");
assertThat(response.header("Original-Header")).isEqualTo("foo");
}
@Test public void multipleApplicationInterceptors() throws Exception {
@ -344,12 +339,12 @@ public final class InterceptorTest {
.build();
Response response = client.newCall(request).execute();
assertEquals(Arrays.asList("Cupcake", "Donut"),
response.headers("Response-Interceptor"));
assertThat(response.headers("Response-Interceptor")).isEqualTo(
Arrays.asList("Cupcake", "Donut"));
RecordedRequest recordedRequest = server.takeRequest();
assertEquals(Arrays.asList("Android", "Bob"),
recordedRequest.getHeaders().values("Request-Interceptor"));
assertThat(recordedRequest.getHeaders().values("Request-Interceptor")).isEqualTo(
Arrays.asList("Android", "Bob"));
}
@Test public void asyncApplicationInterceptors() throws Exception {
@ -397,7 +392,7 @@ public final class InterceptorTest {
.build();
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. */
@ -412,7 +407,7 @@ public final class InterceptorTest {
.url(server.url("/a"))
.build();
Response responseA = client.newCall(requestA).execute();
assertEquals("a", responseA.body().string());
assertThat(responseA.body().string()).isEqualTo("a");
}
return chain.proceed(chain.request());
@ -423,7 +418,7 @@ public final class InterceptorTest {
.url(server.url("/b"))
.build();
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. */
@ -482,7 +477,7 @@ public final class InterceptorTest {
client.newCall(request).execute();
fail();
} catch (RuntimeException expected) {
assertEquals("boom!", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo("boom!");
}
}
@ -507,9 +502,10 @@ public final class InterceptorTest {
.build();
Response response = client.newCall(request).execute();
assertNotNull(response.request().header("User-Agent"));
assertEquals("user request", response.request().header("User-Agent"));
assertEquals("intercepted request", response.networkResponse().request().header("User-Agent"));
assertThat(response.request().header("User-Agent")).isNotNull();
assertThat(response.request().header("User-Agent")).isEqualTo("user request");
assertThat(response.networkResponse().request().header("User-Agent")).isEqualTo(
"intercepted request");
}
@Test public void applicationInterceptorThrowsRuntimeExceptionAsynchronous() throws Exception {
@ -537,7 +533,7 @@ public final class InterceptorTest {
.build();
client.newCall(request).enqueue(callback);
assertEquals("boom!", executor.takeException().getMessage());
assertThat(executor.takeException().getMessage()).isEqualTo("boom!");
}
@Test public void applicationInterceptorReturnsNull() throws Exception {
@ -563,7 +559,8 @@ public final class InterceptorTest {
client.newCall(request).execute();
fail();
} 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();
fail();
} 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 -> {
Response response = chain.proceed(chain.request());
assertNotNull(chain.connection());
assertThat(chain.connection()).isNotNull();
return response;
};
@ -637,8 +635,8 @@ public final class InterceptorTest {
client.newCall(request).execute();
fail();
} catch (IllegalStateException expected) {
assertEquals("interceptor " + interceptor + " returned a response with no body",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
("interceptor " + interceptor + " returned a response with no body"));
}
}
@ -662,23 +660,23 @@ public final class InterceptorTest {
client.newCall(request).execute();
fail();
} catch (IllegalStateException expected) {
assertEquals("interceptor " + interceptor + " returned a response with no body",
expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
("interceptor " + interceptor + " returned a response with no body"));
}
}
@Test public void connectTimeout() throws Exception {
Interceptor interceptor1 = chainA -> {
assertEquals(5000, chainA.connectTimeoutMillis());
assertThat(chainA.connectTimeoutMillis()).isEqualTo(5000);
Interceptor.Chain chainB = chainA.withConnectTimeout(100, TimeUnit.MILLISECONDS);
assertEquals(100, chainB.connectTimeoutMillis());
assertThat(chainB.connectTimeoutMillis()).isEqualTo(100);
return chainB.proceed(chainA.request());
};
Interceptor interceptor2 = chain -> {
assertEquals(100, chain.connectTimeoutMillis());
assertThat(chain.connectTimeoutMillis()).isEqualTo(100);
return chain.proceed(chain.request());
};
@ -713,16 +711,16 @@ public final class InterceptorTest {
@Test public void chainWithReadTimeout() throws Exception {
Interceptor interceptor1 = chainA -> {
assertEquals(5000, chainA.readTimeoutMillis());
assertThat(chainA.readTimeoutMillis()).isEqualTo(5000);
Interceptor.Chain chainB = chainA.withReadTimeout(100, TimeUnit.MILLISECONDS);
assertEquals(100, chainB.readTimeoutMillis());
assertThat(chainB.readTimeoutMillis()).isEqualTo(100);
return chainB.proceed(chainA.request());
};
Interceptor interceptor2 = chain -> {
assertEquals(100, chain.readTimeoutMillis());
assertThat(chain.readTimeoutMillis()).isEqualTo(100);
return chain.proceed(chain.request());
};
@ -751,16 +749,16 @@ public final class InterceptorTest {
@Test public void chainWithWriteTimeout() throws Exception {
Interceptor interceptor1 = chainA -> {
assertEquals(5000, chainA.writeTimeoutMillis());
assertThat(chainA.writeTimeoutMillis()).isEqualTo(5000);
Interceptor.Chain chainB = chainA.withWriteTimeout(100, TimeUnit.MILLISECONDS);
assertEquals(100, chainB.writeTimeoutMillis());
assertThat(chainB.writeTimeoutMillis()).isEqualTo(100);
return chainB.proceed(chainA.request());
};
Interceptor interceptor2 = chain -> {
assertEquals(100, chain.writeTimeoutMillis());
assertThat(chain.writeTimeoutMillis()).isEqualTo(100);
return chain.proceed(chain.request());
};
@ -795,9 +793,9 @@ public final class InterceptorTest {
Call call = chain.call();
callRef.set(call);
assertFalse(call.isCanceled());
assertThat(call.isCanceled()).isFalse();
call.cancel();
assertTrue(call.isCanceled());
assertThat(call.isCanceled()).isTrue();
return chain.proceed(chain.request());
};
@ -817,7 +815,7 @@ public final class InterceptorTest {
} catch (IOException expected) {
}
assertSame(call, callRef.get());
assertThat(callRef.get()).isSameAs(call);
}
private RequestBody uppercase(RequestBody original) {

View File

@ -24,8 +24,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
/**
@ -55,13 +54,13 @@ public class MediaTypeTest {
@Test public void testParse() throws Exception {
MediaType mediaType = parse("text/plain;boundary=foo;charset=utf-8");
assertEquals("text", mediaType.type());
assertEquals("plain", mediaType.subtype());
assertEquals("UTF-8", mediaType.charset().name());
assertEquals("text/plain;boundary=foo;charset=utf-8", mediaType.toString());
assertEquals(mediaType, parse("text/plain;boundary=foo;charset=utf-8"));
assertEquals(mediaType.hashCode(),
parse("text/plain;boundary=foo;charset=utf-8").hashCode());
assertThat(mediaType.type()).isEqualTo("text");
assertThat(mediaType.subtype()).isEqualTo("plain");
assertThat(mediaType.charset().name()).isEqualTo("UTF-8");
assertThat(mediaType.toString()).isEqualTo("text/plain;boundary=foo;charset=utf-8");
assertThat(parse("text/plain;boundary=foo;charset=utf-8")).isEqualTo(mediaType);
assertThat(parse("text/plain;boundary=foo;charset=utf-8").hashCode()).isEqualTo(
(long) mediaType.hashCode());
}
@Test public void testValidParse() throws Exception {
@ -119,36 +118,36 @@ public class MediaTypeTest {
@Test public void testDoubleQuotesAreSpecial() throws Exception {
MediaType mediaType = parse("text/plain;a=\";charset=utf-8;b=\"");
assertNull(mediaType.charset());
assertThat(mediaType.charset()).isNull();
}
@Test public void testSingleQuotesAreNotSpecial() throws Exception {
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 {
MediaType mediaType = parse("!#$%&'*+-.{|}~/!#$%&'*+-.{|}~; !#$%&'*+-.{|}~=!#$%&'*+-.{|}~");
assertEquals("!#$%&'*+-.{|}~", mediaType.type());
assertEquals("!#$%&'*+-.{|}~", mediaType.subtype());
assertThat(mediaType.type()).isEqualTo("!#$%&'*+-.{|}~");
assertThat(mediaType.subtype()).isEqualTo("!#$%&'*+-.{|}~");
}
@Test public void testCharsetIsOneOfManyParameters() throws Exception {
MediaType mediaType = parse("text/plain;a=1;b=2;charset=utf-8;c=3");
assertEquals("text", mediaType.type());
assertEquals("plain", mediaType.subtype());
assertEquals("UTF-8", mediaType.charset().name());
assertThat(mediaType.type()).isEqualTo("text");
assertThat(mediaType.subtype()).isEqualTo("plain");
assertThat(mediaType.charset().name()).isEqualTo("UTF-8");
}
@Test public void testCharsetAndQuoting() throws Exception {
MediaType mediaType = parse(
"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() {
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() {
@ -158,12 +157,12 @@ public class MediaTypeTest {
@Test public void testIllegalCharsetName() {
MediaType mediaType = parse("text/plain; charset=\"!@#$%^&*()\"");
assertNull(mediaType.charset());
assertThat(mediaType.charset()).isNull();
}
@Test public void testUnsupportedCharset() {
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 {
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 {
MediaType mediaType = parse("text/plain;charset=\"'utf-8'\"");
assertNull(mediaType.charset());
assertThat(mediaType.charset()).isNull();
}
@Test public void testCharsetNameIsDoubleQuotedSingleQuote() throws Exception {
MediaType mediaType = parse("text/plain;charset=\"'\"");
assertNull(mediaType.charset());
assertThat(mediaType.charset()).isNull();
}
@Test public void testDefaultCharset() throws Exception {
MediaType noCharset = parse("text/plain");
assertEquals("UTF-8", noCharset.charset(UTF_8).name());
assertEquals("US-ASCII", noCharset.charset(Charset.forName("US-ASCII")).name());
assertThat(noCharset.charset(UTF_8).name()).isEqualTo("UTF-8");
assertThat(noCharset.charset(Charset.forName("US-ASCII")).name()).isEqualTo("US-ASCII");
MediaType charset = parse("text/plain; charset=iso-8859-1");
assertEquals("ISO-8859-1", charset.charset(UTF_8).name());
assertEquals("ISO-8859-1", charset.charset(Charset.forName("US-ASCII")).name());
assertThat(charset.charset(UTF_8).name()).isEqualTo("ISO-8859-1");
assertThat(charset.charset(Charset.forName("US-ASCII")).name()).isEqualTo("ISO-8859-1");
}
@Test public void testParseDanglingSemicolon() throws Exception {
MediaType mediaType = parse("text/plain;");
assertEquals("text", mediaType.type());
assertEquals("plain", mediaType.subtype());
assertNull(mediaType.charset());
assertEquals("text/plain;", mediaType.toString());
assertThat(mediaType.type()).isEqualTo("text");
assertThat(mediaType.subtype()).isEqualTo("plain");
assertThat(mediaType.charset()).isNull();
assertThat(mediaType.toString()).isEqualTo("text/plain;");
}
private void assertMediaType(String string) {
assertEquals(string, parse(string).toString());
assertThat(parse(string).toString()).isEqualTo(string);
}
private void assertInvalid(String string, String exceptionMessage) {
@ -213,10 +212,10 @@ public class MediaTypeTest {
parse(string);
fail("Expected get of \"" + string + "\" to throw with: " + exceptionMessage);
} catch (IllegalArgumentException e) {
assertEquals(exceptionMessage, e.getMessage());
assertThat(e.getMessage()).isEqualTo(exceptionMessage);
}
} 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 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;
public final class MultipartBodyTest {
@ -30,7 +30,7 @@ public final class MultipartBodyTest {
new MultipartBody.Builder().build();
fail();
} 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!"))
.build();
assertEquals("123", body.boundary());
assertEquals(MultipartBody.MIXED, body.type());
assertEquals("multipart/mixed; boundary=123", body.contentType().toString());
assertEquals(1, body.parts().size());
assertEquals(53, body.contentLength());
assertThat(body.boundary()).isEqualTo("123");
assertThat(body.type()).isEqualTo(MultipartBody.MIXED);
assertThat(body.contentType().toString()).isEqualTo("multipart/mixed; boundary=123");
assertThat(body.parts().size()).isEqualTo(1);
assertThat(body.contentLength()).isEqualTo(53);
Buffer buffer = new Buffer();
body.writeTo(buffer);
assertEquals(buffer.size(), body.contentLength());
assertEquals(expected, buffer.readUtf8());
assertThat(body.contentLength()).isEqualTo(buffer.size());
assertThat(buffer.readUtf8()).isEqualTo(expected);
}
@Test public void threeParts() throws Exception {
@ -80,16 +80,16 @@ public final class MultipartBodyTest {
.addPart(RequestBody.create(null, "Fox"))
.build();
assertEquals("123", body.boundary());
assertEquals(MultipartBody.MIXED, body.type());
assertEquals("multipart/mixed; boundary=123", body.contentType().toString());
assertEquals(3, body.parts().size());
assertEquals(112, body.contentLength());
assertThat(body.boundary()).isEqualTo("123");
assertThat(body.type()).isEqualTo(MultipartBody.MIXED);
assertThat(body.contentType().toString()).isEqualTo("multipart/mixed; boundary=123");
assertThat(body.parts().size()).isEqualTo(3);
assertThat(body.contentLength()).isEqualTo(112);
Buffer buffer = new Buffer();
body.writeTo(buffer);
assertEquals(buffer.size(), body.contentLength());
assertEquals(expected, buffer.readUtf8());
assertThat(body.contentLength()).isEqualTo(buffer.size());
assertThat(buffer.readUtf8()).isEqualTo(expected);
}
@Test public void fieldAndTwoFiles() throws Exception {
@ -140,16 +140,17 @@ public final class MultipartBodyTest {
.build())
.build();
assertEquals("AaB03x", body.boundary());
assertEquals(MultipartBody.FORM, body.type());
assertEquals("multipart/form-data; boundary=AaB03x", body.contentType().toString());
assertEquals(2, body.parts().size());
assertEquals(568, body.contentLength());
assertThat(body.boundary()).isEqualTo("AaB03x");
assertThat(body.type()).isEqualTo(MultipartBody.FORM);
assertThat(body.contentType().toString()).isEqualTo(
"multipart/form-data; boundary=AaB03x");
assertThat(body.parts().size()).isEqualTo(2);
assertThat(body.contentLength()).isEqualTo(568);
Buffer buffer = new Buffer();
body.writeTo(buffer);
assertEquals(buffer.size(), body.contentLength());
assertEquals(expected, buffer.readUtf8());
assertThat(body.contentLength()).isEqualTo(buffer.size());
assertThat(buffer.readUtf8()).isEqualTo(expected);
}
@Test public void stringEscapingIsWeird() throws Exception {
@ -188,7 +189,7 @@ public final class MultipartBodyTest {
Buffer buffer = new Buffer();
body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8());
assertThat(buffer.readUtf8()).isEqualTo(expected);
}
@Test public void streamingPartHasNoLength() throws Exception {
@ -228,15 +229,15 @@ public final class MultipartBodyTest {
.addPart(RequestBody.create(null, "Fox"))
.build();
assertEquals("123", body.boundary());
assertEquals(MultipartBody.MIXED, body.type());
assertEquals("multipart/mixed; boundary=123", body.contentType().toString());
assertEquals(3, body.parts().size());
assertEquals(-1, body.contentLength());
assertThat(body.boundary()).isEqualTo("123");
assertThat(body.type()).isEqualTo(MultipartBody.MIXED);
assertThat(body.contentType().toString()).isEqualTo("multipart/mixed; boundary=123");
assertThat(body.parts().size()).isEqualTo(3);
assertThat(body.contentLength()).isEqualTo(-1);
Buffer buffer = new Buffer();
body.writeTo(buffer);
assertEquals(expected, buffer.readUtf8());
assertThat(buffer.readUtf8()).isEqualTo(expected);
}
@Test public void contentTypeHeaderIsForbidden() throws Exception {
@ -263,13 +264,13 @@ public final class MultipartBodyTest {
MultipartBody body = new MultipartBody.Builder()
.addPart(Headers.of("Foo", "Bar"), RequestBody.create(null, "Baz"))
.build();
assertEquals(1, body.parts().size());
assertThat(body.parts().size()).isEqualTo(1);
Buffer part1Buffer = new Buffer();
MultipartBody.Part part1 = body.part(0);
part1.body().writeTo(part1Buffer);
assertEquals(Headers.of("Foo", "Bar"), part1.headers());
assertEquals("Baz", part1Buffer.readUtf8());
assertThat(part1.headers()).isEqualTo(Headers.of("Foo", "Bar"));
assertThat(part1Buffer.readUtf8()).isEqualTo("Baz");
}
@Test public void nonAsciiFilename() throws Exception {
@ -290,6 +291,6 @@ public final class MultipartBodyTest {
Buffer buffer = new 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 static okhttp3.TestUtil.defaultClient;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class OkHttpClientTest {
@ -53,11 +51,11 @@ public final class OkHttpClientTest {
@Test public void durationDefaults() {
OkHttpClient client = defaultClient();
assertEquals(0, client.callTimeoutMillis());
assertEquals(10_000, client.connectTimeoutMillis());
assertEquals(10_000, client.readTimeoutMillis());
assertEquals(10_000, client.writeTimeoutMillis());
assertEquals(0, client.pingIntervalMillis());
assertThat(client.callTimeoutMillis()).isEqualTo(0);
assertThat(client.connectTimeoutMillis()).isEqualTo(10_000);
assertThat(client.readTimeoutMillis()).isEqualTo(10_000);
assertThat(client.writeTimeoutMillis()).isEqualTo(10_000);
assertThat(client.pingIntervalMillis()).isEqualTo(0);
}
@Test public void timeoutValidRange() {
@ -103,8 +101,8 @@ public final class OkHttpClientTest {
.addInterceptor(interceptor)
.addNetworkInterceptor(interceptor)
.build();
assertEquals(0, original.interceptors().size());
assertEquals(0, original.networkInterceptors().size());
assertThat(original.interceptors().size()).isEqualTo(0);
assertThat(original.networkInterceptors().size()).isEqualTo(0);
}
/**
@ -116,15 +114,15 @@ public final class OkHttpClientTest {
// Values should be non-null.
OkHttpClient a = client.newBuilder().build();
assertNotNull(a.dispatcher());
assertNotNull(a.connectionPool());
assertNotNull(a.sslSocketFactory());
assertThat(a.dispatcher()).isNotNull();
assertThat(a.connectionPool()).isNotNull();
assertThat(a.sslSocketFactory()).isNotNull();
// Multiple clients share the instances.
OkHttpClient b = client.newBuilder().build();
assertSame(a.dispatcher(), b.dispatcher());
assertSame(a.connectionPool(), b.connectionPool());
assertSame(a.sslSocketFactory(), b.sslSocketFactory());
assertThat(b.dispatcher()).isSameAs(a.dispatcher());
assertThat(b.connectionPool()).isSameAs(a.connectionPool());
assertThat(b.sslSocketFactory()).isSameAs(a.sslSocketFactory());
}
@Test public void setProtocolsRejectsHttp10() throws Exception {
@ -139,7 +137,7 @@ public final class OkHttpClientTest {
@Test public void certificatePinnerEquality() {
OkHttpClient clientA = TestUtil.defaultClient();
OkHttpClient clientB = TestUtil.defaultClient();
assertEquals(clientA.certificatePinner(), clientB.certificatePinner());
assertThat(clientB.certificatePinner()).isEqualTo(clientA.certificatePinner());
}
@Test public void nullInterceptor() {
@ -148,7 +146,7 @@ public final class OkHttpClientTest {
builder.addInterceptor(null);
fail();
} 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);
fail();
} catch (IllegalArgumentException expected) {
assertEquals("interceptor == null", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo("interceptor == null");
}
}
@ -169,7 +167,7 @@ public final class OkHttpClientTest {
builder.build();
fail();
} 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();
fail();
} 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));
fail();
} catch (IllegalArgumentException expected) {
assertEquals("protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, http/1.1]", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
("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));
fail();
} catch (IllegalArgumentException expected) {
assertEquals("protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, h2_prior_knowledge]", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo(
("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()
.protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE))
.build();
assertEquals(1, okHttpClient.protocols().size());
assertEquals(Protocol.H2_PRIOR_KNOWLEDGE, okHttpClient.protocols().get(0));
assertThat(okHttpClient.protocols().size()).isEqualTo(1);
assertThat(okHttpClient.protocols().get(0)).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE);
}
@Test public void nullDefaultProxySelector() throws Exception {
@ -224,7 +224,7 @@ public final class OkHttpClientTest {
Request request = new Request.Builder().url(server.url("/")).build();
Response response = client.newCall(request).execute();
assertEquals("abc", response.body().string());
assertThat(response.body().string()).isEqualTo("abc");
}
@Test public void sslSocketFactorySetAsSocketFactory() throws Exception {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -29,7 +29,7 @@ import org.junit.Before;
import org.junit.Test;
import static okhttp3.TestUtil.defaultClient;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
public final class SocksProxyTest {
private final SocksProxy socksProxy = new SocksProxy();
@ -55,14 +55,14 @@ public final class SocksProxyTest {
Request request1 = new Request.Builder().url(server.url("/")).build();
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();
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.
assertEquals(1, socksProxy.connectionCount());
assertThat(socksProxy.connectionCount()).isEqualTo(1);
}
@Test public void proxySelector() throws Exception {
@ -84,9 +84,9 @@ public final class SocksProxyTest {
Request request = new Request.Builder().url(server.url("/")).build();
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 {
@ -104,8 +104,8 @@ public final class SocksProxyTest {
Request request = new Request.Builder().url(url).build();
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.Parameter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
/** Runs the web platform URL tests against Java URL models. */
@RunWith(Parameterized.class)
@ -101,9 +99,10 @@ public final class WebPlatformUrlTest {
}
if (testData.expectParseFailure()) {
assertNull("Expected URL to fail parsing", url);
assertThat(url).overridingErrorMessage("Expected URL to fail parsing").isNull();
} 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())
? Integer.toString(url.port())
: "";
@ -112,12 +111,13 @@ public final class WebPlatformUrlTest {
String effectiveHost = url.host().contains(":")
? ("[" + url.host() + "]")
: url.host();
assertEquals("scheme", testData.scheme, url.scheme());
assertEquals("host", testData.host, effectiveHost);
assertEquals("port", testData.port, effectivePort);
assertEquals("path", testData.path, url.encodedPath());
assertEquals("query", testData.query, effectiveQuery);
assertEquals("fragment", testData.fragment, effectiveFragment);
assertThat(url.scheme()).overridingErrorMessage("scheme").isEqualTo(testData.scheme);
assertThat(effectiveHost).overridingErrorMessage("host").isEqualTo(testData.host);
assertThat(effectivePort).overridingErrorMessage("port").isEqualTo(testData.port);
assertThat(url.encodedPath()).overridingErrorMessage("path").isEqualTo(testData.path);
assertThat(effectiveQuery).overridingErrorMessage("query").isEqualTo(testData.query);
assertThat(effectiveFragment).overridingErrorMessage("fragment").isEqualTo(
testData.fragment);
}
}

View File

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

View File

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

View File

@ -30,7 +30,7 @@ import org.junit.Rule;
import org.junit.Test;
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;
public final class FileOperatorTest {
@ -55,10 +55,10 @@ public final class FileOperatorTest {
Buffer buffer = new Buffer();
operator.read(0, buffer, 5);
assertEquals("Hello", buffer.readUtf8());
assertThat(buffer.readUtf8()).isEqualTo("Hello");
operator.read(4, buffer, 5);
assertEquals("o, Wo", buffer.readUtf8());
assertThat(buffer.readUtf8()).isEqualTo("o, Wo");
}
@Test public void write() throws Exception {
@ -66,13 +66,13 @@ public final class FileOperatorTest {
Buffer buffer1 = new Buffer().writeUtf8("Hello, World");
operator.write(0, buffer1, 5);
assertEquals(", World", buffer1.readUtf8());
assertThat(buffer1.readUtf8()).isEqualTo(", World");
Buffer buffer2 = new Buffer().writeUtf8("icopter!");
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 {
@ -99,12 +99,12 @@ public final class FileOperatorTest {
operator.read(4, buffer, 19);
operator.write(80, buffer, buffer.size());
assertEquals(snapshot(), ByteString.encodeUtf8(""
assertThat(ByteString.encodeUtf8(""
+ "god creates dinosaurs. "
+ "god destroys dinosaurs. "
+ "god creates man. "
+ "man destroys god. "
+ "man creates dinosaurs. "));
+ "man creates dinosaurs. ")).isEqualTo(snapshot());
}
@Test public void multipleOperatorsShareOneFile() throws Exception {
@ -124,13 +124,13 @@ public final class FileOperatorTest {
operatorA.write(36, bufferA, 33);
operatorB.read(0, bufferB, 9);
assertEquals("Dodgson!\n", bufferB.readUtf8());
assertThat(bufferB.readUtf8()).isEqualTo("Dodgson!\n");
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);
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 {
@ -141,7 +141,7 @@ public final class FileOperatorTest {
Buffer buffer = new Buffer();
operator.read(0, buffer, data.size());
assertEquals(data, buffer.readByteString());
assertThat(buffer.readByteString()).isEqualTo(data);
}
@Test public void largeWrite() throws Exception {
@ -152,7 +152,7 @@ public final class FileOperatorTest {
Buffer buffer = new Buffer().write(data);
operator.write(0, buffer, data.size());
assertEquals(data, snapshot());
assertThat(snapshot()).isEqualTo(data);
}
@Test public void readBounds() throws Exception {

View File

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

View File

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

View File

@ -29,9 +29,7 @@ import okhttp3.tls.HandshakeCertificates;
import org.junit.Test;
import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
public class ConnectionSpecSelectorTest {
static {
@ -52,7 +50,7 @@ public class ConnectionSpecSelectorTest {
boolean retry = connectionSpecSelector.connectionFailed(
new IOException("Non-handshake exception"));
assertFalse(retry);
assertThat(retry).isFalse();
socket.close();
}
@ -67,7 +65,7 @@ public class ConnectionSpecSelectorTest {
new SSLHandshakeException("Certificate handshake exception");
trustIssueException.initCause(new CertificateException());
boolean retry = connectionSpecSelector.connectionFailed(trustIssueException);
assertFalse(retry);
assertThat(retry).isFalse();
socket.close();
}
@ -80,7 +78,7 @@ public class ConnectionSpecSelectorTest {
connectionSpecSelector.configureSecureSocket(socket);
boolean retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION);
assertTrue(retry);
assertThat(retry).isTrue();
socket.close();
}
@ -103,7 +101,7 @@ public class ConnectionSpecSelectorTest {
assertEnabledProtocols(socket, TlsVersion.TLS_1_2);
boolean retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION);
assertTrue(retry);
assertThat(retry).isTrue();
socket.close();
// 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);
retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION);
assertFalse(retry);
assertThat(retry).isFalse();
socket.close();
// 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) {
Set<String> actual = new LinkedHashSet<>(Arrays.asList(socket.getEnabledProtocols()));
Set<String> expected = new LinkedHashSet<>(Arrays.asList(javaNames(required)));
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
private static String[] javaNames(TlsVersion... tlsVersions) {

View File

@ -18,16 +18,15 @@ package okhttp3.internal.connection;
import java.io.IOException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.assertj.core.api.Assertions.assertThat;
public class RouteExceptionTest {
@Test public void getConnectionIOException_single() {
IOException firstException = new IOException();
RouteException re = new RouteException(firstException);
assertSame(firstException, re.getFirstConnectException());
assertSame(firstException, re.getLastConnectException());
assertThat(re.getFirstConnectException()).isSameAs(firstException);
assertThat(re.getLastConnectException()).isSameAs(firstException);
}
@Test public void getConnectionIOException_multiple() {
@ -39,12 +38,12 @@ public class RouteExceptionTest {
re.addConnectException(thirdException);
IOException connectionIOException = re.getFirstConnectException();
assertSame(firstException, connectionIOException);
assertThat(connectionIOException).isSameAs(firstException);
Throwable[] suppressedExceptions = connectionIOException.getSuppressed();
assertEquals(2, suppressedExceptions.length);
assertSame(secondException, suppressedExceptions[0]);
assertSame(thirdException, suppressedExceptions[1]);
assertThat(suppressedExceptions.length).isEqualTo(2);
assertThat(suppressedExceptions[0]).isSameAs(secondException);
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 okhttp3.tls.internal.TlsUtil.localhost;
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.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class RouteSelectorTest {
@ -89,19 +86,19 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE);
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(1));
RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
dns.assertRequests(uriHost);
assertFalse(selection.hasNext());
assertThat(selection.hasNext()).isFalse();
try {
selection.next();
fail();
} catch (NoSuchElementException expected) {
}
assertFalse(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isFalse();
try {
routeSelector.next();
fail();
@ -114,7 +111,7 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE);
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(1));
RouteSelector.Selection selection = routeSelector.next();
Route route = selection.next();
@ -122,7 +119,7 @@ public final class RouteSelectorTest {
routeSelector = new RouteSelector(address, routeDatabase, null, EventListener.NONE);
selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
assertFalse(selection.hasNext());
assertThat(selection.hasNext()).isFalse();
try {
selection.next();
@ -130,7 +127,7 @@ public final class RouteSelectorTest {
} catch (NoSuchElementException expected) {
}
assertFalse(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isFalse();
try {
routeSelector.next();
fail();
@ -144,14 +141,14 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE);
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyAHost, dns.allocate(2));
RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
assertRoute(selection.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort);
assertFalse(selection.hasNext());
assertFalse(routeSelector.hasNext());
assertThat(selection.hasNext()).isFalse();
assertThat(routeSelector.hasNext()).isFalse();
dns.assertRequests(proxyAHost);
proxySelector.assertRequests(); // No proxy selector requests!
}
@ -162,14 +159,14 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE);
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(2));
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, 1), uriPort);
assertFalse(selection.hasNext());
assertFalse(routeSelector.hasNext());
assertThat(selection.hasNext()).isFalse();
assertThat(routeSelector.hasNext()).isFalse();
dns.assertRequests(uriHost);
proxySelector.assertRequests(); // No proxy selector requests!
}
@ -177,7 +174,7 @@ public final class RouteSelectorTest {
@Test public void proxySelectorReturnsNull() throws Exception {
ProxySelector nullProxySelector = new ProxySelector() {
@Override public List<Proxy> select(URI uri) {
assertEquals(uriHost, uri.getHost());
assertThat(uri.getHost()).isEqualTo(uriHost);
return null;
}
@ -191,14 +188,14 @@ public final class RouteSelectorTest {
authenticator, null, protocols, connectionSpecs, nullProxySelector);
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE);
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(1));
RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
dns.assertRequests(uriHost);
assertFalse(selection.hasNext());
assertFalse(routeSelector.hasNext());
assertThat(selection.hasNext()).isFalse();
assertThat(routeSelector.hasNext()).isFalse();
}
@Test public void proxySelectorReturnsNoProxies() throws Exception {
@ -206,14 +203,14 @@ public final class RouteSelectorTest {
RouteSelector routeSelector = new RouteSelector(address, routeDatabase, null,
EventListener.NONE);
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(2));
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, 1), uriPort);
assertFalse(selection.hasNext());
assertFalse(routeSelector.hasNext());
assertThat(selection.hasNext()).isFalse();
assertThat(routeSelector.hasNext()).isFalse();
dns.assertRequests(uriHost);
proxySelector.assertRequests(address.url().uri());
}
@ -228,24 +225,24 @@ public final class RouteSelectorTest {
proxySelector.assertRequests(address.url().uri());
// First try the IP addresses of the first proxy, in sequence.
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyAHost, dns.allocate(2));
RouteSelector.Selection selection1 = routeSelector.next();
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort);
dns.assertRequests(proxyAHost);
assertFalse(selection1.hasNext());
assertThat(selection1.hasNext()).isFalse();
// Next try the IP address of the second proxy.
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyBHost, dns.allocate(1));
RouteSelector.Selection selection2 = routeSelector.next();
assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort);
dns.assertRequests(proxyBHost);
assertFalse(selection2.hasNext());
assertThat(selection2.hasNext()).isFalse();
// No more proxies to try.
assertFalse(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isFalse();
}
@Test public void proxySelectorDirectConnectionsAreSkipped() throws Exception {
@ -257,14 +254,14 @@ public final class RouteSelectorTest {
proxySelector.assertRequests(address.url().uri());
// Only the origin server will be attempted.
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(uriHost, dns.allocate(1));
RouteSelector.Selection selection = routeSelector.next();
assertRoute(selection.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
dns.assertRequests(uriHost);
assertFalse(selection.hasNext());
assertFalse(routeSelector.hasNext());
assertThat(selection.hasNext()).isFalse();
assertThat(routeSelector.hasNext()).isFalse();
}
@Test public void proxyDnsFailureContinuesToNextProxy() throws Exception {
@ -277,14 +274,14 @@ public final class RouteSelectorTest {
EventListener.NONE);
proxySelector.assertRequests(address.url().uri());
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyAHost, dns.allocate(1));
RouteSelector.Selection selection1 = routeSelector.next();
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
dns.assertRequests(proxyAHost);
assertFalse(selection1.hasNext());
assertThat(selection1.hasNext()).isFalse();
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.clear(proxyBHost);
try {
routeSelector.next();
@ -293,14 +290,14 @@ public final class RouteSelectorTest {
}
dns.assertRequests(proxyBHost);
assertTrue(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isTrue();
dns.set(proxyAHost, dns.allocate(1));
RouteSelector.Selection selection2 = routeSelector.next();
assertRoute(selection2.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
dns.assertRequests(proxyAHost);
assertFalse(selection2.hasNext());
assertFalse(routeSelector.hasNext());
assertThat(selection2.hasNext()).isFalse();
assertThat(routeSelector.hasNext()).isFalse();
}
@Test public void multipleProxiesMultipleInetAddressesMultipleConfigurations() throws Exception {
@ -316,7 +313,7 @@ public final class RouteSelectorTest {
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
dns.assertRequests(proxyAHost);
assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort);
assertFalse(selection1.hasNext());
assertThat(selection1.hasNext()).isFalse();
// Proxy B
dns.set(proxyBHost, dns.allocate(2));
@ -324,10 +321,10 @@ public final class RouteSelectorTest {
assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort);
dns.assertRequests(proxyBHost);
assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 1), proxyBPort);
assertFalse(selection2.hasNext());
assertThat(selection2.hasNext()).isFalse();
// No more proxies to attempt.
assertFalse(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isFalse();
}
@Test public void failedRouteWithSingleProxy() throws Exception {
@ -343,7 +340,7 @@ public final class RouteSelectorTest {
List<Route> regularRoutes = selection1.getAll();
// 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.
routeDatabase.failed(regularRoutes.get(0));
// Reset selector
@ -351,15 +348,15 @@ public final class RouteSelectorTest {
// The first selection prioritizes the non-failed routes.
RouteSelector.Selection selection2 = routeSelector.next();
assertEquals(regularRoutes.get(1), selection2.next());
assertFalse(selection2.hasNext());
assertThat(selection2.next()).isEqualTo(regularRoutes.get(1));
assertThat(selection2.hasNext()).isFalse();
// The second selection will contain all failed routes.
RouteSelector.Selection selection3 = routeSelector.next();
assertEquals(regularRoutes.get(0), selection3.next());
assertFalse(selection3.hasNext());
assertThat(selection3.next()).isEqualTo(regularRoutes.get(0));
assertThat(selection3.hasNext()).isFalse();
assertFalse(routeSelector.hasNext());
assertThat(routeSelector.hasNext()).isFalse();
}
@Test public void failedRouteWithMultipleProxies() throws IOException {
@ -385,15 +382,15 @@ public final class RouteSelectorTest {
RouteSelector.Selection selection2 = routeSelector.next();
dns.assertRequests(proxyAHost, proxyBHost);
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.
RouteSelector.Selection selection3 = routeSelector.next();
dns.assertRequests();
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 {
@ -409,42 +406,42 @@ public final class RouteSelectorTest {
assertRoute(routes.get(0), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
assertRoute(routes.get(1), address, NO_PROXY, dns.lookup(uriHost, 1), uriPort);
assertSame(routes.get(0), selection.next());
assertSame(routes.get(1), selection.next());
assertFalse(selection.hasNext());
assertFalse(routeSelector.hasNext());
assertThat(selection.next()).isSameAs(routes.get(0));
assertThat(selection.next()).isSameAs(routes.get(1));
assertThat(selection.hasNext()).isFalse();
assertThat(routeSelector.hasNext()).isFalse();
}
@Test public void getHostString() throws Exception {
// Name proxy specification.
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);
assertEquals("127.0.0.1", RouteSelector.getHostString(socketAddress));
assertThat(RouteSelector.getHostString(socketAddress)).isEqualTo("127.0.0.1");
// InetAddress proxy specification.
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(
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(
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 {
Route route = new Route(httpAddress(), Proxy.NO_PROXY,
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,
int socketPort) {
assertEquals(address, route.address());
assertEquals(proxy, route.proxy());
assertEquals(socketAddress, route.socketAddress().getAddress());
assertEquals(socketPort, route.socketAddress().getPort());
assertThat(route.address()).isEqualTo(address);
assertThat(route.proxy()).isEqualTo(proxy);
assertThat(route.socketAddress().getAddress()).isEqualTo(socketAddress);
assertThat(route.socketAddress().getPort()).isEqualTo(socketPort);
}
/** 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.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
public class HttpDateTest {
@ -43,48 +42,51 @@ public class HttpDateTest {
@Test public void parseStandardFormats() throws Exception {
// RFC 822, updated by RFC 1123 with GMT.
assertEquals(0L, HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT").getTime());
assertEquals(1402057830000L, HttpDate.parse("Fri, 06 Jun 2014 12:30:30 GMT").getTime());
assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT").getTime()).isEqualTo(0L);
assertThat(HttpDate.parse("Fri, 06 Jun 2014 12:30:30 GMT").getTime()).isEqualTo(1402057830000L);
// RFC 850, obsoleted by RFC 1036 with GMT.
assertEquals(0L, HttpDate.parse("Thursday, 01-Jan-70 00:00:00 GMT").getTime());
assertEquals(1402057830000L, HttpDate.parse("Friday, 06-Jun-14 12:30:30 GMT").getTime());
assertThat(HttpDate.parse("Thursday, 01-Jan-70 00:00:00 GMT").getTime()).isEqualTo(0L);
assertThat(HttpDate.parse("Friday, 06-Jun-14 12:30:30 GMT").getTime()).isEqualTo(1402057830000L);
// ANSI C's asctime(): should use GMT, not platform default.
assertEquals(0L, HttpDate.parse("Thu Jan 1 00:00:00 1970").getTime());
assertEquals(1402057830000L, HttpDate.parse("Fri Jun 6 12:30:30 2014").getTime());
assertThat(HttpDate.parse("Thu Jan 1 00:00:00 1970").getTime()).isEqualTo(0L);
assertThat(HttpDate.parse("Fri Jun 6 12:30:30 2014").getTime()).isEqualTo(1402057830000L);
}
@Test public void format() throws Exception {
assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", HttpDate.format(new Date(0)));
assertEquals("Fri, 06 Jun 2014 12:30:30 GMT", HttpDate.format(new Date(1402057830000L)));
assertThat(HttpDate.format(new Date(0))).isEqualTo("Thu, 01 Jan 1970 00:00:00 GMT");
assertThat(HttpDate.format(new Date(1402057830000L))).isEqualTo(
"Fri, 06 Jun 2014 12:30:30 GMT");
}
@Test public void parseNonStandardStrings() throws Exception {
// RFC 822, updated by RFC 1123 with any TZ
assertEquals(3600000L, HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT-01:00").getTime());
assertEquals(28800000L, HttpDate.parse("Thu, 01 Jan 1970 00:00:00 PST").getTime());
assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00:00 GMT-01:00").getTime()).isEqualTo(3600000L);
assertThat(HttpDate.parse("Thu, 01 Jan 1970 00:00:00 PST").getTime()).isEqualTo(28800000L);
// 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.
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.
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.
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.
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.
assertEquals(3600000L, HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 GMT-01:00").getTime());
assertEquals(28800000L, HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 PST").getTime());
assertThat(HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 GMT-01:00").getTime()).isEqualTo(
3600000L);
assertThat(HttpDate.parse("Thursday, 01-Jan-1970 00:00:00 PST").getTime()).isEqualTo(28800000L);
// 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
// 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.
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 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 List<Proxy> proxies = new ArrayList<>();
@ -39,7 +39,7 @@ public final class RecordingProxySelector extends ProxySelector {
}
public void assertRequests(URI... expectedUris) {
assertEquals(Arrays.asList(expectedUris), requestedUris);
assertThat(requestedUris).isEqualTo(Arrays.asList(expectedUris));
requestedUris.clear();
}

View File

@ -20,7 +20,7 @@ import java.net.ProtocolException;
import okhttp3.Protocol;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class StatusLineTest {
@ -29,18 +29,18 @@ public final class StatusLineTest {
int version = 1;
int code = 200;
StatusLine statusLine = StatusLine.parse("HTTP/1." + version + " " + code + " " + message);
assertEquals(message, statusLine.message);
assertEquals(Protocol.HTTP_1_1, statusLine.protocol);
assertEquals(code, statusLine.code);
assertThat(statusLine.message).isEqualTo(message);
assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1);
assertThat(statusLine.code).isEqualTo(code);
}
@Test public void emptyMessage() throws IOException {
int version = 1;
int code = 503;
StatusLine statusLine = StatusLine.parse("HTTP/1." + version + " " + code + " ");
assertEquals("", statusLine.message);
assertEquals(Protocol.HTTP_1_1, statusLine.protocol);
assertEquals(code, statusLine.code);
assertThat(statusLine.message).isEqualTo("");
assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1);
assertThat(statusLine.code).isEqualTo(code);
}
/**
@ -51,17 +51,17 @@ public final class StatusLineTest {
int version = 1;
int code = 503;
StatusLine statusLine = StatusLine.parse("HTTP/1." + version + " " + code);
assertEquals("", statusLine.message);
assertEquals(Protocol.HTTP_1_1, statusLine.protocol);
assertEquals(code, statusLine.code);
assertThat(statusLine.message).isEqualTo("");
assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1);
assertThat(statusLine.code).isEqualTo(code);
}
// https://github.com/square/okhttp/issues/386
@Test public void shoutcast() throws IOException {
StatusLine statusLine = StatusLine.parse("ICY 200 OK");
assertEquals("OK", statusLine.message);
assertEquals(Protocol.HTTP_1_0, statusLine.protocol);
assertEquals(200, statusLine.code);
assertThat(statusLine.message).isEqualTo("OK");
assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_0);
assertThat(statusLine.code).isEqualTo(200);
}
@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_SETTINGS;
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 {
/** Real stream traffic applied to the log format. */
@Test public void exampleStream() {
assertEquals(">> 0x00000000 5 SETTINGS ",
frameLog(false, 0, 5, TYPE_SETTINGS, FLAG_NONE));
assertEquals(">> 0x00000003 100 HEADERS END_HEADERS",
frameLog(false, 3, 100, TYPE_HEADERS, FLAG_END_HEADERS));
assertEquals(">> 0x00000003 0 DATA END_STREAM",
frameLog(false, 3, 0, TYPE_DATA, FLAG_END_STREAM));
assertEquals("<< 0x00000000 15 SETTINGS ",
frameLog(true, 0, 15, TYPE_SETTINGS, FLAG_NONE));
assertEquals(">> 0x00000000 0 SETTINGS ACK",
frameLog(false, 0, 0, TYPE_SETTINGS, FLAG_ACK));
assertEquals("<< 0x00000000 0 SETTINGS ACK",
frameLog(true, 0, 0, TYPE_SETTINGS, FLAG_ACK));
assertEquals("<< 0x00000003 22 HEADERS END_HEADERS",
frameLog(true, 3, 22, TYPE_HEADERS, FLAG_END_HEADERS));
assertEquals("<< 0x00000003 226 DATA END_STREAM",
frameLog(true, 3, 226, TYPE_DATA, FLAG_END_STREAM));
assertEquals(">> 0x00000000 8 GOAWAY ",
frameLog(false, 0, 8, TYPE_GOAWAY, FLAG_NONE));
assertThat(frameLog(false, 0, 5, TYPE_SETTINGS, FLAG_NONE)).isEqualTo(
">> 0x00000000 5 SETTINGS ");
assertThat(frameLog(false, 3, 100, TYPE_HEADERS, FLAG_END_HEADERS)).isEqualTo(
">> 0x00000003 100 HEADERS END_HEADERS");
assertThat(frameLog(false, 3, 0, TYPE_DATA, FLAG_END_STREAM)).isEqualTo(
">> 0x00000003 0 DATA END_STREAM");
assertThat(frameLog(true, 0, 15, TYPE_SETTINGS, FLAG_NONE)).isEqualTo(
"<< 0x00000000 15 SETTINGS ");
assertThat(frameLog(false, 0, 0, TYPE_SETTINGS, FLAG_ACK)).isEqualTo(
">> 0x00000000 0 SETTINGS ACK");
assertThat(frameLog(true, 0, 0, TYPE_SETTINGS, FLAG_ACK)).isEqualTo(
"<< 0x00000000 0 SETTINGS ACK");
assertThat(frameLog(true, 3, 22, TYPE_HEADERS, FLAG_END_HEADERS)).isEqualTo(
"<< 0x00000003 22 HEADERS END_HEADERS");
assertThat(frameLog(true, 3, 226, TYPE_DATA, FLAG_END_STREAM)).isEqualTo(
"<< 0x00000003 226 DATA END_STREAM");
assertThat(frameLog(false, 0, 8, TYPE_GOAWAY, FLAG_NONE)).isEqualTo(
">> 0x00000000 8 GOAWAY ");
}
@Test public void flagOverlapOn0x1() {
assertEquals("<< 0x00000000 0 SETTINGS ACK",
frameLog(true, 0, 0, TYPE_SETTINGS, (byte) 0x1));
assertEquals("<< 0x00000000 8 PING ACK",
frameLog(true, 0, 8, TYPE_PING, (byte) 0x1));
assertEquals("<< 0x00000003 0 HEADERS END_STREAM",
frameLog(true, 3, 0, TYPE_HEADERS, (byte) 0x1));
assertEquals("<< 0x00000003 0 DATA END_STREAM",
frameLog(true, 3, 0, TYPE_DATA, (byte) 0x1));
assertThat(frameLog(true, 0, 0, TYPE_SETTINGS, (byte) 0x1)).isEqualTo(
"<< 0x00000000 0 SETTINGS ACK");
assertThat(frameLog(true, 0, 8, TYPE_PING, (byte) 0x1)).isEqualTo(
"<< 0x00000000 8 PING ACK");
assertThat(frameLog(true, 3, 0, TYPE_HEADERS, (byte) 0x1)).isEqualTo(
"<< 0x00000003 0 HEADERS END_STREAM");
assertThat(frameLog(true, 3, 0, TYPE_DATA, (byte) 0x1)).isEqualTo(
"<< 0x00000003 0 DATA END_STREAM");
}
@Test public void flagOverlapOn0x4() {
assertEquals("<< 0x00000003 10000 HEADERS END_HEADERS",
frameLog(true, 3, 10000, TYPE_HEADERS, (byte) 0x4));
assertEquals("<< 0x00000003 10000 CONTINUATION END_HEADERS",
frameLog(true, 3, 10000, TYPE_CONTINUATION, (byte) 0x4));
assertEquals("<< 0x00000004 10000 PUSH_PROMISE END_PUSH_PROMISE",
frameLog(true, 4, 10000, TYPE_PUSH_PROMISE, (byte) 0x4));
assertThat(frameLog(true, 3, 10000, TYPE_HEADERS, (byte) 0x4)).isEqualTo(
"<< 0x00000003 10000 HEADERS END_HEADERS");
assertThat(frameLog(true, 3, 10000, TYPE_CONTINUATION, (byte) 0x4)).isEqualTo(
"<< 0x00000003 10000 CONTINUATION END_HEADERS");
assertThat(frameLog(true, 4, 10000, TYPE_PUSH_PROMISE, (byte) 0x4)).isEqualTo(
"<< 0x00000004 10000 PUSH_PROMISE END_PUSH_PROMISE");
}
@Test public void flagOverlapOn0x20() {
assertEquals("<< 0x00000003 10000 HEADERS PRIORITY",
frameLog(true, 3, 10000, TYPE_HEADERS, (byte) 0x20));
assertEquals("<< 0x00000003 10000 DATA COMPRESSED",
frameLog(true, 3, 10000, TYPE_DATA, (byte) 0x20));
assertThat(frameLog(true, 3, 10000, TYPE_HEADERS, (byte) 0x20)).isEqualTo(
"<< 0x00000003 10000 HEADERS PRIORITY");
assertThat(frameLog(true, 3, 10000, TYPE_DATA, (byte) 0x20)).isEqualTo(
"<< 0x00000003 10000 DATA COMPRESSED");
}
/**
@ -92,7 +92,7 @@ public final class FrameLogTest {
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));
assertEquals(Arrays.asList(
assertThat(formattedFlags).isEqualTo(Arrays.asList(
"",
"END_STREAM",
"00000010",
@ -157,6 +157,6 @@ public final class FrameLogTest {
"00111101",
"00111110",
"00111111"
), formattedFlags);
));
}
}

View File

@ -25,8 +25,7 @@ import org.junit.Test;
import static okhttp3.TestUtil.headerEntries;
import static okio.ByteString.decodeHex;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class HpackTest {
@ -55,9 +54,9 @@ public final class HpackTest {
bytesIn.writeAll(bytesOut);
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();
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. */
@ -115,8 +115,8 @@ public final class HpackTest {
Hpack.Writer writer = new Hpack.Writer(110, false, bytesOut);
writer.writeHeaders(headerBlock);
assertEquals(bytesIn, bytesOut);
assertEquals(2, writer.headerCount);
assertThat(bytesOut).isEqualTo(bytesIn);
assertThat(writer.headerCount).isEqualTo(2);
int tableLength = writer.dynamicTable.length;
Header entry = writer.dynamicTable[tableLength - 1];
@ -160,7 +160,7 @@ public final class HpackTest {
hpackReader.readHeaders();
assertEquals(2, hpackReader.headerCount);
assertThat(hpackReader.headerCount).isEqualTo(2);
Header entry1 = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
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
// 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.
bytesIn.writeByte(0x3F); // Dynamic table size update (size = 55).
bytesIn.writeByte(0x18);
hpackReader.readHeaders();
assertEquals(1, hpackReader.headerCount);
assertThat(hpackReader.headerCount).isEqualTo(1);
}
/** Header table backing array is initially 8 long, let's ensure it grows. */
@ -198,7 +198,7 @@ public final class HpackTest {
hpackReader.readHeaders();
assertEquals(256, hpackReader.headerCount);
assertThat(hpackReader.headerCount).isEqualTo(256);
}
@Test public void huffmanDecodingSupported() throws IOException {
@ -210,8 +210,8 @@ public final class HpackTest {
hpackReader.readHeaders();
assertEquals(1, hpackReader.headerCount);
assertEquals(52, hpackReader.dynamicTableByteCount);
assertThat(hpackReader.headerCount).isEqualTo(1);
assertThat(hpackReader.dynamicTableByteCount).isEqualTo(52);
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
checkEntry(entry, ":path", "www.example.com", 52);
@ -230,13 +230,14 @@ public final class HpackTest {
hpackReader.readHeaders();
assertEquals(1, hpackReader.headerCount);
assertEquals(55, hpackReader.dynamicTableByteCount);
assertThat(hpackReader.headerCount).isEqualTo(1);
assertThat(hpackReader.dynamicTableByteCount).isEqualTo(55);
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
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");
hpackWriter.writeHeaders(headerBlock);
assertEquals(bytesIn, bytesOut);
assertThat(bytesOut).isEqualTo(bytesIn);
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 {
@ -272,9 +273,9 @@ public final class HpackTest {
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 {
@ -285,9 +286,10 @@ public final class HpackTest {
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 {
@ -302,9 +304,9 @@ public final class HpackTest {
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 {
@ -316,9 +318,9 @@ public final class HpackTest {
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 {
@ -332,18 +334,18 @@ public final class HpackTest {
bytesIn.writeUtf8("custom-header");
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];
checkEntry(entry, "custom-key", "custom-header", 55);
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 {
@ -362,18 +364,18 @@ public final class HpackTest {
bytesIn.writeByte(0xbe); // Indexed name and value (idx = 63)
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];
checkEntry(entry, "custom-key", "custom-header", 55);
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 {
@ -382,12 +384,13 @@ public final class HpackTest {
hpackReader.readHeaders();
assertEquals(0, hpackReader.headerCount);
assertEquals(0, hpackReader.dynamicTableByteCount);
assertThat(hpackReader.headerCount).isEqualTo(0);
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
@ -398,7 +401,7 @@ public final class HpackTest {
hpackReader.readHeaders();
fail();
} catch (IOException e) {
assertEquals("index == 0", e.getMessage());
assertThat(e.getMessage()).isEqualTo("index == 0");
}
}
@ -410,7 +413,7 @@ public final class HpackTest {
hpackReader.readHeaders();
fail();
} 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();
fail();
} 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);
hpackReader.readHeaders();
assertEquals(0, hpackReader.maxDynamicTableByteCount());
assertThat(hpackReader.maxDynamicTableByteCount()).isEqualTo(0);
bytesIn.writeByte(0x3f); // encode size 4096
bytesIn.writeByte(0xe1);
bytesIn.writeByte(0x1f);
hpackReader.readHeaders();
assertEquals(4096, hpackReader.maxDynamicTableByteCount());
assertThat(hpackReader.maxDynamicTableByteCount()).isEqualTo(4096);
}
// Example taken from twitter/hpack DecoderTest.testIllegalHeaderTableSizeUpdate
@ -452,7 +455,7 @@ public final class HpackTest {
hpackReader.readHeaders();
fail();
} 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();
fail();
} 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();
// 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 {
@ -493,7 +497,8 @@ public final class HpackTest {
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 {
@ -509,9 +514,8 @@ public final class HpackTest {
hpackReader.readHeaders();
assertEquals(
Arrays.asList(new Header("custom-foo", "Basic"), new Header("custom-foo", "Basic2")),
hpackReader.getAndResetHeaderList());
assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(
Arrays.asList(new Header("custom-foo", "Basic"), new Header("custom-foo", "Basic2")));
}
/**
@ -548,7 +552,7 @@ public final class HpackTest {
hpackReader.readHeaders();
fail();
} 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() {
assertEquals(1, hpackReader.headerCount);
assertThat(hpackReader.headerCount).isEqualTo(1);
// [ 1] (s = 57) :authority: www.example.com
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 57
assertEquals(57, hpackReader.dynamicTableByteCount);
assertThat(hpackReader.dynamicTableByteCount).isEqualTo(57);
// Decoded header list:
assertEquals(headerEntries(
assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET",
":scheme", "http",
":path", "/",
":authority", "www.example.com"), hpackReader.getAndResetHeaderList());
":authority", "www.example.com"));
}
private void secondRequestWithoutHuffman() {
@ -599,7 +603,7 @@ public final class HpackTest {
}
private void checkReadSecondRequestWithoutHuffman() {
assertEquals(2, hpackReader.headerCount);
assertThat(hpackReader.headerCount).isEqualTo(2);
// [ 1] (s = 53) cache-control: no-cache
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 2];
@ -610,15 +614,15 @@ public final class HpackTest {
checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 110
assertEquals(110, hpackReader.dynamicTableByteCount);
assertThat(hpackReader.dynamicTableByteCount).isEqualTo(110);
// Decoded header list:
assertEquals(headerEntries(
assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET",
":scheme", "http",
":path", "/",
":authority", "www.example.com",
"cache-control", "no-cache"), hpackReader.getAndResetHeaderList());
"cache-control", "no-cache"));
}
private void thirdRequestWithoutHuffman() {
@ -638,7 +642,7 @@ public final class HpackTest {
}
private void checkReadThirdRequestWithoutHuffman() {
assertEquals(3, hpackReader.headerCount);
assertThat(hpackReader.headerCount).isEqualTo(3);
// [ 1] (s = 54) custom-key: custom-value
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 3];
@ -653,15 +657,15 @@ public final class HpackTest {
checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 164
assertEquals(164, hpackReader.dynamicTableByteCount);
assertThat(hpackReader.dynamicTableByteCount).isEqualTo(164);
// Decoded header list:
assertEquals(headerEntries(
assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET",
":scheme", "https",
":path", "/index.html",
":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() {
assertEquals(1, hpackReader.headerCount);
assertThat(hpackReader.headerCount).isEqualTo(1);
// [ 1] (s = 57) :authority: www.example.com
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 1];
checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 57
assertEquals(57, hpackReader.dynamicTableByteCount);
assertThat(hpackReader.dynamicTableByteCount).isEqualTo(57);
// Decoded header list:
assertEquals(headerEntries(
assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET",
":scheme", "http",
":path", "/",
":authority", "www.example.com"), hpackReader.getAndResetHeaderList());
":authority", "www.example.com"));
}
private void secondRequestWithHuffman() {
@ -730,7 +734,7 @@ public final class HpackTest {
}
private void checkReadSecondRequestWithHuffman() {
assertEquals(2, hpackReader.headerCount);
assertThat(hpackReader.headerCount).isEqualTo(2);
// [ 1] (s = 53) cache-control: no-cache
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 2];
@ -741,15 +745,15 @@ public final class HpackTest {
checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 110
assertEquals(110, hpackReader.dynamicTableByteCount);
assertThat(hpackReader.dynamicTableByteCount).isEqualTo(110);
// Decoded header list:
assertEquals(headerEntries(
assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET",
":scheme", "http",
":path", "/",
":authority", "www.example.com",
"cache-control", "no-cache"), hpackReader.getAndResetHeaderList());
"cache-control", "no-cache"));
}
private void thirdRequestWithHuffman() {
@ -771,7 +775,7 @@ public final class HpackTest {
}
private void checkReadThirdRequestWithHuffman() {
assertEquals(3, hpackReader.headerCount);
assertThat(hpackReader.headerCount).isEqualTo(3);
// [ 1] (s = 54) custom-key: custom-value
Header entry = hpackReader.dynamicTable[readerHeaderTableLength() - 3];
@ -786,24 +790,24 @@ public final class HpackTest {
checkEntry(entry, ":authority", "www.example.com", 57);
// Table size: 164
assertEquals(164, hpackReader.dynamicTableByteCount);
assertThat(hpackReader.dynamicTableByteCount).isEqualTo(164);
// Decoded header list:
assertEquals(headerEntries(
assertThat(hpackReader.getAndResetHeaderList()).isEqualTo(headerEntries(
":method", "GET",
":scheme", "https",
":path", "/index.html",
":authority", "www.example.com",
"custom-key", "custom-value"), hpackReader.getAndResetHeaderList());
"custom-key", "custom-value"));
}
@Test public void readSingleByteInt() throws IOException {
assertEquals(10, newReader(byteStream()).readInt(10, 31));
assertEquals(10, newReader(byteStream()).readInt(0xe0 | 10, 31));
assertThat(newReader(byteStream()).readInt(10, 31)).isEqualTo(10);
assertThat(newReader(byteStream()).readInt(0xe0 | 10, 31)).isEqualTo(10);
}
@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 {
@ -823,26 +827,26 @@ public final class HpackTest {
@Test public void max31BitValue() throws IOException {
hpackWriter.writeInt(0x7fffffff, 31, 0);
assertBytes(31, 224, 255, 255, 255, 7);
assertEquals(0x7fffffff,
newReader(byteStream(224, 255, 255, 255, 7)).readInt(31, 31));
assertThat(newReader(byteStream(224, 255, 255, 255, 7)).readInt(31, 31)).isEqualTo(
(long) 0x7fffffff);
}
@Test public void prefixMask() throws IOException {
hpackWriter.writeInt(31, 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 {
hpackWriter.writeInt(30, 31, 0);
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 {
hpackWriter.writeInt(0, 31, 0);
assertBytes(0);
assertEquals(0, newReader(byteStream()).readInt(0, 31));
assertThat(newReader(byteStream()).readInt(0, 31)).isEqualTo(0);
}
@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();
fail();
} 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 {
hpackWriter.writeByteString(ByteString.encodeUtf8(""));
assertBytes(0);
assertEquals(ByteString.EMPTY, newReader(byteStream(0)).readByteString());
assertThat(newReader(byteStream(0)).readByteString()).isEqualTo(ByteString.EMPTY);
}
@Test public void emitsDynamicTableSizeUpdate() throws IOException {
@ -931,13 +936,13 @@ public final class HpackTest {
"custom-key1", "custom-header",
"custom-key2", "custom-header");
hpackWriter.writeHeaders(headerBlock);
assertEquals(2, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(2);
hpackWriter.setHeaderTableSizeSetting(56);
assertEquals(1, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(1);
hpackWriter.setHeaderTableSizeSetting(0);
assertEquals(0, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(0);
}
@Test public void noEvictionOnDynamicTableSizeIncrease() throws IOException {
@ -946,15 +951,15 @@ public final class HpackTest {
"custom-key1", "custom-header",
"custom-key2", "custom-header");
hpackWriter.writeHeaders(headerBlock);
assertEquals(2, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(2);
hpackWriter.setHeaderTableSizeSetting(8192);
assertEquals(2, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(2);
}
@Test public void dynamicTableSizeHasAnUpperBound() {
hpackWriter.setHeaderTableSizeSetting(1048576);
assertEquals(16384, hpackWriter.maxDynamicTableByteCount);
assertThat(hpackWriter.maxDynamicTableByteCount).isEqualTo(16384);
}
@Test public void huffmanEncode() throws IOException {
@ -973,33 +978,33 @@ public final class HpackTest {
.readByteString();
ByteString actual = bytesOut.readByteString();
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test public void staticTableIndexedHeaders() throws IOException {
hpackWriter.writeHeaders(headerEntries(":method", "GET"));
assertBytes(0x82);
assertEquals(0, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":method", "POST"));
assertBytes(0x83);
assertEquals(0, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":path", "/"));
assertBytes(0x84);
assertEquals(0, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":path", "/index.html"));
assertBytes(0x85);
assertEquals(0, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":scheme", "http"));
assertBytes(0x86);
assertEquals(0, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":scheme", "https"));
assertBytes(0x87);
assertEquals(0, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(0);
}
@Test public void dynamicTableIndexedHeader() throws IOException {
@ -1007,64 +1012,64 @@ public final class HpackTest {
assertBytes(0x40,
10, 'c', 'u', 's', 't', 'o', 'm', '-', 'k', 'e', 'y',
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"));
assertBytes(0xbe);
assertEquals(1, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(1);
}
@Test public void doNotIndexPseudoHeaders() throws IOException {
hpackWriter.writeHeaders(headerEntries(":method", "PUT"));
assertBytes(0x02, 3, 'P', 'U', 'T');
assertEquals(0, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(0);
hpackWriter.writeHeaders(headerEntries(":path", "/okhttp"));
assertBytes(0x04, 7, '/', 'o', 'k', 'h', 't', 't', 'p');
assertEquals(0, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(0);
}
@Test public void incrementalIndexingWithAuthorityPseudoHeader() throws IOException {
hpackWriter.writeHeaders(headerEntries(":authority", "foo.com"));
assertBytes(0x41, 7, 'f', 'o', 'o', '.', 'c', 'o', 'm');
assertEquals(1, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(1);
hpackWriter.writeHeaders(headerEntries(":authority", "foo.com"));
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.
hpackWriter.writeHeaders(headerEntries(":authority", "bar.com"));
assertBytes(0x41, 7, 'b', 'a', 'r', '.', 'c', 'o', 'm');
assertEquals(2, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(2);
hpackWriter.writeHeaders(headerEntries(":authority", "bar.com"));
assertBytes(0xbe);
assertEquals(2, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(2);
}
@Test public void incrementalIndexingWithStaticTableIndexedName() throws IOException {
hpackWriter.writeHeaders(headerEntries("accept-encoding", "gzip"));
assertBytes(0x50, 4, 'g', 'z', 'i', 'p');
assertEquals(1, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(1);
hpackWriter.writeHeaders(headerEntries("accept-encoding", "gzip"));
assertBytes(0xbe);
assertEquals(1, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(1);
}
@Test public void incrementalIndexingWithDynamcTableIndexedName() throws IOException {
hpackWriter.writeHeaders(headerEntries("foo", "bar"));
assertBytes(0x40, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r');
assertEquals(1, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(1);
hpackWriter.writeHeaders(headerEntries("foo", "bar1"));
assertBytes(0x7e, 4, 'b', 'a', 'r', '1');
assertEquals(2, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(2);
hpackWriter.writeHeaders(headerEntries("foo", "bar1"));
assertBytes(0xbe);
assertEquals(2, hpackWriter.headerCount);
assertThat(hpackWriter.headerCount).isEqualTo(2);
}
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) {
assertEquals(name, entry.name.utf8());
assertEquals(value, entry.value.utf8());
assertEquals(size, entry.hpackSize);
assertThat(entry.name.utf8()).isEqualTo(name);
assertThat(entry.value.utf8()).isEqualTo(value);
assertThat(entry.hpackSize).isEqualTo(size);
}
private void assertBytes(int... bytes) throws IOException {
ByteString expected = intArrayToByteArray(bytes);
ByteString actual = bytesOut.readByteString();
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
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_PADDED;
import static okhttp3.internal.http2.Http2.FLAG_PRIORITY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class Http2Test {
@ -65,15 +63,16 @@ public final class Http2Test {
frame.writeInt(expectedStreamId & 0x7fffffff);
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() {
@Override public void headers(boolean inFinished, int streamId,
int associatedStreamId, List<Header> headerBlock) {
assertTrue(inFinished);
assertEquals(expectedStreamId, streamId);
assertEquals(-1, associatedStreamId);
assertEquals(sentHeaders, headerBlock);
assertThat(inFinished).isTrue();
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(associatedStreamId).isEqualTo(-1);
assertThat(headerBlock).isEqualTo(sentHeaders);
}
});
}
@ -93,17 +92,17 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler() {
@Override public void priority(int streamId, int streamDependency, int weight,
boolean exclusive) {
assertEquals(0, streamDependency);
assertEquals(256, weight);
assertFalse(exclusive);
assertThat(streamDependency).isEqualTo(0);
assertThat(weight).isEqualTo(256);
assertThat(exclusive).isFalse();
}
@Override public void headers(boolean inFinished, int streamId,
int associatedStreamId, List<Header> nameValueBlock) {
assertFalse(inFinished);
assertEquals(expectedStreamId, streamId);
assertEquals(-1, associatedStreamId);
assertEquals(sentHeaders, nameValueBlock);
assertThat(inFinished).isFalse();
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(associatedStreamId).isEqualTo(-1);
assertThat(nameValueBlock).isEqualTo(sentHeaders);
}
});
}
@ -128,16 +127,17 @@ public final class Http2Test {
frame.writeInt(expectedStreamId & 0x7fffffff);
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.
reader.nextFrame(false, new BaseTestHandler() {
@Override public void headers(boolean inFinished, int streamId,
int associatedStreamId, List<Header> headerBlock) {
assertFalse(inFinished);
assertEquals(expectedStreamId, streamId);
assertEquals(-1, associatedStreamId);
assertEquals(sentHeaders, headerBlock);
assertThat(inFinished).isFalse();
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(associatedStreamId).isEqualTo(-1);
assertThat(headerBlock).isEqualTo(sentHeaders);
}
});
}
@ -161,14 +161,15 @@ public final class Http2Test {
frame.writeInt(expectedPromisedStreamId & 0x7fffffff);
frame.writeAll(headerBytes);
assertEquals(frame, sendPushPromiseFrames(expectedPromisedStreamId, pushPromise));
assertThat(sendPushPromiseFrames(expectedPromisedStreamId, pushPromise)).isEqualTo(
frame);
reader.nextFrame(false, new BaseTestHandler() {
@Override
public void pushPromise(int streamId, int promisedStreamId, List<Header> headerBlock) {
assertEquals(expectedStreamId, streamId);
assertEquals(expectedPromisedStreamId, promisedStreamId);
assertEquals(pushPromise, headerBlock);
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(promisedStreamId).isEqualTo(expectedPromisedStreamId);
assertThat(headerBlock).isEqualTo(pushPromise);
}
});
}
@ -196,15 +197,16 @@ public final class Http2Test {
frame.writeInt(expectedStreamId & 0x7fffffff);
frame.writeAll(headerBlock);
assertEquals(frame, sendPushPromiseFrames(expectedPromisedStreamId, pushPromise));
assertThat(sendPushPromiseFrames(expectedPromisedStreamId, pushPromise)).isEqualTo(
frame);
// Reading the above frames should result in a concatenated headerBlock.
reader.nextFrame(false, new BaseTestHandler() {
@Override
public void pushPromise(int streamId, int promisedStreamId, List<Header> headerBlock) {
assertEquals(expectedStreamId, streamId);
assertEquals(expectedPromisedStreamId, promisedStreamId);
assertEquals(pushPromise, headerBlock);
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(promisedStreamId).isEqualTo(expectedPromisedStreamId);
assertThat(headerBlock).isEqualTo(pushPromise);
}
});
}
@ -218,8 +220,8 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler() {
@Override public void rstStream(int streamId, ErrorCode errorCode) {
assertEquals(expectedStreamId, streamId);
assertEquals(ErrorCode.PROTOCOL_ERROR, errorCode);
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR);
}
});
}
@ -238,9 +240,10 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler() {
@Override public void settings(boolean clearPrevious, Settings settings) {
assertFalse(clearPrevious); // No clearPrevious in HTTP/2.
assertEquals(reducedTableSizeBytes, settings.getHeaderTableSize());
assertFalse(settings.getEnablePush(true));
// No clearPrevious in HTTP/2.
assertThat(clearPrevious).isFalse();
assertThat(settings.getHeaderTableSize()).isEqualTo(reducedTableSizeBytes);
assertThat(settings.getEnablePush(true)).isFalse();
}
});
}
@ -257,7 +260,7 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler());
fail();
} 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));
}
});
assertEquals(settingValue.intValue(), 1);
assertThat(1).isEqualTo(settingValue.intValue());
}
@Test public void readSettingsFrameExperimentalId() throws IOException {
@ -305,7 +308,8 @@ public final class Http2Test {
reader.nextFrame(false, new BaseTestHandler());
fail();
} 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());
fail();
} 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());
fail();
} 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());
fail();
} 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);
// Check writer sends the same bytes.
assertEquals(frame, sendPingFrame(true, expectedPayload1, expectedPayload2));
assertThat(sendPingFrame(true, expectedPayload1, expectedPayload2)).isEqualTo(frame);
reader.nextFrame(false, new BaseTestHandler() {
@Override public void ping(boolean ack, int payload1, int payload2) {
assertTrue(ack);
assertEquals(expectedPayload1, payload1);
assertEquals(expectedPayload2, payload2);
assertThat(ack).isTrue();
assertThat(payload1).isEqualTo(expectedPayload1);
assertThat(payload2).isEqualTo(expectedPayload2);
}
});
}
@ -391,17 +397,17 @@ public final class Http2Test {
frame.write(expectedData);
// 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() {
@Override public void data(boolean inFinished, int streamId, BufferedSource source,
int length) throws IOException {
assertFalse(inFinished);
assertEquals(expectedStreamId, streamId);
assertEquals(Http2.INITIAL_MAX_FRAME_SIZE, length);
assertThat(inFinished).isFalse();
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(length).isEqualTo(Http2.INITIAL_MAX_FRAME_SIZE);
ByteString data = source.readByteString(length);
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());
fail();
} 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());
fail();
} catch (IOException e) {
assertEquals("PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA",
e.getMessage());
assertThat(e.getMessage()).isEqualTo(
"PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA");
}
}
@ -464,7 +470,8 @@ public final class Http2Test {
frame.write(padding);
reader.nextFrame(false, assertData());
assertTrue(frame.exhausted()); // Padding was skipped.
// Padding was skipped.
assertThat(frame.exhausted()).isTrue();
}
@Test public void readPaddedDataFrameZeroPadding() throws IOException {
@ -497,7 +504,8 @@ public final class Http2Test {
frame.write(padding);
reader.nextFrame(false, assertHeaderBlock());
assertTrue(frame.exhausted()); // Padding was skipped.
// Padding was skipped.
assertThat(frame.exhausted()).isTrue();
}
@Test public void readPaddedHeadersFrameZeroPadding() throws IOException {
@ -538,7 +546,7 @@ public final class Http2Test {
frame.writeAll(headerBlock);
reader.nextFrame(false, assertHeaderBlock());
assertTrue(frame.exhausted());
assertThat(frame.exhausted()).isTrue();
}
@Test public void tooLargeDataFrame() throws IOException {
@ -546,7 +554,7 @@ public final class Http2Test {
sendDataFrame(new Buffer().write(new byte[0x1000000]));
fail();
} 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);
// Check writer sends the same bytes.
assertEquals(frame, windowUpdate(expectedWindowSizeIncrement));
assertThat(windowUpdate(expectedWindowSizeIncrement)).isEqualTo(frame);
reader.nextFrame(false, new BaseTestHandler() {
@Override public void windowUpdate(int streamId, long windowSizeIncrement) {
assertEquals(expectedStreamId, streamId);
assertEquals(expectedWindowSizeIncrement, windowSizeIncrement);
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(windowSizeIncrement).isEqualTo(expectedWindowSizeIncrement);
}
});
}
@ -575,15 +583,15 @@ public final class Http2Test {
windowUpdate(0);
fail();
} catch (IllegalArgumentException e) {
assertEquals("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 0",
e.getMessage());
assertThat(e.getMessage()).isEqualTo(
"windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 0");
}
try {
windowUpdate(0x80000000L);
fail();
} catch (IllegalArgumentException e) {
assertEquals("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 2147483648",
e.getMessage());
assertThat(e.getMessage()).isEqualTo(
"windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 2147483648");
}
}
@ -598,14 +606,15 @@ public final class Http2Test {
frame.writeInt(expectedError.httpCode);
// 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() {
@Override public void goAway(
int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
assertEquals(expectedStreamId, lastGoodStreamId);
assertEquals(expectedError, errorCode);
assertEquals(0, debugData.size());
assertThat(lastGoodStreamId).isEqualTo(expectedStreamId);
assertThat(errorCode).isEqualTo(expectedError);
assertThat(debugData.size()).isEqualTo(0);
}
});
}
@ -624,14 +633,14 @@ public final class Http2Test {
frame.write(expectedData.toByteArray());
// 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() {
@Override public void goAway(
int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
assertEquals(0, lastGoodStreamId);
assertEquals(expectedError, errorCode);
assertEquals(expectedData, debugData);
assertThat(lastGoodStreamId).isEqualTo(0);
assertThat(errorCode).isEqualTo(expectedError);
assertThat(debugData).isEqualTo(expectedData);
}
});
}
@ -644,7 +653,7 @@ public final class Http2Test {
fail();
} catch (IllegalArgumentException e) {
// 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));
assertEquals(newMaxFrameSize, writer.maxDataLength());
assertThat(writer.maxDataLength()).isEqualTo(newMaxFrameSize);
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);
fail();
} 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() {
@Override public void headers(boolean inFinished, int streamId,
int associatedStreamId, List<Header> headerBlock) {
assertFalse(inFinished);
assertEquals(expectedStreamId, streamId);
assertEquals(-1, associatedStreamId);
assertEquals(headerEntries("foo", "barrr", "baz", "qux"), headerBlock);
assertThat(inFinished).isFalse();
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(associatedStreamId).isEqualTo(-1);
assertThat(headerBlock).isEqualTo(headerEntries("foo", "barrr", "baz", "qux"));
}
};
}
@ -732,12 +741,12 @@ public final class Http2Test {
return new BaseTestHandler() {
@Override public void data(boolean inFinished, int streamId, BufferedSource source,
int length) throws IOException {
assertFalse(inFinished);
assertEquals(expectedStreamId, streamId);
assertEquals(1123, length);
assertThat(inFinished).isFalse();
assertThat(streamId).isEqualTo(expectedStreamId);
assertThat(length).isEqualTo(1123);
ByteString data = source.readByteString(length);
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.GzipSink;
import okio.Okio;
import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Before;
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.SECONDS;
import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.assertj.core.data.Offset.offset;
import static org.hamcrest.CoreMatchers.containsString;
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.fail;
import static org.junit.Assume.assumeTrue;
@ -163,15 +162,16 @@ public final class HttpOverHttp2Test {
.build());
Response response = call.execute();
assertEquals("ABCDE", response.body().string());
assertEquals(200, response.code());
assertEquals("", response.message());
assertEquals(protocol, response.protocol());
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
Assertions.assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.message()).isEqualTo("");
Assertions.assertThat(response.protocol()).isEqualTo(protocol);
RecordedRequest request = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
assertEquals(scheme, request.getHeader(":scheme"));
assertEquals(server.getHostName() + ":" + server.getPort(), request.getHeader(":authority"));
Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1");
Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme);
Assertions.assertThat(request.getHeader(":authority")).isEqualTo(
(server.getHostName() + ":" + server.getPort()));
}
@Test public void emptyResponse() throws IOException {
@ -182,7 +182,7 @@ public final class HttpOverHttp2Test {
.build());
Response response = call.execute();
assertEquals(-1, response.body().byteStream().read());
Assertions.assertThat(response.body().byteStream().read()).isEqualTo(-1);
response.body().close();
}
@ -205,12 +205,12 @@ public final class HttpOverHttp2Test {
.build());
Response response = call.execute();
assertEquals("ABCDE", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
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());
assertNull(request.getHeader("Content-Length"));
Assertions.assertThat(request.getHeader("Content-Length")).isNull();
}
@Test public void userSuppliedContentLengthHeader() throws Exception {
@ -236,12 +236,13 @@ public final class HttpOverHttp2Test {
.build());
Response response = call.execute();
assertEquals("ABCDE", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
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());
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 {
@ -269,12 +270,13 @@ public final class HttpOverHttp2Test {
.build());
Response response = call.execute();
assertEquals("ABCDE", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
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());
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 {
@ -290,12 +292,12 @@ public final class HttpOverHttp2Test {
Response response1 = call1.execute();
Response response2 = call2.execute();
assertEquals("ABC", response1.body().source().readUtf8(3));
assertEquals("GHI", response2.body().source().readUtf8(3));
assertEquals("DEF", response1.body().source().readUtf8(3));
assertEquals("JKL", response2.body().source().readUtf8(3));
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(1, server.takeRequest().getSequenceNumber());
Assertions.assertThat(response1.body().source().readUtf8(3)).isEqualTo("ABC");
Assertions.assertThat(response2.body().source().readUtf8(3)).isEqualTo("GHI");
Assertions.assertThat(response1.body().source().readUtf8(3)).isEqualTo("DEF");
Assertions.assertThat(response2.body().source().readUtf8(3)).isEqualTo("JKL");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
response1.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
// the connection flow-control window so new requests can proceed.
call1.cancel();
assertFalse("Call should not have completed successfully.",
Util.discard(response1.body().source(), 1, TimeUnit.SECONDS));
Assertions.assertThat(Util.discard(response1.body().source(), 1, TimeUnit.SECONDS)).overridingErrorMessage(
"Call should not have completed successfully.").isFalse();
Call call2 = client.newCall(new Request.Builder()
.url(server.url("/"))
.build());
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. */
@ -361,7 +363,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals("abc", response2.body().string());
Assertions.assertThat(response2.body().string()).isEqualTo("abc");
}
@Test public void concurrentRequestWithEmptyFlowControlWindow() throws Exception {
@ -377,9 +379,10 @@ public final class HttpOverHttp2Test {
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]);
assertEquals(8192, read);
Assertions.assertThat(read).isEqualTo(8192);
// 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.
@ -387,13 +390,13 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
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
// flow-control window.
response1.close();
assertEquals("abc", response2.body().string());
Assertions.assertThat(response2.body().string()).isEqualTo("abc");
}
/** 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("/r2", countDownLatch));
countDownLatch.await();
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(1, server.takeRequest().getSequenceNumber());
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
@Test public void gzippedResponseBody() throws Exception {
@ -420,7 +423,7 @@ public final class HttpOverHttp2Test {
.build());
Response response = call.execute();
assertEquals("ABCABCABC", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("ABCABCABC");
}
@Test public void authenticate() throws Exception {
@ -440,13 +443,13 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("Successful auth!", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("Successful auth!");
RecordedRequest denied = server.takeRequest();
assertNull(denied.getHeader("Authorization"));
Assertions.assertThat(denied.getHeader("Authorization")).isNull();
RecordedRequest accepted = server.takeRequest();
assertEquals("GET / HTTP/1.1", accepted.getRequestLine());
assertEquals(credential, accepted.getHeader("Authorization"));
Assertions.assertThat(accepted.getRequestLine()).isEqualTo("GET / HTTP/1.1");
Assertions.assertThat(accepted.getHeader("Authorization")).isEqualTo(credential);
}
@Test public void redirect() throws Exception {
@ -460,12 +463,12 @@ public final class HttpOverHttp2Test {
.build());
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();
assertEquals("/", request1.getPath());
Assertions.assertThat(request1.getPath()).isEqualTo("/");
RecordedRequest request2 = server.takeRequest();
assertEquals("/foo", request2.getPath());
Assertions.assertThat(request2.getPath()).isEqualTo("/foo");
}
@Test public void readAfterLastByte() throws Exception {
@ -477,11 +480,11 @@ public final class HttpOverHttp2Test {
Response response = call.execute();
InputStream in = response.body().byteStream();
assertEquals('A', in.read());
assertEquals('B', in.read());
assertEquals('C', in.read());
assertEquals(-1, in.read());
assertEquals(-1, in.read());
Assertions.assertThat(in.read()).isEqualTo('A');
Assertions.assertThat(in.read()).isEqualTo('B');
Assertions.assertThat(in.read()).isEqualTo('C');
Assertions.assertThat(in.read()).isEqualTo(-1);
Assertions.assertThat(in.read()).isEqualTo(-1);
in.close();
}
@ -502,7 +505,7 @@ public final class HttpOverHttp2Test {
call1.execute();
fail("Should have timed out!");
} 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.
@ -510,11 +513,11 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals("A", response2.body().string());
Assertions.assertThat(response2.body().string()).isEqualTo("A");
// Confirm that the connection was reused.
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(1, server.takeRequest().getSequenceNumber());
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
/**
@ -537,7 +540,7 @@ public final class HttpOverHttp2Test {
.build());
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();
fail("Should have timed out!");
} 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.
@ -575,11 +578,11 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals(body, response2.body().string());
Assertions.assertThat(response2.body().string()).isEqualTo(body);
// Confirm that the connection was reused.
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(1, server.takeRequest().getSequenceNumber());
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
@Test public void connectionTimeout() throws Exception {
@ -604,7 +607,7 @@ public final class HttpOverHttp2Test {
.build());
Response response1 = call1.execute();
assertEquals("A", response1.body().string());
Assertions.assertThat(response1.body().string()).isEqualTo("A");
try {
call2.execute();
@ -613,8 +616,8 @@ public final class HttpOverHttp2Test {
}
// Confirm that the connection was reused.
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(1, server.takeRequest().getSequenceNumber());
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
@Test public void responsesAreCached() throws IOException {
@ -631,26 +634,26 @@ public final class HttpOverHttp2Test {
.build());
Response response1 = call1.execute();
assertEquals("A", response1.body().string());
assertEquals(1, cache.requestCount());
assertEquals(1, cache.networkCount());
assertEquals(0, cache.hitCount());
Assertions.assertThat(response1.body().string()).isEqualTo("A");
Assertions.assertThat(cache.requestCount()).isEqualTo(1);
Assertions.assertThat(cache.networkCount()).isEqualTo(1);
Assertions.assertThat(cache.hitCount()).isEqualTo(0);
Call call2 = client.newCall(new Request.Builder()
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals("A", response2.body().string());
Assertions.assertThat(response2.body().string()).isEqualTo("A");
Call call3 = client.newCall(new Request.Builder()
.url(server.url("/"))
.build());
Response response3 = call3.execute();
assertEquals("A", response3.body().string());
Assertions.assertThat(response3.body().string()).isEqualTo("A");
assertEquals(3, cache.requestCount());
assertEquals(1, cache.networkCount());
assertEquals(2, cache.hitCount());
Assertions.assertThat(cache.requestCount()).isEqualTo(3);
Assertions.assertThat(cache.networkCount()).isEqualTo(1);
Assertions.assertThat(cache.hitCount()).isEqualTo(2);
}
@Test public void conditionalCache() throws IOException {
@ -668,21 +671,21 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response1 = call1.execute();
assertEquals("A", response1.body().string());
Assertions.assertThat(response1.body().string()).isEqualTo("A");
assertEquals(1, cache.requestCount());
assertEquals(1, cache.networkCount());
assertEquals(0, cache.hitCount());
Assertions.assertThat(cache.requestCount()).isEqualTo(1);
Assertions.assertThat(cache.networkCount()).isEqualTo(1);
Assertions.assertThat(cache.hitCount()).isEqualTo(0);
Call call2 = client.newCall(new Request.Builder()
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals("A", response2.body().string());
Assertions.assertThat(response2.body().string()).isEqualTo("A");
assertEquals(2, cache.requestCount());
assertEquals(2, cache.networkCount());
assertEquals(1, cache.hitCount());
Assertions.assertThat(cache.requestCount()).isEqualTo(2);
Assertions.assertThat(cache.networkCount()).isEqualTo(2);
Assertions.assertThat(cache.hitCount()).isEqualTo(1);
}
@Test public void responseCachedWithoutConsumingFullBody() throws IOException {
@ -701,14 +704,14 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response1 = call1.execute();
assertEquals("AB", response1.body().source().readUtf8(2));
Assertions.assertThat(response1.body().source().readUtf8(2)).isEqualTo("AB");
response1.body().close();
Call call2 = client.newCall(new Request.Builder()
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals("ABCD", response2.body().source().readUtf8());
Assertions.assertThat(response2.body().source().readUtf8()).isEqualTo("ABCD");
response2.body().close();
}
@ -729,10 +732,10 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("");
RecordedRequest request = server.takeRequest();
assertEquals("a=b", request.getHeader("Cookie"));
Assertions.assertThat(request.getHeader("Cookie")).isEqualTo("a=b");
}
@Test public void receiveResponseCookies() throws Exception {
@ -748,7 +751,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("");
cookieJar.assertResponseCookies("a=b; path=/");
}
@ -767,13 +770,13 @@ public final class HttpOverHttp2Test {
call1.cancel();
// 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()
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals("def", response2.body().string());
assertEquals(0, server.takeRequest().getSequenceNumber());
Assertions.assertThat(response2.body().string()).isEqualTo("def");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Clean up the connection.
response.close();
@ -790,10 +793,12 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("abc", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("abc");
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
assertEquals(1, server.takeRequest().getSequenceNumber()); // Reused connection.
// New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Reused connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
@Test public void recoverFromOneInternalErrorRequiresNewConnection() throws Exception {
@ -811,10 +816,12 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("abc", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("abc");
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
// New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
}
@Test public void recoverFromMultipleRefusedStreamsRequiresNewConnection() throws Exception {
@ -835,11 +842,14 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("abc", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("abc");
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
assertEquals(1, server.takeRequest().getSequenceNumber()); // Reused connection.
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
// New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Reused connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
// New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
}
@Test public void recoverFromCancelReusesConnection() throws Exception {
@ -860,8 +870,8 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("def", response.body().string());
assertEquals(1, server.takeRequest().getSequenceNumber());
Assertions.assertThat(response.body().string()).isEqualTo("def");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
@Test public void recoverFromMultipleCancelReusesConnection() throws Exception {
@ -886,8 +896,8 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("ghi", response.body().string());
assertEquals(2, server.takeRequest().getSequenceNumber());
Assertions.assertThat(response.body().string()).isEqualTo("ghi");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2);
}
/** 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) {
}
});
assertEquals(expectedSequenceNumber, server.takeRequest().getSequenceNumber());
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(
(long) expectedSequenceNumber);
call.cancel();
latch.await();
}
@ -935,7 +946,7 @@ public final class HttpOverHttp2Test {
call.execute();
fail();
} catch (StreamResetException expected) {
assertEquals(errorCode, expected.errorCode);
Assertions.assertThat(expected.errorCode).isEqualTo(errorCode);
}
}
@ -985,24 +996,24 @@ public final class HttpOverHttp2Test {
.build();
blockingAuthClient.newCall(request).enqueue(callback);
String response1 = responses.take();
assertEquals("", response1);
assertEquals(0, server.takeRequest().getSequenceNumber());
Assertions.assertThat(response1).isEqualTo("");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Now make the second request which will restrict the first HTTP/2 connection from creating new
// streams.
client.newCall(request).enqueue(callback);
String response2 = responses.take();
assertEquals("DEF", response2);
assertEquals(1, server.takeRequest().getSequenceNumber());
assertEquals(0, server.takeRequest().getSequenceNumber());
Assertions.assertThat(response2).isEqualTo("DEF");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
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
// one.
latch.countDown();
String response3 = responses.take();
assertEquals("ABC", response3);
assertEquals(1, server.takeRequest().getSequenceNumber());
assertEquals(2, server.takeRequest().getSequenceNumber());
Assertions.assertThat(response3).isEqualTo("ABC");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2);
}
@Test public void nonAsciiResponseHeader() throws Exception {
@ -1016,8 +1027,8 @@ public final class HttpOverHttp2Test {
Response response = call.execute();
response.close();
assertEquals("α", response.header("Alpha"));
assertEquals("Beta", response.header("β"));
Assertions.assertThat(response.header("Alpha")).isEqualTo("α");
Assertions.assertThat(response.header("β")).isEqualTo("Beta");
}
@Test public void serverSendsPushPromise_GET() throws Exception {
@ -1033,18 +1044,20 @@ public final class HttpOverHttp2Test {
.build());
Response response = call.execute();
assertEquals("ABCDE", response.body().string());
assertEquals(200, response.code());
assertEquals("", response.message());
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
Assertions.assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.message()).isEqualTo("");
RecordedRequest request = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
assertEquals(scheme, request.getHeader(":scheme"));
assertEquals(server.getHostName() + ":" + server.getPort(), request.getHeader(":authority"));
Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1");
Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme);
Assertions.assertThat(request.getHeader(":authority")).isEqualTo(
(server.getHostName() + ":" + server.getPort()));
RecordedRequest pushedRequest = server.takeRequest();
assertEquals("GET /foo/bar HTTP/1.1", pushedRequest.getRequestLine());
assertEquals("bar", pushedRequest.getHeader("foo"));
Assertions.assertThat(pushedRequest.getRequestLine()).isEqualTo(
"GET /foo/bar HTTP/1.1");
Assertions.assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar");
}
@Test public void serverSendsPushPromise_HEAD() throws Exception {
@ -1059,18 +1072,20 @@ public final class HttpOverHttp2Test {
.url(server.url("/foo"))
.build());
Response response = call.execute();
assertEquals("ABCDE", response.body().string());
assertEquals(200, response.code());
assertEquals("", response.message());
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE");
Assertions.assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.message()).isEqualTo("");
RecordedRequest request = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
assertEquals(scheme, request.getHeader(":scheme"));
assertEquals(server.getHostName() + ":" + server.getPort(), request.getHeader(":authority"));
Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1");
Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme);
Assertions.assertThat(request.getHeader(":authority")).isEqualTo(
(server.getHostName() + ":" + server.getPort()));
RecordedRequest pushedRequest = server.takeRequest();
assertEquals("HEAD /foo/bar HTTP/1.1", pushedRequest.getRequestLine());
assertEquals("bar", pushedRequest.getHeader("foo"));
Assertions.assertThat(pushedRequest.getRequestLine()).isEqualTo(
"HEAD /foo/bar HTTP/1.1");
Assertions.assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar");
}
@Test public void noDataFramesSentWithNullRequestBody() throws Exception {
@ -1082,9 +1097,9 @@ public final class HttpOverHttp2Test {
.method("DELETE", null)
.build());
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();
@ -1100,9 +1115,9 @@ public final class HttpOverHttp2Test {
.method("DELETE", Util.EMPTY_REQUEST)
.build());
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();
@ -1125,16 +1140,20 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
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.
List<String> logs = http2Handler.takeAll();
assertEquals(1, countFrames(logs, "FINE: >> 0x00000000 8 PING "));
assertEquals(1, countFrames(logs, "FINE: << 0x00000000 8 PING "));
assertEquals(1, countFrames(logs, "FINE: >> 0x00000000 8 PING ACK"));
assertEquals(1, countFrames(logs, "FINE: << 0x00000000 8 PING ACK"));
Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo(
(long) 1);
Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ")).isEqualTo(
(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 {
@ -1157,16 +1176,20 @@ public final class HttpOverHttp2Test {
call.execute();
fail();
} 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;
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.
List<String> logs = http2Handler.takeAll();
assertEquals(1, countFrames(logs, "FINE: >> 0x00000000 8 PING "));
assertEquals(0, countFrames(logs, "FINE: << 0x00000000 8 PING ACK"));
Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo(
(long) 1);
Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo(
(long) 0);
}
private String firstFrame(List<String> logs, String type) {
@ -1203,7 +1226,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("");
server.enqueue(new MockResponse()
.setBody("ABC"));
@ -1227,13 +1250,17 @@ public final class HttpOverHttp2Test {
.build());
Response response3 = call3.execute();
assertEquals("ABC", response1.body().string());
assertEquals("DEF", response2.body().string());
assertEquals("GHI", response3.body().string());
assertEquals(0, server.takeRequest().getSequenceNumber()); // Settings connection.
assertEquals(1, server.takeRequest().getSequenceNumber()); // Reuse settings connection.
assertEquals(2, server.takeRequest().getSequenceNumber()); // Reuse settings connection.
assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection!
Assertions.assertThat(response1.body().string()).isEqualTo("ABC");
Assertions.assertThat(response2.body().string()).isEqualTo("DEF");
Assertions.assertThat(response3.body().string()).isEqualTo("GHI");
// Settings connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Reuse settings 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 {
@ -1247,15 +1274,15 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response1 = call1.execute();
assertEquals("ABC", response1.body().string());
Assertions.assertThat(response1.body().string()).isEqualTo("ABC");
Call call2 = client.newCall(new Request.Builder()
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals("DEF", response2.body().string());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(0, server.takeRequest().getSequenceNumber());
Assertions.assertThat(response2.body().string()).isEqualTo("DEF");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
}
/**
@ -1282,7 +1309,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("ABC", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("ABC");
// Wait until the GOAWAY has been processed.
RealConnection connection = (RealConnection) chain.connection();
while (connection.isHealthy(false)) ;
@ -1296,10 +1323,10 @@ public final class HttpOverHttp2Test {
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("DEF", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("DEF");
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(0, server.takeRequest().getSequenceNumber());
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
}
@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);
assertEquals("DEF", bodies.poll(2, SECONDS));
assertEquals("ABC", bodies.poll(2, SECONDS));
assertEquals(2, server.getRequestCount());
Assertions.assertThat(bodies.poll(2, SECONDS)).isEqualTo("DEF");
Assertions.assertThat(bodies.poll(2, SECONDS)).isEqualTo("ABC");
Assertions.assertThat(server.getRequestCount()).isEqualTo(2);
}
/**
@ -1366,7 +1393,7 @@ public final class HttpOverHttp2Test {
.url("https://android.com/call2")
.build());
Response response2 = call2.execute();
assertEquals("call2 response", response2.body().string());
Assertions.assertThat(response2.body().string()).isEqualTo("call2 response");
} catch (IOException e) {
throw new RuntimeException(e);
}
@ -1392,27 +1419,27 @@ public final class HttpOverHttp2Test {
.url("https://android.com/call1")
.build());
Response response2 = call1.execute();
assertEquals("call1 response", response2.body().string());
Assertions.assertThat(response2.body().string()).isEqualTo("call1 response");
RecordedRequest call1Connect = server.takeRequest();
assertEquals("CONNECT", call1Connect.getMethod());
assertEquals(0, call1Connect.getSequenceNumber());
Assertions.assertThat(call1Connect.getMethod()).isEqualTo("CONNECT");
Assertions.assertThat(call1Connect.getSequenceNumber()).isEqualTo(0);
RecordedRequest call2Connect = server.takeRequest();
assertEquals("CONNECT", call2Connect.getMethod());
assertEquals(0, call2Connect.getSequenceNumber());
Assertions.assertThat(call2Connect.getMethod()).isEqualTo("CONNECT");
Assertions.assertThat(call2Connect.getSequenceNumber()).isEqualTo(0);
RecordedRequest call2Get = server.takeRequest();
assertEquals("GET", call2Get.getMethod());
assertEquals("/call2", call2Get.getPath());
assertEquals(0, call2Get.getSequenceNumber());
Assertions.assertThat(call2Get.getMethod()).isEqualTo("GET");
Assertions.assertThat(call2Get.getPath()).isEqualTo("/call2");
Assertions.assertThat(call2Get.getSequenceNumber()).isEqualTo(0);
RecordedRequest call1Get = server.takeRequest();
assertEquals("GET", call1Get.getMethod());
assertEquals("/call1", call1Get.getPath());
assertEquals(1, call1Get.getSequenceNumber());
Assertions.assertThat(call1Get.getMethod()).isEqualTo("GET");
Assertions.assertThat(call1Get.getPath()).isEqualTo("/call1");
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 */
@ -1435,10 +1462,11 @@ public final class HttpOverHttp2Test {
.build());
Response response = call.execute();
assertEquals("", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("");
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 {
@ -1464,7 +1492,7 @@ public final class HttpOverHttp2Test {
.url(server.url(path))
.build());
Response response = call.execute();
assertEquals("A", response.body().string());
Assertions.assertThat(response.body().string()).isEqualTo("A");
countDownLatch.countDown();
} catch (Exception e) {
throw new RuntimeException(e);

View File

@ -21,8 +21,8 @@ import okio.Buffer;
import okio.ByteString;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
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}. */
public final class HuffmanTest {
@ -41,7 +41,7 @@ public final class HuffmanTest {
private void assertRoundTrip(ByteString data) throws IOException {
Buffer buffer = new 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());
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.MAX_CONCURRENT_STREAMS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
public final class SettingsTest {
@Test public void unsetField() {
Settings settings = new Settings();
assertEquals(-3, settings.getMaxConcurrentStreams(-3));
assertThat(settings.getMaxConcurrentStreams(-3)).isEqualTo(-3);
}
@Test public void setFields() {
Settings settings = new Settings();
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);
assertTrue(settings.getEnablePush(false));
assertThat(settings.getEnablePush(false)).isTrue();
settings.clear();
assertEquals(-3, settings.getMaxConcurrentStreams(-3));
assertThat(settings.getMaxConcurrentStreams(-3)).isEqualTo(-3);
settings.set(MAX_CONCURRENT_STREAMS, 75);
assertEquals(75, settings.getMaxConcurrentStreams(-3));
assertThat(settings.getMaxConcurrentStreams(-3)).isEqualTo(75);
settings.clear();
assertEquals(16384, settings.getMaxFrameSize(16384));
assertThat(settings.getMaxFrameSize(16384)).isEqualTo(16384);
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);
assertEquals(16777215, settings.getMaxHeaderListSize(-1));
assertThat(settings.getMaxHeaderListSize(-1)).isEqualTo(16777215);
assertEquals(DEFAULT_INITIAL_WINDOW_SIZE,
settings.getInitialWindowSize());
assertThat(settings.getInitialWindowSize()).isEqualTo(DEFAULT_INITIAL_WINDOW_SIZE);
settings.set(Settings.INITIAL_WINDOW_SIZE, 108);
assertEquals(108, settings.getInitialWindowSize());
assertThat(settings.getInitialWindowSize()).isEqualTo(108);
}
@Test public void merge() {
@ -70,9 +68,9 @@ public final class SettingsTest {
b.set(Settings.MAX_CONCURRENT_STREAMS, 60000);
a.merge(b);
assertEquals(10000, a.getHeaderTableSize());
assertEquals(40000, a.getMaxHeaderListSize(-1));
assertEquals(50000, a.getInitialWindowSize());
assertEquals(60000, a.getMaxConcurrentStreams(-1));
assertThat(a.getHeaderTableSize()).isEqualTo(10000);
assertThat(a.getMaxHeaderListSize(-1)).isEqualTo(40000);
assertThat(a.getInitialWindowSize()).isEqualTo(50000);
assertThat(a.getMaxConcurrentStreams(-1)).isEqualTo(60000);
}
}

View File

@ -18,7 +18,7 @@ package okhttp3.internal.platform;
import org.junit.Test;
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;
public class Jdk8WithJettyBootPlatformTest {
@ -26,6 +26,6 @@ public class Jdk8WithJettyBootPlatformTest {
public void testBuildsWithJettyBoot() {
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 static okhttp3.internal.platform.PlatformTest.getPlatform;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
public class Jdk9PlatformTest {
@ -27,7 +26,7 @@ public class Jdk9PlatformTest {
public void buildsWhenJdk9() {
assumeTrue(getPlatform().equals("jdk9"));
assertNotNull(Jdk9Platform.buildIfSupported());
assertThat(Jdk9Platform.buildIfSupported()).isNotNull();
}
@Test
@ -36,12 +35,12 @@ public class Jdk9PlatformTest {
Jdk9Platform platform = Jdk9Platform.buildIfSupported();
assertEquals("getApplicationProtocol", platform.getProtocolMethod.getName());
assertEquals("setApplicationProtocols", platform.setProtocolMethod.getName());
assertThat(platform.getProtocolMethod.getName()).isEqualTo("getApplicationProtocol");
assertThat(platform.setProtocolMethod.getName()).isEqualTo("setApplicationProtocols");
}
@Test
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 static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
public class PlatformTest {
@Test public void alwaysBuilds() {
@ -26,7 +26,7 @@ public class PlatformTest {
/** Guard against the default value changing by accident. */
@Test public void defaultPrefix() {
assertEquals("OkHttp", new Platform().getPrefix());
assertThat(new Platform().getPrefix()).isEqualTo("OkHttp");
}
public static String getPlatform() {
@ -39,6 +39,6 @@ public class PlatformTest {
@Test
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 static okhttp3.internal.publicsuffix.PublicSuffixDatabase.PUBLIC_SUFFIX_RESOURCE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class PublicSuffixDatabaseTest {
@ -40,12 +38,14 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("square.com\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), new byte[]{});
assertEquals("example.com", publicSuffixDatabase.getEffectiveTldPlusOne("example.com"));
assertEquals("example.com", publicSuffixDatabase.getEffectiveTldPlusOne("foo.example.com"));
assertEquals("bar.square.com",
publicSuffixDatabase.getEffectiveTldPlusOne("foo.bar.square.com"));
assertEquals("foo.my.square.com",
publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.com"));
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("example.com")).isEqualTo(
"example.com");
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.example.com")).isEqualTo(
"example.com");
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.bar.square.com")).isEqualTo(
"bar.square.com");
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.com")).isEqualTo(
"foo.my.square.com");
}
@Test public void wildcardMatch() {
@ -55,11 +55,11 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("example.com\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), new byte[]{});
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("my.square.com"));
assertEquals("foo.my.square.com",
publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.com"));
assertEquals("foo.my.square.com",
publicSuffixDatabase.getEffectiveTldPlusOne("bar.foo.my.square.com"));
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("my.square.com")).isNull();
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.com")).isEqualTo(
"foo.my.square.com");
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("bar.foo.my.square.com")).isEqualTo(
"foo.my.square.com");
}
@Test public void boundarySearches() {
@ -69,10 +69,10 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("fff\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), new byte[]{});
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("aaa"));
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("ggg"));
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("ccc"));
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("eee"));
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("aaa")).isNull();
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("ggg")).isNull();
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("ccc")).isNull();
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("eee")).isNull();
}
@Test public void exceptionRule() {
@ -85,9 +85,11 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("square.com\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), exception.readByteArray());
assertEquals("my.square.jp", publicSuffixDatabase.getEffectiveTldPlusOne("my.square.jp"));
assertEquals("my.square.jp", publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.jp"));
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("my1.square.jp"));
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("my.square.jp")).isEqualTo(
"my.square.jp");
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.my.square.jp")).isEqualTo(
"my.square.jp");
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("my1.square.jp")).isNull();
}
@Test public void noEffectiveTldPlusOne() {
@ -100,8 +102,8 @@ public final class PublicSuffixDatabaseTest {
.writeUtf8("square.com\n");
publicSuffixDatabase.setListBytes(buffer.readByteArray(), exception.readByteArray());
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("example.com"));
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne("foo.square.jp"));
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("example.com")).isNull();
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne("foo.square.jp")).isNull();
}
@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.
publicSuffix = publicSuffix.replaceAll("\\*", "square");
}
assertNull(publicSuffixDatabase.getEffectiveTldPlusOne(publicSuffix));
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(publicSuffix)).isNull();
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()) {
String exception = buffer.readUtf8LineStrict();
assertEquals(exception, publicSuffixDatabase.getEffectiveTldPlusOne(exception));
assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(exception)).isEqualTo(
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();
try {
String result = publicSuffixDatabase.getEffectiveTldPlusOne("squareup.com");
assertEquals("squareup.com", result);
assertThat(result).isEqualTo("squareup.com");
} finally {
assertTrue(Thread.interrupted());
assertThat(Thread.interrupted()).isTrue();
}
}
@ -276,9 +279,9 @@ public final class PublicSuffixDatabaseTest {
String result = publicSuffixDatabase.getEffectiveTldPlusOne(canonicalDomain);
if (registrablePart == null) {
assertNull(result);
assertThat(result).isNull();
} 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.tls.internal.TlsUtil.newKeyManager;
import static okhttp3.tls.internal.TlsUtil.newTrustManager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
@ -102,7 +101,7 @@ public final class CertificatePinnerChainValidationTest {
.url(server.url("/"))
.build());
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.
server.enqueue(new MockResponse()
@ -112,7 +111,7 @@ public final class CertificatePinnerChainValidationTest {
.url(server.url("/"))
.build());
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. */
@ -162,7 +161,7 @@ public final class CertificatePinnerChainValidationTest {
.url(server.url("/"))
.build());
Response response1 = call1.execute();
assertEquals("abc", response1.body().string());
assertThat(response1.body().string()).isEqualTo("abc");
response1.close();
// Force a fresh connection for the next request.
@ -176,7 +175,7 @@ public final class CertificatePinnerChainValidationTest {
.url(server.url("/"))
.build());
Response response2 = call2.execute();
assertEquals("def", response2.body().string());
assertThat(response2.body().string()).isEqualTo("def");
response2.close();
}
@ -251,7 +250,7 @@ public final class CertificatePinnerChainValidationTest {
} catch (SSLPeerUnverifiedException expected) {
// Certificate pinning fails!
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) {
// On Android, the handshake fails before the certificate pinner runs.
String message = expected.getMessage();
assertTrue(message, message.contains("Could not validate certificate"));
assertThat(message).contains("Could not validate certificate");
} catch (SSLPeerUnverifiedException expected) {
// On OpenJDK, the handshake succeeds but the certificate pinner fails.
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.tls.internal.TlsUtil.newKeyManager;
import static okhttp3.tls.internal.TlsUtil.newTrustManager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
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());
Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal());
assertEquals(new X500Principal("CN=Jethro Willis"), response.handshake().localPrincipal());
assertEquals("abc", response.body().string());
assertThat(response.handshake().peerPrincipal()).isEqualTo(
new X500Principal("CN=Local Host"));
assertThat(response.handshake().localPrincipal()).isEqualTo(
new X500Principal("CN=Jethro Willis"));
assertThat(response.body().string()).isEqualTo("abc");
}
@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());
Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal());
assertEquals(new X500Principal("CN=Jethro Willis"), response.handshake().localPrincipal());
assertEquals("abc", response.body().string());
assertThat(response.handshake().peerPrincipal()).isEqualTo(
new X500Principal("CN=Local Host"));
assertThat(response.handshake().localPrincipal()).isEqualTo(
new X500Principal("CN=Jethro Willis"));
assertThat(response.body().string()).isEqualTo("abc");
}
@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());
Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal());
assertNull(response.handshake().localPrincipal());
assertEquals("abc", response.body().string());
assertThat(response.handshake().peerPrincipal()).isEqualTo(
new X500Principal("CN=Local Host"));
assertThat(response.handshake().localPrincipal()).isNull();
assertThat(response.body().string()).isEqualTo("abc");
}
@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());
Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal());
assertNull(response.handshake().localPrincipal());
assertEquals("abc", response.body().string());
assertThat(response.handshake().peerPrincipal()).isEqualTo(
new X500Principal("CN=Local Host"));
assertThat(response.handshake().localPrincipal()).isNull();
assertThat(response.body().string()).isEqualTo("abc");
}
@Test public void missingClientAuthFailsForNeeds() throws Exception {
@ -191,9 +196,9 @@ public final class ClientAuthTest {
} catch (SSLHandshakeException expected) {
} catch (SSLException expected) {
String jvmVersion = System.getProperty("java.specification.version");
assertEquals("11", jvmVersion);
assertThat(jvmVersion).isEqualTo("11");
} catch (SocketException expected) {
assertEquals("jdk9", getPlatform());
assertThat(getPlatform()).isEqualTo("jdk9");
}
}
@ -247,9 +252,9 @@ public final class ClientAuthTest {
} catch (SSLException expected) {
// javax.net.ssl.SSLException: readRecord
String jvmVersion = System.getProperty("java.specification.version");
assertEquals("11", jvmVersion);
assertThat(jvmVersion).isEqualTo("11");
} 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 static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class DistinguishedNameParserTest {
@ -120,7 +120,8 @@ public final class DistinguishedNameParserTest {
private void assertCn(String expected, String dn) {
X500Principal principal = new X500Principal(dn);
DistinguishedNameParser parser = new DistinguishedNameParser(principal);
assertEquals(dn, expected, parser.findMostSpecific("cn"));
assertThat(parser.findMostSpecific("cn")).overridingErrorMessage(dn).isEqualTo(
expected);
}
private void expectExceptionInPrincipal(String dn) {

View File

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

View File

@ -32,9 +32,8 @@ import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.Offset.offset;
import static org.junit.Assert.fail;
public final class RealWebSocketTest {
@ -65,10 +64,11 @@ public final class RealWebSocketTest {
@Test public void close() throws IOException {
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.webSocket.close(1000, "Goodbye!");
assertFalse(client.processNextFrame());
assertThat(client.processNextFrame()).isFalse();
client.listener.assertClosing(1000, "Goodbye!");
server.listener.assertClosed(1000, "Hello!");
client.listener.assertClosed(1000, "Goodbye!");
@ -77,8 +77,8 @@ public final class RealWebSocketTest {
@Test public void clientCloseThenMethodsReturnFalse() throws IOException {
client.webSocket.close(1000, "Hello!");
assertFalse(client.webSocket.close(1000, "Hello!"));
assertFalse(client.webSocket.send("Hello!"));
assertThat(client.webSocket.close(1000, "Hello!")).isFalse();
assertThat(client.webSocket.send("Hello!")).isFalse();
}
@Test public void clientCloseWith0Fails() throws IOException {
@ -86,7 +86,7 @@ public final class RealWebSocketTest {
client.webSocket.close(0, null);
fail();
} 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.listener.assertFailure(IOException.class, "source is closed");
assertFalse(client.webSocket.send("Hello!"));
assertThat(client.webSocket.send("Hello!")).isFalse();
}
@Test public void socketClosedDuringMessageKillsWebSocket() throws IOException {
client2Server.source().close();
assertTrue(client.webSocket.send("Hello!"));
assertThat(client.webSocket.send("Hello!")).isTrue();
client.listener.assertFailure(IOException.class, "source is closed");
// A failed write prevents further use of the WebSocket instance.
assertFalse(client.webSocket.send("Hello!"));
assertFalse(client.webSocket.pong(ByteString.encodeUtf8("Ping!")));
assertThat(client.webSocket.send("Hello!")).isFalse();
assertThat(client.webSocket.pong(ByteString.encodeUtf8("Ping!"))).isFalse();
}
@Test public void serverCloseThenWritingPingSucceeds() throws IOException {
@ -114,7 +114,7 @@ public final class RealWebSocketTest {
client.processNextFrame();
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 {
@ -122,7 +122,7 @@ public final class RealWebSocketTest {
client.processNextFrame();
client.listener.assertClosing(1000, "Hello!");
assertTrue(client.webSocket.send("Hi!"));
assertThat(client.webSocket.send("Hi!")).isTrue();
server.processNextFrame();
server.listener.assertTextMessage("Hi!");
}
@ -131,7 +131,7 @@ public final class RealWebSocketTest {
server.webSocket.close(1000, "Hello!");
client.processNextFrame();
client.listener.assertClosing(1000, "Hello!");
assertTrue(client.webSocket.close(1000, "Bye!"));
assertThat(client.webSocket.close(1000, "Bye!")).isTrue();
}
@Test public void emptyCloseInitiatesShutdown() throws IOException {
@ -139,7 +139,7 @@ public final class RealWebSocketTest {
client.processNextFrame();
client.listener.assertClosing(1005, "");
assertTrue(client.webSocket.close(1000, "Bye!"));
assertThat(client.webSocket.close(1000, "Bye!")).isTrue();
server.processNextFrame();
server.listener.assertClosing(1000, "Bye!");
@ -148,13 +148,13 @@ public final class RealWebSocketTest {
@Test public void clientCloseClosesConnection() throws IOException {
client.webSocket.close(1000, "Hello!");
assertFalse(client.closed);
assertThat(client.closed).isFalse();
server.processNextFrame(); // Read client closing, send server close.
server.listener.assertClosing(1000, "Hello!");
server.webSocket.close(1000, "Goodbye!");
client.processNextFrame(); // Read server closing, close connection.
assertTrue(client.closed);
assertThat(client.closed).isTrue();
client.listener.assertClosing(1000, "Goodbye!");
// Server and client both finished closing, connection is closed.
@ -166,7 +166,7 @@ public final class RealWebSocketTest {
server.webSocket.close(1000, "Hello!");
client.processNextFrame(); // Read server close, send client close, close connection.
assertFalse(client.closed);
assertThat(client.closed).isFalse();
client.listener.assertClosing(1000, "Hello!");
client.webSocket.close(1000, "Hello!");
@ -182,7 +182,7 @@ public final class RealWebSocketTest {
server.webSocket.close(1000, "Hello!");
client.processNextFrame(); // Read close, close connection close.
assertFalse(client.closed);
assertThat(client.closed).isFalse();
client.webSocket.close(1000, "Hi!");
server.processNextFrame();
@ -191,7 +191,7 @@ public final class RealWebSocketTest {
client.listener.assertClosed(1000, "Hello!");
server.listener.assertClosed(1000, "Hi!");
client.webSocket.awaitTermination(5, TimeUnit.SECONDS);
assertTrue(client.closed);
assertThat(client.closed).isTrue();
server.listener.assertExhausted(); // Client 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 {
server.webSocket.send("Hello!");
server.webSocket.close(1000, "Bye!");
assertTrue(client.processNextFrame());
assertThat(client.processNextFrame()).isTrue();
client.listener.assertTextMessage("Hello!");
assertFalse(client.processNextFrame());
assertThat(client.processNextFrame()).isFalse();
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.
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.");
server.processNextFrame();
@ -220,13 +220,14 @@ public final class RealWebSocketTest {
@Test public void protocolErrorInCloseResponseClosesConnection() throws IOException {
client.webSocket.close(1000, "Hello");
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.
server.sink.write(ByteString.decodeHex("888760b420bb635c68de0cd84f")).emit();
client.processNextFrame();// Detects error, disconnects immediately since close already sent.
assertTrue(client.closed);
assertThat(client.closed).isTrue();
client.listener.assertFailure(
ProtocolException.class, "Server-sent frames must not be masked.");
@ -238,11 +239,12 @@ public final class RealWebSocketTest {
client.webSocket.close(1000, "Hello!");
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.
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.");
server.listener.assertClosing(1000, "Hello!");
@ -269,7 +271,7 @@ public final class RealWebSocketTest {
client.webSocket.close(1000, "Bye!");
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.
@ -292,17 +294,20 @@ public final class RealWebSocketTest {
server.processNextFrame(); // Ping.
client.processNextFrame(); // Pong.
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.
client.processNextFrame(); // Pong.
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.
client.processNextFrame(); // Pong.
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 {
@ -313,7 +318,8 @@ public final class RealWebSocketTest {
client.listener.assertFailure(SocketTimeoutException.class,
"sent ping but didn't receive pong within 500ms (after 0 successful ping/pongs)");
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 {
@ -332,14 +338,16 @@ public final class RealWebSocketTest {
server.processNextFrame(); // Ping.
client.processNextFrame(); // Pong.
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
// 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,
"sent ping but didn't receive pong within 500ms (after 1 successful ping/pongs)");
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. */

View File

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

View File

@ -26,8 +26,7 @@ import okio.ByteString;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class WebSocketReaderTest {
@ -49,7 +48,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame();
fail();
} 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();
fail();
} catch (ProtocolException e) {
assertEquals("Reserved flags are unsupported.", e.getMessage());
assertThat(e.getMessage()).isEqualTo("Reserved flags are unsupported.");
}
data.clear();
data.write(ByteString.decodeHex("aa00")); // Empty ping, flag 2 set.
@ -67,7 +66,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame();
fail();
} catch (ProtocolException e) {
assertEquals("Reserved flags are unsupported.", e.getMessage());
assertThat(e.getMessage()).isEqualTo("Reserved flags are unsupported.");
}
data.clear();
data.write(ByteString.decodeHex("ca00")); // Empty ping, flag 3 set.
@ -75,7 +74,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame();
fail();
} 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();
fail();
} 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();
fail();
} 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();
fail();
} 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();
fail();
} 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();
fail();
} 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();
fail();
} 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();
fail();
} 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
try {
clientReader.processNextFrame();
fail();
} 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();
} catch (ProtocolException e) {
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) {

View File

@ -28,10 +28,7 @@ import okhttp3.WebSocketListener;
import okhttp3.internal.platform.Platform;
import okio.ByteString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
public final class WebSocketRecorder extends WebSocketListener {
private final String name;
@ -135,36 +132,36 @@ public final class WebSocketRecorder extends WebSocketListener {
public void assertTextMessage(String payload) {
Object actual = nextEvent();
assertEquals(new Message(payload), actual);
assertThat(actual).isEqualTo(new Message(payload));
}
public void assertBinaryMessage(ByteString payload) {
Object actual = nextEvent();
assertEquals(new Message(payload), actual);
assertThat(actual).isEqualTo(new Message(payload));
}
public void assertPing(ByteString payload) {
Object actual = nextEvent();
assertEquals(new Ping(payload), actual);
assertThat(actual).isEqualTo(new Ping(payload));
}
public void assertPong(ByteString payload) {
Object actual = nextEvent();
assertEquals(new Pong(payload), actual);
assertThat(actual).isEqualTo(new Pong(payload));
}
public void assertClosing(int code, String reason) {
Object actual = nextEvent();
assertEquals(new Closing(code, reason), actual);
assertThat(actual).isEqualTo(new Closing(code, reason));
}
public void assertClosed(int code, String reason) {
Object actual = nextEvent();
assertEquals(new Closed(code, reason), actual);
assertThat(actual).isEqualTo(new Closed(code, reason));
}
public void assertExhausted() {
assertTrue("Remaining events: " + events, events.isEmpty());
assertThat(events.isEmpty()).overridingErrorMessage("Remaining events: " + events).isTrue();
}
public WebSocket assertOpen() {
@ -181,8 +178,8 @@ public final class WebSocketRecorder extends WebSocketListener {
throw new AssertionError("Expected Failure but was " + event);
}
Failure failure = (Failure) event;
assertNull(failure.response);
assertSame(t, failure.t);
assertThat(failure.response).isNull();
assertThat(failure.t).isSameAs(t);
}
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);
}
Failure failure = (Failure) event;
assertNull(failure.response);
assertEquals(cls, failure.t.getClass());
assertThat(failure.response).isNull();
assertThat(failure.t.getClass()).isEqualTo(cls);
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);
}
Failure failure = (Failure) event;
assertEquals(code, failure.response.code());
assertThat(failure.response.code()).isEqualTo(code);
if (body != null) {
assertEquals(body, failure.responseBody);
assertThat(failure.responseBody).isEqualTo(body);
}
assertEquals(cls, failure.t.getClass());
assertEquals(message, failure.t.getMessage());
assertThat(failure.t.getClass()).isEqualTo(cls);
assertThat(failure.t.getMessage()).isEqualTo(message);
}
/** 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.PAYLOAD_BYTE_MAX;
import static okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_SHORT_MAX;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class WebSocketWriterTest {
@ -50,7 +49,8 @@ public final class WebSocketWriterTest {
@Rule public final TestRule noDataLeftBehind = (base, description) -> new Statement() {
@Override public void evaluate() throws Throwable {
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(bytes);
assertTrue(data.exhausted());
assertThat(data.exhausted()).isTrue();
}
@Test public void serverLargeBufferedPayloadWrittenAsOneFrame() throws IOException {
@ -97,7 +97,7 @@ public final class WebSocketWriterTest {
assertData("817e");
assertData(Util.format("%04x", length));
assertData(bytes);
assertTrue(data.exhausted());
assertThat(data.exhausted()).isTrue();
}
@Test public void serverLargeNonBufferedPayloadWrittenAsMultipleFrames() throws IOException {
@ -125,7 +125,7 @@ public final class WebSocketWriterTest {
assertData(bytes.readByteArray(24_576));
assertData("807e06a0");
assertData(bytes.readByteArray(1_696));
assertTrue(data.exhausted());
assertThat(data.exhausted()).isTrue();
}
@Test public void closeFlushes() throws IOException {
@ -150,7 +150,7 @@ public final class WebSocketWriterTest {
sink.write(payload, payload.size());
fail();
} 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"));
fail();
} 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"));
fail();
} 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)));
fail();
} 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)));
fail();
} 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);
fail();
} 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);
fail();
} 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 {
ByteString actual = data.readByteString(expected.size());
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
private void assertData(byte[] data) throws IOException {
@ -394,7 +398,8 @@ public final class WebSocketWriterTest {
int count = Math.min(byteCount, data.length - i);
Buffer expectedChunk = new Buffer();
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>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -38,8 +38,7 @@ import org.junit.Before;
import org.junit.Test;
import static okhttp3.internal.Util.closeQuietly;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
public final class HandshakeCertificatesTest {
private ExecutorService executorService;
@ -92,17 +91,16 @@ public final class HandshakeCertificatesTest {
Future<Handshake> clientHandshakeFuture = doClientHandshake(client, serverAddress);
Handshake serverHandshake = serverHandshakeFuture.get();
assertEquals(serverHandshake.peerCertificates(),
Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate()));
assertEquals(serverHandshake.localCertificates(),
Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate()));
assertThat(Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate())).isEqualTo(
serverHandshake.peerCertificates());
assertThat(Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate())).isEqualTo(
serverHandshake.localCertificates());
Handshake clientHandshake = clientHandshakeFuture.get();
assertEquals(clientHandshake.peerCertificates(),
Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate()));
assertEquals(clientHandshake.localCertificates(),
Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate()));
assertThat(Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate())).isEqualTo(
clientHandshake.peerCertificates());
assertThat(Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate())).isEqualTo(
clientHandshake.localCertificates());
}
@Test public void keyManager() {
@ -122,8 +120,8 @@ public final class HandshakeCertificatesTest {
.build();
assertPrivateKeysEquals(certificate.keyPair().getPrivate(),
handshakeCertificates.keyManager().getPrivateKey("private"));
assertEquals(Arrays.asList(certificate.certificate(), intermediate.certificate()),
Arrays.asList(handshakeCertificates.keyManager().getCertificateChain("private")));
assertThat(Arrays.asList(handshakeCertificates.keyManager().getCertificateChain("private"))).isEqualTo(
Arrays.asList(certificate.certificate(), intermediate.certificate()));
}
@Test public void platformTrustedCertificates() {
@ -137,7 +135,7 @@ public final class HandshakeCertificatesTest {
names.add(name.substring(0, name.indexOf(" ")));
}
// 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 {
@ -186,6 +184,7 @@ public final class HandshakeCertificatesTest {
}
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.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.Offset.offset;
public final class HeldCertificateTest {
@Test public void defaultCertificate() throws CertificateParsingException {
@ -41,17 +40,18 @@ public final class HeldCertificateTest {
HeldCertificate heldCertificate = new HeldCertificate.Builder().build();
X509Certificate certificate = heldCertificate.certificate();
assertEquals("self-signed",
certificate.getIssuerX500Principal().getName(),
certificate.getSubjectX500Principal().getName());
assertTrue(certificate.getIssuerX500Principal().getName().matches("CN=[0-9a-f-]{36}"));
assertEquals(BigInteger.ONE, certificate.getSerialNumber());
assertNull(certificate.getSubjectAlternativeNames());
assertThat(certificate.getSubjectX500Principal().getName()).overridingErrorMessage(
"self-signed").isEqualTo(certificate.getIssuerX500Principal().getName());
assertThat(certificate.getIssuerX500Principal().getName().matches("CN=[0-9a-f-]{36}")).isTrue();
assertThat(certificate.getSerialNumber()).isEqualTo(BigInteger.ONE);
assertThat(certificate.getSubjectAlternativeNames()).isNull();
double deltaMillis = 1000.0;
long durationMillis = TimeUnit.MINUTES.toMillis(60 * 24);
assertEquals((double) now, certificate.getNotBefore().getTime(), deltaMillis);
assertEquals((double) now + durationMillis, certificate.getNotAfter().getTime(), deltaMillis);
assertThat((double) certificate.getNotBefore().getTime()).isCloseTo(
(double) now, offset(deltaMillis));
assertThat((double) certificate.getNotAfter().getTime()).isCloseTo(
(double) now + durationMillis, offset(deltaMillis));
}
@Test public void customInterval() {
@ -60,8 +60,8 @@ public final class HeldCertificateTest {
.validityInterval(5_000L, 10_000L)
.build();
X509Certificate certificate = heldCertificate.certificate();
assertEquals(5_000L, certificate.getNotBefore().getTime());
assertEquals(10_000L, certificate.getNotAfter().getTime());
assertThat(certificate.getNotBefore().getTime()).isEqualTo(5_000L);
assertThat(certificate.getNotAfter().getTime()).isEqualTo(10_000L);
}
@Test public void customDuration() {
@ -74,8 +74,10 @@ public final class HeldCertificateTest {
double deltaMillis = 1000.0;
long durationMillis = 5_000L;
assertEquals((double) now, certificate.getNotBefore().getTime(), deltaMillis);
assertEquals((double) now + durationMillis, certificate.getNotAfter().getTime(), deltaMillis);
assertThat((double) certificate.getNotBefore().getTime()).isCloseTo(
(double) now, offset(deltaMillis));
assertThat((double) certificate.getNotAfter().getTime()).isCloseTo(
(double) now + durationMillis, offset(deltaMillis));
}
@Test public void subjectAlternativeNames() throws CertificateParsingException {
@ -87,9 +89,9 @@ public final class HeldCertificateTest {
X509Certificate certificate = heldCertificate.certificate();
List<List<?>> subjectAlternativeNames = new ArrayList<>(
certificate.getSubjectAlternativeNames());
assertEquals(subjectAlternativeNames, Arrays.asList(
assertThat(Arrays.asList(
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() {
@ -98,7 +100,7 @@ public final class HeldCertificateTest {
.build();
X509Certificate certificate = heldCertificate.certificate();
assertEquals("CN=cash.app", certificate.getSubjectX500Principal().getName());
assertThat(certificate.getSubjectX500Principal().getName()).isEqualTo("CN=cash.app");
}
@Test public void organizationalUnit() {
@ -108,7 +110,8 @@ public final class HeldCertificateTest {
.build();
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. */
@ -142,7 +145,7 @@ public final class HeldCertificateTest {
.rsa2048()
.build();
assertEquals(heldCertificate.certificatePem(), ""
assertThat((""
+ "-----BEGIN CERTIFICATE-----\n"
+ "MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\n"
+ "LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT\n"
@ -153,9 +156,9 @@ public final class HeldCertificateTest {
+ "UVwKh5Ry7es3OxtY3IgQunPUoLc0Gw71gl9Z+7t2FJ5VkcI5gWfutmdxZ2bDXCI8\n"
+ "8V0vxo1pHXnbBrnxhS/Z3TBerw8RyQqcaWOdp+pBXyIWmR+jHk9cHZCqQveTIBsY\n"
+ "jaA9VEhgdaVhxBsT2qzUNDsXlOzGsliznDfoqETb\n"
+ "-----END CERTIFICATE-----\n");
+ "-----END CERTIFICATE-----\n")).isEqualTo(heldCertificate.certificatePem());
assertEquals(heldCertificate.privateKeyPkcs1Pem(), ""
assertThat((""
+ "-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIICWwIBAAKBgQCApFHhtrLan28q+oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1w\n"
+ "J4YEoUCjDlPOtpht7XLbUmBnbIzN89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274w\n"
@ -170,9 +173,9 @@ public final class HeldCertificateTest {
+ "xs/h8kq5HE+woNdjPzZHVEJ2Xt46/PKbf/iBjcKJnOlrf5ieH3FjjU5BjHHzmX39\n"
+ "TUHjVwwGeveNVwrCFQJAEjoNNj5VRy4nVO5iBOubMDDOf0TYUuGhY3s/zMMRTTh2\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"
+ "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAICkUeG2stqfbyr6\n"
+ "gyiVm5pN9YEDRXlowi+rfYGyWhC7ouW9fXAnhgShQKMOU862mG3tcttSYGdsjM3z\n"
@ -188,7 +191,7 @@ public final class HeldCertificateTest {
+ "8pt/+IGNwomc6Wt/mJ4fcWONTkGMcfOZff1NQeNXDAZ6941XCsIVAkASOg02PlVH\n"
+ "LidU7mIE65swMM5/RNhS4aFjez/MwxFNOHaxc9VgCwYPXCLOtdf7AVovdyG0XWgb\n"
+ "UXH+NyxKwboE\n"
+ "-----END PRIVATE KEY-----\n");
+ "-----END PRIVATE KEY-----\n")).isEqualTo(heldCertificate.privateKeyPkcs8Pem());
}
@Test public void ecdsaSignedByRsa() {
@ -202,8 +205,8 @@ public final class HeldCertificateTest {
.signedBy(root)
.build();
assertEquals("SHA256WITHRSA", root.certificate().getSigAlgName());
assertEquals("SHA256WITHRSA", leaf.certificate().getSigAlgName());
assertThat(root.certificate().getSigAlgName()).isEqualTo("SHA256WITHRSA");
assertThat(leaf.certificate().getSigAlgName()).isEqualTo("SHA256WITHRSA");
}
@Test public void rsaSignedByEcdsa() {
@ -217,7 +220,7 @@ public final class HeldCertificateTest {
.signedBy(root)
.build();
assertEquals("SHA256WITHECDSA", root.certificate().getSigAlgName());
assertEquals("SHA256WITHECDSA", leaf.certificate().getSigAlgName());
assertThat(root.certificate().getSigAlgName()).isEqualTo("SHA256WITHECDSA");
assertThat(leaf.certificate().getSigAlgName()).isEqualTo("SHA256WITHECDSA");
}
}

View File

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

View File

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