From 6c4855a7c7f1bfd8838bfaa54640d68b60697c0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Quenaudon?= Date: Wed, 13 Mar 2019 21:07:33 -0400 Subject: [PATCH] Use AssertJ in tests (#4713) --- mockwebserver/pom.xml | 5 + .../mockwebserver/CustomDispatcherTest.java | 18 +- .../mockwebserver/MockWebServerTest.java | 190 +-- .../mockwebserver/RecordedRequestTest.java | 8 +- okcurl/pom.xml | 5 + .../src/test/java/okhttp3/curl/MainTest.java | 60 +- okhttp-dnsoverhttps/pom.xml | 5 + .../dnsoverhttps/DnsOverHttpsTest.java | 57 +- .../dnsoverhttps/DnsRecordCodecTest.java | 17 +- okhttp-hpacktests/pom.xml | 7 +- .../internal/http2/HpackDecodeTestBase.java | 5 +- okhttp-logging-interceptor/pom.xml | 5 + .../logging/HttpLoggingInterceptorTest.java | 46 +- .../logging/LoggingEventListenerTest.java | 6 +- okhttp-sse/pom.xml | 5 + .../internal/sse/EventSourceHttpTest.java | 6 +- .../internal/sse/EventSourceRecorder.java | 12 +- .../sse/ServerSentEventIteratorTest.java | 54 +- okhttp-testing-support/pom.xml | 4 + .../src/main/java/okhttp3/FakeDns.java | 5 +- .../main/java/okhttp3/RecordingCookieJar.java | 4 +- .../src/main/java/okhttp3/TestUtil.java | 4 +- okhttp-tests/pom.xml | 5 + .../src/test/java/okhttp3/AddressTest.java | 16 +- .../test/java/okhttp3/CacheControlTest.java | 153 +- .../src/test/java/okhttp3/CacheTest.java | 729 ++++----- .../src/test/java/okhttp3/CallTest.java | 605 ++++---- .../okhttp3/CertificateChainCleanerTest.java | 57 +- .../java/okhttp3/CertificatePinnerTest.java | 51 +- .../test/java/okhttp3/CipherSuiteTest.java | 59 +- .../okhttp3/ConnectionCoalescingTest.java | 28 +- .../java/okhttp3/ConnectionReuseTest.java | 59 +- .../test/java/okhttp3/ConnectionSpecTest.java | 94 +- .../src/test/java/okhttp3/ConscryptTest.java | 12 +- .../src/test/java/okhttp3/CookieTest.java | 436 +++--- .../src/test/java/okhttp3/CookiesTest.java | 92 +- .../src/test/java/okhttp3/DispatcherTest.java | 71 +- .../src/test/java/okhttp3/DuplexTest.java | 53 +- .../test/java/okhttp3/EventListenerTest.java | 234 +-- .../src/test/java/okhttp3/FormBodyTest.java | 205 +-- .../src/test/java/okhttp3/HeadersTest.java | 318 ++-- .../src/test/java/okhttp3/HttpUrlTest.java | 1341 +++++++++-------- .../test/java/okhttp3/InterceptorTest.java | 126 +- .../src/test/java/okhttp3/MediaTypeTest.java | 67 +- .../test/java/okhttp3/MultipartBodyTest.java | 69 +- .../test/java/okhttp3/OkHttpClientTest.java | 56 +- .../src/test/java/okhttp3/ProtocolTest.java | 26 +- .../test/java/okhttp3/RecordedResponse.java | 69 +- .../java/okhttp3/RecordingEventListener.java | 9 +- .../src/test/java/okhttp3/RequestTest.java | 146 +- .../test/java/okhttp3/ResponseBodyTest.java | 99 +- .../src/test/java/okhttp3/ResponseTest.java | 18 +- .../src/test/java/okhttp3/SocksProxyTest.java | 16 +- .../test/java/okhttp3/URLConnectionTest.java | 728 +++++---- .../test/java/okhttp3/WebPlatformUrlTest.java | 22 +- .../okhttp3/WholeOperationTimeoutTest.java | 43 +- .../test/java/okhttp3/internal/UtilTest.java | 6 +- .../internal/cache/DiskLruCacheTest.java | 310 ++-- .../internal/cache2/FileOperatorTest.java | 26 +- .../okhttp3/internal/cache2/RelayTest.java | 97 +- .../connection/ConnectionPoolTest.java | 105 +- .../ConnectionSpecSelectorTest.java | 16 +- .../connection/RouteExceptionTest.java | 17 +- .../connection/RouteSelectorTest.java | 123 +- .../okhttp3/internal/http/HttpDateTest.java | 46 +- .../internal/http/RecordingProxySelector.java | 4 +- .../okhttp3/internal/http/StatusLineTest.java | 26 +- .../okhttp3/internal/http2/FrameLogTest.java | 78 +- .../okhttp3/internal/http2/HpackTest.java | 241 +-- .../internal/http2/Http2ConnectionTest.java | 571 +++---- .../okhttp3/internal/http2/Http2Test.java | 171 ++- .../internal/http2/HttpOverHttp2Test.java | 382 ++--- .../okhttp3/internal/http2/HuffmanTest.java | 4 +- .../okhttp3/internal/http2/SettingsTest.java | 36 +- .../Jdk8WithJettyBootPlatformTest.java | 4 +- .../internal/platform/Jdk9PlatformTest.java | 11 +- .../internal/platform/PlatformTest.java | 6 +- .../PublicSuffixDatabaseTest.java | 65 +- .../CertificatePinnerChainValidationTest.java | 17 +- .../okhttp3/internal/tls/ClientAuthTest.java | 41 +- .../tls/DistinguishedNameParserTest.java | 5 +- .../internal/tls/HostnameVerifierTest.java | 145 +- .../internal/ws/RealWebSocketTest.java | 78 +- .../internal/ws/WebSocketHttpTest.java | 72 +- .../internal/ws/WebSocketReaderTest.java | 33 +- .../internal/ws/WebSocketRecorder.java | 38 +- .../internal/ws/WebSocketWriterTest.java | 35 +- okhttp-tls/pom.xml | 5 + .../tls/HandshakeCertificatesTest.java | 29 +- .../java/okhttp3/tls/HeldCertificateTest.java | 61 +- okhttp-urlconnection/pom.xml | 5 + pom.xml | 7 + 92 files changed, 4937 insertions(+), 4619 deletions(-) diff --git a/mockwebserver/pom.xml b/mockwebserver/pom.xml index 888ddcf7c..acd99abb2 100644 --- a/mockwebserver/pom.xml +++ b/mockwebserver/pom.xml @@ -34,6 +34,11 @@ junit junit + + org.assertj + assertj-core + test + diff --git a/mockwebserver/src/test/java/okhttp3/mockwebserver/CustomDispatcherTest.java b/mockwebserver/src/test/java/okhttp3/mockwebserver/CustomDispatcherTest.java index 0a43dd916..ab69ac808 100644 --- a/mockwebserver/src/test/java/okhttp3/mockwebserver/CustomDispatcherTest.java +++ b/mockwebserver/src/test/java/okhttp3/mockwebserver/CustomDispatcherTest.java @@ -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) { diff --git a/mockwebserver/src/test/java/okhttp3/mockwebserver/MockWebServerTest.java b/mockwebserver/src/test/java/okhttp3/mockwebserver/MockWebServerTest.java index 67f417e73..df4d59b4a 100644 --- a/mockwebserver/src/test/java/okhttp3/mockwebserver/MockWebServerTest.java +++ b/mockwebserver/src/test/java/okhttp3/mockwebserver/MockWebServerTest.java @@ -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); } } diff --git a/mockwebserver/src/test/java/okhttp3/mockwebserver/RecordedRequestTest.java b/mockwebserver/src/test/java/okhttp3/mockwebserver/RecordedRequestTest.java index acd37905f..8a58c17e2 100644 --- a/mockwebserver/src/test/java/okhttp3/mockwebserver/RecordedRequestTest.java +++ b/mockwebserver/src/test/java/okhttp3/mockwebserver/RecordedRequestTest.java @@ -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/"); } } diff --git a/okcurl/pom.xml b/okcurl/pom.xml index 48ee2a4b7..63032f87a 100644 --- a/okcurl/pom.xml +++ b/okcurl/pom.xml @@ -43,6 +43,11 @@ junit test + + org.assertj + assertj-core + test + diff --git a/okcurl/src/test/java/okhttp3/curl/MainTest.java b/okcurl/src/test/java/okhttp3/curl/MainTest.java index 12fe6d5ec..d4542fbed 100644 --- a/okcurl/src/test/java/okhttp3/curl/MainTest.java +++ b/okcurl/src/test/java/okhttp3/curl/MainTest.java @@ -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) { diff --git a/okhttp-dnsoverhttps/pom.xml b/okhttp-dnsoverhttps/pom.xml index 8c72b658b..1fafbb7dc 100644 --- a/okhttp-dnsoverhttps/pom.xml +++ b/okhttp-dnsoverhttps/pom.xml @@ -46,6 +46,11 @@ conscrypt-openjdk-uber test + + org.assertj + assertj-core + test + diff --git a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.java b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.java index c6c16278d..6c939bfdb 100644 --- a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.java +++ b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.java @@ -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 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 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 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) { diff --git a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.java b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.java index 3a12b4d25..8eea96c7b 100644 --- a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.java +++ b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.java @@ -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 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 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 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"); } } } diff --git a/okhttp-hpacktests/pom.xml b/okhttp-hpacktests/pom.xml index a2a22ae36..d45338750 100644 --- a/okhttp-hpacktests/pom.xml +++ b/okhttp-hpacktests/pom.xml @@ -8,7 +8,7 @@ com.squareup.okhttp3 parent - 3.13.0-SNAPSHOT + 3.14.0-SNAPSHOT okhttp-hpacktests @@ -45,6 +45,11 @@ ${project.version} test + + org.assertj + assertj-core + test + diff --git a/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeTestBase.java b/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeTestBase.java index a3f69da38..879fe6aba 100644 --- a/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeTestBase.java +++ b/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeTestBase.java @@ -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
expected, List
observed) { - assertEquals(message, new LinkedHashSet<>(expected), new LinkedHashSet<>(observed)); + assertThat(new LinkedHashSet<>(observed)).overridingErrorMessage(message).isEqualTo( + new LinkedHashSet<>(expected)); } protected Story getStory() { diff --git a/okhttp-logging-interceptor/pom.xml b/okhttp-logging-interceptor/pom.xml index 35bbc9a52..dfc7064db 100644 --- a/okhttp-logging-interceptor/pom.xml +++ b/okhttp-logging-interceptor/pom.xml @@ -47,6 +47,11 @@ ${project.version} test + + org.assertj + assertj-core + test + diff --git a/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java b/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java index 1a6bf878b..a3d18befe 100644 --- a/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java +++ b/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java @@ -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) { diff --git a/okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.java b/okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.java index 946ab4424..a1d301542 100644 --- a/okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.java +++ b/okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.java @@ -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 diff --git a/okhttp-sse/pom.xml b/okhttp-sse/pom.xml index bf4c8c459..298331770 100644 --- a/okhttp-sse/pom.xml +++ b/okhttp-sse/pom.xml @@ -41,6 +41,11 @@ ${project.version} test + + org.assertj + assertj-core + test + diff --git a/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceHttpTest.java b/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceHttpTest.java index 8b7da9a1d..0dbec41be 100644 --- a/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceHttpTest.java +++ b/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceHttpTest.java @@ -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"); diff --git a/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceRecorder.java b/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceRecorder.java index cf4afd4ec..ffcf8daa9 100644 --- a/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceRecorder.java +++ b/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceRecorder.java @@ -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 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(); } } diff --git a/okhttp-sse/src/test/java/okhttp3/internal/sse/ServerSentEventIteratorTest.java b/okhttp-sse/src/test/java/okhttp3/internal/sse/ServerSentEventIteratorTest.java index 697a2d201..77297370a 100644 --- a/okhttp-sse/src/test/java/okhttp3/internal/sse/ServerSentEventIteratorTest.java +++ b/okhttp-sse/src/test/java/okhttp3/internal/sse/ServerSentEventIteratorTest.java @@ -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 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); } } diff --git a/okhttp-testing-support/pom.xml b/okhttp-testing-support/pom.xml index c73293ed1..50f0635ff 100644 --- a/okhttp-testing-support/pom.xml +++ b/okhttp-testing-support/pom.xml @@ -28,6 +28,10 @@ jsr305 provided + + org.assertj + assertj-core + diff --git a/okhttp-testing-support/src/main/java/okhttp3/FakeDns.java b/okhttp-testing-support/src/main/java/okhttp3/FakeDns.java index e12ea9c62..82cacacba 100644 --- a/okhttp-testing-support/src/main/java/okhttp3/FakeDns.java +++ b/okhttp-testing-support/src/main/java/okhttp3/FakeDns.java @@ -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> 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(); } diff --git a/okhttp-testing-support/src/main/java/okhttp3/RecordingCookieJar.java b/okhttp-testing-support/src/main/java/okhttp3/RecordingCookieJar.java index bd4f9be14..a4988b8e3 100644 --- a/okhttp-testing-support/src/main/java/okhttp3/RecordingCookieJar.java +++ b/okhttp-testing-support/src/main/java/okhttp3/RecordingCookieJar.java @@ -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> 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 cookies) { diff --git a/okhttp-testing-support/src/main/java/okhttp3/TestUtil.java b/okhttp-testing-support/src/main/java/okhttp3/TestUtil.java index a1fc9db52..f3038c090 100644 --- a/okhttp-testing-support/src/main/java/okhttp3/TestUtil.java +++ b/okhttp-testing-support/src/main/java/okhttp3/TestUtil.java @@ -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); } } diff --git a/okhttp-tests/pom.xml b/okhttp-tests/pom.xml index 1b0bd2b99..d7f65dbc3 100644 --- a/okhttp-tests/pom.xml +++ b/okhttp-tests/pom.xml @@ -66,6 +66,11 @@ ${project.version} test + + org.assertj + assertj-core + test + diff --git a/okhttp-tests/src/test/java/okhttp3/AddressTest.java b/okhttp-tests/src/test/java/okhttp3/AddressTest.java index 7a1b7f1bd..9d3bf4165 100644 --- a/okhttp-tests/src/test/java/okhttp3/AddressTest.java +++ b/okhttp-tests/src/test/java/okhttp3/AddressTest.java @@ -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 + "}"); } } diff --git a/okhttp-tests/src/test/java/okhttp3/CacheControlTest.java b/okhttp-tests/src/test/java/okhttp3/CacheControlTest.java index 356f96ab4..a1030b611 100644 --- a/okhttp-tests/src/test/java/okhttp3/CacheControlTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CacheControlTest.java @@ -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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/CacheTest.java b/okhttp-tests/src/test/java/okhttp3/CacheTest.java index ece9069d9..e8f00dbea 100644 --- a/okhttp-tests/src/test/java/okhttp3/CacheTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CacheTest.java @@ -53,11 +53,8 @@ import org.junit.Test; import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AT_END; 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 CacheTest { @@ -181,17 +178,17 @@ public final class CacheTest { .url(server.url("/")) .build(); Response response = client.newCall(request).execute(); - assertEquals(expectedResponseCode, response.code()); + assertThat(response.code()).isEqualTo(expectedResponseCode); // Exhaust the content stream. response.body().string(); Response cached = cache.get(request); if (shouldPut) { - assertNotNull(Integer.toString(responseCode), cached); + assertThat(cached).isNotNull(); cached.body().close(); } else { - assertNull(Integer.toString(responseCode), cached); + assertThat(cached).isNull(); } server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers } @@ -225,27 +222,27 @@ public final class CacheTest { Response response1 = client.newCall(request).execute(); BufferedSource in1 = response1.body().source(); - assertEquals("I love ", in1.readUtf8("I love ".length())); + assertThat(in1.readUtf8("I love ".length())).isEqualTo("I love "); in1.skip("puppies but hate ".length()); - assertEquals("spiders", in1.readUtf8("spiders".length())); - assertTrue(in1.exhausted()); + assertThat(in1.readUtf8("spiders".length())).isEqualTo("spiders"); + assertThat(in1.exhausted()).isTrue(); in1.close(); - assertEquals(1, cache.writeSuccessCount()); - assertEquals(0, cache.writeAbortCount()); + assertThat(cache.writeSuccessCount()).isEqualTo(1); + assertThat(cache.writeAbortCount()).isEqualTo(0); Response response2 = client.newCall(request).execute(); BufferedSource in2 = response2.body().source(); - assertEquals("I love puppies but hate spiders", - in2.readUtf8("I love puppies but hate spiders".length())); - assertEquals(200, response2.code()); - assertEquals("Fantastic", response2.message()); + assertThat(in2.readUtf8("I love puppies but hate spiders".length())).isEqualTo( + "I love puppies but hate spiders"); + assertThat(response2.code()).isEqualTo(200); + assertThat(response2.message()).isEqualTo("Fantastic"); - assertTrue(in2.exhausted()); + assertThat(in2.exhausted()).isTrue(); in2.close(); - assertEquals(1, cache.writeSuccessCount()); - assertEquals(0, cache.writeAbortCount()); - assertEquals(2, cache.requestCount()); - assertEquals(1, cache.hitCount()); + assertThat(cache.writeSuccessCount()).isEqualTo(1); + assertThat(cache.writeAbortCount()).isEqualTo(0); + assertThat(cache.requestCount()).isEqualTo(2); + assertThat(cache.hitCount()).isEqualTo(1); } @Test public void secureResponseCaching() throws IOException { @@ -264,7 +261,7 @@ public final class CacheTest { Request request = new Request.Builder().url(server.url("/")).build(); Response response1 = client.newCall(request).execute(); BufferedSource in = response1.body().source(); - assertEquals("ABC", in.readUtf8()); + assertThat(in.readUtf8()).isEqualTo("ABC"); // OpenJDK 6 fails on this line, complaining that the connection isn't open yet CipherSuite cipherSuite = response1.handshake().cipherSuite(); @@ -274,17 +271,17 @@ public final class CacheTest { Principal localPrincipal = response1.handshake().localPrincipal(); Response response2 = client.newCall(request).execute(); // Cached! - assertEquals("ABC", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("ABC"); - assertEquals(2, cache.requestCount()); - assertEquals(1, cache.networkCount()); - assertEquals(1, cache.hitCount()); + assertThat(cache.requestCount()).isEqualTo(2); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(1); - assertEquals(cipherSuite, response2.handshake().cipherSuite()); - assertEquals(localCerts, response2.handshake().localCertificates()); - assertEquals(serverCerts, response2.handshake().peerCertificates()); - assertEquals(peerPrincipal, response2.handshake().peerPrincipal()); - assertEquals(localPrincipal, response2.handshake().localPrincipal()); + assertThat(response2.handshake().cipherSuite()).isEqualTo(cipherSuite); + assertThat(response2.handshake().localCertificates()).isEqualTo(localCerts); + assertThat(response2.handshake().peerCertificates()).isEqualTo(serverCerts); + assertThat(response2.handshake().peerPrincipal()).isEqualTo(peerPrincipal); + assertThat(response2.handshake().localPrincipal()).isEqualTo(localPrincipal); } @Test public void responseCachingAndRedirects() throws Exception { @@ -302,14 +299,15 @@ public final class CacheTest { Request request = new Request.Builder().url(server.url("/")).build(); Response response1 = client.newCall(request).execute(); - assertEquals("ABC", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("ABC"); Response response2 = client.newCall(request).execute(); // Cached! - assertEquals("ABC", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("ABC"); - assertEquals(4, cache.requestCount()); // 2 requests + 2 redirects - assertEquals(2, cache.networkCount()); - assertEquals(2, cache.hitCount()); + // 2 requests + 2 redirects + assertThat(cache.requestCount()).isEqualTo(4); + assertThat(cache.networkCount()).isEqualTo(2); + assertThat(cache.hitCount()).isEqualTo(2); } @Test public void redirectToCachedResult() throws Exception { @@ -324,25 +322,25 @@ public final class CacheTest { Request request1 = new Request.Builder().url(server.url("/foo")).build(); Response response1 = client.newCall(request1).execute(); - assertEquals("ABC", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("ABC"); RecordedRequest recordedRequest1 = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", recordedRequest1.getRequestLine()); - assertEquals(0, recordedRequest1.getSequenceNumber()); + assertThat(recordedRequest1.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(recordedRequest1.getSequenceNumber()).isEqualTo(0); Request request2 = new Request.Builder().url(server.url("/bar")).build(); Response response2 = client.newCall(request2).execute(); - assertEquals("ABC", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("ABC"); RecordedRequest recordedRequest2 = server.takeRequest(); - assertEquals("GET /bar HTTP/1.1", recordedRequest2.getRequestLine()); - assertEquals(1, recordedRequest2.getSequenceNumber()); + assertThat(recordedRequest2.getRequestLine()).isEqualTo("GET /bar HTTP/1.1"); + assertThat(recordedRequest2.getSequenceNumber()).isEqualTo(1); // an unrelated request should reuse the pooled connection Request request3 = new Request.Builder().url(server.url("/baz")).build(); Response response3 = client.newCall(request3).execute(); - assertEquals("DEF", response3.body().string()); + assertThat(response3.body().string()).isEqualTo("DEF"); RecordedRequest recordedRequest3 = server.takeRequest(); - assertEquals("GET /baz HTTP/1.1", recordedRequest3.getRequestLine()); - assertEquals(2, recordedRequest3.getSequenceNumber()); + assertThat(recordedRequest3.getRequestLine()).isEqualTo("GET /baz HTTP/1.1"); + assertThat(recordedRequest3.getSequenceNumber()).isEqualTo(2); } @Test public void secureResponseCachingAndRedirects() throws IOException { @@ -366,17 +364,19 @@ public final class CacheTest { .build(); Response response1 = get(server.url("/")); - assertEquals("ABC", response1.body().string()); - assertNotNull(response1.handshake().cipherSuite()); + assertThat(response1.body().string()).isEqualTo("ABC"); + assertThat(response1.handshake().cipherSuite()).isNotNull(); // Cached! Response response2 = get(server.url("/")); - assertEquals("ABC", response2.body().string()); - assertNotNull(response2.handshake().cipherSuite()); + assertThat(response2.body().string()).isEqualTo("ABC"); + assertThat(response2.handshake().cipherSuite()).isNotNull(); - assertEquals(4, cache.requestCount()); // 2 direct + 2 redirect = 4 - assertEquals(2, cache.hitCount()); - assertEquals(response1.handshake().cipherSuite(), response2.handshake().cipherSuite()); + // 2 direct + 2 redirect = 4 + assertThat(cache.requestCount()).isEqualTo(4); + assertThat(cache.hitCount()).isEqualTo(2); + assertThat(response2.handshake().cipherSuite()).isEqualTo( + response1.handshake().cipherSuite()); } /** @@ -408,14 +408,15 @@ public final class CacheTest { .build(); Response response1 = get(server.url("/")); - assertEquals("ABC", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("ABC"); // Cached! Response response2 = get(server.url("/")); - assertEquals("ABC", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("ABC"); - assertEquals(4, cache.requestCount()); // 2 direct + 2 redirect = 4 - assertEquals(2, cache.hitCount()); + // 2 direct + 2 redirect = 4 + assertThat(cache.requestCount()).isEqualTo(4); + assertThat(cache.hitCount()).isEqualTo(2); } @Test public void foundCachedWithExpiresHeader() throws Exception { @@ -457,8 +458,8 @@ public final class CacheTest { .setBody("c")); HttpUrl url = server.url("/"); - assertEquals("a", get(url).body().string()); - assertEquals("a", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("a"); + assertThat(get(url).body().string()).isEqualTo("a"); } private void temporaryRedirectNotCachedWithoutCachingHeader(int responseCode) throws Exception { @@ -471,8 +472,8 @@ public final class CacheTest { .setBody("b")); HttpUrl url = server.url("/"); - assertEquals("a", get(url).body().string()); - assertEquals("b", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("a"); + assertThat(get(url).body().string()).isEqualTo("b"); } /** https://github.com/square/okhttp/issues/2198 */ @@ -488,11 +489,11 @@ public final class CacheTest { 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("ABC", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("ABC"); } @Test public void serverDisconnectsPrematurelyWithContentLengthHeader() throws IOException { @@ -517,7 +518,7 @@ public final class CacheTest { .setBody("Request #2")); BufferedSource bodySource = get(server.url("/")).body().source(); - assertEquals("ABCDE", bodySource.readUtf8Line()); + assertThat(bodySource.readUtf8Line()).isEqualTo("ABCDE"); try { bodySource.readUtf8(21); fail("This implementation silently ignored a truncated HTTP body."); @@ -526,12 +527,12 @@ public final class CacheTest { bodySource.close(); } - assertEquals(1, cache.writeAbortCount()); - assertEquals(0, cache.writeSuccessCount()); + assertThat(cache.writeAbortCount()).isEqualTo(1); + assertThat(cache.writeSuccessCount()).isEqualTo(0); Response response = get(server.url("/")); - assertEquals("Request #2", response.body().string()); - assertEquals(1, cache.writeAbortCount()); - assertEquals(1, cache.writeSuccessCount()); + assertThat(response.body().string()).isEqualTo("Request #2"); + assertThat(cache.writeAbortCount()).isEqualTo(1); + assertThat(cache.writeSuccessCount()).isEqualTo(1); } @Test public void clientPrematureDisconnectWithContentLengthHeader() throws IOException { @@ -557,7 +558,7 @@ public final class CacheTest { Response response1 = get(server.url("/")); BufferedSource in = response1.body().source(); - assertEquals("ABCDE", in.readUtf8(5)); + assertThat(in.readUtf8(5)).isEqualTo("ABCDE"); in.close(); try { in.readByte(); @@ -565,12 +566,12 @@ public final class CacheTest { } catch (IllegalStateException expected) { } - assertEquals(1, cache.writeAbortCount()); - assertEquals(0, cache.writeSuccessCount()); + assertThat(cache.writeAbortCount()).isEqualTo(1); + assertThat(cache.writeSuccessCount()).isEqualTo(0); Response response2 = get(server.url("/")); - assertEquals("Request #2", response2.body().string()); - assertEquals(1, cache.writeAbortCount()); - assertEquals(1, cache.writeSuccessCount()); + assertThat(response2.body().string()).isEqualTo("Request #2"); + assertThat(cache.writeAbortCount()).isEqualTo(1); + assertThat(cache.writeSuccessCount()).isEqualTo(1); } @Test public void defaultExpirationDateFullyCachedForLessThan24Hours() throws Exception { @@ -585,11 +586,11 @@ public final class CacheTest { HttpUrl url = server.url("/"); Response response1 = get(url); - assertEquals("A", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("A"); Response response2 = get(url); - assertEquals("A", response2.body().string()); - assertNull(response2.header("Warning")); + assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.header("Warning")).isNull(); } @Test public void defaultExpirationDateConditionallyCached() throws Exception { @@ -601,7 +602,8 @@ public final class CacheTest { RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Date: " + formatDate(-15, TimeUnit.SECONDS))); - assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); + assertThat(conditionalRequest.getHeader("If-Modified-Since")).isEqualTo( + lastModifiedDate); } @Test public void defaultExpirationDateFullyCachedForMoreThan24Hours() throws Exception { @@ -614,10 +616,11 @@ public final class CacheTest { .addHeader("Date: " + formatDate(-5, TimeUnit.DAYS)) .setBody("A")); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Response response = get(server.url("/")); - assertEquals("A", response.body().string()); - assertEquals("113 HttpURLConnection \"Heuristic expiration\"", response.header("Warning")); + assertThat(response.body().string()).isEqualTo("A"); + assertThat(response.header("Warning")).isEqualTo( + "113 HttpURLConnection \"Heuristic expiration\""); } @Test public void noDefaultExpirationForUrlsWithQueryString() throws Exception { @@ -629,8 +632,8 @@ public final class CacheTest { .setBody("B")); HttpUrl url = server.url("/").newBuilder().addQueryParameter("foo", "bar").build(); - assertEquals("A", get(url).body().string()); - assertEquals("B", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); + assertThat(get(url).body().string()).isEqualTo("B"); } @Test public void expirationDateInThePastWithLastModifiedHeader() throws Exception { @@ -638,7 +641,8 @@ public final class CacheTest { RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); - assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); + assertThat(conditionalRequest.getHeader("If-Modified-Since")).isEqualTo( + lastModifiedDate); } @Test public void expirationDateInThePastWithNoLastModifiedHeader() throws Exception { @@ -664,7 +668,8 @@ public final class CacheTest { .addHeader("Date: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Cache-Control: max-age=60")); - assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); + assertThat(conditionalRequest.getHeader("If-Modified-Since")).isEqualTo( + lastModifiedDate); } @Test public void maxAgeInThePastWithDateHeaderButNoLastModifiedHeader() throws Exception { @@ -760,14 +765,14 @@ public final class CacheTest { .build(); Response response1 = client.newCall(request).execute(); response1.body().close(); - assertEquals("1", response1.header("X-Response-ID")); + assertThat(response1.header("X-Response-ID")).isEqualTo("1"); Response response2 = get(url); response2.body().close(); if (expectCached) { - assertEquals("1", response2.header("X-Response-ID")); + assertThat(response2.header("X-Response-ID")).isEqualTo("1"); } else { - assertEquals("2", response2.header("X-Response-ID")); + assertThat(response2.header("X-Response-ID")).isEqualTo("2"); } } @@ -803,16 +808,16 @@ public final class CacheTest { HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(url) .method(requestMethod, requestBodyOrNull(requestMethod)) .build(); Response invalidate = client.newCall(request).execute(); - assertEquals("B", invalidate.body().string()); + assertThat(invalidate.body().string()).isEqualTo("B"); - assertEquals("C", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("C"); } @Test public void postInvalidatesCacheWithUncacheableResponse() throws Exception { @@ -830,16 +835,16 @@ public final class CacheTest { HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(url) .method("POST", requestBodyOrNull("POST")) .build(); Response invalidate = client.newCall(request).execute(); - assertEquals("B", invalidate.body().string()); + assertThat(invalidate.body().string()).isEqualTo("B"); - assertEquals("C", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("C"); } @Test public void putInvalidatesWithNoContentResponse() throws Exception { @@ -857,22 +862,22 @@ public final class CacheTest { HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(url) .put(RequestBody.create(MediaType.get("text/plain"), "foo")) .build(); Response invalidate = client.newCall(request).execute(); - assertEquals("", invalidate.body().string()); + assertThat(invalidate.body().string()).isEqualTo(""); - assertEquals("C", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("C"); } @Test public void etag() throws Exception { RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("ETag: v1")); - assertEquals("v1", conditionalRequest.getHeader("If-None-Match")); + assertThat(conditionalRequest.getHeader("If-None-Match")).isEqualTo("v1"); } /** If both If-Modified-Since and If-None-Match conditions apply, send only If-None-Match. */ @@ -882,8 +887,8 @@ public final class CacheTest { .addHeader("ETag: v1") .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); - assertEquals("v1", conditionalRequest.getHeader("If-None-Match")); - assertNull(conditionalRequest.getHeader("If-Modified-Since")); + assertThat(conditionalRequest.getHeader("If-None-Match")).isEqualTo("v1"); + assertThat(conditionalRequest.getHeader("If-Modified-Since")).isNull(); } @Test public void etagAndExpirationDateInTheFuture() throws Exception { @@ -904,7 +909,8 @@ public final class CacheTest { .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Cache-Control: no-cache")); - assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); + assertThat(conditionalRequest.getHeader("If-Modified-Since")).isEqualTo( + lastModifiedDate); } @Test public void pragmaNoCache() throws Exception { @@ -918,7 +924,8 @@ public final class CacheTest { .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Pragma: no-cache")); - assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); + assertThat(conditionalRequest.getHeader("If-Modified-Since")).isEqualTo( + lastModifiedDate); } @Test public void cacheControlNoStore() throws Exception { @@ -951,9 +958,9 @@ public final class CacheTest { .header("Range", "bytes=1000-1001") .build(); Response range = client.newCall(request).execute(); - assertEquals("AA", range.body().string()); + assertThat(range.body().string()).isEqualTo("AA"); - assertEquals("BB", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("BB"); } /** @@ -976,9 +983,9 @@ public final class CacheTest { HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); - assertEquals("B", get(url).body().string()); - assertEquals("B", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); + assertThat(get(url).body().string()).isEqualTo("B"); + assertThat(get(url).body().string()).isEqualTo("B"); } @Test public void clientSideNoStore() throws Exception { @@ -994,13 +1001,13 @@ public final class CacheTest { .cacheControl(new CacheControl.Builder().noStore().build()) .build(); Response response1 = client.newCall(request1).execute(); - assertEquals("A", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("A"); Request request2 = new Request.Builder() .url(server.url("/")) .build(); Response response2 = client.newCall(request2).execute(); - assertEquals("B", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("B"); } @Test public void nonIdentityEncodingAndConditionalCache() throws Exception { @@ -1027,9 +1034,9 @@ public final class CacheTest { // At least three request/response pairs are required because after the first request is cached // a different execution path might be taken. Thus modifications to the cache applied during // the second request might not be visible until another request is performed. - assertEquals("ABCABCABC", get(server.url("/")).body().string()); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); } @Test public void previouslyNotGzippedContentIsNotModifiedAndSpecifiesGzipEncoding() throws Exception { @@ -1045,9 +1052,9 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("DEFDEFDEF")); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); - assertEquals("DEFDEFDEF", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); + assertThat(get(server.url("/")).body().string()).isEqualTo("DEFDEFDEF"); } @Test public void changedGzippedContentIsNotModifiedAndSpecifiesNewEncoding() throws Exception { @@ -1064,9 +1071,9 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("DEFDEFDEF")); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); - assertEquals("DEFDEFDEF", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); + assertThat(get(server.url("/")).body().string()).isEqualTo("DEFDEFDEF"); } @Test public void notModifiedSpecifiesEncoding() throws Exception { @@ -1081,9 +1088,9 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("DEFDEFDEF")); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); - assertEquals("DEFDEFDEF", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); + assertThat(get(server.url("/")).body().string()).isEqualTo("DEFDEFDEF"); } /** https://github.com/square/okhttp/issues/947 */ @@ -1096,8 +1103,8 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("FAIL")); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); - assertEquals("ABCABCABC", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); + assertThat(get(server.url("/")).body().string()).isEqualTo("ABCABCABC"); } @Test public void conditionalCacheHitIsNotDoublePooled() throws Exception { @@ -1110,9 +1117,9 @@ public final class CacheTest { .clearHeaders() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals(1, client.connectionPool().idleConnectionCount()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(client.connectionPool().idleConnectionCount()).isEqualTo(1); } @Test public void expiresDateBeforeModifiedDate() throws Exception { @@ -1130,14 +1137,14 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(server.url("/")) .header("Cache-Control", "max-age=30") .build(); Response response = client.newCall(request).execute(); - assertEquals("B", response.body().string()); + assertThat(response.body().string()).isEqualTo("B"); } @Test public void requestMinFresh() throws IOException { @@ -1148,14 +1155,14 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(server.url("/")) .header("Cache-Control", "min-fresh=120") .build(); Response response = client.newCall(request).execute(); - assertEquals("B", response.body().string()); + assertThat(response.body().string()).isEqualTo("B"); } @Test public void requestMaxStale() throws IOException { @@ -1166,15 +1173,16 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(server.url("/")) .header("Cache-Control", "max-stale=180") .build(); Response response = client.newCall(request).execute(); - assertEquals("A", response.body().string()); - assertEquals("110 HttpURLConnection \"Response is stale\"", response.header("Warning")); + assertThat(response.body().string()).isEqualTo("A"); + assertThat(response.header("Warning")).isEqualTo( + "110 HttpURLConnection \"Response is stale\""); } @Test public void requestMaxStaleDirectiveWithNoValue() throws IOException { @@ -1186,7 +1194,7 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); // With max-stale, we'll return that stale response. Request request = new Request.Builder() @@ -1194,8 +1202,9 @@ public final class CacheTest { .header("Cache-Control", "max-stale") .build(); Response response = client.newCall(request).execute(); - assertEquals("A", response.body().string()); - assertEquals("110 HttpURLConnection \"Response is stale\"", response.header("Warning")); + assertThat(response.body().string()).isEqualTo("A"); + assertThat(response.header("Warning")).isEqualTo( + "110 HttpURLConnection \"Response is stale\""); } @Test public void requestMaxStaleNotHonoredWithMustRevalidate() throws IOException { @@ -1206,14 +1215,14 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(server.url("/")) .header("Cache-Control", "max-stale=180") .build(); Response response = client.newCall(request).execute(); - assertEquals("B", response.body().string()); + assertThat(response.body().string()).isEqualTo("B"); } @Test public void requestOnlyIfCachedWithNoResponseCached() throws IOException { @@ -1224,11 +1233,11 @@ public final class CacheTest { .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); - assertTrue(response.body().source().exhausted()); - assertEquals(504, response.code()); - assertEquals(1, cache.requestCount()); - assertEquals(0, cache.networkCount()); - assertEquals(0, cache.hitCount()); + assertThat(response.body().source().exhausted()).isTrue(); + assertThat(response.code()).isEqualTo(504); + assertThat(cache.requestCount()).isEqualTo(1); + assertThat(cache.networkCount()).isEqualTo(0); + assertThat(cache.hitCount()).isEqualTo(0); } @Test public void requestOnlyIfCachedWithFullResponseCached() throws IOException { @@ -1237,16 +1246,16 @@ public final class CacheTest { .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(server.url("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); - assertEquals("A", response.body().string()); - assertEquals(2, cache.requestCount()); - assertEquals(1, cache.networkCount()); - assertEquals(1, cache.hitCount()); + assertThat(response.body().string()).isEqualTo("A"); + assertThat(cache.requestCount()).isEqualTo(2); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(1); } @Test public void requestOnlyIfCachedWithConditionalResponseCached() throws IOException { @@ -1255,34 +1264,34 @@ public final class CacheTest { .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(-1, TimeUnit.MINUTES))); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(server.url("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); - assertTrue(response.body().source().exhausted()); - assertEquals(504, response.code()); - assertEquals(2, cache.requestCount()); - assertEquals(1, cache.networkCount()); - assertEquals(0, cache.hitCount()); + assertThat(response.body().source().exhausted()).isTrue(); + assertThat(response.code()).isEqualTo(504); + assertThat(cache.requestCount()).isEqualTo(2); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(0); } @Test public void requestOnlyIfCachedWithUnhelpfulResponseCached() throws IOException { server.enqueue(new MockResponse() .setBody("A")); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(server.url("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); - assertTrue(response.body().source().exhausted()); - assertEquals(504, response.code()); - assertEquals(2, cache.requestCount()); - assertEquals(1, cache.networkCount()); - assertEquals(0, cache.hitCount()); + assertThat(response.body().source().exhausted()).isTrue(); + assertThat(response.code()).isEqualTo(504); + assertThat(cache.requestCount()).isEqualTo(2); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(0); } @Test public void requestCacheControlNoCache() throws Exception { @@ -1295,13 +1304,13 @@ public final class CacheTest { .setBody("B")); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(url) .header("Cache-Control", "no-cache") .build(); Response response = client.newCall(request).execute(); - assertEquals("B", response.body().string()); + assertThat(response.body().string()).isEqualTo("B"); } @Test public void requestPragmaNoCache() throws Exception { @@ -1314,13 +1323,13 @@ public final class CacheTest { .setBody("B")); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(url) .header("Pragma", "no-cache") .build(); Response response = client.newCall(request).execute(); - assertEquals("B", response.body().string()); + assertThat(response.body().string()).isEqualTo("B"); } @Test public void clientSuppliedIfModifiedSinceWithCachedResult() throws Exception { @@ -1330,8 +1339,8 @@ public final class CacheTest { String ifModifiedSinceDate = formatDate(-24, TimeUnit.HOURS); RecordedRequest request = assertClientSuppliedCondition(response, "If-Modified-Since", ifModifiedSinceDate); - assertEquals(ifModifiedSinceDate, request.getHeader("If-Modified-Since")); - assertNull(request.getHeader("If-None-Match")); + assertThat(request.getHeader("If-Modified-Since")).isEqualTo(ifModifiedSinceDate); + assertThat(request.getHeader("If-None-Match")).isNull(); } @Test public void clientSuppliedIfNoneMatchSinceWithCachedResult() throws Exception { @@ -1341,8 +1350,8 @@ public final class CacheTest { .addHeader("Date: " + formatDate(-2, TimeUnit.MINUTES)) .addHeader("Cache-Control: max-age=0"); RecordedRequest request = assertClientSuppliedCondition(response, "If-None-Match", "v1"); - assertEquals("v1", request.getHeader("If-None-Match")); - assertNull(request.getHeader("If-Modified-Since")); + assertThat(request.getHeader("If-None-Match")).isEqualTo("v1"); + assertThat(request.getHeader("If-Modified-Since")).isNull(); } private RecordedRequest assertClientSuppliedCondition(MockResponse seed, String conditionName, @@ -1352,15 +1361,15 @@ public final class CacheTest { .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(url) .header(conditionName, conditionValue) .build(); Response response = client.newCall(request).execute(); - assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, response.code()); - assertEquals("", response.body().string()); + assertThat(response.code()).isEqualTo(HttpURLConnection.HTTP_NOT_MODIFIED); + assertThat(response.body().string()).isEqualTo(""); server.takeRequest(); // seed return server.takeRequest(); @@ -1387,16 +1396,16 @@ public final class CacheTest { server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); // The first request has no conditions. RecordedRequest request1 = server.takeRequest(); - assertNull(request1.getHeader("If-Modified-Since")); + assertThat(request1.getHeader("If-Modified-Since")).isNull(); // The 2nd request uses the server's date format. RecordedRequest request2 = server.takeRequest(); - assertEquals(lastModifiedString, request2.getHeader("If-Modified-Since")); + assertThat(request2.getHeader("If-Modified-Since")).isEqualTo(lastModifiedString); } @Test public void clientSuppliedConditionWithoutCachedResult() throws Exception { @@ -1408,8 +1417,8 @@ public final class CacheTest { .header("If-Modified-Since", formatDate(-24, TimeUnit.HOURS)) .build(); Response response = client.newCall(request).execute(); - assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, response.code()); - assertEquals("", response.body().string()); + assertThat(response.code()).isEqualTo(HttpURLConnection.HTTP_NOT_MODIFIED); + assertThat(response.body().string()).isEqualTo(""); } @Test public void authorizationRequestFullyCached() throws Exception { @@ -1425,8 +1434,8 @@ public final class CacheTest { .header("Authorization", "password") .build(); Response response = client.newCall(request).execute(); - assertEquals("A", response.body().string()); - assertEquals("A", get(url).body().string()); + assertThat(response.body().string()).isEqualTo("A"); + assertThat(get(url).body().string()).isEqualTo("A"); } @Test public void contentLocationDoesNotPopulateCache() throws Exception { @@ -1437,8 +1446,8 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/foo")).body().string()); - assertEquals("B", get(server.url("/bar")).body().string()); + assertThat(get(server.url("/foo")).body().string()).isEqualTo("A"); + assertThat(get(server.url("/bar")).body().string()).isEqualTo("B"); } @Test public void connectionIsReturnedToPoolAfterConditionalSuccess() throws Exception { @@ -1451,13 +1460,13 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/a")).body().string()); - assertEquals("A", get(server.url("/a")).body().string()); - assertEquals("B", get(server.url("/b")).body().string()); + assertThat(get(server.url("/a")).body().string()).isEqualTo("A"); + assertThat(get(server.url("/a")).body().string()).isEqualTo("A"); + assertThat(get(server.url("/b")).body().string()).isEqualTo("B"); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals(1, server.takeRequest().getSequenceNumber()); - assertEquals(2, server.takeRequest().getSequenceNumber()); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void statisticsConditionalCacheMiss() throws Exception { @@ -1470,15 +1479,15 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("C")); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals(1, cache.requestCount()); - assertEquals(1, cache.networkCount()); - assertEquals(0, cache.hitCount()); - assertEquals("B", get(server.url("/")).body().string()); - assertEquals("C", get(server.url("/")).body().string()); - assertEquals(3, cache.requestCount()); - assertEquals(3, cache.networkCount()); - assertEquals(0, cache.hitCount()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(cache.requestCount()).isEqualTo(1); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(0); + assertThat(get(server.url("/")).body().string()).isEqualTo("B"); + assertThat(get(server.url("/")).body().string()).isEqualTo("C"); + assertThat(cache.requestCount()).isEqualTo(3); + assertThat(cache.networkCount()).isEqualTo(3); + assertThat(cache.hitCount()).isEqualTo(0); } @Test public void statisticsConditionalCacheHit() throws Exception { @@ -1491,15 +1500,15 @@ public final class CacheTest { server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals(1, cache.requestCount()); - assertEquals(1, cache.networkCount()); - assertEquals(0, cache.hitCount()); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals(3, cache.requestCount()); - assertEquals(3, cache.networkCount()); - assertEquals(2, cache.hitCount()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(cache.requestCount()).isEqualTo(1); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(0); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(cache.requestCount()).isEqualTo(3); + assertThat(cache.networkCount()).isEqualTo(3); + assertThat(cache.hitCount()).isEqualTo(2); } @Test public void statisticsFullCacheHit() throws Exception { @@ -1507,15 +1516,15 @@ public final class CacheTest { .addHeader("Cache-Control: max-age=60") .setBody("A")); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals(1, cache.requestCount()); - assertEquals(1, cache.networkCount()); - assertEquals(0, cache.hitCount()); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals(3, cache.requestCount()); - assertEquals(1, cache.networkCount()); - assertEquals(2, cache.hitCount()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(cache.requestCount()).isEqualTo(1); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(0); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(cache.requestCount()).isEqualTo(3); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(2); } @Test public void varyMatchesChangedRequestHeaderField() throws Exception { @@ -1532,14 +1541,14 @@ public final class CacheTest { .header("Accept-Language", "fr-CA") .build(); Response frResponse = client.newCall(frRequest).execute(); - assertEquals("A", frResponse.body().string()); + assertThat(frResponse.body().string()).isEqualTo("A"); Request enRequest = new Request.Builder() .url(url) .header("Accept-Language", "en-US") .build(); Response enResponse = client.newCall(enRequest).execute(); - assertEquals("B", enResponse.body().string()); + assertThat(enResponse.body().string()).isEqualTo("B"); } @Test public void varyMatchesUnchangedRequestHeaderField() throws Exception { @@ -1556,13 +1565,13 @@ public final class CacheTest { .header("Accept-Language", "fr-CA") .build(); Response response1 = client.newCall(request).execute(); - assertEquals("A", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("A"); Request request1 = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .build(); Response response2 = client.newCall(request1).execute(); - assertEquals("A", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("A"); } @Test public void varyMatchesAbsentRequestHeaderField() throws Exception { @@ -1573,8 +1582,8 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); } @Test public void varyMatchesAddedRequestHeaderField() throws Exception { @@ -1585,12 +1594,12 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(server.url("/")).header("Foo", "bar") .build(); Response response = client.newCall(request).execute(); - assertEquals("B", response.body().string()); + assertThat(response.body().string()).isEqualTo("B"); } @Test public void varyMatchesRemovedRequestHeaderField() throws Exception { @@ -1605,8 +1614,8 @@ public final class CacheTest { .url(server.url("/")).header("Foo", "bar") .build(); Response fooresponse = client.newCall(request).execute(); - assertEquals("A", fooresponse.body().string()); - assertEquals("B", get(server.url("/")).body().string()); + assertThat(fooresponse.body().string()).isEqualTo("A"); + assertThat(get(server.url("/")).body().string()).isEqualTo("B"); } @Test public void varyFieldsAreCaseInsensitive() throws Exception { @@ -1623,13 +1632,13 @@ public final class CacheTest { .header("Accept-Language", "fr-CA") .build(); Response response1 = client.newCall(request).execute(); - assertEquals("A", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("A"); Request request1 = new Request.Builder() .url(url) .header("accept-language", "fr-CA") .build(); Response response2 = client.newCall(request1).execute(); - assertEquals("A", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("A"); } @Test public void varyMultipleFieldsWithMatch() throws Exception { @@ -1649,7 +1658,7 @@ public final class CacheTest { .header("Accept-Encoding", "identity") .build(); Response response1 = client.newCall(request).execute(); - assertEquals("A", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("A"); Request request1 = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") @@ -1657,7 +1666,7 @@ public final class CacheTest { .header("Accept-Encoding", "identity") .build(); Response response2 = client.newCall(request1).execute(); - assertEquals("A", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("A"); } @Test public void varyMultipleFieldsWithNoMatch() throws Exception { @@ -1677,7 +1686,7 @@ public final class CacheTest { .header("Accept-Encoding", "identity") .build(); Response frResponse = client.newCall(frRequest).execute(); - assertEquals("A", frResponse.body().string()); + assertThat(frResponse.body().string()).isEqualTo("A"); Request enRequest = new Request.Builder() .url(url) .header("Accept-Language", "en-CA") @@ -1685,7 +1694,7 @@ public final class CacheTest { .header("Accept-Encoding", "identity") .build(); Response enResponse = client.newCall(enRequest).execute(); - assertEquals("B", enResponse.body().string()); + assertThat(enResponse.body().string()).isEqualTo("B"); } @Test public void varyMultipleFieldValuesWithMatch() throws Exception { @@ -1703,7 +1712,7 @@ public final class CacheTest { .addHeader("Accept-Language", "en-US") .build(); Response response1 = client.newCall(request1).execute(); - assertEquals("A", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("A"); Request request2 = new Request.Builder() .url(url) @@ -1711,7 +1720,7 @@ public final class CacheTest { .addHeader("Accept-Language", "en-US") .build(); Response response2 = client.newCall(request2).execute(); - assertEquals("A", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("A"); } @Test public void varyMultipleFieldValuesWithNoMatch() throws Exception { @@ -1729,7 +1738,7 @@ public final class CacheTest { .addHeader("Accept-Language", "en-US") .build(); Response response1 = client.newCall(request1).execute(); - assertEquals("A", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("A"); Request request2 = new Request.Builder() .url(url) @@ -1737,7 +1746,7 @@ public final class CacheTest { .addHeader("Accept-Language", "en-US") .build(); Response response2 = client.newCall(request2).execute(); - assertEquals("B", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("B"); } @Test public void varyAsterisk() throws Exception { @@ -1748,8 +1757,8 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("B")); - assertEquals("A", get(server.url("/")).body().string()); - assertEquals("B", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); + assertThat(get(server.url("/")).body().string()).isEqualTo("B"); } @Test public void varyAndHttps() throws Exception { @@ -1773,14 +1782,14 @@ public final class CacheTest { .header("Accept-Language", "en-US") .build(); Response response1 = client.newCall(request1).execute(); - assertEquals("A", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("A"); Request request2 = new Request.Builder() .url(url) .header("Accept-Language", "en-US") .build(); Response response2 = client.newCall(request2).execute(); - assertEquals("A", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("A"); } @Test public void cachePlusCookies() throws Exception { @@ -1799,9 +1808,9 @@ public final class CacheTest { .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); cookieJar.assertResponseCookies("a=FIRST; path=/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); cookieJar.assertResponseCookies("a=SECOND; path=/"); } @@ -1816,12 +1825,12 @@ public final class CacheTest { .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.url("/")); - assertEquals("A", response1.body().string()); - assertEquals("GET, HEAD", response1.header("Allow")); + assertThat(response1.body().string()).isEqualTo("A"); + assertThat(response1.header("Allow")).isEqualTo("GET, HEAD"); Response response2 = get(server.url("/")); - assertEquals("A", response2.body().string()); - assertEquals("GET, HEAD, PUT", response2.header("Allow")); + assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.header("Allow")).isEqualTo("GET, HEAD, PUT"); } @Test public void getHeadersReturnsCachedHopByHopHeaders() throws Exception { @@ -1835,12 +1844,12 @@ public final class CacheTest { .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.url("/")); - assertEquals("A", response1.body().string()); - assertEquals("identity", response1.header("Transfer-Encoding")); + assertThat(response1.body().string()).isEqualTo("A"); + assertThat(response1.header("Transfer-Encoding")).isEqualTo("identity"); Response response2 = get(server.url("/")); - assertEquals("A", response2.body().string()); - assertEquals("identity", response2.header("Transfer-Encoding")); + assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.header("Transfer-Encoding")).isEqualTo("identity"); } @Test public void getHeadersDeletesCached100LevelWarnings() throws Exception { @@ -1853,12 +1862,12 @@ public final class CacheTest { .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.url("/")); - assertEquals("A", response1.body().string()); - assertEquals("199 test danger", response1.header("Warning")); + assertThat(response1.body().string()).isEqualTo("A"); + assertThat(response1.header("Warning")).isEqualTo("199 test danger"); Response response2 = get(server.url("/")); - assertEquals("A", response2.body().string()); - assertNull(response2.header("Warning")); + assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.header("Warning")).isNull(); } @Test public void getHeadersRetainsCached200LevelWarnings() throws Exception { @@ -1871,12 +1880,12 @@ public final class CacheTest { .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.url("/")); - assertEquals("A", response1.body().string()); - assertEquals("299 test danger", response1.header("Warning")); + assertThat(response1.body().string()).isEqualTo("A"); + assertThat(response1.header("Warning")).isEqualTo("299 test danger"); Response response2 = get(server.url("/")); - assertEquals("A", response2.body().string()); - assertEquals("299 test danger", response2.header("Warning")); + assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.header("Warning")).isEqualTo("299 test danger"); } @Test public void doNotCachePartialResponse() throws Exception { @@ -1902,28 +1911,31 @@ public final class CacheTest { // A cache miss writes the cache. long t0 = System.currentTimeMillis(); Response response1 = get(server.url("/a")); - assertEquals("A", response1.body().string()); - assertNull(response1.header("Allow")); - assertEquals(0, response1.receivedResponseAtMillis() - t0, 250.0); + assertThat(response1.body().string()).isEqualTo("A"); + assertThat(response1.header("Allow")).isNull(); + assertThat((double) (response1.receivedResponseAtMillis() - t0)).isCloseTo( + (double) 0, offset(250.0)); // A conditional cache hit updates the cache. Thread.sleep(500); // Make sure t0 and t1 are distinct. long t1 = System.currentTimeMillis(); Response response2 = get(server.url("/a")); - assertEquals(HttpURLConnection.HTTP_OK, response2.code()); - assertEquals("A", response2.body().string()); - assertEquals("GET, HEAD", response2.header("Allow")); - assertEquals(0, response2.receivedResponseAtMillis() - t1, 250.0); + assertThat(response2.code()).isEqualTo(HttpURLConnection.HTTP_OK); + assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.header("Allow")).isEqualTo("GET, HEAD"); + assertThat((double) (response2.receivedResponseAtMillis() - t1)).isCloseTo( + (double) 0, offset(250.0)); // A full cache hit reads the cache. Thread.sleep(500); // Make sure t1 and t2 are distinct. long t2 = System.currentTimeMillis(); Response response3 = get(server.url("/a")); - assertEquals("A", response3.body().string()); - assertEquals("GET, HEAD", response3.header("Allow")); - assertEquals(0, response3.receivedResponseAtMillis() - t1, 250.0); + assertThat(response3.body().string()).isEqualTo("A"); + assertThat(response3.header("Allow")).isEqualTo("GET, HEAD"); + assertThat((double) (response3.receivedResponseAtMillis() - t1)).isCloseTo( + (double) 0, offset(250.0)); - assertEquals(2, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(2); } @Test public void responseSourceHeaderCached() throws IOException { @@ -1932,12 +1944,12 @@ public final class CacheTest { .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Request request = new Request.Builder() .url(server.url("/")).header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); - assertEquals("A", response.body().string()); + assertThat(response.body().string()).isEqualTo("A"); } @Test public void responseSourceHeaderConditionalCacheFetched() throws IOException { @@ -1950,9 +1962,9 @@ public final class CacheTest { .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Response response = get(server.url("/")); - assertEquals("B", response.body().string()); + assertThat(response.body().string()).isEqualTo("B"); } @Test public void responseSourceHeaderConditionalCacheNotFetched() throws IOException { @@ -1963,9 +1975,9 @@ public final class CacheTest { server.enqueue(new MockResponse() .setResponseCode(304)); - assertEquals("A", get(server.url("/")).body().string()); + assertThat(get(server.url("/")).body().string()).isEqualTo("A"); Response response = get(server.url("/")); - assertEquals("A", response.body().string()); + assertThat(response.body().string()).isEqualTo("A"); } @Test public void responseSourceHeaderFetched() throws IOException { @@ -1973,7 +1985,7 @@ public final class CacheTest { .setBody("A")); Response response = get(server.url("/")); - assertEquals("A", response.body().string()); + assertThat(response.body().string()).isEqualTo("A"); } @Test public void emptyResponseHeaderNameFromCacheIsLenient() throws Exception { @@ -1985,8 +1997,8 @@ public final class CacheTest { .setBody("body")); Response response = get(server.url("/")); - assertEquals("A", response.header("")); - assertEquals("body", response.body().string()); + assertThat(response.header("")).isEqualTo("A"); + assertThat(response.body().string()).isEqualTo("body"); } /** @@ -2045,9 +2057,9 @@ public final class CacheTest { .build(); Response response = get(url); - assertEquals(entryBody, response.body().string()); - assertEquals("3", response.header("Content-Length")); - assertEquals("foo", response.header("etag")); + assertThat(response.body().string()).isEqualTo(entryBody); + assertThat(response.header("Content-Length")).isEqualTo("3"); + assertThat(response.header("etag")).isEqualTo("foo"); } /** Exercise the cache format in OkHttp 2.7 and all earlier releases. */ @@ -2095,8 +2107,8 @@ public final class CacheTest { .build(); Response response = get(url); - assertEquals(entryBody, response.body().string()); - assertEquals("3", response.header("Content-Length")); + assertThat(response.body().string()).isEqualTo(entryBody); + assertThat(response.header("Content-Length")).isEqualTo("3"); } /** The TLS version is present in OkHttp 3.0 and beyond. */ @@ -2145,8 +2157,8 @@ public final class CacheTest { .build(); Response response = get(url); - assertEquals(entryBody, response.body().string()); - assertEquals("3", response.header("Content-Length")); + assertThat(response.body().string()).isEqualTo(entryBody); + assertThat(response.header("Content-Length")).isEqualTo("3"); } @Test public void testGoldenCacheHttpResponseOkHttp30() throws Exception { @@ -2182,8 +2194,8 @@ public final class CacheTest { .build(); Response response = get(url); - assertEquals(entryBody, response.body().string()); - assertEquals("3", response.header("Content-Length")); + assertThat(response.body().string()).isEqualTo(entryBody); + assertThat(response.header("Content-Length")).isEqualTo("3"); } @Test public void evictAll() throws Exception { @@ -2194,10 +2206,10 @@ public final class CacheTest { .setBody("B")); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); client.cache().evictAll(); - assertEquals(0, client.cache().size()); - assertEquals("B", get(url).body().string()); + assertThat(client.cache().size()).isEqualTo(0); + assertThat(get(url).body().string()).isEqualTo("B"); } @Test public void networkInterceptorInvokedForConditionalGet() throws Exception { @@ -2209,7 +2221,7 @@ public final class CacheTest { // Seed the cache. HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); final AtomicReference ifNoneMatch = new AtomicReference<>(); client = client.newBuilder() @@ -2220,8 +2232,8 @@ public final class CacheTest { .build(); // Confirm the value is cached and intercepted. - assertEquals("A", get(url).body().string()); - assertEquals("v1", ifNoneMatch.get()); + assertThat(get(url).body().string()).isEqualTo("A"); + assertThat(ifNoneMatch.get()).isEqualTo("v1"); } @Test public void networkInterceptorNotInvokedForFullyCached() throws Exception { @@ -2231,13 +2243,13 @@ public final class CacheTest { // Seed the cache. HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); // Confirm the interceptor isn't exercised. client = client.newBuilder() .addNetworkInterceptor(chain -> { throw new AssertionError(); }) .build(); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); } @Test public void iterateCache() throws Exception { @@ -2245,29 +2257,29 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("a")); HttpUrl urlA = server.url("/a"); - assertEquals("a", get(urlA).body().string()); + assertThat(get(urlA).body().string()).isEqualTo("a"); server.enqueue(new MockResponse() .setBody("b")); HttpUrl urlB = server.url("/b"); - assertEquals("b", get(urlB).body().string()); + assertThat(get(urlB).body().string()).isEqualTo("b"); server.enqueue(new MockResponse() .setBody("c")); HttpUrl urlC = server.url("/c"); - assertEquals("c", get(urlC).body().string()); + assertThat(get(urlC).body().string()).isEqualTo("c"); // Confirm the iterator returns those responses... Iterator i = cache.urls(); - assertTrue(i.hasNext()); - assertEquals(urlA.toString(), i.next()); - assertTrue(i.hasNext()); - assertEquals(urlB.toString(), i.next()); - assertTrue(i.hasNext()); - assertEquals(urlC.toString(), i.next()); + assertThat(i.hasNext()).isTrue(); + assertThat(i.next()).isEqualTo(urlA.toString()); + assertThat(i.hasNext()).isTrue(); + assertThat(i.next()).isEqualTo(urlB.toString()); + assertThat(i.hasNext()).isTrue(); + assertThat(i.next()).isEqualTo(urlC.toString()); // ... and nothing else. - assertFalse(i.hasNext()); + assertThat(i.hasNext()).isFalse(); try { i.next(); fail(); @@ -2281,17 +2293,17 @@ public final class CacheTest { .addHeader("Cache-Control: max-age=60") .setBody("a")); HttpUrl url = server.url("/a"); - assertEquals("a", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("a"); // Remove it with iteration. Iterator i = cache.urls(); - assertEquals(url.toString(), i.next()); + assertThat(i.next()).isEqualTo(url.toString()); i.remove(); // Confirm that subsequent requests suffer a cache miss. server.enqueue(new MockResponse() .setBody("b")); - assertEquals("b", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("b"); } @Test public void iteratorRemoveWithoutNextThrows() throws Exception { @@ -2299,10 +2311,10 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("a")); HttpUrl url = server.url("/a"); - assertEquals("a", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("a"); Iterator i = cache.urls(); - assertTrue(i.hasNext()); + assertThat(i.hasNext()).isTrue(); try { i.remove(); fail(); @@ -2315,10 +2327,10 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("a")); HttpUrl url = server.url("/a"); - assertEquals("a", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("a"); Iterator i = cache.urls(); - assertEquals(url.toString(), i.next()); + assertThat(i.next()).isEqualTo(url.toString()); i.remove(); // Too many calls to remove(). @@ -2334,15 +2346,15 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("a")); HttpUrl url = server.url("/a"); - assertEquals("a", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("a"); // The URL will remain available if hasNext() returned true... Iterator i = cache.urls(); - assertTrue(i.hasNext()); + assertThat(i.hasNext()).isTrue(); // ...so even when we evict the element, we still get something back. cache.evictAll(); - assertEquals(url.toString(), i.next()); + assertThat(i.next()).isEqualTo(url.toString()); // Remove does nothing. But most importantly, it doesn't throw! i.remove(); @@ -2353,13 +2365,13 @@ public final class CacheTest { server.enqueue(new MockResponse() .setBody("a")); HttpUrl url = server.url("/a"); - assertEquals("a", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("a"); Iterator i = cache.urls(); cache.evictAll(); // The URL was evicted before hasNext() made any promises. - assertFalse(i.hasNext()); + assertThat(i.hasNext()).isFalse(); try { i.next(); fail(); @@ -2381,15 +2393,15 @@ public final class CacheTest { .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); - assertEquals("A", get(url).body().string()); - assertEquals("B", get(url).body().string()); - assertEquals("B", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); + assertThat(get(url).body().string()).isEqualTo("A"); + assertThat(get(url).body().string()).isEqualTo("B"); + assertThat(get(url).body().string()).isEqualTo("B"); - assertNull(server.takeRequest().getHeader("If-None-Match")); - assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); - assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); - assertEquals("v2", server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isNull(); + assertThat(server.takeRequest().getHeader("If-None-Match")).isEqualTo("v1"); + assertThat(server.takeRequest().getHeader("If-None-Match")).isEqualTo("v1"); + assertThat(server.takeRequest().getHeader("If-None-Match")).isEqualTo("v2"); } @Test public void combinedCacheHeadersCanBeNonAscii() throws Exception { @@ -2406,16 +2418,16 @@ public final class CacheTest { .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.url("/")); - assertEquals("α", response1.header("Alpha")); - assertEquals("Beta", response1.header("β")); - assertEquals("abcd", response1.body().string()); + assertThat(response1.header("Alpha")).isEqualTo("α"); + assertThat(response1.header("β")).isEqualTo("Beta"); + assertThat(response1.body().string()).isEqualTo("abcd"); Response response2 = get(server.url("/")); - assertEquals("α", response2.header("Alpha")); - assertEquals("Beta", response2.header("β")); - assertEquals("Γ", response2.header("Gamma")); - assertEquals("Delta", response2.header("Δ")); - assertEquals("abcd", response2.body().string()); + assertThat(response2.header("Alpha")).isEqualTo("α"); + assertThat(response2.header("β")).isEqualTo("Beta"); + assertThat(response2.header("Gamma")).isEqualTo("Γ"); + assertThat(response2.header("Δ")).isEqualTo("Delta"); + assertThat(response2.body().string()).isEqualTo("abcd"); } @Test public void etagConditionCanBeNonAscii() throws Exception { @@ -2427,13 +2439,13 @@ public final class CacheTest { .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.url("/")); - assertEquals("abcd", response1.body().string()); + assertThat(response1.body().string()).isEqualTo("abcd"); Response response2 = get(server.url("/")); - assertEquals("abcd", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("abcd"); - assertNull(server.takeRequest().getHeader("If-None-Match")); - assertEquals("α", server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isNull(); + assertThat(server.takeRequest().getHeader("If-None-Match")).isEqualTo("α"); } private Response get(HttpUrl url) throws IOException { @@ -2469,8 +2481,8 @@ public final class CacheTest { .setBody("B")); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); - assertEquals("B", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); + assertThat(get(url).body().string()).isEqualTo("B"); } /** @return the request with the conditional get headers. */ @@ -2489,23 +2501,23 @@ public final class CacheTest { HttpUrl valid = server.url("/valid"); Response response1 = get(valid); - assertEquals("A", response1.body().string()); - assertEquals(HttpURLConnection.HTTP_OK, response1.code()); - assertEquals("A-OK", response1.message()); + assertThat(response1.body().string()).isEqualTo("A"); + assertThat(response1.code()).isEqualTo(HttpURLConnection.HTTP_OK); + assertThat(response1.message()).isEqualTo("A-OK"); Response response2 = get(valid); - assertEquals("A", response2.body().string()); - assertEquals(HttpURLConnection.HTTP_OK, response2.code()); - assertEquals("A-OK", response2.message()); + assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.code()).isEqualTo(HttpURLConnection.HTTP_OK); + assertThat(response2.message()).isEqualTo("A-OK"); HttpUrl invalid = server.url("/invalid"); Response response3 = get(invalid); - assertEquals("B", response3.body().string()); - assertEquals(HttpURLConnection.HTTP_OK, response3.code()); - assertEquals("B-OK", response3.message()); + assertThat(response3.body().string()).isEqualTo("B"); + assertThat(response3.code()).isEqualTo(HttpURLConnection.HTTP_OK); + assertThat(response3.message()).isEqualTo("B-OK"); Response response4 = get(invalid); - assertEquals("C", response4.body().string()); - assertEquals(HttpURLConnection.HTTP_OK, response4.code()); - assertEquals("C-OK", response4.message()); + assertThat(response4.body().string()).isEqualTo("C"); + assertThat(response4.code()).isEqualTo(HttpURLConnection.HTTP_OK); + assertThat(response4.message()).isEqualTo("C-OK"); server.takeRequest(); // regular get return server.takeRequest(); // conditional get @@ -2519,8 +2531,8 @@ public final class CacheTest { .setBody("B")); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); + assertThat(get(url).body().string()).isEqualTo("A"); } @Test public void immutableIsCachedAfterMultipleCalls() throws Exception { @@ -2533,9 +2545,9 @@ public final class CacheTest { .setBody("C")); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); - assertEquals("B", get(url).body().string()); - assertEquals("B", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); + assertThat(get(url).body().string()).isEqualTo("B"); + assertThat(get(url).body().string()).isEqualTo("B"); } @Test public void immutableIsNotCachedBeyondFreshnessLifetime() throws Exception { @@ -2548,7 +2560,8 @@ public final class CacheTest { .addHeader("Cache-Control: immutable") .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Date: " + formatDate(-15, TimeUnit.SECONDS))); - assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); + assertThat(conditionalRequest.getHeader("If-Modified-Since")).isEqualTo( + lastModifiedDate); } private void assertFullyCached(MockResponse response) throws Exception { @@ -2556,8 +2569,8 @@ public final class CacheTest { server.enqueue(response.setBody("B")); HttpUrl url = server.url("/"); - assertEquals("A", get(url).body().string()); - assertEquals("A", get(url).body().string()); + assertThat(get(url).body().string()).isEqualTo("A"); + assertThat(get(url).body().string()).isEqualTo("A"); } /** diff --git a/okhttp-tests/src/test/java/okhttp3/CallTest.java b/okhttp-tests/src/test/java/okhttp3/CallTest.java index bf1ec1683..4cd1ad4db 100644 --- a/okhttp-tests/src/test/java/okhttp3/CallTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CallTest.java @@ -92,13 +92,9 @@ import static okhttp3.CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256; import static okhttp3.TestUtil.awaitGarbageCollection; import static okhttp3.internal.platform.PlatformTest.getJvmSpecVersion; import static okhttp3.tls.internal.TlsUtil.localhost; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; @@ -150,10 +146,10 @@ public final class CallTest { .assertReceivedResponseAtMillis(sentAt, receivedAt); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("GET", recordedRequest.getMethod()); - assertEquals("SyncApiTest", recordedRequest.getHeader("User-Agent")); - assertEquals(0, recordedRequest.getBody().size()); - assertNull(recordedRequest.getHeader("Content-Length")); + assertThat(recordedRequest.getMethod()).isEqualTo("GET"); + assertThat(recordedRequest.getHeader("User-Agent")).isEqualTo("SyncApiTest"); + assertThat(recordedRequest.getBody().size()).isEqualTo(0); + assertThat(recordedRequest.getHeader("Content-Length")).isNull(); } @Test public void buildRequestUsingHttpUrl() throws Exception { @@ -167,7 +163,8 @@ public final class CallTest { requestBuilder.url("ftp://hostname/path"); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Expected URL scheme 'http' or 'https' but was 'ftp'", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo( + "Expected URL scheme 'http' or 'https' but was 'ftp'"); } } @@ -177,7 +174,7 @@ public final class CallTest { requestBuilder.url("http://localhost:65536/"); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Invalid URL port: \"65536\"", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("Invalid URL port: \"65536\""); } } @@ -208,7 +205,8 @@ public final class CallTest { .assertHeader("B", "123", "234"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals(Arrays.asList("345", "456"), recordedRequest.getHeaders().values("A")); + assertThat(recordedRequest.getHeaders().values("A")).isEqualTo( + Arrays.asList("345", "456")); } @Test public void repeatedHeaderNames_HTTP_2() throws Exception { @@ -240,10 +238,10 @@ public final class CallTest { .assertHeader("Content-Type", "text/plain"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("HEAD", recordedRequest.getMethod()); - assertEquals("SyncApiTest", recordedRequest.getHeader("User-Agent")); - assertEquals(0, recordedRequest.getBody().size()); - assertNull(recordedRequest.getHeader("Content-Length")); + assertThat(recordedRequest.getMethod()).isEqualTo("HEAD"); + assertThat(recordedRequest.getHeader("User-Agent")).isEqualTo("SyncApiTest"); + assertThat(recordedRequest.getBody().size()).isEqualTo(0); + assertThat(recordedRequest.getHeader("Content-Length")).isNull(); } @Test public void headResponseContentLengthIsIgnored() throws Exception { @@ -258,7 +256,7 @@ public final class CallTest { .head() .build(); Response response = client.newCall(headRequest).execute(); - assertEquals(200, response.code()); + assertThat(response.code()).isEqualTo(200); assertArrayEquals(new byte[0], response.body().bytes()); Request getRequest = new Request.Builder() @@ -268,8 +266,8 @@ public final class CallTest { .assertCode(200) .assertBody("abc"); - 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 headResponseContentEncodingIsIgnored() throws Exception { @@ -295,8 +293,8 @@ public final class CallTest { .assertCode(200) .assertBody("abc"); - 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 head_HTTPS() throws Exception { @@ -322,10 +320,11 @@ public final class CallTest { .assertBody("abc"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("POST", recordedRequest.getMethod()); - assertEquals("def", recordedRequest.getBody().readUtf8()); - assertEquals("3", recordedRequest.getHeader("Content-Length")); - assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); + assertThat(recordedRequest.getMethod()).isEqualTo("POST"); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("def"); + assertThat(recordedRequest.getHeader("Content-Length")).isEqualTo("3"); + assertThat(recordedRequest.getHeader("Content-Type")).isEqualTo( + "text/plain; charset=utf-8"); } @Test public void post_HTTPS() throws Exception { @@ -351,10 +350,10 @@ public final class CallTest { .assertBody("abc"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("POST", recordedRequest.getMethod()); - assertEquals(0, recordedRequest.getBody().size()); - assertEquals("0", recordedRequest.getHeader("Content-Length")); - assertNull(recordedRequest.getHeader("Content-Type")); + assertThat(recordedRequest.getMethod()).isEqualTo("POST"); + assertThat(recordedRequest.getBody().size()).isEqualTo(0); + assertThat(recordedRequest.getHeader("Content-Length")).isEqualTo("0"); + assertThat(recordedRequest.getHeader("Content-Type")).isNull(); } @Test public void postZerolength_HTTPS() throws Exception { @@ -411,18 +410,18 @@ public final class CallTest { .build(); Response response = client.newCall(request).execute(); - assertEquals(200, response.code()); + assertThat(response.code()).isEqualTo(200); response.body().close(); RecordedRequest recordedRequest1 = server.takeRequest(); - assertEquals("POST", recordedRequest1.getMethod()); - assertEquals(body, recordedRequest1.getBody().readUtf8()); - assertNull(recordedRequest1.getHeader("Authorization")); + assertThat(recordedRequest1.getMethod()).isEqualTo("POST"); + assertThat(recordedRequest1.getBody().readUtf8()).isEqualTo(body); + assertThat(recordedRequest1.getHeader("Authorization")).isNull(); RecordedRequest recordedRequest2 = server.takeRequest(); - assertEquals("POST", recordedRequest2.getMethod()); - assertEquals(body, recordedRequest2.getBody().readUtf8()); - assertEquals(credential, recordedRequest2.getHeader("Authorization")); + assertThat(recordedRequest2.getMethod()).isEqualTo("POST"); + assertThat(recordedRequest2.getBody().readUtf8()).isEqualTo(body); + assertThat(recordedRequest2.getHeader("Authorization")).isEqualTo(credential); } @Test public void attemptAuthorization20Times() throws Exception { @@ -455,7 +454,7 @@ public final class CallTest { client.newCall(new Request.Builder().url(server.url("/0")).build()).execute(); fail(); } catch (IOException expected) { - assertEquals("Too many follow-up requests: 21", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("Too many follow-up requests: 21"); } } @@ -478,7 +477,7 @@ public final class CallTest { executeSynchronously("/") .assertCode(401); - assertNotNull(authenticator.onlyRoute()); + assertThat(authenticator.onlyRoute()).isNotNull(); } @Test public void delete() throws Exception { @@ -494,10 +493,10 @@ public final class CallTest { .assertBody("abc"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("DELETE", recordedRequest.getMethod()); - assertEquals(0, recordedRequest.getBody().size()); - assertEquals("0", recordedRequest.getHeader("Content-Length")); - assertNull(recordedRequest.getHeader("Content-Type")); + assertThat(recordedRequest.getMethod()).isEqualTo("DELETE"); + assertThat(recordedRequest.getBody().size()).isEqualTo(0); + assertThat(recordedRequest.getHeader("Content-Length")).isEqualTo("0"); + assertThat(recordedRequest.getHeader("Content-Type")).isNull(); } @Test public void delete_HTTPS() throws Exception { @@ -523,8 +522,8 @@ public final class CallTest { .assertBody("abc"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("DELETE", recordedRequest.getMethod()); - assertEquals("def", recordedRequest.getBody().readUtf8()); + assertThat(recordedRequest.getMethod()).isEqualTo("DELETE"); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("def"); } @Test public void put() throws Exception { @@ -540,10 +539,11 @@ public final class CallTest { .assertBody("abc"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("PUT", recordedRequest.getMethod()); - assertEquals("def", recordedRequest.getBody().readUtf8()); - assertEquals("3", recordedRequest.getHeader("Content-Length")); - assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); + assertThat(recordedRequest.getMethod()).isEqualTo("PUT"); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("def"); + assertThat(recordedRequest.getHeader("Content-Length")).isEqualTo("3"); + assertThat(recordedRequest.getHeader("Content-Type")).isEqualTo( + "text/plain; charset=utf-8"); } @Test public void put_HTTPS() throws Exception { @@ -569,10 +569,11 @@ public final class CallTest { .assertBody("abc"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("PATCH", recordedRequest.getMethod()); - assertEquals("def", recordedRequest.getBody().readUtf8()); - assertEquals("3", recordedRequest.getHeader("Content-Length")); - assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); + assertThat(recordedRequest.getMethod()).isEqualTo("PATCH"); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("def"); + assertThat(recordedRequest.getHeader("Content-Length")).isEqualTo("3"); + assertThat(recordedRequest.getHeader("Content-Type")).isEqualTo( + "text/plain; charset=utf-8"); } @Test public void patch_HTTP_2() throws Exception { @@ -598,10 +599,11 @@ public final class CallTest { .assertBody("abc"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("CUSTOM", recordedRequest.getMethod()); - assertEquals("def", recordedRequest.getBody().readUtf8()); - assertEquals("3", recordedRequest.getHeader("Content-Length")); - assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); + assertThat(recordedRequest.getMethod()).isEqualTo("CUSTOM"); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("def"); + assertThat(recordedRequest.getHeader("Content-Length")).isEqualTo("3"); + assertThat(recordedRequest.getHeader("Content-Type")).isEqualTo( + "text/plain; charset=utf-8"); } @Test public void unspecifiedRequestBodyContentTypeDoesNotGetDefault() throws Exception { @@ -615,9 +617,9 @@ public final class CallTest { executeSynchronously(request).assertCode(200); RecordedRequest recordedRequest = server.takeRequest(); - assertNull(recordedRequest.getHeader("Content-Type")); - assertEquals("3", recordedRequest.getHeader("Content-Length")); - assertEquals("abc", recordedRequest.getBody().readUtf8()); + assertThat(recordedRequest.getHeader("Content-Type")).isNull(); + assertThat(recordedRequest.getHeader("Content-Length")).isEqualTo("3"); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("abc"); } @Test public void illegalToExecuteTwice() throws Exception { @@ -638,17 +640,17 @@ public final class CallTest { call.execute(); fail(); } catch (IllegalStateException e) { - assertEquals("Already Executed", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Already Executed"); } try { call.enqueue(callback); fail(); } catch (IllegalStateException e) { - assertEquals("Already Executed", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Already Executed"); } - assertEquals("SyncApiTest", server.takeRequest().getHeader("User-Agent")); + assertThat(server.takeRequest().getHeader("User-Agent")).isEqualTo("SyncApiTest"); } @Test public void illegalToExecuteTwice_Async() throws Exception { @@ -668,17 +670,17 @@ public final class CallTest { call.execute(); fail(); } catch (IllegalStateException e) { - assertEquals("Already Executed", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Already Executed"); } try { call.enqueue(callback); fail(); } catch (IllegalStateException e) { - assertEquals("Already Executed", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Already Executed"); } - assertEquals("SyncApiTest", server.takeRequest().getHeader("User-Agent")); + assertThat(server.takeRequest().getHeader("User-Agent")).isEqualTo("SyncApiTest"); callback.await(request.url()).assertSuccessful(); } @@ -697,8 +699,8 @@ public final class CallTest { Call cloned = call.clone(); Response response2 = cloned.execute(); - assertEquals(response1.body().string(), "abc"); - assertEquals(response2.body().string(), "def"); + assertThat("abc").isEqualTo(response1.body().string()); + assertThat("def").isEqualTo(response2.body().string()); } @Test public void legalToExecuteTwiceCloning_Async() throws Exception { @@ -722,8 +724,8 @@ public final class CallTest { bodies.add(firstResponse.getBody()); bodies.add(secondResponse.getBody()); - assertTrue(bodies.contains("abc")); - assertTrue(bodies.contains("def")); + assertThat(bodies.contains("abc")).isTrue(); + assertThat(bodies.contains("def")).isTrue(); } @Test public void get_Async() throws Exception { @@ -742,7 +744,7 @@ public final class CallTest { .assertHeader("Content-Type", "text/plain") .assertBody("abc"); - assertEquals("AsyncApiTest", server.takeRequest().getHeader("User-Agent")); + assertThat(server.takeRequest().getHeader("User-Agent")).isEqualTo("AsyncApiTest"); } @Test public void exceptionThrownByOnResponseIsRedactedAndLogged() throws Exception { @@ -762,8 +764,8 @@ public final class CallTest { } }); - assertEquals("INFO: Callback failure for call to " + server.url("/") + "...", - logHandler.take()); + assertThat(logHandler.take()).isEqualTo( + ("INFO: Callback failure for call to " + server.url("/") + "...")); } @Test public void connectionPooling() throws Exception { @@ -775,9 +777,9 @@ public final class CallTest { executeSynchronously("/b").assertBody("def"); executeSynchronously("/c").assertBody("ghi"); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals(1, server.takeRequest().getSequenceNumber()); - assertEquals(2, server.takeRequest().getSequenceNumber()); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void connectionPooling_Async() throws Exception { @@ -794,9 +796,9 @@ public final class CallTest { client.newCall(new Request.Builder().url(server.url("/c")).build()).enqueue(callback); callback.await(server.url("/c")).assertBody("ghi"); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals(1, server.takeRequest().getSequenceNumber()); - assertEquals(2, server.takeRequest().getSequenceNumber()); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void connectionReuseWhenResponseBodyConsumed_Async() throws Exception { @@ -811,9 +813,9 @@ public final class CallTest { @Override public void onResponse(Call call, Response response) throws IOException { InputStream bytes = response.body().byteStream(); - assertEquals('a', bytes.read()); - assertEquals('b', bytes.read()); - assertEquals('c', bytes.read()); + assertThat(bytes.read()).isEqualTo('a'); + assertThat(bytes.read()).isEqualTo('b'); + assertThat(bytes.read()).isEqualTo('c'); // This request will share a connection with 'A' cause it's all done. client.newCall(new Request.Builder().url(server.url("/b")).build()).enqueue(callback); @@ -821,8 +823,10 @@ public final class CallTest { }); callback.await(server.url("/b")).assertCode(200).assertBody("def"); - assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. - assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reuse! + // New connection. + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + // Connection reuse! + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void timeoutsUpdatedOnReusedConnections() throws Exception { @@ -842,7 +846,7 @@ public final class CallTest { Request request = new Request.Builder().url(server.url("/b")).build(); Response response = client.newCall(request).execute(); BufferedSource bodySource = response.body().source(); - assertEquals('d', bodySource.readByte()); + assertThat(bodySource.readByte()).isEqualTo((byte) 'd'); // The second byte of this request will be delayed by 750ms so we should time out after 250ms. long startNanos = System.nanoTime(); @@ -853,7 +857,8 @@ public final class CallTest { // Timed out as expected. long elapsedNanos = System.nanoTime() - startNanos; long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos); - assertTrue(Util.format("Timed out: %sms", elapsedMillis), elapsedMillis < 500); + assertThat(elapsedMillis < 500).overridingErrorMessage( + Util.format("Timed out: %sms", elapsedMillis)).isTrue(); } finally { bodySource.close(); } @@ -939,7 +944,7 @@ public final class CallTest { Request request = new Request.Builder().url(server.url("/")).build(); c.newCall(request).enqueue(callback); RecordedResponse response = callback.await(request.url()); - assertEquals(request, response.request); + assertThat(response.request).isEqualTo(request); } @Test public void reusedSinksGetIndependentTimeoutInstances() throws Exception { @@ -962,7 +967,7 @@ public final class CallTest { .method("POST", requestBody1) .build(); Response response1 = client.newCall(request1).execute(); - assertEquals(200, response1.code()); + assertThat(response1.code()).isEqualTo(200); // Call 2: check for the absence of a deadline on the request body. RequestBody requestBody2 = new RequestBody() { @@ -971,7 +976,7 @@ public final class CallTest { } @Override public void writeTo(BufferedSink sink) throws IOException { - assertFalse(sink.timeout().hasDeadline()); + assertThat(sink.timeout().hasDeadline()).isFalse(); sink.writeUtf8("def"); } }; @@ -980,11 +985,11 @@ public final class CallTest { .method("POST", requestBody2) .build(); Response response2 = client.newCall(request2).execute(); - assertEquals(200, response2.code()); + assertThat(response2.code()).isEqualTo(200); // Use sequence numbers to confirm the connection was pooled. - 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 reusedSourcesGetIndependentTimeoutInstances() throws Exception { @@ -995,19 +1000,19 @@ public final class CallTest { Request request1 = new Request.Builder().url(server.url("/")).build(); Response response1 = client.newCall(request1).execute(); BufferedSource body1 = response1.body().source(); - assertEquals("abc", body1.readUtf8()); + assertThat(body1.readUtf8()).isEqualTo("abc"); body1.timeout().deadline(5, TimeUnit.SECONDS); // Call 2: check for the absence of a deadline on the request body. Request request2 = new Request.Builder().url(server.url("/")).build(); Response response2 = client.newCall(request2).execute(); BufferedSource body2 = response2.body().source(); - assertEquals("def", body2.readUtf8()); - assertFalse(body2.timeout().hasDeadline()); + assertThat(body2.readUtf8()).isEqualTo("def"); + assertThat(body2.timeout().hasDeadline()).isFalse(); // Use sequence numbers to confirm the connection was pooled. - 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 tls() throws Exception { @@ -1041,7 +1046,7 @@ public final class CallTest { client = client.newBuilder() .dns(new DoubleInetAddressDns()) .build(); - assertTrue(client.retryOnConnectionFailure()); + assertThat(client.retryOnConnectionFailure()).isTrue(); executeSynchronously("/").assertBody("seed connection pool"); executeSynchronously("/").assertBody("retry success"); @@ -1097,7 +1102,7 @@ public final class CallTest { SSLProtocolException.class, // RI response to the FAIL_HANDSHAKE SSLHandshakeException.class // Android's response to the FAIL_HANDSHAKE ); - assertFalse(client.connectionSpecs().contains(ConnectionSpec.COMPATIBLE_TLS)); + assertThat(client.connectionSpecs().contains(ConnectionSpec.COMPATIBLE_TLS)).isFalse(); } @Test public void recoverFromTlsHandshakeFailure() throws Exception { @@ -1146,9 +1151,9 @@ public final class CallTest { List clientSockets = clientSocketFactory.getSocketsCreated(); SSLSocket firstSocket = clientSockets.get(0); - assertFalse(Arrays.asList(firstSocket.getEnabledCipherSuites()).contains(tlsFallbackScsv)); + assertThat(Arrays.asList(firstSocket.getEnabledCipherSuites()).contains(tlsFallbackScsv)).isFalse(); SSLSocket secondSocket = clientSockets.get(1); - assertTrue(Arrays.asList(secondSocket.getEnabledCipherSuites()).contains(tlsFallbackScsv)); + assertThat(Arrays.asList(secondSocket.getEnabledCipherSuites()).contains(tlsFallbackScsv)).isTrue(); } @Test public void recoverFromTlsHandshakeFailure_Async() throws Exception { @@ -1194,7 +1199,7 @@ public final class CallTest { } catch (SSLException expected) { // JDK 11 response to the FAIL_HANDSHAKE String jvmVersion = System.getProperty("java.specification.version"); - assertEquals("11", jvmVersion); + assertThat(jvmVersion).isEqualTo("11"); } } @@ -1269,7 +1274,8 @@ public final class CallTest { client.newCall(request).execute(); fail(); } catch (UnknownServiceException expected) { - assertEquals("CLEARTEXT communication not enabled for client", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo( + "CLEARTEXT communication not enabled for client"); } } @@ -1288,7 +1294,8 @@ public final class CallTest { call.execute(); fail(); } catch (UnknownServiceException expected) { - assertEquals("H2_PRIOR_KNOWLEDGE cannot be used with HTTPS", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo( + "H2_PRIOR_KNOWLEDGE cannot be used with HTTPS"); } } @@ -1304,7 +1311,7 @@ public final class CallTest { Request request = new Request.Builder().url(server.url("/")).build(); Response response = client.newCall(request).execute(); - assertEquals(301, response.code()); + assertThat(response.code()).isEqualTo(301); response.body().close(); } @@ -1331,7 +1338,7 @@ public final class CallTest { .build(); Request request2 = new Request.Builder().url(server.url("/")).build(); Response response2 = client.newCall(request2).execute(); - assertNotSame(response2.handshake(), response1.handshake()); + assertThat(response1.handshake()).isNotSameAs(response2.handshake()); response2.body().close(); } @@ -1352,7 +1359,7 @@ public final class CallTest { client.newCall(request).execute(); fail(); } catch (SSLPeerUnverifiedException expected) { - assertTrue(expected.getMessage().startsWith("Certificate pinning failure!")); + assertThat(expected.getMessage().startsWith("Certificate pinning failure!")).isTrue(); } } @@ -1370,9 +1377,10 @@ public final class CallTest { .assertBody("abc"); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("def", recordedRequest.getBody().readUtf8()); - assertEquals("3", recordedRequest.getHeader("Content-Length")); - assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("def"); + assertThat(recordedRequest.getHeader("Content-Length")).isEqualTo("3"); + assertThat(recordedRequest.getHeader("Content-Type")).isEqualTo( + "text/plain; charset=utf-8"); } @Test public void postBodyRetransmittedOnFailureRecovery() throws Exception { @@ -1383,25 +1391,25 @@ public final class CallTest { // Seed the connection pool so we have something that can fail. 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("/")) .post(RequestBody.create(MediaType.get("text/plain"), "body!")) .build(); Response response2 = client.newCall(request2).execute(); - assertEquals("def", response2.body().string()); + assertThat(response2.body().string()).isEqualTo("def"); RecordedRequest get = server.takeRequest(); - assertEquals(0, get.getSequenceNumber()); + assertThat(get.getSequenceNumber()).isEqualTo(0); RecordedRequest post1 = server.takeRequest(); - assertEquals("body!", post1.getBody().readUtf8()); - assertEquals(1, post1.getSequenceNumber()); + assertThat(post1.getBody().readUtf8()).isEqualTo("body!"); + assertThat(post1.getSequenceNumber()).isEqualTo(1); RecordedRequest post2 = server.takeRequest(); - assertEquals("body!", post2.getBody().readUtf8()); - assertEquals(0, post2.getSequenceNumber()); + assertThat(post2.getBody().readUtf8()).isEqualTo("body!"); + assertThat(post2.getSequenceNumber()).isEqualTo(0); } @Test public void postBodyRetransmittedOnFailureRecovery_HTTP2() throws Exception { @@ -1427,7 +1435,7 @@ public final class CallTest { .assertCode(200) .assertBody("A"); long request1ReceivedAt = System.currentTimeMillis(); - assertNull(server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isNull(); // Hit that stored response. It's different, but Vary says it doesn't matter. Thread.sleep(10); // Make sure the timestamps are unique. @@ -1489,7 +1497,7 @@ public final class CallTest { .assertHeader("Donut", "a") .assertBody("A"); long request1ReceivedAt = System.currentTimeMillis(); - assertNull(server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isNull(); // Hit that stored response. It's different, but Vary says it doesn't matter. Thread.sleep(10); // Make sure the timestamps are unique. @@ -1497,7 +1505,7 @@ public final class CallTest { RecordedResponse cacheHit = executeSynchronously( "/", "Accept-Language", "en-US", "Accept-Charset", "UTF-8"); long request2ReceivedAt = System.currentTimeMillis(); - assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isEqualTo("v1"); // Check the merged response. The request is the application's original request. cacheHit.assertCode(200) @@ -1548,14 +1556,14 @@ public final class CallTest { .build(); client.newCall(request1).enqueue(callback); callback.await(request1.url()).assertCode(200).assertBody("A"); - assertNull(server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isNull(); Request request2 = new Request.Builder() .url(server.url("/")) .build(); client.newCall(request2).enqueue(callback); callback.await(request2.url()).assertCode(200).assertBody("A"); - assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isEqualTo("v1"); } @Test public void conditionalCacheMiss() throws Exception { @@ -1577,7 +1585,7 @@ public final class CallTest { .assertCode(200) .assertBody("A"); long request1ReceivedAt = System.currentTimeMillis(); - assertNull(server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isNull(); // Different request, but Vary says it doesn't matter. Thread.sleep(10); // Make sure the timestamps are unique. @@ -1585,7 +1593,7 @@ public final class CallTest { RecordedResponse cacheMiss = executeSynchronously( "/", "Accept-Language", "en-US", "Accept-Charset", "UTF-8"); long request2ReceivedAt = System.currentTimeMillis(); - assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isEqualTo("v1"); // Check the user response. It has the application's original request. cacheMiss.assertCode(200) @@ -1627,14 +1635,14 @@ public final class CallTest { .build(); client.newCall(request1).enqueue(callback); callback.await(request1.url()).assertCode(200).assertBody("A"); - assertNull(server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isNull(); Request request2 = new Request.Builder() .url(server.url("/")) .build(); client.newCall(request2).enqueue(callback); callback.await(request2.url()).assertCode(200).assertBody("B"); - assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); + assertThat(server.takeRequest().getHeader("If-None-Match")).isEqualTo("v1"); } @Test public void onlyIfCachedReturns504WhenNotCached() throws Exception { @@ -1688,9 +1696,12 @@ public final class CallTest { .assertCode(301) .assertHeader("Test", "Redirect from /a to /b"); - assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. - assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reused. - assertEquals(2, server.takeRequest().getSequenceNumber()); // Connection reused again! + // New connection. + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + // Connection reused. + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + // Connection reused again! + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void postRedirectsToGet() throws Exception { @@ -1704,14 +1715,14 @@ public final class CallTest { .url(server.url("/page1")) .post(RequestBody.create(MediaType.get("text/plain"), "Request Body")) .build()).execute(); - assertEquals("Page 2", response.body().string()); + assertThat(response.body().string()).isEqualTo("Page 2"); RecordedRequest page1 = server.takeRequest(); - assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine()); - assertEquals("Request Body", page1.getBody().readUtf8()); + assertThat(page1.getRequestLine()).isEqualTo("POST /page1 HTTP/1.1"); + assertThat(page1.getBody().readUtf8()).isEqualTo("Request Body"); RecordedRequest page2 = server.takeRequest(); - assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine()); + assertThat(page2.getRequestLine()).isEqualTo("GET /page2 HTTP/1.1"); } @Test public void getClientRequestTimeout() throws Exception { @@ -1727,7 +1738,7 @@ public final class CallTest { .build(); Response response = client.newCall(request).execute(); - assertEquals("Body", response.body().string()); + assertThat(response.body().string()).isEqualTo("Body"); } @Test public void getClientRequestTimeoutWithBackPressure() throws Exception { @@ -1743,7 +1754,7 @@ public final class CallTest { .build(); Response response = client.newCall(request).execute(); - assertEquals("You took too long!", response.body().string()); + assertThat(response.body().string()).isEqualTo("You took too long!"); } @Test public void requestBodyRetransmittedOnClientRequestTimeout() throws Exception { @@ -1760,13 +1771,13 @@ public final class CallTest { .build(); Response response = client.newCall(request).execute(); - assertEquals("Body", response.body().string()); + assertThat(response.body().string()).isEqualTo("Body"); RecordedRequest request1 = server.takeRequest(); - assertEquals("Hello", request1.getBody().readUtf8()); + assertThat(request1.getBody().readUtf8()).isEqualTo("Hello"); RecordedRequest request2 = server.takeRequest(); - assertEquals("Hello", request2.getBody().readUtf8()); + assertThat(request2.getBody().readUtf8()).isEqualTo("Hello"); } @Test public void disableClientRequestTimeoutRetry() throws IOException { @@ -1785,8 +1796,8 @@ public final class CallTest { .build(); Response response = client.newCall(request).execute(); - assertEquals(408, response.code()); - assertEquals("You took too long!", response.body().string()); + assertThat(response.code()).isEqualTo(408); + assertThat(response.body().string()).isEqualTo("You took too long!"); } @Test public void maxClientRequestTimeoutRetries() throws IOException { @@ -1806,10 +1817,10 @@ public final class CallTest { .build(); Response response = client.newCall(request).execute(); - assertEquals(408, response.code()); - assertEquals("You took too long!", response.body().string()); + assertThat(response.code()).isEqualTo(408); + assertThat(response.body().string()).isEqualTo("You took too long!"); - assertEquals(2, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(2); } @Test public void maxUnavailableTimeoutRetries() throws IOException { @@ -1831,10 +1842,10 @@ public final class CallTest { .build(); Response response = client.newCall(request).execute(); - assertEquals(503, response.code()); - assertEquals("You took too long!", response.body().string()); + assertThat(response.code()).isEqualTo(503); + assertThat(response.body().string()).isEqualTo("You took too long!"); - assertEquals(2, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(2); } @Test public void retryOnUnavailableWith0RetryAfter() throws IOException { @@ -1851,7 +1862,7 @@ public final class CallTest { .build(); Response response = client.newCall(request).execute(); - assertEquals("Body", response.body().string()); + assertThat(response.body().string()).isEqualTo("Body"); } @Test public void canRetryNormalRequestBody() throws Exception { @@ -1877,12 +1888,12 @@ public final class CallTest { }) .build(); Response response = client.newCall(request).execute(); - assertEquals(200, response.code()); - assertEquals("thank you for retrying", response.body().string()); + assertThat(response.code()).isEqualTo(200); + assertThat(response.body().string()).isEqualTo("thank you for retrying"); - assertEquals("attempt 0", server.takeRequest().getBody().readUtf8()); - assertEquals("attempt 1", server.takeRequest().getBody().readUtf8()); - assertEquals(2, server.getRequestCount()); + assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("attempt 0"); + assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("attempt 1"); + assertThat(server.getRequestCount()).isEqualTo(2); } @Test public void cannotRetryOneShotRequestBody() throws Exception { @@ -1912,11 +1923,11 @@ public final class CallTest { }) .build(); Response response = client.newCall(request).execute(); - assertEquals(503, response.code()); - assertEquals("please retry", response.body().string()); + assertThat(response.code()).isEqualTo(503); + assertThat(response.body().string()).isEqualTo("please retry"); - assertEquals("attempt 0", server.takeRequest().getBody().readUtf8()); - assertEquals(1, server.getRequestCount()); + assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("attempt 0"); + assertThat(server.getRequestCount()).isEqualTo(1); } @Test public void propfindRedirectsToPropfindAndMaintainsRequestBody() throws Exception { @@ -1934,15 +1945,15 @@ public final class CallTest { .build()).execute(); // then - assertEquals("Page 2", response.body().string()); + assertThat(response.body().string()).isEqualTo("Page 2"); RecordedRequest page1 = server.takeRequest(); - assertEquals("PROPFIND /page1 HTTP/1.1", page1.getRequestLine()); - assertEquals("Request Body", page1.getBody().readUtf8()); + assertThat(page1.getRequestLine()).isEqualTo("PROPFIND /page1 HTTP/1.1"); + assertThat(page1.getBody().readUtf8()).isEqualTo("Request Body"); RecordedRequest page2 = server.takeRequest(); - assertEquals("PROPFIND /page2 HTTP/1.1", page2.getRequestLine()); - assertEquals("Request Body", page2.getBody().readUtf8()); + assertThat(page2.getRequestLine()).isEqualTo("PROPFIND /page2 HTTP/1.1"); + assertThat(page2.getBody().readUtf8()).isEqualTo("Request Body"); } @Test public void responseCookies() throws Exception { @@ -1958,11 +1969,11 @@ public final class CallTest { executeSynchronously("/").assertCode(200); List responseCookies = cookieJar.takeResponseCookies(); - assertEquals(2, responseCookies.size()); - assertEquals("a=b; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/", - responseCookies.get(0).toString()); - assertEquals("c=d; expires=Fri, 02 Jan 1970 23:59:59 GMT; path=/bar; secure", - responseCookies.get(1).toString()); + assertThat(responseCookies.size()).isEqualTo(2); + assertThat(responseCookies.get(0).toString()).isEqualTo( + "a=b; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"); + assertThat(responseCookies.get(1).toString()).isEqualTo( + "c=d; expires=Fri, 02 Jan 1970 23:59:59 GMT; path=/bar; secure"); } @Test public void requestCookies() throws Exception { @@ -1980,7 +1991,7 @@ public final class CallTest { executeSynchronously("/").assertCode(200); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("a=b; c=d", recordedRequest.getHeader("Cookie")); + assertThat(recordedRequest.getHeader("Cookie")).isEqualTo("a=b; c=d"); } @Test public void redirectsDoNotIncludeTooManyCookies() throws Exception { @@ -2003,13 +2014,13 @@ public final class CallTest { Response response = client.newCall(new Request.Builder() .url(server.url("/page1")) .build()).execute(); - assertEquals("Page 2", response.body().string()); + assertThat(response.body().string()).isEqualTo("Page 2"); RecordedRequest request1 = server.takeRequest(); - assertEquals("c=cookie", request1.getHeader("Cookie")); + assertThat(request1.getHeader("Cookie")).isEqualTo("c=cookie"); RecordedRequest request2 = server2.takeRequest(); - assertNull(request2.getHeader("Cookie")); + assertThat(request2.getHeader("Cookie")).isNull(); } @Test public void redirectsDoNotIncludeTooManyAuthHeaders() throws Exception { @@ -2026,11 +2037,11 @@ public final class CallTest { Request request = new Request.Builder().url(server.url("/a")).build(); Response response = client.newCall(request).execute(); - assertEquals("Page 2", response.body().string()); + assertThat(response.body().string()).isEqualTo("Page 2"); RecordedRequest redirectRequest = server2.takeRequest(); - assertNull(redirectRequest.getHeader("Authorization")); - assertEquals("/b", redirectRequest.getPath()); + assertThat(redirectRequest.getHeader("Authorization")).isNull(); + assertThat(redirectRequest.getPath()).isEqualTo("/b"); } @Test public void redirect_Async() throws Exception { @@ -2059,9 +2070,12 @@ public final class CallTest { .assertCode(301) .assertHeader("Test", "Redirect from /a to /b"); - assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. - assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reused. - assertEquals(2, server.takeRequest().getSequenceNumber()); // Connection reused again! + // New connection. + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + // Connection reused. + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + // Connection reused again! + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void follow20Redirects() throws Exception { @@ -2106,7 +2120,7 @@ public final class CallTest { client.newCall(new Request.Builder().url(server.url("/0")).build()).execute(); fail(); } catch (IOException expected) { - assertEquals("Too many follow-up requests: 21", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("Too many follow-up requests: 21"); } } @@ -2169,7 +2183,7 @@ public final class CallTest { fail(); } catch (IOException expected) { } - assertEquals(0, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(0); } @Test public void cancelDuringHttpConnect() throws Exception { @@ -2198,7 +2212,8 @@ public final class CallTest { } catch (IOException expected) { } long elapsedNanos = System.nanoTime() - startNanos; - assertEquals(cancelDelayMillis, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), 100f); + assertThat((float) TimeUnit.NANOSECONDS.toMillis(elapsedNanos)).isCloseTo( + (float) cancelDelayMillis, offset(100f)); } @Test public void cancelImmediatelyAfterEnqueue() throws Exception { @@ -2279,7 +2294,7 @@ public final class CallTest { fail(); } catch (IOException expected) { } - assertEquals(1, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(1); } @Test public void cancelInFlightBeforeResponseReadThrowsIOE() throws Exception { @@ -2338,7 +2353,7 @@ public final class CallTest { callA.enqueue(callback); callB.enqueue(callback); - assertEquals("/a", server.takeRequest().getPath()); + assertThat(server.takeRequest().getPath()).isEqualTo("/a"); callback.await(requestA.url()).assertBody("A"); // At this point we know the callback is ready, and that it will receive a cancel failure. @@ -2366,7 +2381,7 @@ public final class CallTest { }); call.enqueue(callback); - assertEquals("/a", server.takeRequest().getPath()); + assertThat(server.takeRequest().getPath()).isEqualTo("/a"); callback.await(requestA.url()).assertFailure("Canceled", "stream was reset: CANCEL", "Socket closed"); @@ -2415,8 +2430,8 @@ public final class CallTest { }); latch.await(); - assertEquals("A", bodyRef.get()); - assertFalse(failureRef.get()); + assertThat(bodyRef.get()).isEqualTo("A"); + assertThat(failureRef.get()).isFalse(); } @Test public void canceledAfterResponseIsDeliveredBreaksStreamButSignalsOnce_HTTPS() @@ -2447,7 +2462,7 @@ public final class CallTest { fail(); } catch (IOException expected) { } - assertEquals(0, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(0); } @Test public void gzip() throws Exception { @@ -2507,12 +2522,12 @@ public final class CallTest { // The response is not decompressed. Response response = call.execute(); - assertEquals("gzip", response.header("Content-Encoding")); - assertEquals(gzippedBody.snapshot(), response.body().source().readByteString()); + assertThat(response.header("Content-Encoding")).isEqualTo("gzip"); + assertThat(response.body().source().readByteString()).isEqualTo(gzippedBody.snapshot()); // The request did not offer gzip support. RecordedRequest recordedRequest = server.takeRequest(); - assertNull(recordedRequest.getHeader("Accept-Encoding")); + assertThat(recordedRequest.getHeader("Accept-Encoding")).isNull(); } @Test public void asyncResponseCanBeConsumedLater() throws Exception { @@ -2540,13 +2555,15 @@ public final class CallTest { }); Response response = responseRef.take(); - assertEquals(200, response.code()); - assertEquals("abc", response.body().string()); + assertThat(response.code()).isEqualTo(200); + assertThat(response.body().string()).isEqualTo("abc"); // Make another request just to confirm that that connection can be reused... executeSynchronously("/").assertBody("def"); - assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. - assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reused. + // New connection. + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + // Connection reused. + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); // ... even before we close the response body! response.body().close(); @@ -2558,8 +2575,8 @@ public final class CallTest { executeSynchronously("/"); RecordedRequest recordedRequest = server.takeRequest(); - assertTrue(recordedRequest.getHeader("User-Agent") - .matches(Version.userAgent())); + assertThat(recordedRequest.getHeader("User-Agent") + .matches(Version.userAgent())).isTrue(); } @Test public void setFollowRedirectsFalse() throws Exception { @@ -2591,7 +2608,7 @@ public final class CallTest { .assertCode(200) .assertSuccessful(); - assertEquals("abc", server.takeRequest().getBody().readUtf8()); + assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("abc"); } @Test public void expect100ContinueEmptyRequestBody() throws Exception { @@ -2635,7 +2652,7 @@ public final class CallTest { } RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("", recordedRequest.getBody().readUtf8()); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo(""); } @Test public void expect100ContinueTimesOutWithoutContinue_HTTP2() throws Exception { @@ -2657,7 +2674,7 @@ public final class CallTest { .assertSuccessful(); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("abc", recordedRequest.getBody().readUtf8()); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("abc"); } @Test public void serverRespondsWithUnsolicited100Continue_HTTP2() throws Exception { @@ -2686,7 +2703,7 @@ public final class CallTest { } RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("abc", recordedRequest.getBody().readUtf8()); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("abc"); } @Test public void serverRespondsWith100ContinueOnly_HTTP2() throws Exception { @@ -2708,8 +2725,8 @@ public final class CallTest { .url(server.url("/")) .build()); - 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 successfulExpectContinuePermitsConnectionReuseWithHttp2() throws Exception { @@ -2730,8 +2747,8 @@ public final class CallTest { .url(server.url("/")) .build()); - 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 unsuccessfulExpectContinuePermitsConnectionReuseWithHttp2() throws Exception { @@ -2749,8 +2766,8 @@ public final class CallTest { .url(server.url("/")) .build()); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals(1, server.takeRequest().getSequenceNumber()); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } /** We forbid non-ASCII characters in outgoing request headers, but accept UTF-8. */ @@ -2829,7 +2846,7 @@ public final class CallTest { .url(server.url("/")) .post(requestBody) .build()); - assertEquals("Response 1", call.execute().body().string()); + assertThat(call.execute().body().string()).isEqualTo("Response 1"); } /** Test which headers are sent unencrypted to the HTTP proxy. */ @@ -2855,19 +2872,20 @@ public final class CallTest { .header("User-Agent", "App 1.0") .build(); Response response = client.newCall(request).execute(); - assertEquals("encrypted response from the origin server", response.body().string()); + assertThat(response.body().string()).isEqualTo( + "encrypted response from the origin server"); RecordedRequest connect = server.takeRequest(); - assertNull(connect.getHeader("Private")); - assertEquals(Version.userAgent(), connect.getHeader("User-Agent")); - assertEquals("Keep-Alive", connect.getHeader("Proxy-Connection")); - assertEquals("android.com:443", connect.getHeader("Host")); + assertThat(connect.getHeader("Private")).isNull(); + assertThat(connect.getHeader("User-Agent")).isEqualTo(Version.userAgent()); + assertThat(connect.getHeader("Proxy-Connection")).isEqualTo("Keep-Alive"); + assertThat(connect.getHeader("Host")).isEqualTo("android.com:443"); RecordedRequest get = server.takeRequest(); - assertEquals("Secret", get.getHeader("Private")); - assertEquals("App 1.0", get.getHeader("User-Agent")); + assertThat(get.getHeader("Private")).isEqualTo("Secret"); + assertThat(get.getHeader("User-Agent")).isEqualTo("App 1.0"); - assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls); + assertThat(hostnameVerifier.calls).isEqualTo(Arrays.asList("verify android.com")); } /** Respond to a proxy authorization challenge. */ @@ -2894,19 +2912,19 @@ public final class CallTest { .url("https://android.com/foo") .build(); Response response = client.newCall(request).execute(); - assertEquals("response body", response.body().string()); + assertThat(response.body().string()).isEqualTo("response body"); RecordedRequest connect1 = server.takeRequest(); - assertEquals("CONNECT android.com:443 HTTP/1.1", connect1.getRequestLine()); - assertNull(connect1.getHeader("Proxy-Authorization")); + assertThat(connect1.getRequestLine()).isEqualTo("CONNECT android.com:443 HTTP/1.1"); + assertThat(connect1.getHeader("Proxy-Authorization")).isNull(); RecordedRequest connect2 = server.takeRequest(); - assertEquals("CONNECT android.com:443 HTTP/1.1", connect2.getRequestLine()); - assertEquals("password", connect2.getHeader("Proxy-Authorization")); + assertThat(connect2.getRequestLine()).isEqualTo("CONNECT android.com:443 HTTP/1.1"); + assertThat(connect2.getHeader("Proxy-Authorization")).isEqualTo("password"); RecordedRequest get = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", get.getRequestLine()); - assertNull(get.getHeader("Proxy-Authorization")); + assertThat(get.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(get.getHeader("Proxy-Authorization")).isNull(); } /** Confirm that the proxy authenticator works for unencrypted HTTP proxies. */ @@ -2926,15 +2944,15 @@ public final class CallTest { .url("http://android.com/foo") .build(); Response response = client.newCall(request).execute(); - assertEquals("response body", response.body().string()); + assertThat(response.body().string()).isEqualTo("response body"); RecordedRequest get1 = server.takeRequest(); - assertEquals("GET http://android.com/foo HTTP/1.1", get1.getRequestLine()); - assertNull(get1.getHeader("Proxy-Authorization")); + assertThat(get1.getRequestLine()).isEqualTo("GET http://android.com/foo HTTP/1.1"); + assertThat(get1.getHeader("Proxy-Authorization")).isNull(); RecordedRequest get2 = server.takeRequest(); - assertEquals("GET http://android.com/foo HTTP/1.1", get2.getRequestLine()); - assertEquals("password", get2.getHeader("Proxy-Authorization")); + assertThat(get2.getRequestLine()).isEqualTo("GET http://android.com/foo HTTP/1.1"); + assertThat(get2.getHeader("Proxy-Authorization")).isEqualTo("password"); } /** @@ -2966,16 +2984,16 @@ public final class CallTest { .url("https://android.com/foo") .build(); Response response = client.newCall(request).execute(); - assertEquals("response body", response.body().string()); + assertThat(response.body().string()).isEqualTo("response body"); // First CONNECT call needs a new connection. - assertEquals(0, server.takeRequest().getSequenceNumber()); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // Second CONNECT call needs a new connection. - assertEquals(0, server.takeRequest().getSequenceNumber()); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // GET reuses the connection from the second connect. - assertEquals(1, server.takeRequest().getSequenceNumber()); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void tooManyProxyAuthFailuresWithConnectionClose() throws IOException { @@ -3031,13 +3049,13 @@ public final class CallTest { .header("Proxy-Authorization", "password") .build(); Response response = client.newCall(request).execute(); - assertEquals("response body", response.body().string()); + assertThat(response.body().string()).isEqualTo("response body"); RecordedRequest connect1 = server.takeRequest(); - assertNull(connect1.getHeader("Proxy-Authorization")); + assertThat(connect1.getHeader("Proxy-Authorization")).isNull(); RecordedRequest connect2 = server.takeRequest(); - assertEquals("password", connect2.getHeader("Proxy-Authorization")); + assertThat(connect2.getHeader("Proxy-Authorization")).isEqualTo("password"); } /** Confirm that we can send authentication information without being prompted first. */ @@ -3057,12 +3075,12 @@ public final class CallTest { .proxy(server.toProxyAddress()) .hostnameVerifier(new RecordingHostnameVerifier()) .proxyAuthenticator((route, response) -> { - assertEquals("CONNECT", response.request().method()); - assertEquals(HttpURLConnection.HTTP_PROXY_AUTH, response.code()); - assertEquals("android.com", response.request().url().host()); + assertThat(response.request().method()).isEqualTo("CONNECT"); + assertThat(response.code()).isEqualTo(HttpURLConnection.HTTP_PROXY_AUTH); + assertThat(response.request().url().host()).isEqualTo("android.com"); List challenges = response.challenges(); - assertEquals("OkHttp-Preemptive", challenges.get(0).scheme()); + assertThat(challenges.get(0).scheme()).isEqualTo("OkHttp-Preemptive"); return response.request().newBuilder() .header("Proxy-Authorization", credential) @@ -3077,14 +3095,14 @@ public final class CallTest { executeSynchronously(request).assertSuccessful(); RecordedRequest connect = server.takeRequest(); - assertEquals("CONNECT", connect.getMethod()); - assertEquals(credential, connect.getHeader("Proxy-Authorization")); - assertEquals("/", connect.getPath()); + assertThat(connect.getMethod()).isEqualTo("CONNECT"); + assertThat(connect.getHeader("Proxy-Authorization")).isEqualTo(credential); + assertThat(connect.getPath()).isEqualTo("/"); RecordedRequest get = server.takeRequest(); - assertEquals("GET", get.getMethod()); - assertNull(get.getHeader("Proxy-Authorization")); - assertEquals("/foo", get.getPath()); + assertThat(get.getMethod()).isEqualTo("GET"); + assertThat(get.getHeader("Proxy-Authorization")).isNull(); + assertThat(get.getPath()).isEqualTo("/foo"); } @Test public void preemptiveThenReactiveProxyAuthentication() throws Exception { @@ -3122,14 +3140,14 @@ public final class CallTest { executeSynchronously(request).assertSuccessful(); RecordedRequest connect1 = server.takeRequest(); - assertEquals("CONNECT", connect1.getMethod()); - assertEquals(credential, connect1.getHeader("Proxy-Authorization")); + assertThat(connect1.getMethod()).isEqualTo("CONNECT"); + assertThat(connect1.getHeader("Proxy-Authorization")).isEqualTo(credential); RecordedRequest connect2 = server.takeRequest(); - assertEquals("CONNECT", connect2.getMethod()); - assertEquals(credential, connect2.getHeader("Proxy-Authorization")); + assertThat(connect2.getMethod()).isEqualTo("CONNECT"); + assertThat(connect2.getHeader("Proxy-Authorization")).isEqualTo(credential); - assertEquals(Arrays.asList("OkHttp-Preemptive", "Basic"), challengeSchemes); + assertThat(challengeSchemes).isEqualTo(Arrays.asList("OkHttp-Preemptive", "Basic")); } @Test public void interceptorGetsHttp2() throws Exception { @@ -3148,7 +3166,7 @@ public final class CallTest { // Make an HTTP/2 request and confirm that the protocol matches. server.enqueue(new MockResponse()); executeSynchronously("/"); - assertEquals(Protocol.HTTP_2, protocolRef.get()); + assertThat(protocolRef.get()).isEqualTo(Protocol.HTTP_2); } @Test public void serverSendsInvalidResponseHeaders() throws Exception { @@ -3188,7 +3206,8 @@ public final class CallTest { new Request.Builder().addHeader("a b", "c"); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Unexpected char 0x20 at 1 in header name: a b", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo( + "Unexpected char 0x20 at 1 in header name: a b"); } } @@ -3197,7 +3216,8 @@ public final class CallTest { new Request.Builder().addHeader("a\tb", "c"); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Unexpected char 0x09 at 1 in header name: a\tb", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo( + "Unexpected char 0x09 at 1 in header name: a\tb"); } } @@ -3209,7 +3229,7 @@ public final class CallTest { Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Response response = call.execute(); - assertEquals("c", response.header("a b")); + assertThat(response.header("a b")).isEqualTo("c"); } @Test public void responseHeaderNameWithTabPermitted() throws Exception { @@ -3220,7 +3240,7 @@ public final class CallTest { Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Response response = call.execute(); - assertEquals("c", response.header("a\tb")); + assertThat(response.header("a\tb")).isEqualTo("c"); } @Test public void connectFails() throws Exception { @@ -3247,7 +3267,7 @@ public final class CallTest { .build(); executeSynchronously(request); - assertEquals("abc", server.takeRequest().getBody().readUtf8()); + assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("abc"); } @Ignore // This may fail in DNS lookup, which we don't have timeouts for. @@ -3263,29 +3283,29 @@ public final class CallTest { @Test public void uploadBodySmallChunkedEncoding() throws Exception { upload(true, 1048576, 256); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals(1048576, recordedRequest.getBodySize()); - assertFalse(recordedRequest.getChunkSizes().isEmpty()); + assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); + assertThat(recordedRequest.getChunkSizes().isEmpty()).isFalse(); } @Test public void uploadBodyLargeChunkedEncoding() throws Exception { upload(true, 1048576, 65536); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals(1048576, recordedRequest.getBodySize()); - assertFalse(recordedRequest.getChunkSizes().isEmpty()); + assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); + assertThat(recordedRequest.getChunkSizes().isEmpty()).isFalse(); } @Test public void uploadBodySmallFixedLength() throws Exception { upload(false, 1048576, 256); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals(1048576, recordedRequest.getBodySize()); - assertTrue(recordedRequest.getChunkSizes().isEmpty()); + assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); + assertThat(recordedRequest.getChunkSizes().isEmpty()).isTrue(); } @Test public void uploadBodyLargeFixedLength() throws Exception { upload(false, 1048576, 65536); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals(1048576, recordedRequest.getBodySize()); - assertTrue(recordedRequest.getChunkSizes().isEmpty()); + assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); + assertThat(recordedRequest.getChunkSizes().isEmpty()).isTrue(); } private void upload( @@ -3319,15 +3339,15 @@ public final class CallTest { .url("https://[::1]/") .build(); Response response = client.newCall(request).execute(); - assertEquals("response body", response.body().string()); + assertThat(response.body().string()).isEqualTo("response body"); RecordedRequest connect = server.takeRequest(); - assertEquals("CONNECT [::1]:443 HTTP/1.1", connect.getRequestLine()); - assertEquals("[::1]:443", connect.getHeader("Host")); + assertThat(connect.getRequestLine()).isEqualTo("CONNECT [::1]:443 HTTP/1.1"); + assertThat(connect.getHeader("Host")).isEqualTo("[::1]:443"); RecordedRequest get = server.takeRequest(); - assertEquals("GET / HTTP/1.1", get.getRequestLine()); - assertEquals("[::1]", get.getHeader("Host")); + assertThat(get.getRequestLine()).isEqualTo("GET / HTTP/1.1"); + assertThat(get.getHeader("Host")).isEqualTo("[::1]"); } private RequestBody requestBody(final boolean chunked, final long size, final int writeSize) { @@ -3380,10 +3400,10 @@ public final class CallTest { awaitGarbageCollection(); String message = logHandler.take(); - assertTrue(message.contains("A connection to " + server.url("/") + " was leaked." - + " Did you forget to close a response body?")); - assertTrue(message.contains("okhttp3.RealCall.execute(")); - assertTrue(message.contains("okhttp3.CallTest.leakedResponseBodyLogsStackTrace(")); + assertThat(message.contains("A connection to " + server.url("/") + " was leaked." + + " Did you forget to close a response body?")).isTrue(); + assertThat(message.contains("okhttp3.RealCall.execute(")).isTrue(); + assertThat(message.contains("okhttp3.CallTest.leakedResponseBodyLogsStackTrace(")).isTrue(); } finally { logger.setLevel(original); } @@ -3423,10 +3443,10 @@ public final class CallTest { awaitGarbageCollection(); String message = logHandler.take(); - assertTrue(message.contains("A connection to " + server.url("/") + " was leaked." - + " Did you forget to close a response body?")); - assertTrue(message.contains("okhttp3.RealCall.enqueue(")); - assertTrue(message.contains("okhttp3.CallTest.asyncLeakedResponseBodyLogsStackTrace(")); + assertThat(message.contains("A connection to " + server.url("/") + " was leaked." + + " Did you forget to close a response body?")).isTrue(); + assertThat(message.contains("okhttp3.RealCall.enqueue(")).isTrue(); + assertThat(message.contains("okhttp3.CallTest.asyncLeakedResponseBodyLogsStackTrace(")).isTrue(); } finally { logger.setLevel(original); } @@ -3447,7 +3467,7 @@ public final class CallTest { executeSynchronously(request) .assertFailure(IOException.class); - assertEquals(1, client.connectionPool().idleConnectionCount()); + assertThat(client.connectionPool().idleConnectionCount()).isEqualTo(1); } @Test public void failedProxyAuthenticatorReleasesConnection() throws IOException { @@ -3465,7 +3485,7 @@ public final class CallTest { executeSynchronously(request) .assertFailure(IOException.class); - assertEquals(1, client.connectionPool().idleConnectionCount()); + assertThat(client.connectionPool().idleConnectionCount()).isEqualTo(1); } @Test public void httpsWithIpAddress() throws Exception { @@ -3503,7 +3523,8 @@ public final class CallTest { // Confirm that the IP address was used in the host header. RecordedRequest recordedRequest = server.takeRequest(); - assertEquals(localIpAddress + ":" + server.getPort(), recordedRequest.getHeader("Host")); + assertThat(recordedRequest.getHeader("Host")).isEqualTo( + (localIpAddress + ":" + server.getPort())); } @Test public void postWithFileNotFound() throws Exception { @@ -3532,7 +3553,7 @@ public final class CallTest { executeSynchronously(request) .assertFailure(FileNotFoundException.class); - assertEquals(1L, called.get()); + assertThat(called.get()).isEqualTo(1L); } @Test public void clientReadsHeadersDataTrailersHttp1ChunkedTransferEncoding() throws Exception { @@ -3551,14 +3572,14 @@ public final class CallTest { Response response = call.execute(); BufferedSource source = response.body().source(); - assertEquals("v1", response.header("h1")); - assertEquals("v2", response.header("h2")); + assertThat(response.header("h1")).isEqualTo("v1"); + assertThat(response.header("h2")).isEqualTo("v2"); - assertEquals("Hello", source.readUtf8(5)); - assertEquals("Bonjour", source.readUtf8(7)); + assertThat(source.readUtf8(5)).isEqualTo("Hello"); + assertThat(source.readUtf8(7)).isEqualTo("Bonjour"); - assertTrue(source.exhausted()); - assertEquals(Headers.of("trailers", "boom"), response.trailers()); + assertThat(source.exhausted()).isTrue(); + assertThat(response.trailers()).isEqualTo(Headers.of("trailers", "boom")); } @Test public void clientReadsHeadersDataTrailersHttp2() throws IOException { @@ -3578,14 +3599,14 @@ public final class CallTest { try (Response response = call.execute()) { BufferedSource source = response.body().source(); - assertEquals("v1", response.header("h1")); - assertEquals("v2", response.header("h2")); + assertThat(response.header("h1")).isEqualTo("v1"); + assertThat(response.header("h2")).isEqualTo("v2"); - assertEquals("Hello", source.readUtf8(5)); - assertEquals("Bonjour", source.readUtf8(7)); + assertThat(source.readUtf8(5)).isEqualTo("Hello"); + assertThat(source.readUtf8(7)).isEqualTo("Bonjour"); - assertTrue(source.exhausted()); - assertEquals(Headers.of("trailers", "boom"), response.trailers()); + assertThat(source.exhausted()).isTrue(); + assertThat(response.trailers()).isEqualTo(Headers.of("trailers", "boom")); } } @@ -3639,7 +3660,7 @@ public final class CallTest { .build(); executeSynchronously("/").assertFailure("Canceled"); - assertTrue(closed.get()); + assertThat(closed.get()).isTrue(); } private void makeFailingCall() { @@ -3667,7 +3688,7 @@ public final class CallTest { call.execute(); fail(); } catch (IOException expected) { - assertEquals("write body fail!", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("write body fail!"); } } diff --git a/okhttp-tests/src/test/java/okhttp3/CertificateChainCleanerTest.java b/okhttp-tests/src/test/java/okhttp3/CertificateChainCleanerTest.java index e61cb9f29..a2185a934 100644 --- a/okhttp-tests/src/test/java/okhttp3/CertificateChainCleanerTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CertificateChainCleanerTest.java @@ -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() { diff --git a/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java b/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java index a0e03cdcc..6e57f2cfd 100644 --- a/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java @@ -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 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 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 expectedPin1 = Arrays.asList(new Pin("EXAMPLE.com", certA1Sha256Pin)); - assertEquals(expectedPin1, certificatePinner.findMatchingPins("example.com")); + assertThat(certificatePinner.findMatchingPins("example.com")).isEqualTo(expectedPin1); List 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 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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/CipherSuiteTest.java b/okhttp-tests/src/test/java/okhttp3/CipherSuiteTest.java index 64754ad5c..3a72df03a 100644 --- a/okhttp-tests/src/test/java/okhttp3/CipherSuiteTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CipherSuiteTest.java @@ -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 { diff --git a/okhttp-tests/src/test/java/okhttp3/ConnectionCoalescingTest.java b/okhttp-tests/src/test/java/okhttp3/ConnectionCoalescingTest.java index 8fb237fbe..868057c13 100644 --- a/okhttp-tests/src/test/java/okhttp3/ConnectionCoalescingTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ConnectionCoalescingTest.java @@ -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(); } } diff --git a/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java b/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java index 62efebdd1..fbce95e42 100644 --- a/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java @@ -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); } } } diff --git a/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java b/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java index 13b2824f0..a889e5c88 100644 --- a/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java @@ -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 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 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 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 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 diff --git a/okhttp-tests/src/test/java/okhttp3/ConscryptTest.java b/okhttp-tests/src/test/java/okhttp3/ConscryptTest.java index cccde97ae..5c5184d22 100644 --- a/okhttp-tests/src/test/java/okhttp3/ConscryptTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ConscryptTest.java @@ -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"); } diff --git a/okhttp-tests/src/test/java/okhttp3/CookieTest.java b/okhttp-tests/src/test/java/okhttp3/CookieTest.java index 3304fa588..31186a842 100644 --- a/okhttp-tests/src/test/java/okhttp3/CookieTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CookieTest.java @@ -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 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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/CookiesTest.java b/okhttp-tests/src/test/java/okhttp3/CookiesTest.java index d28fbb4fe..514252822 100644 --- a/okhttp-tests/src/test/java/okhttp3/CookiesTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CookiesTest.java @@ -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 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 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 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 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 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 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 actualCookies = cookieJar.loadForRequest(url2); - assertEquals(Collections.emptyList(), actualCookies); + assertThat(actualCookies).isEmpty(); } private HttpUrl urlWithIpAddress(MockWebServer server, String path) throws Exception { diff --git a/okhttp-tests/src/test/java/okhttp3/DispatcherTest.java b/okhttp-tests/src/test/java/okhttp3/DispatcherTest.java index 7cab7d76d..8d24fc435 100644 --- a/okhttp-tests/src/test/java/okhttp3/DispatcherTest.java +++ b/okhttp-tests/src/test/java/okhttp3/DispatcherTest.java @@ -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) { diff --git a/okhttp-tests/src/test/java/okhttp3/DuplexTest.java b/okhttp-tests/src/test/java/okhttp3/DuplexTest.java index 3e39260d8..c67e333b1 100644 --- a/okhttp-tests/src/test/java/okhttp3/DuplexTest.java +++ b/okhttp-tests/src/test/java/okhttp3/DuplexTest.java @@ -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(); diff --git a/okhttp-tests/src/test/java/okhttp3/EventListenerTest.java b/okhttp-tests/src/test/java/okhttp3/EventListenerTest.java index f9cf8aa2d..8f614badb 100644 --- a/okhttp-tests/src/test/java/okhttp3/EventListenerTest.java +++ b/okhttp-tests/src/test/java/okhttp3/EventListenerTest.java @@ -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 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 expectedEvents = Arrays.asList("CallStart", "CallFailed"); - assertEquals(expectedEvents, listener.recordedEventTypes()); + Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } private void assertSuccessfulEventOrder(Matcher 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 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 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 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 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 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 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 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 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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/FormBodyTest.java b/okhttp-tests/src/test/java/okhttp3/FormBodyTest.java index b0cb8a6d0..e352298f0 100644 --- a/okhttp-tests/src/test/java/okhttp3/FormBodyTest.java +++ b/okhttp-tests/src/test/java/okhttp3/FormBodyTest.java @@ -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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/HeadersTest.java b/okhttp-tests/src/test/java/okhttp3/HeadersTest.java index 4bfc5d200..ef1e5ed34 100644 --- a/okhttp-tests/src/test/java/okhttp3/HeadersTest.java +++ b/okhttp-tests/src/test/java/okhttp3/HeadersTest.java @@ -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> 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> 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> 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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"); } } } diff --git a/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java b/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java index 23a32d7e9..edd04aced 100644 --- a/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java +++ b/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java @@ -29,8 +29,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import static java.util.Collections.singletonList; -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; @RunWith(Parameterized.class) @@ -54,12 +53,16 @@ public final class HttpUrlTest { @Test public void parseTrimsAsciiWhitespace() throws Exception { HttpUrl expected = parse("http://host/"); - assertEquals(expected, parse("http://host/\f\n\t \r")); // Leading. - assertEquals(expected, parse("\r\n\f \thttp://host/")); // Trailing. - assertEquals(expected, parse(" http://host/ ")); // Both. - assertEquals(expected, parse(" http://host/ ")); // Both. - assertEquals(expected, parse("http://host/").resolve(" ")); - assertEquals(expected, parse("http://host/").resolve(" . ")); + // Leading. + assertThat(parse("http://host/\f\n\t \r")).isEqualTo(expected); + // Trailing. + assertThat(parse("\r\n\f \thttp://host/")).isEqualTo(expected); + // Both. + assertThat(parse(" http://host/ ")).isEqualTo(expected); + // Both. + assertThat(parse(" http://host/ ")).isEqualTo(expected); + assertThat(parse("http://host/").resolve(" ")).isEqualTo(expected); + assertThat(parse("http://host/").resolve(" . ")).isEqualTo(expected); } @Test public void parseHostAsciiNonPrintable() throws Exception { @@ -70,45 +73,75 @@ public final class HttpUrlTest { @Test public void parseDoesNotTrimOtherWhitespaceCharacters() throws Exception { // Whitespace characters list from Google's Guava team: http://goo.gl/IcR9RD - assertEquals("/%0B", parse("http://h/\u000b").encodedPath()); // line tabulation - assertEquals("/%1C", parse("http://h/\u001c").encodedPath()); // information separator 4 - assertEquals("/%1D", parse("http://h/\u001d").encodedPath()); // information separator 3 - assertEquals("/%1E", parse("http://h/\u001e").encodedPath()); // information separator 2 - assertEquals("/%1F", parse("http://h/\u001f").encodedPath()); // information separator 1 - assertEquals("/%C2%85", parse("http://h/\u0085").encodedPath()); // next line - assertEquals("/%C2%A0", parse("http://h/\u00a0").encodedPath()); // non-breaking space - assertEquals("/%E1%9A%80", parse("http://h/\u1680").encodedPath()); // ogham space mark - assertEquals("/%E1%A0%8E", parse("http://h/\u180e").encodedPath()); // mongolian vowel separator - assertEquals("/%E2%80%80", parse("http://h/\u2000").encodedPath()); // en quad - assertEquals("/%E2%80%81", parse("http://h/\u2001").encodedPath()); // em quad - assertEquals("/%E2%80%82", parse("http://h/\u2002").encodedPath()); // en space - assertEquals("/%E2%80%83", parse("http://h/\u2003").encodedPath()); // em space - assertEquals("/%E2%80%84", parse("http://h/\u2004").encodedPath()); // three-per-em space - assertEquals("/%E2%80%85", parse("http://h/\u2005").encodedPath()); // four-per-em space - assertEquals("/%E2%80%86", parse("http://h/\u2006").encodedPath()); // six-per-em space - assertEquals("/%E2%80%87", parse("http://h/\u2007").encodedPath()); // figure space - assertEquals("/%E2%80%88", parse("http://h/\u2008").encodedPath()); // punctuation space - assertEquals("/%E2%80%89", parse("http://h/\u2009").encodedPath()); // thin space - assertEquals("/%E2%80%8A", parse("http://h/\u200a").encodedPath()); // hair space - assertEquals("/%E2%80%8B", parse("http://h/\u200b").encodedPath()); // zero-width space - assertEquals("/%E2%80%8C", parse("http://h/\u200c").encodedPath()); // zero-width non-joiner - assertEquals("/%E2%80%8D", parse("http://h/\u200d").encodedPath()); // zero-width joiner - assertEquals("/%E2%80%8E", parse("http://h/\u200e").encodedPath()); // left-to-right mark - assertEquals("/%E2%80%8F", parse("http://h/\u200f").encodedPath()); // right-to-left mark - assertEquals("/%E2%80%A8", parse("http://h/\u2028").encodedPath()); // line separator - assertEquals("/%E2%80%A9", parse("http://h/\u2029").encodedPath()); // paragraph separator - assertEquals("/%E2%80%AF", parse("http://h/\u202f").encodedPath()); // narrow non-breaking space - assertEquals("/%E2%81%9F", parse("http://h/\u205f").encodedPath()); // medium mathematical space - assertEquals("/%E3%80%80", parse("http://h/\u3000").encodedPath()); // ideographic space + // line tabulation + assertThat(parse("http://h/\u000b").encodedPath()).isEqualTo("/%0B"); + // information separator 4 + assertThat(parse("http://h/\u001c").encodedPath()).isEqualTo("/%1C"); + // information separator 3 + assertThat(parse("http://h/\u001d").encodedPath()).isEqualTo("/%1D"); + // information separator 2 + assertThat(parse("http://h/\u001e").encodedPath()).isEqualTo("/%1E"); + // information separator 1 + assertThat(parse("http://h/\u001f").encodedPath()).isEqualTo("/%1F"); + // next line + assertThat(parse("http://h/\u0085").encodedPath()).isEqualTo("/%C2%85"); + // non-breaking space + assertThat(parse("http://h/\u00a0").encodedPath()).isEqualTo("/%C2%A0"); + // ogham space mark + assertThat(parse("http://h/\u1680").encodedPath()).isEqualTo("/%E1%9A%80"); + // mongolian vowel separator + assertThat(parse("http://h/\u180e").encodedPath()).isEqualTo("/%E1%A0%8E"); + // en quad + assertThat(parse("http://h/\u2000").encodedPath()).isEqualTo("/%E2%80%80"); + // em quad + assertThat(parse("http://h/\u2001").encodedPath()).isEqualTo("/%E2%80%81"); + // en space + assertThat(parse("http://h/\u2002").encodedPath()).isEqualTo("/%E2%80%82"); + // em space + assertThat(parse("http://h/\u2003").encodedPath()).isEqualTo("/%E2%80%83"); + // three-per-em space + assertThat(parse("http://h/\u2004").encodedPath()).isEqualTo("/%E2%80%84"); + // four-per-em space + assertThat(parse("http://h/\u2005").encodedPath()).isEqualTo("/%E2%80%85"); + // six-per-em space + assertThat(parse("http://h/\u2006").encodedPath()).isEqualTo("/%E2%80%86"); + // figure space + assertThat(parse("http://h/\u2007").encodedPath()).isEqualTo("/%E2%80%87"); + // punctuation space + assertThat(parse("http://h/\u2008").encodedPath()).isEqualTo("/%E2%80%88"); + // thin space + assertThat(parse("http://h/\u2009").encodedPath()).isEqualTo("/%E2%80%89"); + // hair space + assertThat(parse("http://h/\u200a").encodedPath()).isEqualTo("/%E2%80%8A"); + // zero-width space + assertThat(parse("http://h/\u200b").encodedPath()).isEqualTo("/%E2%80%8B"); + // zero-width non-joiner + assertThat(parse("http://h/\u200c").encodedPath()).isEqualTo("/%E2%80%8C"); + // zero-width joiner + assertThat(parse("http://h/\u200d").encodedPath()).isEqualTo("/%E2%80%8D"); + // left-to-right mark + assertThat(parse("http://h/\u200e").encodedPath()).isEqualTo("/%E2%80%8E"); + // right-to-left mark + assertThat(parse("http://h/\u200f").encodedPath()).isEqualTo("/%E2%80%8F"); + // line separator + assertThat(parse("http://h/\u2028").encodedPath()).isEqualTo("/%E2%80%A8"); + // paragraph separator + assertThat(parse("http://h/\u2029").encodedPath()).isEqualTo("/%E2%80%A9"); + // narrow non-breaking space + assertThat(parse("http://h/\u202f").encodedPath()).isEqualTo("/%E2%80%AF"); + // medium mathematical space + assertThat(parse("http://h/\u205f").encodedPath()).isEqualTo("/%E2%81%9F"); + // ideographic space + assertThat(parse("http://h/\u3000").encodedPath()).isEqualTo("/%E3%80%80"); } @Test public void scheme() throws Exception { - assertEquals(parse("http://host/"), parse("http://host/")); - assertEquals(parse("http://host/"), parse("Http://host/")); - assertEquals(parse("http://host/"), parse("http://host/")); - assertEquals(parse("http://host/"), parse("HTTP://host/")); - assertEquals(parse("https://host/"), parse("https://host/")); - assertEquals(parse("https://host/"), parse("HTTPS://host/")); + assertThat(parse("http://host/")).isEqualTo(parse("http://host/")); + assertThat(parse("Http://host/")).isEqualTo(parse("http://host/")); + assertThat(parse("http://host/")).isEqualTo(parse("http://host/")); + assertThat(parse("HTTP://host/")).isEqualTo(parse("http://host/")); + assertThat(parse("https://host/")).isEqualTo(parse("https://host/")); + assertThat(parse("HTTPS://host/")).isEqualTo(parse("https://host/")); assertInvalid("image640://480.png", "Expected URL scheme 'http' or 'https' but was 'image640'"); assertInvalid("httpp://host/", "Expected URL scheme 'http' or 'https' but was 'httpp'"); @@ -131,201 +164,205 @@ public final class HttpUrlTest { @Test public void newBuilderResolve() throws Exception { // Non-exhaustive tests because implementation is the same as resolve. HttpUrl base = parse("http://host/a/b"); - assertEquals(parse("https://host2/"), base.newBuilder("https://host2").build()); - assertEquals(parse("http://host2/"), base.newBuilder("//host2").build()); - assertEquals(parse("http://host/path"), base.newBuilder("/path").build()); - assertEquals(parse("http://host/a/path"), base.newBuilder("path").build()); - assertEquals(parse("http://host/a/b?query"), base.newBuilder("?query").build()); - assertEquals(parse("http://host/a/b#fragment"), base.newBuilder("#fragment").build()); - assertEquals(parse("http://host/a/b"), base.newBuilder("").build()); - assertNull(base.newBuilder("ftp://b")); - assertNull(base.newBuilder("ht+tp://b")); - assertNull(base.newBuilder("ht-tp://b")); - assertNull(base.newBuilder("ht.tp://b")); + assertThat(base.newBuilder("https://host2").build()).isEqualTo(parse("https://host2/")); + assertThat(base.newBuilder("//host2").build()).isEqualTo(parse("http://host2/")); + assertThat(base.newBuilder("/path").build()).isEqualTo(parse("http://host/path")); + assertThat(base.newBuilder("path").build()).isEqualTo(parse("http://host/a/path")); + assertThat(base.newBuilder("?query").build()).isEqualTo(parse("http://host/a/b?query")); + assertThat(base.newBuilder("#fragment").build()).isEqualTo( + parse("http://host/a/b#fragment")); + assertThat(base.newBuilder("").build()).isEqualTo(parse("http://host/a/b")); + assertThat(base.newBuilder("ftp://b")).isNull(); + assertThat(base.newBuilder("ht+tp://b")).isNull(); + assertThat(base.newBuilder("ht-tp://b")).isNull(); + assertThat(base.newBuilder("ht.tp://b")).isNull(); } @Test public void redactedUrl() { HttpUrl baseWithPasswordAndUsername = parse("http://username:password@host/a/b#fragment"); HttpUrl baseWithUsernameOnly = parse("http://username@host/a/b#fragment"); HttpUrl baseWithPasswordOnly = parse("http://password@host/a/b#fragment"); - assertEquals("http://host/...", baseWithPasswordAndUsername.redact()); - assertEquals("http://host/...", baseWithUsernameOnly.redact()); - assertEquals("http://host/...", baseWithPasswordOnly.redact()); + assertThat(baseWithPasswordAndUsername.redact()).isEqualTo("http://host/..."); + assertThat(baseWithUsernameOnly.redact()).isEqualTo("http://host/..."); + assertThat(baseWithPasswordOnly.redact()).isEqualTo("http://host/..."); } @Test public void resolveNoScheme() throws Exception { HttpUrl base = parse("http://host/a/b"); - assertEquals(parse("http://host2/"), base.resolve("//host2")); - assertEquals(parse("http://host/path"), base.resolve("/path")); - assertEquals(parse("http://host/a/path"), base.resolve("path")); - assertEquals(parse("http://host/a/b?query"), base.resolve("?query")); - assertEquals(parse("http://host/a/b#fragment"), base.resolve("#fragment")); - assertEquals(parse("http://host/a/b"), base.resolve("")); - assertEquals(parse("http://host/path"), base.resolve("\\path")); + assertThat(base.resolve("//host2")).isEqualTo(parse("http://host2/")); + assertThat(base.resolve("/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("path")).isEqualTo(parse("http://host/a/path")); + assertThat(base.resolve("?query")).isEqualTo(parse("http://host/a/b?query")); + assertThat(base.resolve("#fragment")).isEqualTo(parse("http://host/a/b#fragment")); + assertThat(base.resolve("")).isEqualTo(parse("http://host/a/b")); + assertThat(base.resolve("\\path")).isEqualTo(parse("http://host/path")); } @Test public void resolveUnsupportedScheme() throws Exception { HttpUrl base = parse("http://a/"); - assertNull(base.resolve("ftp://b")); - assertNull(base.resolve("ht+tp://b")); - assertNull(base.resolve("ht-tp://b")); - assertNull(base.resolve("ht.tp://b")); + assertThat(base.resolve("ftp://b")).isNull(); + assertThat(base.resolve("ht+tp://b")).isNull(); + assertThat(base.resolve("ht-tp://b")).isNull(); + assertThat(base.resolve("ht.tp://b")).isNull(); } @Test public void resolveSchemeLikePath() throws Exception { HttpUrl base = parse("http://a/"); - assertEquals(parse("http://a/http//b/"), base.resolve("http//b/")); - assertEquals(parse("http://a/ht+tp//b/"), base.resolve("ht+tp//b/")); - assertEquals(parse("http://a/ht-tp//b/"), base.resolve("ht-tp//b/")); - assertEquals(parse("http://a/ht.tp//b/"), base.resolve("ht.tp//b/")); + assertThat(base.resolve("http//b/")).isEqualTo(parse("http://a/http//b/")); + assertThat(base.resolve("ht+tp//b/")).isEqualTo(parse("http://a/ht+tp//b/")); + assertThat(base.resolve("ht-tp//b/")).isEqualTo(parse("http://a/ht-tp//b/")); + assertThat(base.resolve("ht.tp//b/")).isEqualTo(parse("http://a/ht.tp//b/")); } /** https://tools.ietf.org/html/rfc3986#section-5.4.1 */ @Test public void rfc3886NormalExamples() { HttpUrl url = parse("http://a/b/c/d;p?q"); - assertNull(url.resolve("g:h")); // No 'g:' scheme in HttpUrl. - assertEquals(parse("http://a/b/c/g"), url.resolve("g")); - assertEquals(parse("http://a/b/c/g"), url.resolve("./g")); - assertEquals(parse("http://a/b/c/g/"), url.resolve("g/")); - assertEquals(parse("http://a/g"), url.resolve("/g")); - assertEquals(parse("http://g"), url.resolve("//g")); - assertEquals(parse("http://a/b/c/d;p?y"), url.resolve("?y")); - assertEquals(parse("http://a/b/c/g?y"), url.resolve("g?y")); - assertEquals(parse("http://a/b/c/d;p?q#s"), url.resolve("#s")); - assertEquals(parse("http://a/b/c/g#s"), url.resolve("g#s")); - assertEquals(parse("http://a/b/c/g?y#s"), url.resolve("g?y#s")); - assertEquals(parse("http://a/b/c/;x"), url.resolve(";x")); - assertEquals(parse("http://a/b/c/g;x"), url.resolve("g;x")); - assertEquals(parse("http://a/b/c/g;x?y#s"), url.resolve("g;x?y#s")); - assertEquals(parse("http://a/b/c/d;p?q"), url.resolve("")); - assertEquals(parse("http://a/b/c/"), url.resolve(".")); - assertEquals(parse("http://a/b/c/"), url.resolve("./")); - assertEquals(parse("http://a/b/"), url.resolve("..")); - assertEquals(parse("http://a/b/"), url.resolve("../")); - assertEquals(parse("http://a/b/g"), url.resolve("../g")); - assertEquals(parse("http://a/"), url.resolve("../..")); - assertEquals(parse("http://a/"), url.resolve("../../")); - assertEquals(parse("http://a/g"), url.resolve("../../g")); + // No 'g:' scheme in HttpUrl. + assertThat(url.resolve("g:h")).isNull(); + assertThat(url.resolve("g")).isEqualTo(parse("http://a/b/c/g")); + assertThat(url.resolve("./g")).isEqualTo(parse("http://a/b/c/g")); + assertThat(url.resolve("g/")).isEqualTo(parse("http://a/b/c/g/")); + assertThat(url.resolve("/g")).isEqualTo(parse("http://a/g")); + assertThat(url.resolve("//g")).isEqualTo(parse("http://g")); + assertThat(url.resolve("?y")).isEqualTo(parse("http://a/b/c/d;p?y")); + assertThat(url.resolve("g?y")).isEqualTo(parse("http://a/b/c/g?y")); + assertThat(url.resolve("#s")).isEqualTo(parse("http://a/b/c/d;p?q#s")); + assertThat(url.resolve("g#s")).isEqualTo(parse("http://a/b/c/g#s")); + assertThat(url.resolve("g?y#s")).isEqualTo(parse("http://a/b/c/g?y#s")); + assertThat(url.resolve(";x")).isEqualTo(parse("http://a/b/c/;x")); + assertThat(url.resolve("g;x")).isEqualTo(parse("http://a/b/c/g;x")); + assertThat(url.resolve("g;x?y#s")).isEqualTo(parse("http://a/b/c/g;x?y#s")); + assertThat(url.resolve("")).isEqualTo(parse("http://a/b/c/d;p?q")); + assertThat(url.resolve(".")).isEqualTo(parse("http://a/b/c/")); + assertThat(url.resolve("./")).isEqualTo(parse("http://a/b/c/")); + assertThat(url.resolve("..")).isEqualTo(parse("http://a/b/")); + assertThat(url.resolve("../")).isEqualTo(parse("http://a/b/")); + assertThat(url.resolve("../g")).isEqualTo(parse("http://a/b/g")); + assertThat(url.resolve("../..")).isEqualTo(parse("http://a/")); + assertThat(url.resolve("../../")).isEqualTo(parse("http://a/")); + assertThat(url.resolve("../../g")).isEqualTo(parse("http://a/g")); } /** https://tools.ietf.org/html/rfc3986#section-5.4.2 */ @Test public void rfc3886AbnormalExamples() { HttpUrl url = parse("http://a/b/c/d;p?q"); - assertEquals(parse("http://a/g"), url.resolve("../../../g")); - assertEquals(parse("http://a/g"), url.resolve("../../../../g")); - assertEquals(parse("http://a/g"), url.resolve("/./g")); - assertEquals(parse("http://a/g"), url.resolve("/../g")); - assertEquals(parse("http://a/b/c/g."), url.resolve("g.")); - assertEquals(parse("http://a/b/c/.g"), url.resolve(".g")); - assertEquals(parse("http://a/b/c/g.."), url.resolve("g..")); - assertEquals(parse("http://a/b/c/..g"), url.resolve("..g")); - assertEquals(parse("http://a/b/g"), url.resolve("./../g")); - assertEquals(parse("http://a/b/c/g/"), url.resolve("./g/.")); - assertEquals(parse("http://a/b/c/g/h"), url.resolve("g/./h")); - assertEquals(parse("http://a/b/c/h"), url.resolve("g/../h")); - assertEquals(parse("http://a/b/c/g;x=1/y"), url.resolve("g;x=1/./y")); - assertEquals(parse("http://a/b/c/y"), url.resolve("g;x=1/../y")); - assertEquals(parse("http://a/b/c/g?y/./x"), url.resolve("g?y/./x")); - assertEquals(parse("http://a/b/c/g?y/../x"), url.resolve("g?y/../x")); - assertEquals(parse("http://a/b/c/g#s/./x"), url.resolve("g#s/./x")); - assertEquals(parse("http://a/b/c/g#s/../x"), url.resolve("g#s/../x")); - assertEquals(parse("http://a/b/c/g"), url.resolve("http:g")); // "http:g" also okay. + assertThat(url.resolve("../../../g")).isEqualTo(parse("http://a/g")); + assertThat(url.resolve("../../../../g")).isEqualTo(parse("http://a/g")); + assertThat(url.resolve("/./g")).isEqualTo(parse("http://a/g")); + assertThat(url.resolve("/../g")).isEqualTo(parse("http://a/g")); + assertThat(url.resolve("g.")).isEqualTo(parse("http://a/b/c/g.")); + assertThat(url.resolve(".g")).isEqualTo(parse("http://a/b/c/.g")); + assertThat(url.resolve("g..")).isEqualTo(parse("http://a/b/c/g..")); + assertThat(url.resolve("..g")).isEqualTo(parse("http://a/b/c/..g")); + assertThat(url.resolve("./../g")).isEqualTo(parse("http://a/b/g")); + assertThat(url.resolve("./g/.")).isEqualTo(parse("http://a/b/c/g/")); + assertThat(url.resolve("g/./h")).isEqualTo(parse("http://a/b/c/g/h")); + assertThat(url.resolve("g/../h")).isEqualTo(parse("http://a/b/c/h")); + assertThat(url.resolve("g;x=1/./y")).isEqualTo(parse("http://a/b/c/g;x=1/y")); + assertThat(url.resolve("g;x=1/../y")).isEqualTo(parse("http://a/b/c/y")); + assertThat(url.resolve("g?y/./x")).isEqualTo(parse("http://a/b/c/g?y/./x")); + assertThat(url.resolve("g?y/../x")).isEqualTo(parse("http://a/b/c/g?y/../x")); + assertThat(url.resolve("g#s/./x")).isEqualTo(parse("http://a/b/c/g#s/./x")); + assertThat(url.resolve("g#s/../x")).isEqualTo(parse("http://a/b/c/g#s/../x")); + // "http:g" also okay. + assertThat(url.resolve("http:g")).isEqualTo(parse("http://a/b/c/g")); } @Test public void parseAuthoritySlashCountDoesntMatter() throws Exception { - assertEquals(parse("http://host/path"), parse("http:host/path")); - assertEquals(parse("http://host/path"), parse("http:/host/path")); - assertEquals(parse("http://host/path"), parse("http:\\host/path")); - assertEquals(parse("http://host/path"), parse("http://host/path")); - assertEquals(parse("http://host/path"), parse("http:\\/host/path")); - assertEquals(parse("http://host/path"), parse("http:/\\host/path")); - assertEquals(parse("http://host/path"), parse("http:\\\\host/path")); - assertEquals(parse("http://host/path"), parse("http:///host/path")); - assertEquals(parse("http://host/path"), parse("http:\\//host/path")); - assertEquals(parse("http://host/path"), parse("http:/\\/host/path")); - assertEquals(parse("http://host/path"), parse("http://\\host/path")); - assertEquals(parse("http://host/path"), parse("http:\\\\/host/path")); - assertEquals(parse("http://host/path"), parse("http:/\\\\host/path")); - assertEquals(parse("http://host/path"), parse("http:\\\\\\host/path")); - assertEquals(parse("http://host/path"), parse("http:////host/path")); + assertThat(parse("http:host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:/host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http://host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:\\/host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:/\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:\\\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:///host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:\\//host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:/\\/host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http://\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:\\\\/host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:/\\\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:\\\\\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http:////host/path")).isEqualTo(parse("http://host/path")); } @Test public void resolveAuthoritySlashCountDoesntMatterWithDifferentScheme() throws Exception { HttpUrl base = parse("https://a/b/c"); - assertEquals(parse("http://host/path"), base.resolve("http:host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:/host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http://host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\/host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:/\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:///host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\//host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:/\\/host/path")); - assertEquals(parse("http://host/path"), base.resolve("http://\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\\\/host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:/\\\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\\\\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:////host/path")); + assertThat(base.resolve("http:host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:/host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http://host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\/host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:/\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:///host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\//host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:/\\/host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http://\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\\\/host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:/\\\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\\\\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:////host/path")).isEqualTo(parse("http://host/path")); } @Test public void resolveAuthoritySlashCountMattersWithSameScheme() throws Exception { HttpUrl base = parse("http://a/b/c"); - assertEquals(parse("http://a/b/host/path"), base.resolve("http:host/path")); - assertEquals(parse("http://a/host/path"), base.resolve("http:/host/path")); - assertEquals(parse("http://a/host/path"), base.resolve("http:\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http://host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\/host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:/\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:///host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\//host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:/\\/host/path")); - assertEquals(parse("http://host/path"), base.resolve("http://\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\\\/host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:/\\\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:\\\\\\host/path")); - assertEquals(parse("http://host/path"), base.resolve("http:////host/path")); + assertThat(base.resolve("http:host/path")).isEqualTo(parse("http://a/b/host/path")); + assertThat(base.resolve("http:/host/path")).isEqualTo(parse("http://a/host/path")); + assertThat(base.resolve("http:\\host/path")).isEqualTo(parse("http://a/host/path")); + assertThat(base.resolve("http://host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\/host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:/\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:///host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\//host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:/\\/host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http://\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\\\/host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:/\\\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:\\\\\\host/path")).isEqualTo(parse("http://host/path")); + assertThat(base.resolve("http:////host/path")).isEqualTo(parse("http://host/path")); } @Test public void username() throws Exception { - assertEquals(parse("http://host/path"), parse("http://@host/path")); - assertEquals(parse("http://user@host/path"), parse("http://user@host/path")); + assertThat(parse("http://@host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http://user@host/path")).isEqualTo(parse("http://user@host/path")); } /** Given multiple '@' characters, the last one is the delimiter. */ @Test public void authorityWithMultipleAtSigns() throws Exception { HttpUrl httpUrl = parse("http://foo@bar@baz/path"); - assertEquals("foo@bar", httpUrl.username()); - assertEquals("", httpUrl.password()); - assertEquals(parse("http://foo%40bar@baz/path"), httpUrl); + assertThat(httpUrl.username()).isEqualTo("foo@bar"); + assertThat(httpUrl.password()).isEqualTo(""); + assertThat(httpUrl).isEqualTo(parse("http://foo%40bar@baz/path")); } /** Given multiple ':' characters, the first one is the delimiter. */ @Test public void authorityWithMultipleColons() throws Exception { HttpUrl httpUrl = parse("http://foo:pass1@bar:pass2@baz/path"); - assertEquals("foo", httpUrl.username()); - assertEquals("pass1@bar:pass2", httpUrl.password()); - assertEquals(parse("http://foo:pass1%40bar%3Apass2@baz/path"), httpUrl); + assertThat(httpUrl.username()).isEqualTo("foo"); + assertThat(httpUrl.password()).isEqualTo("pass1@bar:pass2"); + assertThat(httpUrl).isEqualTo(parse("http://foo:pass1%40bar%3Apass2@baz/path")); } @Test public void usernameAndPassword() throws Exception { - assertEquals(parse("http://username:password@host/path"), + assertThat(parse("http://username:password@host/path")).isEqualTo( parse("http://username:password@host/path")); - assertEquals(parse("http://username@host/path"), - parse("http://username:@host/path")); + assertThat(parse("http://username:@host/path")).isEqualTo( + parse("http://username@host/path")); } @Test public void passwordWithEmptyUsername() throws Exception { // Chrome doesn't mind, but Firefox rejects URLs with empty usernames and non-empty passwords. - assertEquals(parse("http://host/path"), parse("http://:@host/path")); - assertEquals("password%40", parse("http://:password@@host/path").encodedPassword()); + assertThat(parse("http://:@host/path")).isEqualTo(parse("http://host/path")); + assertThat(parse("http://:password@@host/path").encodedPassword()).isEqualTo( + "password%40"); } @Test public void unprintableCharactersArePercentEncoded() throws Exception { - assertEquals("/%00", parse("http://host/\u0000").encodedPath()); - assertEquals("/%08", parse("http://host/\u0008").encodedPath()); - assertEquals("/%EF%BF%BD", parse("http://host/\ufffd").encodedPath()); + assertThat(parse("http://host/\u0000").encodedPath()).isEqualTo("/%00"); + assertThat(parse("http://host/\u0008").encodedPath()).isEqualTo("/%08"); + assertThat(parse("http://host/\ufffd").encodedPath()).isEqualTo("/%EF%BF%BD"); } @Test public void usernameCharacters() throws Exception { @@ -351,32 +388,32 @@ public final class HttpUrlTest { } @Test public void hostnameLowercaseCharactersMappedDirectly() throws Exception { - assertEquals("abcd", parse("http://abcd").host()); - assertEquals("xn--4xa", parse("http://σ").host()); + assertThat(parse("http://abcd").host()).isEqualTo("abcd"); + assertThat(parse("http://σ").host()).isEqualTo("xn--4xa"); } @Test public void hostnameUppercaseCharactersConvertedToLowercase() throws Exception { - assertEquals("abcd", parse("http://ABCD").host()); - assertEquals("xn--4xa", parse("http://Σ").host()); + assertThat(parse("http://ABCD").host()).isEqualTo("abcd"); + assertThat(parse("http://Σ").host()).isEqualTo("xn--4xa"); } @Test public void hostnameIgnoredCharacters() throws Exception { // The soft hyphen (­) should be ignored. - assertEquals("abcd", parse("http://AB\u00adCD").host()); + assertThat(parse("http://AB\u00adCD").host()).isEqualTo("abcd"); } @Test public void hostnameMultipleCharacterMapping() throws Exception { // Map the single character telephone symbol (℡) to the string "tel". - assertEquals("tel", parse("http://\u2121").host()); + assertThat(parse("http://\u2121").host()).isEqualTo("tel"); } @Test public void hostnameMappingLastMappedCodePoint() throws Exception { - assertEquals("xn--pu5l", parse("http://\uD87E\uDE1D").host()); + assertThat(parse("http://\uD87E\uDE1D").host()).isEqualTo("xn--pu5l"); } @Ignore("The java.net.IDN implementation doesn't ignore characters that it should.") @Test public void hostnameMappingLastIgnoredCodePoint() throws Exception { - assertEquals("abcd", parse("http://ab\uDB40\uDDEFcd").host()); + assertThat(parse("http://ab\uDB40\uDDEFcd").host()).isEqualTo("abcd"); } @Test public void hostnameMappingLastDisallowedCodePoint() throws Exception { @@ -385,48 +422,50 @@ public final class HttpUrlTest { @Test public void hostIpv6() throws Exception { // Square braces are absent from host()... - assertEquals("::1", parse("http://[::1]/").host()); + assertThat(parse("http://[::1]/").host()).isEqualTo("::1"); // ... but they're included in toString(). - assertEquals("http://[::1]/", parse("http://[::1]/").toString()); + assertThat(parse("http://[::1]/").toString()).isEqualTo("http://[::1]/"); // IPv6 colons don't interfere with port numbers or passwords. - assertEquals(8080, parse("http://[::1]:8080/").port()); - assertEquals("password", parse("http://user:password@[::1]/").password()); - assertEquals("::1", parse("http://user:password@[::1]:8080/").host()); + assertThat(parse("http://[::1]:8080/").port()).isEqualTo(8080); + assertThat(parse("http://user:password@[::1]/").password()).isEqualTo("password"); + assertThat(parse("http://user:password@[::1]:8080/").host()).isEqualTo("::1"); // Permit the contents of IPv6 addresses to be percent-encoded... - assertEquals("::1", parse("http://[%3A%3A%31]/").host()); + assertThat(parse("http://[%3A%3A%31]/").host()).isEqualTo("::1"); // Including the Square braces themselves! (This is what Chrome does.) - assertEquals("::1", parse("http://%5B%3A%3A1%5D/").host()); + assertThat(parse("http://%5B%3A%3A1%5D/").host()).isEqualTo("::1"); } @Test public void hostIpv6AddressDifferentFormats() throws Exception { // Multiple representations of the same address; see http://tools.ietf.org/html/rfc5952. String a3 = "2001:db8::1:0:0:1"; - assertEquals(a3, parse("http://[2001:db8:0:0:1:0:0:1]").host()); - assertEquals(a3, parse("http://[2001:0db8:0:0:1:0:0:1]").host()); - assertEquals(a3, parse("http://[2001:db8::1:0:0:1]").host()); - assertEquals(a3, parse("http://[2001:db8::0:1:0:0:1]").host()); - assertEquals(a3, parse("http://[2001:0db8::1:0:0:1]").host()); - assertEquals(a3, parse("http://[2001:db8:0:0:1::1]").host()); - assertEquals(a3, parse("http://[2001:db8:0000:0:1::1]").host()); - assertEquals(a3, parse("http://[2001:DB8:0:0:1::1]").host()); + assertThat(parse("http://[2001:db8:0:0:1:0:0:1]").host()).isEqualTo(a3); + assertThat(parse("http://[2001:0db8:0:0:1:0:0:1]").host()).isEqualTo(a3); + assertThat(parse("http://[2001:db8::1:0:0:1]").host()).isEqualTo(a3); + assertThat(parse("http://[2001:db8::0:1:0:0:1]").host()).isEqualTo(a3); + assertThat(parse("http://[2001:0db8::1:0:0:1]").host()).isEqualTo(a3); + assertThat(parse("http://[2001:db8:0:0:1::1]").host()).isEqualTo(a3); + assertThat(parse("http://[2001:db8:0000:0:1::1]").host()).isEqualTo(a3); + assertThat(parse("http://[2001:DB8:0:0:1::1]").host()).isEqualTo(a3); } @Test public void hostIpv6AddressLeadingCompression() throws Exception { - assertEquals("::1", parse("http://[::0001]").host()); - assertEquals("::1", parse("http://[0000::0001]").host()); - assertEquals("::1", parse("http://[0000:0000:0000:0000:0000:0000:0000:0001]").host()); - assertEquals("::1", parse("http://[0000:0000:0000:0000:0000:0000::0001]").host()); + assertThat(parse("http://[::0001]").host()).isEqualTo("::1"); + assertThat(parse("http://[0000::0001]").host()).isEqualTo("::1"); + assertThat(parse("http://[0000:0000:0000:0000:0000:0000:0000:0001]").host()).isEqualTo( + "::1"); + assertThat(parse("http://[0000:0000:0000:0000:0000:0000::0001]").host()).isEqualTo( + "::1"); } @Test public void hostIpv6AddressTrailingCompression() throws Exception { - assertEquals("1::", parse("http://[0001:0000::]").host()); - assertEquals("1::", parse("http://[0001::0000]").host()); - assertEquals("1::", parse("http://[0001::]").host()); - assertEquals("1::", parse("http://[1::]").host()); + assertThat(parse("http://[0001:0000::]").host()).isEqualTo("1::"); + assertThat(parse("http://[0001::0000]").host()).isEqualTo("1::"); + assertThat(parse("http://[0001::]").host()).isEqualTo("1::"); + assertThat(parse("http://[1::]").host()).isEqualTo("1::"); } @Test public void hostIpv6AddressTooManyDigitsInGroup() throws Exception { @@ -481,8 +520,8 @@ public final class HttpUrlTest { } @Test public void hostIpv6WithIpv4Suffix() throws Exception { - assertEquals("::1:ffff:ffff", parse("http://[::1:255.255.255.255]/").host()); - assertEquals("::1:0:0", parse("http://[0:0:0:0:0:1:0.0.0.0]/").host()); + assertThat(parse("http://[::1:255.255.255.255]/").host()).isEqualTo("::1:ffff:ffff"); + assertThat(parse("http://[0:0:0:0:0:1:0.0.0.0]/").host()).isEqualTo("::1:0:0"); } @Test public void hostIpv6WithIpv4SuffixWithOctalPrefix() throws Exception { @@ -539,52 +578,57 @@ public final class HttpUrlTest { } @Test public void hostIpv6CanonicalForm() throws Exception { - assertEquals("abcd:ef01:2345:6789:abcd:ef01:2345:6789", - parse("http://[abcd:ef01:2345:6789:abcd:ef01:2345:6789]/").host()); - assertEquals("a::b:0:0:0", parse("http://[a:0:0:0:b:0:0:0]/").host()); - assertEquals("a:b:0:0:c::", parse("http://[a:b:0:0:c:0:0:0]/").host()); - assertEquals("a:b::c:0:0", parse("http://[a:b:0:0:0:c:0:0]/").host()); - assertEquals("a::b:0:0:0", parse("http://[a:0:0:0:b:0:0:0]/").host()); - assertEquals("::a:b:0:0:0", parse("http://[0:0:0:a:b:0:0:0]/").host()); - assertEquals("::a:0:0:0:b", parse("http://[0:0:0:a:0:0:0:b]/").host()); - assertEquals("0:a:b:c:d:e:f:1", parse("http://[0:a:b:c:d:e:f:1]/").host()); - assertEquals("a:b:c:d:e:f:1:0", parse("http://[a:b:c:d:e:f:1:0]/").host()); - assertEquals("ff01::101", parse("http://[FF01:0:0:0:0:0:0:101]/").host()); - assertEquals("2001:db8::1", parse("http://[2001:db8::1]/").host()); - assertEquals("2001:db8::2:1", parse("http://[2001:db8:0:0:0:0:2:1]/").host()); - assertEquals("2001:db8:0:1:1:1:1:1", parse("http://[2001:db8:0:1:1:1:1:1]/").host()); - assertEquals("2001:db8::1:0:0:1", parse("http://[2001:db8:0:0:1:0:0:1]/").host()); - assertEquals("2001:0:0:1::1", parse("http://[2001:0:0:1:0:0:0:1]/").host()); - assertEquals("1::", parse("http://[1:0:0:0:0:0:0:0]/").host()); - assertEquals("::1", parse("http://[0:0:0:0:0:0:0:1]/").host()); - assertEquals("::", parse("http://[0:0:0:0:0:0:0:0]/").host()); - assertEquals("192.168.1.254", parse("http://[::ffff:c0a8:1fe]/").host()); + assertThat(parse("http://[abcd:ef01:2345:6789:abcd:ef01:2345:6789]/").host()).isEqualTo( + "abcd:ef01:2345:6789:abcd:ef01:2345:6789"); + assertThat(parse("http://[a:0:0:0:b:0:0:0]/").host()).isEqualTo("a::b:0:0:0"); + assertThat(parse("http://[a:b:0:0:c:0:0:0]/").host()).isEqualTo("a:b:0:0:c::"); + assertThat(parse("http://[a:b:0:0:0:c:0:0]/").host()).isEqualTo("a:b::c:0:0"); + assertThat(parse("http://[a:0:0:0:b:0:0:0]/").host()).isEqualTo("a::b:0:0:0"); + assertThat(parse("http://[0:0:0:a:b:0:0:0]/").host()).isEqualTo("::a:b:0:0:0"); + assertThat(parse("http://[0:0:0:a:0:0:0:b]/").host()).isEqualTo("::a:0:0:0:b"); + assertThat(parse("http://[0:a:b:c:d:e:f:1]/").host()).isEqualTo("0:a:b:c:d:e:f:1"); + assertThat(parse("http://[a:b:c:d:e:f:1:0]/").host()).isEqualTo("a:b:c:d:e:f:1:0"); + assertThat(parse("http://[FF01:0:0:0:0:0:0:101]/").host()).isEqualTo("ff01::101"); + assertThat(parse("http://[2001:db8::1]/").host()).isEqualTo("2001:db8::1"); + assertThat(parse("http://[2001:db8:0:0:0:0:2:1]/").host()).isEqualTo("2001:db8::2:1"); + assertThat(parse("http://[2001:db8:0:1:1:1:1:1]/").host()).isEqualTo( + "2001:db8:0:1:1:1:1:1"); + assertThat(parse("http://[2001:db8:0:0:1:0:0:1]/").host()).isEqualTo( + "2001:db8::1:0:0:1"); + assertThat(parse("http://[2001:0:0:1:0:0:0:1]/").host()).isEqualTo("2001:0:0:1::1"); + assertThat(parse("http://[1:0:0:0:0:0:0:0]/").host()).isEqualTo("1::"); + assertThat(parse("http://[0:0:0:0:0:0:0:1]/").host()).isEqualTo("::1"); + assertThat(parse("http://[0:0:0:0:0:0:0:0]/").host()).isEqualTo("::"); + assertThat(parse("http://[::ffff:c0a8:1fe]/").host()).isEqualTo("192.168.1.254"); } /** The builder permits square braces but does not require them. */ @Test public void hostIpv6Builder() throws Exception { HttpUrl base = parse("http://example.com/"); - assertEquals("http://[::1]/", base.newBuilder().host("[::1]").build().toString()); - assertEquals("http://[::1]/", base.newBuilder().host("[::0001]").build().toString()); - assertEquals("http://[::1]/", base.newBuilder().host("::1").build().toString()); - assertEquals("http://[::1]/", base.newBuilder().host("::0001").build().toString()); + assertThat(base.newBuilder().host("[::1]").build().toString()).isEqualTo( + "http://[::1]/"); + assertThat(base.newBuilder().host("[::0001]").build().toString()).isEqualTo( + "http://[::1]/"); + assertThat(base.newBuilder().host("::1").build().toString()).isEqualTo("http://[::1]/"); + assertThat(base.newBuilder().host("::0001").build().toString()).isEqualTo( + "http://[::1]/"); } @Test public void hostIpv4CanonicalForm() throws Exception { - assertEquals("255.255.255.255", parse("http://255.255.255.255/").host()); - assertEquals("1.2.3.4", parse("http://1.2.3.4/").host()); - assertEquals("0.0.0.0", parse("http://0.0.0.0/").host()); + assertThat(parse("http://255.255.255.255/").host()).isEqualTo("255.255.255.255"); + assertThat(parse("http://1.2.3.4/").host()).isEqualTo("1.2.3.4"); + assertThat(parse("http://0.0.0.0/").host()).isEqualTo("0.0.0.0"); } @Test public void hostWithTrailingDot() throws Exception { - assertEquals("host.", parse("http://host./").host()); + assertThat(parse("http://host./").host()).isEqualTo("host."); } @Test public void port() throws Exception { - assertEquals(parse("http://host/"), parse("http://host:80/")); - assertEquals(parse("http://host:99/"), parse("http://host:99/")); - assertEquals(parse("http://host/"), parse("http://host:/")); - assertEquals(65535, parse("http://host:65535/").port()); + assertThat(parse("http://host:80/")).isEqualTo(parse("http://host/")); + assertThat(parse("http://host:99/")).isEqualTo(parse("http://host:99/")); + assertThat(parse("http://host:/")).isEqualTo(parse("http://host/")); + assertThat(parse("http://host:65535/").port()).isEqualTo(65535); assertInvalid("http://host:0/", "Invalid URL port: \"0\""); assertInvalid("http://host:65536/", "Invalid URL port: \"65536\""); assertInvalid("http://host:-1/", "Invalid URL port: \"-1\""); @@ -628,137 +672,136 @@ public final class HttpUrlTest { @Test public void fragmentNonAscii() throws Exception { HttpUrl url = parse("http://host/#Σ"); - assertEquals("http://host/#Σ", url.toString()); - assertEquals("Σ", url.fragment()); - assertEquals("Σ", url.encodedFragment()); - assertEquals("http://host/#Σ", url.uri().toString()); + assertThat(url.toString()).isEqualTo("http://host/#Σ"); + assertThat(url.fragment()).isEqualTo("Σ"); + assertThat(url.encodedFragment()).isEqualTo("Σ"); + assertThat(url.uri().toString()).isEqualTo("http://host/#Σ"); } @Test public void fragmentNonAsciiThatOffendsJavaNetUri() throws Exception { HttpUrl url = parse("http://host/#\u0080"); - assertEquals("http://host/#\u0080", url.toString()); - assertEquals("\u0080", url.fragment()); - assertEquals("\u0080", url.encodedFragment()); - assertEquals(new URI("http://host/#"), url.uri()); // Control characters may be stripped! + assertThat(url.toString()).isEqualTo("http://host/#\u0080"); + assertThat(url.fragment()).isEqualTo("\u0080"); + assertThat(url.encodedFragment()).isEqualTo("\u0080"); + // Control characters may be stripped! + assertThat(url.uri()).isEqualTo(new URI("http://host/#")); } @Test public void fragmentPercentEncodedNonAscii() throws Exception { HttpUrl url = parse("http://host/#%C2%80"); - assertEquals("http://host/#%C2%80", url.toString()); - assertEquals("\u0080", url.fragment()); - assertEquals("%C2%80", url.encodedFragment()); - assertEquals("http://host/#%C2%80", url.uri().toString()); + assertThat(url.toString()).isEqualTo("http://host/#%C2%80"); + assertThat(url.fragment()).isEqualTo("\u0080"); + assertThat(url.encodedFragment()).isEqualTo("%C2%80"); + assertThat(url.uri().toString()).isEqualTo("http://host/#%C2%80"); } @Test public void fragmentPercentEncodedPartialCodePoint() throws Exception { HttpUrl url = parse("http://host/#%80"); - assertEquals("http://host/#%80", url.toString()); - assertEquals("\ufffd", url.fragment()); // Unicode replacement character. - assertEquals("%80", url.encodedFragment()); - assertEquals("http://host/#%80", url.uri().toString()); + assertThat(url.toString()).isEqualTo("http://host/#%80"); + // Unicode replacement character. + assertThat(url.fragment()).isEqualTo("\ufffd"); + assertThat(url.encodedFragment()).isEqualTo("%80"); + assertThat(url.uri().toString()).isEqualTo("http://host/#%80"); } @Test public void relativePath() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals(parse("http://host/a/b/d/e/f"), base.resolve("d/e/f")); - assertEquals(parse("http://host/d/e/f"), base.resolve("../../d/e/f")); - assertEquals(parse("http://host/a/"), base.resolve("..")); - assertEquals(parse("http://host/"), base.resolve("../..")); - assertEquals(parse("http://host/"), base.resolve("../../..")); - assertEquals(parse("http://host/a/b/"), base.resolve(".")); - assertEquals(parse("http://host/a/"), base.resolve("././..")); - assertEquals(parse("http://host/a/b/c/"), base.resolve("c/d/../e/../")); - assertEquals(parse("http://host/a/b/..e/"), base.resolve("..e/")); - assertEquals(parse("http://host/a/b/e/f../"), base.resolve("e/f../")); - assertEquals(parse("http://host/a/"), base.resolve("%2E.")); - assertEquals(parse("http://host/a/"), base.resolve(".%2E")); - assertEquals(parse("http://host/a/"), base.resolve("%2E%2E")); - assertEquals(parse("http://host/a/"), base.resolve("%2e.")); - assertEquals(parse("http://host/a/"), base.resolve(".%2e")); - assertEquals(parse("http://host/a/"), base.resolve("%2e%2e")); - assertEquals(parse("http://host/a/b/"), base.resolve("%2E")); - assertEquals(parse("http://host/a/b/"), base.resolve("%2e")); + assertThat(base.resolve("d/e/f")).isEqualTo(parse("http://host/a/b/d/e/f")); + assertThat(base.resolve("../../d/e/f")).isEqualTo(parse("http://host/d/e/f")); + assertThat(base.resolve("..")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve("../..")).isEqualTo(parse("http://host/")); + assertThat(base.resolve("../../..")).isEqualTo(parse("http://host/")); + assertThat(base.resolve(".")).isEqualTo(parse("http://host/a/b/")); + assertThat(base.resolve("././..")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve("c/d/../e/../")).isEqualTo(parse("http://host/a/b/c/")); + assertThat(base.resolve("..e/")).isEqualTo(parse("http://host/a/b/..e/")); + assertThat(base.resolve("e/f../")).isEqualTo(parse("http://host/a/b/e/f../")); + assertThat(base.resolve("%2E.")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve(".%2E")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve("%2E%2E")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve("%2e.")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve(".%2e")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve("%2e%2e")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve("%2E")).isEqualTo(parse("http://host/a/b/")); + assertThat(base.resolve("%2e")).isEqualTo(parse("http://host/a/b/")); } @Test public void relativePathWithTrailingSlash() throws Exception { HttpUrl base = parse("http://host/a/b/c/"); - assertEquals(parse("http://host/a/b/"), base.resolve("..")); - assertEquals(parse("http://host/a/b/"), base.resolve("../")); - assertEquals(parse("http://host/a/"), base.resolve("../..")); - assertEquals(parse("http://host/a/"), base.resolve("../../")); - assertEquals(parse("http://host/"), base.resolve("../../..")); - assertEquals(parse("http://host/"), base.resolve("../../../")); - assertEquals(parse("http://host/"), base.resolve("../../../..")); - assertEquals(parse("http://host/"), base.resolve("../../../../")); - assertEquals(parse("http://host/a"), base.resolve("../../../../a")); - assertEquals(parse("http://host/"), base.resolve("../../../../a/..")); - assertEquals(parse("http://host/a/"), base.resolve("../../../../a/b/..")); + assertThat(base.resolve("..")).isEqualTo(parse("http://host/a/b/")); + assertThat(base.resolve("../")).isEqualTo(parse("http://host/a/b/")); + assertThat(base.resolve("../..")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve("../../")).isEqualTo(parse("http://host/a/")); + assertThat(base.resolve("../../..")).isEqualTo(parse("http://host/")); + assertThat(base.resolve("../../../")).isEqualTo(parse("http://host/")); + assertThat(base.resolve("../../../..")).isEqualTo(parse("http://host/")); + assertThat(base.resolve("../../../../")).isEqualTo(parse("http://host/")); + assertThat(base.resolve("../../../../a")).isEqualTo(parse("http://host/a")); + assertThat(base.resolve("../../../../a/..")).isEqualTo(parse("http://host/")); + assertThat(base.resolve("../../../../a/b/..")).isEqualTo(parse("http://host/a/")); } @Test public void pathWithBackslash() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals(parse("http://host/a/b/d/e/f"), base.resolve("d\\e\\f")); - assertEquals(parse("http://host/d/e/f"), base.resolve("../..\\d\\e\\f")); - assertEquals(parse("http://host/"), base.resolve("..\\..")); + assertThat(base.resolve("d\\e\\f")).isEqualTo(parse("http://host/a/b/d/e/f")); + assertThat(base.resolve("../..\\d\\e\\f")).isEqualTo(parse("http://host/d/e/f")); + assertThat(base.resolve("..\\..")).isEqualTo(parse("http://host/")); } @Test public void relativePathWithSameScheme() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals(parse("http://host/a/b/d/e/f"), base.resolve("http:d/e/f")); - assertEquals(parse("http://host/d/e/f"), base.resolve("http:../../d/e/f")); + assertThat(base.resolve("http:d/e/f")).isEqualTo(parse("http://host/a/b/d/e/f")); + assertThat(base.resolve("http:../../d/e/f")).isEqualTo(parse("http://host/d/e/f")); } @Test public void decodeUsername() { - assertEquals("user", parse("http://user@host/").username()); - assertEquals("\uD83C\uDF69", parse("http://%F0%9F%8D%A9@host/").username()); + assertThat(parse("http://user@host/").username()).isEqualTo("user"); + assertThat(parse("http://%F0%9F%8D%A9@host/").username()).isEqualTo("\uD83C\uDF69"); } @Test public void decodePassword() { - assertEquals("password", parse("http://user:password@host/").password()); - assertEquals("", parse("http://user:@host/").password()); - assertEquals("\uD83C\uDF69", parse("http://user:%F0%9F%8D%A9@host/").password()); + assertThat(parse("http://user:password@host/").password()).isEqualTo("password"); + assertThat(parse("http://user:@host/").password()).isEqualTo(""); + assertThat(parse("http://user:%F0%9F%8D%A9@host/").password()).isEqualTo( + "\uD83C\uDF69"); } @Test public void decodeSlashCharacterInDecodedPathSegment() { - assertEquals(Arrays.asList("a/b/c"), - parse("http://host/a%2Fb%2Fc").pathSegments()); + assertThat(parse("http://host/a%2Fb%2Fc").pathSegments()).isEqualTo( + Arrays.asList("a/b/c")); } @Test public void decodeEmptyPathSegments() { - assertEquals(Arrays.asList(""), - parse("http://host/").pathSegments()); + assertThat(parse("http://host/").pathSegments()).isEqualTo(Arrays.asList("")); } @Test public void percentDecode() throws Exception { - assertEquals(Arrays.asList("\u0000"), - parse("http://host/%00").pathSegments()); - assertEquals(Arrays.asList("a", "\u2603", "c"), - parse("http://host/a/%E2%98%83/c").pathSegments()); - assertEquals(Arrays.asList("a", "\uD83C\uDF69", "c"), - parse("http://host/a/%F0%9F%8D%A9/c").pathSegments()); - assertEquals(Arrays.asList("a", "b", "c"), - parse("http://host/a/%62/c").pathSegments()); - assertEquals(Arrays.asList("a", "z", "c"), - parse("http://host/a/%7A/c").pathSegments()); - assertEquals(Arrays.asList("a", "z", "c"), - parse("http://host/a/%7a/c").pathSegments()); + assertThat(parse("http://host/%00").pathSegments()).isEqualTo(Arrays.asList("\u0000")); + assertThat(parse("http://host/a/%E2%98%83/c").pathSegments()).isEqualTo( + Arrays.asList("a", "\u2603", "c")); + assertThat(parse("http://host/a/%F0%9F%8D%A9/c").pathSegments()).isEqualTo( + Arrays.asList("a", "\uD83C\uDF69", "c")); + assertThat(parse("http://host/a/%62/c").pathSegments()).isEqualTo( + Arrays.asList("a", "b", "c")); + assertThat(parse("http://host/a/%7A/c").pathSegments()).isEqualTo( + Arrays.asList("a", "z", "c")); + assertThat(parse("http://host/a/%7a/c").pathSegments()).isEqualTo( + Arrays.asList("a", "z", "c")); } @Test public void malformedPercentEncoding() { - assertEquals(Arrays.asList("a%f", "b"), - parse("http://host/a%f/b").pathSegments()); - assertEquals(Arrays.asList("%", "b"), - parse("http://host/%/b").pathSegments()); - assertEquals(Arrays.asList("%"), - parse("http://host/%").pathSegments()); - assertEquals(Arrays.asList("%00"), - parse("http://github.com/%%30%30").pathSegments()); + assertThat(parse("http://host/a%f/b").pathSegments()).isEqualTo( + Arrays.asList("a%f", "b")); + assertThat(parse("http://host/%/b").pathSegments()).isEqualTo(Arrays.asList("%", "b")); + assertThat(parse("http://host/%").pathSegments()).isEqualTo(Arrays.asList("%")); + assertThat(parse("http://github.com/%%30%30").pathSegments()).isEqualTo( + Arrays.asList("%00")); } @Test public void malformedUtf8Encoding() { // Replace a partial UTF-8 sequence with the Unicode replacement character. - assertEquals(Arrays.asList("a", "\ufffdx", "c"), - parse("http://host/a/%E2%98x/c").pathSegments()); + assertThat(parse("http://host/a/%E2%98x/c").pathSegments()).isEqualTo( + Arrays.asList("a", "\ufffdx", "c")); } @Test public void incompleteUrlComposition() throws Exception { @@ -766,40 +809,42 @@ public final class HttpUrlTest { new HttpUrl.Builder().scheme("http").build(); fail(); } catch (IllegalStateException expected) { - assertEquals("host == null", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("host == null"); } try { new HttpUrl.Builder().host("host").build(); fail(); } catch (IllegalStateException expected) { - assertEquals("scheme == null", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("scheme == null"); } } @Test public void builderToString() { - assertEquals("https://host.com/path", parse("https://host.com/path").newBuilder().toString()); + assertThat(parse("https://host.com/path").newBuilder().toString()).isEqualTo( + "https://host.com/path"); } @Test public void incompleteBuilderToString() { - assertEquals("https:///path", - new HttpUrl.Builder().scheme("https").encodedPath("/path").toString()); - assertEquals("//host.com/path", - new HttpUrl.Builder().host("host.com").encodedPath("/path").toString()); - assertEquals("//host.com:8080/path", - new HttpUrl.Builder().host("host.com").encodedPath("/path").port(8080).toString()); + assertThat(new HttpUrl.Builder().scheme("https").encodedPath("/path").toString()).isEqualTo( + "https:///path"); + assertThat(new HttpUrl.Builder().host("host.com").encodedPath("/path").toString()).isEqualTo( + "//host.com/path"); + assertThat( + (Object) new HttpUrl.Builder().host("host.com").encodedPath("/path").port(8080).toString()).isEqualTo( + "//host.com:8080/path"); } @Test public void minimalUrlComposition() throws Exception { HttpUrl url = new HttpUrl.Builder().scheme("http").host("host").build(); - assertEquals("http://host/", url.toString()); - assertEquals("http", url.scheme()); - assertEquals("", url.username()); - assertEquals("", url.password()); - assertEquals("host", url.host()); - assertEquals(80, url.port()); - assertEquals("/", url.encodedPath()); - assertNull(url.query()); - assertNull(url.fragment()); + assertThat(url.toString()).isEqualTo("http://host/"); + assertThat(url.scheme()).isEqualTo("http"); + assertThat(url.username()).isEqualTo(""); + assertThat(url.password()).isEqualTo(""); + assertThat(url.host()).isEqualTo("host"); + assertThat(url.port()).isEqualTo(80); + assertThat(url.encodedPath()).isEqualTo("/"); + assertThat(url.query()).isNull(); + assertThat(url.fragment()).isNull(); } @Test public void fullUrlComposition() throws Exception { @@ -813,32 +858,33 @@ public final class HttpUrlTest { .query("query") .fragment("fragment") .build(); - assertEquals("http://username:password@host:8080/path?query#fragment", url.toString()); - assertEquals("http", url.scheme()); - assertEquals("username", url.username()); - assertEquals("password", url.password()); - assertEquals("host", url.host()); - assertEquals(8080, url.port()); - assertEquals("/path", url.encodedPath()); - assertEquals("query", url.query()); - assertEquals("fragment", url.fragment()); + assertThat(url.toString()).isEqualTo( + "http://username:password@host:8080/path?query#fragment"); + assertThat(url.scheme()).isEqualTo("http"); + assertThat(url.username()).isEqualTo("username"); + assertThat(url.password()).isEqualTo("password"); + assertThat(url.host()).isEqualTo("host"); + assertThat(url.port()).isEqualTo(8080); + assertThat(url.encodedPath()).isEqualTo("/path"); + assertThat(url.query()).isEqualTo("query"); + assertThat(url.fragment()).isEqualTo("fragment"); } @Test public void changingSchemeChangesDefaultPort() throws Exception { - assertEquals(443, parse("http://example.com") + assertThat(parse("http://example.com") .newBuilder() .scheme("https") - .build().port()); + .build().port()).isEqualTo(443); - assertEquals(80, parse("https://example.com") + assertThat(parse("https://example.com") .newBuilder() .scheme("http") - .build().port()); + .build().port()).isEqualTo(80); - assertEquals(1234, parse("https://example.com:1234") + assertThat(parse("https://example.com:1234") .newBuilder() .scheme("http") - .build().port()); + .build().port()).isEqualTo(1234); } @Test public void composeEncodesWhitespace() throws Exception { @@ -851,13 +897,13 @@ public final class HttpUrlTest { .query("g\r\n\f\t h") .fragment("i\r\n\f\t j") .build(); - assertEquals("http://a%0D%0A%0C%09%20b:c%0D%0A%0C%09%20d@host" - + "/e%0D%0A%0C%09%20f?g%0D%0A%0C%09%20h#i%0D%0A%0C%09 j", url.toString()); - assertEquals("a\r\n\f\t b", url.username()); - assertEquals("c\r\n\f\t d", url.password()); - assertEquals("e\r\n\f\t f", url.pathSegments().get(0)); - assertEquals("g\r\n\f\t h", url.query()); - assertEquals("i\r\n\f\t j", url.fragment()); + assertThat(url.toString()).isEqualTo(("http://a%0D%0A%0C%09%20b:c%0D%0A%0C%09%20d@host" + + "/e%0D%0A%0C%09%20f?g%0D%0A%0C%09%20h#i%0D%0A%0C%09 j")); + assertThat(url.username()).isEqualTo("a\r\n\f\t b"); + assertThat(url.password()).isEqualTo("c\r\n\f\t d"); + assertThat(url.pathSegments().get(0)).isEqualTo("e\r\n\f\t f"); + assertThat(url.query()).isEqualTo("g\r\n\f\t h"); + assertThat(url.fragment()).isEqualTo("i\r\n\f\t j"); } @Test public void composeFromUnencodedComponents() throws Exception { @@ -871,19 +917,20 @@ public final class HttpUrlTest { .query("i:\u0001@/\\?#%j") .fragment("k:\u0001@/\\?#%l") .build(); - assertEquals("http://a%3A%01%40%2F%5C%3F%23%25b:c%3A%01%40%2F%5C%3F%23%25d@ef:8080/" - + "g:%01@%2F%5C%3F%23%25h?i:%01@/\\?%23%25j#k:%01@/\\?#%25l", url.toString()); - assertEquals("http", url.scheme()); - assertEquals("a:\u0001@/\\?#%b", url.username()); - assertEquals("c:\u0001@/\\?#%d", url.password()); - assertEquals(Arrays.asList("g:\u0001@/\\?#%h"), url.pathSegments()); - assertEquals("i:\u0001@/\\?#%j", url.query()); - assertEquals("k:\u0001@/\\?#%l", url.fragment()); - assertEquals("a%3A%01%40%2F%5C%3F%23%25b", url.encodedUsername()); - assertEquals("c%3A%01%40%2F%5C%3F%23%25d", url.encodedPassword()); - assertEquals("/g:%01@%2F%5C%3F%23%25h", url.encodedPath()); - assertEquals("i:%01@/\\?%23%25j", url.encodedQuery()); - assertEquals("k:%01@/\\?#%25l", url.encodedFragment()); + assertThat(url.toString()).isEqualTo( + ("http://a%3A%01%40%2F%5C%3F%23%25b:c%3A%01%40%2F%5C%3F%23%25d@ef:8080/" + + "g:%01@%2F%5C%3F%23%25h?i:%01@/\\?%23%25j#k:%01@/\\?#%25l")); + assertThat(url.scheme()).isEqualTo("http"); + assertThat(url.username()).isEqualTo("a:\u0001@/\\?#%b"); + assertThat(url.password()).isEqualTo("c:\u0001@/\\?#%d"); + assertThat(url.pathSegments()).isEqualTo(Arrays.asList("g:\u0001@/\\?#%h")); + assertThat(url.query()).isEqualTo("i:\u0001@/\\?#%j"); + assertThat(url.fragment()).isEqualTo("k:\u0001@/\\?#%l"); + assertThat(url.encodedUsername()).isEqualTo("a%3A%01%40%2F%5C%3F%23%25b"); + assertThat(url.encodedPassword()).isEqualTo("c%3A%01%40%2F%5C%3F%23%25d"); + assertThat(url.encodedPath()).isEqualTo("/g:%01@%2F%5C%3F%23%25h"); + assertThat(url.encodedQuery()).isEqualTo("i:%01@/\\?%23%25j"); + assertThat(url.encodedFragment()).isEqualTo("k:%01@/\\?#%25l"); } @Test public void composeFromEncodedComponents() throws Exception { @@ -897,19 +944,20 @@ public final class HttpUrlTest { .encodedQuery("i:\u0001@/\\?#%25j") .encodedFragment("k:\u0001@/\\?#%25l") .build(); - assertEquals("http://a%3A%01%40%2F%5C%3F%23%25b:c%3A%01%40%2F%5C%3F%23%25d@ef:8080/" - + "g:%01@%2F%5C%3F%23%25h?i:%01@/\\?%23%25j#k:%01@/\\?#%25l", url.toString()); - assertEquals("http", url.scheme()); - assertEquals("a:\u0001@/\\?#%b", url.username()); - assertEquals("c:\u0001@/\\?#%d", url.password()); - assertEquals(Arrays.asList("g:\u0001@/\\?#%h"), url.pathSegments()); - assertEquals("i:\u0001@/\\?#%j", url.query()); - assertEquals("k:\u0001@/\\?#%l", url.fragment()); - assertEquals("a%3A%01%40%2F%5C%3F%23%25b", url.encodedUsername()); - assertEquals("c%3A%01%40%2F%5C%3F%23%25d", url.encodedPassword()); - assertEquals("/g:%01@%2F%5C%3F%23%25h", url.encodedPath()); - assertEquals("i:%01@/\\?%23%25j", url.encodedQuery()); - assertEquals("k:%01@/\\?#%25l", url.encodedFragment()); + assertThat(url.toString()).isEqualTo( + ("http://a%3A%01%40%2F%5C%3F%23%25b:c%3A%01%40%2F%5C%3F%23%25d@ef:8080/" + + "g:%01@%2F%5C%3F%23%25h?i:%01@/\\?%23%25j#k:%01@/\\?#%25l")); + assertThat(url.scheme()).isEqualTo("http"); + assertThat(url.username()).isEqualTo("a:\u0001@/\\?#%b"); + assertThat(url.password()).isEqualTo("c:\u0001@/\\?#%d"); + assertThat(url.pathSegments()).isEqualTo(Arrays.asList("g:\u0001@/\\?#%h")); + assertThat(url.query()).isEqualTo("i:\u0001@/\\?#%j"); + assertThat(url.fragment()).isEqualTo("k:\u0001@/\\?#%l"); + assertThat(url.encodedUsername()).isEqualTo("a%3A%01%40%2F%5C%3F%23%25b"); + assertThat(url.encodedPassword()).isEqualTo("c%3A%01%40%2F%5C%3F%23%25d"); + assertThat(url.encodedPath()).isEqualTo("/g:%01@%2F%5C%3F%23%25h"); + assertThat(url.encodedQuery()).isEqualTo("i:%01@/\\?%23%25j"); + assertThat(url.encodedFragment()).isEqualTo("k:%01@/\\?#%25l"); } @Test public void composeWithEncodedPath() throws Exception { @@ -918,9 +966,9 @@ public final class HttpUrlTest { .host("host") .encodedPath("/a%2Fb/c") .build(); - assertEquals("http://host/a%2Fb/c", url.toString()); - assertEquals("/a%2Fb/c", url.encodedPath()); - assertEquals(Arrays.asList("a/b", "c"), url.pathSegments()); + assertThat(url.toString()).isEqualTo("http://host/a%2Fb/c"); + assertThat(url.encodedPath()).isEqualTo("/a%2Fb/c"); + assertThat(url.pathSegments()).isEqualTo(Arrays.asList("a/b", "c")); } @Test public void composeMixingPathSegments() throws Exception { @@ -931,138 +979,178 @@ public final class HttpUrlTest { .addPathSegment("d%25e") .addEncodedPathSegment("f%25g") .build(); - assertEquals("http://host/a%2fb/c/d%2525e/f%25g", url.toString()); - assertEquals("/a%2fb/c/d%2525e/f%25g", url.encodedPath()); - assertEquals(Arrays.asList("a%2fb", "c", "d%2525e", "f%25g"), url.encodedPathSegments()); - assertEquals(Arrays.asList("a/b", "c", "d%25e", "f%g"), url.pathSegments()); + assertThat(url.toString()).isEqualTo("http://host/a%2fb/c/d%2525e/f%25g"); + assertThat(url.encodedPath()).isEqualTo("/a%2fb/c/d%2525e/f%25g"); + assertThat(url.encodedPathSegments()).isEqualTo( + Arrays.asList("a%2fb", "c", "d%2525e", "f%25g")); + assertThat(url.pathSegments()).isEqualTo(Arrays.asList("a/b", "c", "d%25e", "f%g")); } @Test public void composeWithAddSegment() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/a/b/c/", base.newBuilder().addPathSegment("").build().encodedPath()); - assertEquals("/a/b/c/d", - base.newBuilder().addPathSegment("").addPathSegment("d").build().encodedPath()); - assertEquals("/a/b/", base.newBuilder().addPathSegment("..").build().encodedPath()); - assertEquals("/a/b/", base.newBuilder().addPathSegment("").addPathSegment("..").build() - .encodedPath()); - assertEquals("/a/b/c/", base.newBuilder().addPathSegment("").addPathSegment("").build() - .encodedPath()); + assertThat(base.newBuilder().addPathSegment("").build().encodedPath()).isEqualTo( + "/a/b/c/"); + assertThat( + (Object) base.newBuilder().addPathSegment("").addPathSegment("d").build().encodedPath()).isEqualTo( + "/a/b/c/d"); + assertThat(base.newBuilder().addPathSegment("..").build().encodedPath()).isEqualTo( + "/a/b/"); + assertThat(base.newBuilder().addPathSegment("").addPathSegment("..").build() + .encodedPath()).isEqualTo("/a/b/"); + assertThat(base.newBuilder().addPathSegment("").addPathSegment("").build() + .encodedPath()).isEqualTo("/a/b/c/"); } @Test public void pathSize() throws Exception { - assertEquals(1, parse("http://host/").pathSize()); - assertEquals(3, parse("http://host/a/b/c").pathSize()); + assertThat(parse("http://host/").pathSize()).isEqualTo(1); + assertThat(parse("http://host/a/b/c").pathSize()).isEqualTo(3); } @Test public void addPathSegments() throws Exception { HttpUrl base = parse("http://host/a/b/c"); // Add a string with zero slashes: resulting URL gains one slash. - assertEquals("/a/b/c/", base.newBuilder().addPathSegments("").build().encodedPath()); - assertEquals("/a/b/c/d", base.newBuilder().addPathSegments("d").build().encodedPath()); + assertThat(base.newBuilder().addPathSegments("").build().encodedPath()).isEqualTo( + "/a/b/c/"); + assertThat(base.newBuilder().addPathSegments("d").build().encodedPath()).isEqualTo( + "/a/b/c/d"); // Add a string with one slash: resulting URL gains two slashes. - assertEquals("/a/b/c//", base.newBuilder().addPathSegments("/").build().encodedPath()); - assertEquals("/a/b/c/d/", base.newBuilder().addPathSegments("d/").build().encodedPath()); - assertEquals("/a/b/c//d", base.newBuilder().addPathSegments("/d").build().encodedPath()); + assertThat(base.newBuilder().addPathSegments("/").build().encodedPath()).isEqualTo( + "/a/b/c//"); + assertThat(base.newBuilder().addPathSegments("d/").build().encodedPath()).isEqualTo( + "/a/b/c/d/"); + assertThat(base.newBuilder().addPathSegments("/d").build().encodedPath()).isEqualTo( + "/a/b/c//d"); // Add a string with two slashes: resulting URL gains three slashes. - assertEquals("/a/b/c///", base.newBuilder().addPathSegments("//").build().encodedPath()); - assertEquals("/a/b/c//d/", base.newBuilder().addPathSegments("/d/").build().encodedPath()); - assertEquals("/a/b/c/d//", base.newBuilder().addPathSegments("d//").build().encodedPath()); - assertEquals("/a/b/c///d", base.newBuilder().addPathSegments("//d").build().encodedPath()); - assertEquals("/a/b/c/d/e/f", base.newBuilder().addPathSegments("d/e/f").build().encodedPath()); + assertThat(base.newBuilder().addPathSegments("//").build().encodedPath()).isEqualTo( + "/a/b/c///"); + assertThat(base.newBuilder().addPathSegments("/d/").build().encodedPath()).isEqualTo( + "/a/b/c//d/"); + assertThat(base.newBuilder().addPathSegments("d//").build().encodedPath()).isEqualTo( + "/a/b/c/d//"); + assertThat(base.newBuilder().addPathSegments("//d").build().encodedPath()).isEqualTo( + "/a/b/c///d"); + assertThat(base.newBuilder().addPathSegments("d/e/f").build().encodedPath()).isEqualTo( + "/a/b/c/d/e/f"); } @Test public void addPathSegmentsOntoTrailingSlash() throws Exception { HttpUrl base = parse("http://host/a/b/c/"); // Add a string with zero slashes: resulting URL gains zero slashes. - assertEquals("/a/b/c/", base.newBuilder().addPathSegments("").build().encodedPath()); - assertEquals("/a/b/c/d", base.newBuilder().addPathSegments("d").build().encodedPath()); + assertThat(base.newBuilder().addPathSegments("").build().encodedPath()).isEqualTo( + "/a/b/c/"); + assertThat(base.newBuilder().addPathSegments("d").build().encodedPath()).isEqualTo( + "/a/b/c/d"); // Add a string with one slash: resulting URL gains one slash. - assertEquals("/a/b/c//", base.newBuilder().addPathSegments("/").build().encodedPath()); - assertEquals("/a/b/c/d/", base.newBuilder().addPathSegments("d/").build().encodedPath()); - assertEquals("/a/b/c//d", base.newBuilder().addPathSegments("/d").build().encodedPath()); + assertThat(base.newBuilder().addPathSegments("/").build().encodedPath()).isEqualTo( + "/a/b/c//"); + assertThat(base.newBuilder().addPathSegments("d/").build().encodedPath()).isEqualTo( + "/a/b/c/d/"); + assertThat(base.newBuilder().addPathSegments("/d").build().encodedPath()).isEqualTo( + "/a/b/c//d"); // Add a string with two slashes: resulting URL gains two slashes. - assertEquals("/a/b/c///", base.newBuilder().addPathSegments("//").build().encodedPath()); - assertEquals("/a/b/c//d/", base.newBuilder().addPathSegments("/d/").build().encodedPath()); - assertEquals("/a/b/c/d//", base.newBuilder().addPathSegments("d//").build().encodedPath()); - assertEquals("/a/b/c///d", base.newBuilder().addPathSegments("//d").build().encodedPath()); - assertEquals("/a/b/c/d/e/f", base.newBuilder().addPathSegments("d/e/f").build().encodedPath()); + assertThat(base.newBuilder().addPathSegments("//").build().encodedPath()).isEqualTo( + "/a/b/c///"); + assertThat(base.newBuilder().addPathSegments("/d/").build().encodedPath()).isEqualTo( + "/a/b/c//d/"); + assertThat(base.newBuilder().addPathSegments("d//").build().encodedPath()).isEqualTo( + "/a/b/c/d//"); + assertThat(base.newBuilder().addPathSegments("//d").build().encodedPath()).isEqualTo( + "/a/b/c///d"); + assertThat(base.newBuilder().addPathSegments("d/e/f").build().encodedPath()).isEqualTo( + "/a/b/c/d/e/f"); } @Test public void addPathSegmentsWithBackslash() throws Exception { HttpUrl base = parse("http://host/"); - assertEquals("/d/e", base.newBuilder().addPathSegments("d\\e").build().encodedPath()); - assertEquals("/d/e", base.newBuilder().addEncodedPathSegments("d\\e").build().encodedPath()); + assertThat(base.newBuilder().addPathSegments("d\\e").build().encodedPath()).isEqualTo( + "/d/e"); + assertThat(base.newBuilder().addEncodedPathSegments("d\\e").build().encodedPath()).isEqualTo( + "/d/e"); } @Test public void addPathSegmentsWithEmptyPaths() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/a/b/c//d/e///f", - base.newBuilder().addPathSegments("/d/e///f").build().encodedPath()); + assertThat(base.newBuilder().addPathSegments("/d/e///f").build().encodedPath()).isEqualTo( + "/a/b/c//d/e///f"); } @Test public void addEncodedPathSegments() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/a/b/c/d/e/%20/", - base.newBuilder().addEncodedPathSegments("d/e/%20/\n").build().encodedPath()); + assertThat( + (Object) base.newBuilder().addEncodedPathSegments("d/e/%20/\n").build().encodedPath()).isEqualTo( + "/a/b/c/d/e/%20/"); } @Test public void addPathSegmentDotDoesNothing() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/a/b/c", base.newBuilder().addPathSegment(".").build().encodedPath()); + assertThat(base.newBuilder().addPathSegment(".").build().encodedPath()).isEqualTo( + "/a/b/c"); } @Test public void addPathSegmentEncodes() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/a/b/c/%252e", - base.newBuilder().addPathSegment("%2e").build().encodedPath()); - assertEquals("/a/b/c/%252e%252e", - base.newBuilder().addPathSegment("%2e%2e").build().encodedPath()); + assertThat(base.newBuilder().addPathSegment("%2e").build().encodedPath()).isEqualTo( + "/a/b/c/%252e"); + assertThat(base.newBuilder().addPathSegment("%2e%2e").build().encodedPath()).isEqualTo( + "/a/b/c/%252e%252e"); } @Test public void addPathSegmentDotDotPopsDirectory() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/a/b/", base.newBuilder().addPathSegment("..").build().encodedPath()); + assertThat(base.newBuilder().addPathSegment("..").build().encodedPath()).isEqualTo( + "/a/b/"); } @Test public void addPathSegmentDotAndIgnoredCharacter() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/a/b/c/.%0A", base.newBuilder().addPathSegment(".\n").build().encodedPath()); + assertThat(base.newBuilder().addPathSegment(".\n").build().encodedPath()).isEqualTo( + "/a/b/c/.%0A"); } @Test public void addEncodedPathSegmentDotAndIgnoredCharacter() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/a/b/c", base.newBuilder().addEncodedPathSegment(".\n").build().encodedPath()); + assertThat(base.newBuilder().addEncodedPathSegment(".\n").build().encodedPath()).isEqualTo( + "/a/b/c"); } @Test public void addEncodedPathSegmentDotDotAndIgnoredCharacter() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/a/b/", base.newBuilder().addEncodedPathSegment("..\n").build().encodedPath()); + assertThat(base.newBuilder().addEncodedPathSegment("..\n").build().encodedPath()).isEqualTo( + "/a/b/"); } @Test public void setPathSegment() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/d/b/c", base.newBuilder().setPathSegment(0, "d").build().encodedPath()); - assertEquals("/a/d/c", base.newBuilder().setPathSegment(1, "d").build().encodedPath()); - assertEquals("/a/b/d", base.newBuilder().setPathSegment(2, "d").build().encodedPath()); + assertThat(base.newBuilder().setPathSegment(0, "d").build().encodedPath()).isEqualTo( + "/d/b/c"); + assertThat(base.newBuilder().setPathSegment(1, "d").build().encodedPath()).isEqualTo( + "/a/d/c"); + assertThat(base.newBuilder().setPathSegment(2, "d").build().encodedPath()).isEqualTo( + "/a/b/d"); } @Test public void setPathSegmentEncodes() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/%2525/b/c", base.newBuilder().setPathSegment(0, "%25").build().encodedPath()); - assertEquals("/.%0A/b/c", base.newBuilder().setPathSegment(0, ".\n").build().encodedPath()); - assertEquals("/%252e/b/c", base.newBuilder().setPathSegment(0, "%2e").build().encodedPath()); + assertThat(base.newBuilder().setPathSegment(0, "%25").build().encodedPath()).isEqualTo( + "/%2525/b/c"); + assertThat(base.newBuilder().setPathSegment(0, ".\n").build().encodedPath()).isEqualTo( + "/.%0A/b/c"); + assertThat(base.newBuilder().setPathSegment(0, "%2e").build().encodedPath()).isEqualTo( + "/%252e/b/c"); } @Test public void setPathSegmentAcceptsEmpty() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("//b/c", base.newBuilder().setPathSegment(0, "").build().encodedPath()); - assertEquals("/a/b/", base.newBuilder().setPathSegment(2, "").build().encodedPath()); + assertThat(base.newBuilder().setPathSegment(0, "").build().encodedPath()).isEqualTo( + "//b/c"); + assertThat(base.newBuilder().setPathSegment(2, "").build().encodedPath()).isEqualTo( + "/a/b/"); } @Test public void setPathSegmentRejectsDot() throws Exception { @@ -1086,7 +1174,7 @@ public final class HttpUrlTest { @Test public void setPathSegmentWithSlash() throws Exception { HttpUrl base = parse("http://host/a/b/c"); HttpUrl url = base.newBuilder().setPathSegment(1, "/").build(); - assertEquals("/a/%2F/c", url.encodedPath()); + assertThat(url.encodedPath()).isEqualTo("/a/%2F/c"); } @Test public void setPathSegmentOutOfBounds() throws Exception { @@ -1099,8 +1187,8 @@ public final class HttpUrlTest { @Test public void setEncodedPathSegmentEncodes() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertEquals("/%25/b/c", - base.newBuilder().setEncodedPathSegment(0, "%25").build().encodedPath()); + assertThat(base.newBuilder().setEncodedPathSegment(0, "%25").build().encodedPath()).isEqualTo( + "/%25/b/c"); } @Test public void setEncodedPathSegmentRejectsDot() throws Exception { @@ -1142,7 +1230,7 @@ public final class HttpUrlTest { @Test public void setEncodedPathSegmentWithSlash() throws Exception { HttpUrl base = parse("http://host/a/b/c"); HttpUrl url = base.newBuilder().setEncodedPathSegment(1, "/").build(); - assertEquals("/a/%2F/c", url.encodedPath()); + assertThat(url.encodedPath()).isEqualTo("/a/%2F/c"); } @Test public void setEncodedPathSegmentOutOfBounds() throws Exception { @@ -1158,7 +1246,7 @@ public final class HttpUrlTest { HttpUrl url = base.newBuilder() .removePathSegment(0) .build(); - assertEquals("/b/c", url.encodedPath()); + assertThat(url.encodedPath()).isEqualTo("/b/c"); } @Test public void removePathSegmentDoesntRemovePath() throws Exception { @@ -1168,8 +1256,8 @@ public final class HttpUrlTest { .removePathSegment(0) .removePathSegment(0) .build(); - assertEquals(Arrays.asList(""), url.pathSegments()); - assertEquals("/", url.encodedPath()); + assertThat(url.pathSegments()).isEqualTo(Arrays.asList("")); + assertThat(url.encodedPath()).isEqualTo("/"); } @Test public void removePathSegmentOutOfBounds() throws Exception { @@ -1183,19 +1271,21 @@ public final class HttpUrlTest { @Test public void toJavaNetUrl() throws Exception { HttpUrl httpUrl = parse("http://username:password@host/path?query#fragment"); URL javaNetUrl = httpUrl.url(); - assertEquals("http://username:password@host/path?query#fragment", javaNetUrl.toString()); + assertThat(javaNetUrl.toString()).isEqualTo( + "http://username:password@host/path?query#fragment"); } @Test public void toUri() throws Exception { HttpUrl httpUrl = parse("http://username:password@host/path?query#fragment"); URI uri = httpUrl.uri(); - assertEquals("http://username:password@host/path?query#fragment", uri.toString()); + assertThat(uri.toString()).isEqualTo( + "http://username:password@host/path?query#fragment"); } @Test public void toUriSpecialQueryCharacters() throws Exception { HttpUrl httpUrl = parse("http://host/?d=abc!@[]^`{}|\\"); URI uri = httpUrl.uri(); - assertEquals("http://host/?d=abc!@[]%5E%60%7B%7D%7C%5C", uri.toString()); + assertThat(uri.toString()).isEqualTo("http://host/?d=abc!@[]%5E%60%7B%7D%7C%5C"); } @Test public void toUriWithUsernameNoPassword() throws Exception { @@ -1204,8 +1294,8 @@ public final class HttpUrlTest { .username("user") .host("host") .build(); - assertEquals("http://user@host/", httpUrl.toString()); - assertEquals("http://user@host/", httpUrl.uri().toString()); + assertThat(httpUrl.toString()).isEqualTo("http://user@host/"); + assertThat(httpUrl.uri().toString()).isEqualTo("http://user@host/"); } @Test public void toUriUsernameSpecialCharacters() throws Exception { @@ -1214,8 +1304,10 @@ public final class HttpUrlTest { .host("host") .username("=[]:;\"~|?#@^/$%*") .build(); - assertEquals("http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/", url.toString()); - assertEquals("http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/", url.uri().toString()); + assertThat(url.toString()).isEqualTo( + "http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/"); + assertThat(url.uri().toString()).isEqualTo( + "http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/"); } @Test public void toUriPasswordSpecialCharacters() throws Exception { @@ -1225,9 +1317,10 @@ public final class HttpUrlTest { .username("user") .password("=[]:;\"~|?#@^/$%*") .build(); - assertEquals("http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/", url.toString()); - assertEquals("http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/", - url.uri().toString()); + assertThat(url.toString()).isEqualTo( + "http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/"); + assertThat(url.uri().toString()).isEqualTo( + "http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/"); } @Test public void toUriPathSpecialCharacters() throws Exception { @@ -1236,8 +1329,9 @@ public final class HttpUrlTest { .host("host") .addPathSegment("=[]:;\"~|?#@^/$%*") .build(); - assertEquals("http://host/=[]:;%22~%7C%3F%23@%5E%2F$%25*", url.toString()); - assertEquals("http://host/=%5B%5D:;%22~%7C%3F%23@%5E%2F$%25*", url.uri().toString()); + assertThat(url.toString()).isEqualTo("http://host/=[]:;%22~%7C%3F%23@%5E%2F$%25*"); + assertThat(url.uri().toString()).isEqualTo( + "http://host/=%5B%5D:;%22~%7C%3F%23@%5E%2F$%25*"); } @Test public void toUriQueryParameterNameSpecialCharacters() throws Exception { @@ -1246,11 +1340,11 @@ public final class HttpUrlTest { .host("host") .addQueryParameter("=[]:;\"~|?#@^/$%*", "a") .build(); - assertEquals("http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a", - url.toString()); - assertEquals("http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a", - url.uri().toString()); - assertEquals("a", url.queryParameter("=[]:;\"~|?#@^/$%*")); + assertThat(url.toString()).isEqualTo( + "http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a"); + assertThat(url.uri().toString()).isEqualTo( + "http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a"); + assertThat(url.queryParameter("=[]:;\"~|?#@^/$%*")).isEqualTo("a"); } @Test public void toUriQueryParameterValueSpecialCharacters() throws Exception { @@ -1259,11 +1353,11 @@ public final class HttpUrlTest { .host("host") .addQueryParameter("a", "=[]:;\"~|?#@^/$%*") .build(); - assertEquals("http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*", - url.toString()); - assertEquals("http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*", - url.uri().toString()); - assertEquals("=[]:;\"~|?#@^/$%*", url.queryParameter("a")); + assertThat(url.toString()).isEqualTo( + "http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*"); + assertThat(url.uri().toString()).isEqualTo( + "http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*"); + assertThat(url.queryParameter("a")).isEqualTo("=[]:;\"~|?#@^/$%*"); } @Test public void toUriQueryValueSpecialCharacters() throws Exception { @@ -1272,8 +1366,8 @@ public final class HttpUrlTest { .host("host") .query("=[]:;\"~|?#@^/$%*") .build(); - assertEquals("http://host/?=[]:;%22~|?%23@^/$%25*", url.toString()); - assertEquals("http://host/?=[]:;%22~%7C?%23@%5E/$%25*", url.uri().toString()); + assertThat(url.toString()).isEqualTo("http://host/?=[]:;%22~|?%23@^/$%25*"); + assertThat(url.uri().toString()).isEqualTo("http://host/?=[]:;%22~%7C?%23@%5E/$%25*"); } @Test public void queryCharactersEncodedWhenComposed() throws Exception { @@ -1282,9 +1376,9 @@ public final class HttpUrlTest { .host("host") .addQueryParameter("a", "!$(),/:;?@[]\\^`{|}~") .build(); - assertEquals("http://host/?a=%21%24%28%29%2C%2F%3A%3B%3F%40%5B%5D%5C%5E%60%7B%7C%7D%7E", - url.toString()); - assertEquals("!$(),/:;?@[]\\^`{|}~", url.queryParameter("a")); + assertThat(url.toString()).isEqualTo( + "http://host/?a=%21%24%28%29%2C%2F%3A%3B%3F%40%5B%5D%5C%5E%60%7B%7C%7D%7E"); + assertThat(url.queryParameter("a")).isEqualTo("!$(),/:;?@[]\\^`{|}~"); } /** @@ -1297,9 +1391,8 @@ public final class HttpUrlTest { .host("host") .addEncodedQueryParameter("a", "!$(),/:;?@[]\\^`{|}~") .build(); - assertEquals("http://host/?a=!$(),/:;?@[]\\^`{|}~", - url.toString()); - assertEquals("!$(),/:;?@[]\\^`{|}~", url.queryParameter("a")); + assertThat(url.toString()).isEqualTo("http://host/?a=!$(),/:;?@[]\\^`{|}~"); + assertThat(url.queryParameter("a")).isEqualTo("!$(),/:;?@[]\\^`{|}~"); } /** @@ -1308,8 +1401,8 @@ public final class HttpUrlTest { */ @Test public void queryCharactersNotReencodedWhenParsed() throws Exception { HttpUrl url = parse("http://host/?a=!$(),/:;?@[]\\^`{|}~"); - assertEquals("http://host/?a=!$(),/:;?@[]\\^`{|}~", url.toString()); - assertEquals("!$(),/:;?@[]\\^`{|}~", url.queryParameter("a")); + assertThat(url.toString()).isEqualTo("http://host/?a=!$(),/:;?@[]\\^`{|}~"); + assertThat(url.queryParameter("a")).isEqualTo("!$(),/:;?@[]\\^`{|}~"); } @Test public void toUriFragmentSpecialCharacters() throws Exception { @@ -1318,98 +1411,113 @@ public final class HttpUrlTest { .host("host") .fragment("=[]:;\"~|?#@^/$%*") .build(); - assertEquals("http://host/#=[]:;\"~|?#@^/$%25*", url.toString()); - assertEquals("http://host/#=[]:;%22~%7C?%23@%5E/$%25*", url.uri().toString()); + assertThat(url.toString()).isEqualTo("http://host/#=[]:;\"~|?#@^/$%25*"); + assertThat(url.uri().toString()).isEqualTo("http://host/#=[]:;%22~%7C?%23@%5E/$%25*"); } @Test public void toUriWithControlCharacters() throws Exception { // Percent-encoded in the path. - assertEquals(new URI("http://host/a%00b"), parse("http://host/a\u0000b").uri()); - assertEquals(new URI("http://host/a%C2%80b"), parse("http://host/a\u0080b").uri()); - assertEquals(new URI("http://host/a%C2%9Fb"), parse("http://host/a\u009fb").uri()); + assertThat(parse("http://host/a\u0000b").uri()).isEqualTo(new URI("http://host/a%00b")); + assertThat(parse("http://host/a\u0080b").uri()).isEqualTo( + new URI("http://host/a%C2%80b")); + assertThat(parse("http://host/a\u009fb").uri()).isEqualTo( + new URI("http://host/a%C2%9Fb")); // Percent-encoded in the query. - assertEquals(new URI("http://host/?a%00b"), parse("http://host/?a\u0000b").uri()); - assertEquals(new URI("http://host/?a%C2%80b"), parse("http://host/?a\u0080b").uri()); - assertEquals(new URI("http://host/?a%C2%9Fb"), parse("http://host/?a\u009fb").uri()); + assertThat(parse("http://host/?a\u0000b").uri()).isEqualTo( + new URI("http://host/?a%00b")); + assertThat(parse("http://host/?a\u0080b").uri()).isEqualTo( + new URI("http://host/?a%C2%80b")); + assertThat(parse("http://host/?a\u009fb").uri()).isEqualTo( + new URI("http://host/?a%C2%9Fb")); // Stripped from the fragment. - assertEquals(new URI("http://host/#a%00b"), parse("http://host/#a\u0000b").uri()); - assertEquals(new URI("http://host/#ab"), parse("http://host/#a\u0080b").uri()); - assertEquals(new URI("http://host/#ab"), parse("http://host/#a\u009fb").uri()); + assertThat(parse("http://host/#a\u0000b").uri()).isEqualTo( + new URI("http://host/#a%00b")); + assertThat(parse("http://host/#a\u0080b").uri()).isEqualTo(new URI("http://host/#ab")); + assertThat(parse("http://host/#a\u009fb").uri()).isEqualTo(new URI("http://host/#ab")); } @Test public void toUriWithSpaceCharacters() throws Exception { // Percent-encoded in the path. - assertEquals(new URI("http://host/a%0Bb"), parse("http://host/a\u000bb").uri()); - assertEquals(new URI("http://host/a%20b"), parse("http://host/a b").uri()); - assertEquals(new URI("http://host/a%E2%80%89b"), parse("http://host/a\u2009b").uri()); - assertEquals(new URI("http://host/a%E3%80%80b"), parse("http://host/a\u3000b").uri()); + assertThat(parse("http://host/a\u000bb").uri()).isEqualTo(new URI("http://host/a%0Bb")); + assertThat(parse("http://host/a b").uri()).isEqualTo(new URI("http://host/a%20b")); + assertThat(parse("http://host/a\u2009b").uri()).isEqualTo( + new URI("http://host/a%E2%80%89b")); + assertThat(parse("http://host/a\u3000b").uri()).isEqualTo( + new URI("http://host/a%E3%80%80b")); // Percent-encoded in the query. - assertEquals(new URI("http://host/?a%0Bb"), parse("http://host/?a\u000bb").uri()); - assertEquals(new URI("http://host/?a%20b"), parse("http://host/?a b").uri()); - assertEquals(new URI("http://host/?a%E2%80%89b"), parse("http://host/?a\u2009b").uri()); - assertEquals(new URI("http://host/?a%E3%80%80b"), parse("http://host/?a\u3000b").uri()); + assertThat(parse("http://host/?a\u000bb").uri()).isEqualTo( + new URI("http://host/?a%0Bb")); + assertThat(parse("http://host/?a b").uri()).isEqualTo(new URI("http://host/?a%20b")); + assertThat(parse("http://host/?a\u2009b").uri()).isEqualTo( + new URI("http://host/?a%E2%80%89b")); + assertThat(parse("http://host/?a\u3000b").uri()).isEqualTo( + new URI("http://host/?a%E3%80%80b")); // Stripped from the fragment. - assertEquals(new URI("http://host/#a%0Bb"), parse("http://host/#a\u000bb").uri()); - assertEquals(new URI("http://host/#a%20b"), parse("http://host/#a b").uri()); - assertEquals(new URI("http://host/#ab"), parse("http://host/#a\u2009b").uri()); - assertEquals(new URI("http://host/#ab"), parse("http://host/#a\u3000b").uri()); + assertThat(parse("http://host/#a\u000bb").uri()).isEqualTo( + new URI("http://host/#a%0Bb")); + assertThat(parse("http://host/#a b").uri()).isEqualTo(new URI("http://host/#a%20b")); + assertThat(parse("http://host/#a\u2009b").uri()).isEqualTo(new URI("http://host/#ab")); + assertThat(parse("http://host/#a\u3000b").uri()).isEqualTo(new URI("http://host/#ab")); } @Test public void toUriWithNonHexPercentEscape() throws Exception { - assertEquals(new URI("http://host/%25xx"), parse("http://host/%xx").uri()); + assertThat(parse("http://host/%xx").uri()).isEqualTo(new URI("http://host/%25xx")); } @Test public void toUriWithTruncatedPercentEscape() throws Exception { - assertEquals(new URI("http://host/%25a"), parse("http://host/%a").uri()); - assertEquals(new URI("http://host/%25"), parse("http://host/%").uri()); + assertThat(parse("http://host/%a").uri()).isEqualTo(new URI("http://host/%25a")); + assertThat(parse("http://host/%").uri()).isEqualTo(new URI("http://host/%25")); } @Test public void fromJavaNetUrl() throws Exception { URL javaNetUrl = new URL("http://username:password@host/path?query#fragment"); HttpUrl httpUrl = HttpUrl.get(javaNetUrl); - assertEquals("http://username:password@host/path?query#fragment", httpUrl.toString()); + assertThat(httpUrl.toString()).isEqualTo( + "http://username:password@host/path?query#fragment"); } @Test public void fromJavaNetUrlUnsupportedScheme() throws Exception { URL javaNetUrl = new URL("mailto:user@example.com"); - assertNull(HttpUrl.get(javaNetUrl)); + assertThat(HttpUrl.get(javaNetUrl)).isNull(); } @Test public void fromUri() throws Exception { URI uri = new URI("http://username:password@host/path?query#fragment"); HttpUrl httpUrl = HttpUrl.get(uri); - assertEquals("http://username:password@host/path?query#fragment", httpUrl.toString()); + assertThat(httpUrl.toString()).isEqualTo( + "http://username:password@host/path?query#fragment"); } @Test public void fromUriUnsupportedScheme() throws Exception { URI uri = new URI("mailto:user@example.com"); - assertNull(HttpUrl.get(uri)); + assertThat(HttpUrl.get(uri)).isNull(); } @Test public void fromUriPartial() throws Exception { URI uri = new URI("/path"); - assertNull(HttpUrl.get(uri)); + assertThat(HttpUrl.get(uri)).isNull(); } @Test public void composeQueryWithComponents() throws Exception { HttpUrl base = parse("http://host/"); HttpUrl url = base.newBuilder().addQueryParameter("a+=& b", "c+=& d").build(); - assertEquals("http://host/?a%2B%3D%26%20b=c%2B%3D%26%20d", url.toString()); - assertEquals("c+=& d", url.queryParameterValue(0)); - assertEquals("a+=& b", url.queryParameterName(0)); - assertEquals("c+=& d", url.queryParameter("a+=& b")); - assertEquals(Collections.singleton("a+=& b"), url.queryParameterNames()); - assertEquals(singletonList("c+=& d"), url.queryParameterValues("a+=& b")); - assertEquals(1, url.querySize()); - assertEquals("a+=& b=c+=& d", url.query()); // Ambiguous! (Though working as designed.) - assertEquals("a%2B%3D%26%20b=c%2B%3D%26%20d", url.encodedQuery()); + assertThat(url.toString()).isEqualTo("http://host/?a%2B%3D%26%20b=c%2B%3D%26%20d"); + assertThat(url.queryParameterValue(0)).isEqualTo("c+=& d"); + assertThat(url.queryParameterName(0)).isEqualTo("a+=& b"); + assertThat(url.queryParameter("a+=& b")).isEqualTo("c+=& d"); + assertThat(url.queryParameterNames()).isEqualTo(Collections.singleton("a+=& b")); + assertThat(url.queryParameterValues("a+=& b")).isEqualTo(singletonList("c+=& d")); + assertThat(url.querySize()).isEqualTo(1); + // Ambiguous! (Though working as designed.) + assertThat(url.query()).isEqualTo("a+=& b=c+=& d"); + assertThat(url.encodedQuery()).isEqualTo("a%2B%3D%26%20b=c%2B%3D%26%20d"); } @Test public void composeQueryWithEncodedComponents() throws Exception { HttpUrl base = parse("http://host/"); HttpUrl url = base.newBuilder().addEncodedQueryParameter("a+=& b", "c+=& d").build(); - assertEquals("http://host/?a+%3D%26%20b=c+%3D%26%20d", url.toString()); - assertEquals("c =& d", url.queryParameter("a =& b")); + assertThat(url.toString()).isEqualTo("http://host/?a+%3D%26%20b=c+%3D%26%20d"); + assertThat(url.queryParameter("a =& b")).isEqualTo("c =& d"); } @Test public void composeQueryRemoveQueryParameter() throws Exception { @@ -1417,8 +1525,8 @@ public final class HttpUrlTest { .addQueryParameter("a+=& b", "c+=& d") .removeAllQueryParameters("a+=& b") .build(); - assertEquals("http://host/", url.toString()); - assertNull(url.queryParameter("a+=& b")); + assertThat(url.toString()).isEqualTo("http://host/"); + assertThat(url.queryParameter("a+=& b")).isNull(); } @Test public void composeQueryRemoveEncodedQueryParameter() throws Exception { @@ -1426,8 +1534,8 @@ public final class HttpUrlTest { .addEncodedQueryParameter("a+=& b", "c+=& d") .removeAllEncodedQueryParameters("a+=& b") .build(); - assertEquals("http://host/", url.toString()); - assertNull(url.queryParameter("a =& b")); + assertThat(url.toString()).isEqualTo("http://host/"); + assertThat(url.queryParameter("a =& b")).isNull(); } @Test public void composeQuerySetQueryParameter() throws Exception { @@ -1435,8 +1543,8 @@ public final class HttpUrlTest { .addQueryParameter("a+=& b", "c+=& d") .setQueryParameter("a+=& b", "ef") .build(); - assertEquals("http://host/?a%2B%3D%26%20b=ef", url.toString()); - assertEquals("ef", url.queryParameter("a+=& b")); + assertThat(url.toString()).isEqualTo("http://host/?a%2B%3D%26%20b=ef"); + assertThat(url.queryParameter("a+=& b")).isEqualTo("ef"); } @Test public void composeQuerySetEncodedQueryParameter() throws Exception { @@ -1444,8 +1552,8 @@ public final class HttpUrlTest { .addEncodedQueryParameter("a+=& b", "c+=& d") .setEncodedQueryParameter("a+=& b", "ef") .build(); - assertEquals("http://host/?a+%3D%26%20b=ef", url.toString()); - assertEquals("ef", url.queryParameter("a =& b")); + assertThat(url.toString()).isEqualTo("http://host/?a+%3D%26%20b=ef"); + assertThat(url.queryParameter("a =& b")).isEqualTo("ef"); } @Test public void composeQueryMultipleEncodedValuesForParameter() throws Exception { @@ -1453,38 +1561,39 @@ public final class HttpUrlTest { .addQueryParameter("a+=& b", "c+=& d") .addQueryParameter("a+=& b", "e+=& f") .build(); - assertEquals("http://host/?a%2B%3D%26%20b=c%2B%3D%26%20d&a%2B%3D%26%20b=e%2B%3D%26%20f", - url.toString()); - assertEquals(2, url.querySize()); - assertEquals(Collections.singleton("a+=& b"), url.queryParameterNames()); - assertEquals(Arrays.asList("c+=& d", "e+=& f"), url.queryParameterValues("a+=& b")); + assertThat(url.toString()).isEqualTo( + "http://host/?a%2B%3D%26%20b=c%2B%3D%26%20d&a%2B%3D%26%20b=e%2B%3D%26%20f"); + assertThat(url.querySize()).isEqualTo(2); + assertThat(url.queryParameterNames()).isEqualTo(Collections.singleton("a+=& b")); + assertThat(url.queryParameterValues("a+=& b")).isEqualTo( + Arrays.asList("c+=& d", "e+=& f")); } @Test public void absentQueryIsZeroNameValuePairs() throws Exception { HttpUrl url = parse("http://host/").newBuilder() .query(null) .build(); - assertEquals(0, url.querySize()); + assertThat(url.querySize()).isEqualTo(0); } @Test public void emptyQueryIsSingleNameValuePairWithEmptyKey() throws Exception { HttpUrl url = parse("http://host/").newBuilder() .query("") .build(); - assertEquals(1, url.querySize()); - assertEquals("", url.queryParameterName(0)); - assertNull(url.queryParameterValue(0)); + assertThat(url.querySize()).isEqualTo(1); + assertThat(url.queryParameterName(0)).isEqualTo(""); + assertThat(url.queryParameterValue(0)).isNull(); } @Test public void ampersandQueryIsTwoNameValuePairsWithEmptyKeys() throws Exception { HttpUrl url = parse("http://host/").newBuilder() .query("&") .build(); - assertEquals(2, url.querySize()); - assertEquals("", url.queryParameterName(0)); - assertNull(url.queryParameterValue(0)); - assertEquals("", url.queryParameterName(1)); - assertNull(url.queryParameterValue(1)); + assertThat(url.querySize()).isEqualTo(2); + assertThat(url.queryParameterName(0)).isEqualTo(""); + assertThat(url.queryParameterValue(0)).isNull(); + assertThat(url.queryParameterName(1)).isEqualTo(""); + assertThat(url.queryParameterValue(1)).isNull(); } @Test public void removeAllDoesNotRemoveQueryIfNoParametersWereRemoved() throws Exception { @@ -1492,58 +1601,58 @@ public final class HttpUrlTest { .query("") .removeAllQueryParameters("a") .build(); - assertEquals("http://host/?", url.toString()); + assertThat(url.toString()).isEqualTo("http://host/?"); } @Test public void queryParametersWithoutValues() throws Exception { HttpUrl url = parse("http://host/?foo&bar&baz"); - assertEquals(3, url.querySize()); - assertEquals(new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz")), - url.queryParameterNames()); - assertNull(url.queryParameterValue(0)); - assertNull(url.queryParameterValue(1)); - assertNull(url.queryParameterValue(2)); - assertEquals(singletonList((String) null), url.queryParameterValues("foo")); - assertEquals(singletonList((String) null), url.queryParameterValues("bar")); - assertEquals(singletonList((String) null), url.queryParameterValues("baz")); + assertThat(url.querySize()).isEqualTo(3); + assertThat(url.queryParameterNames()).isEqualTo( + new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz"))); + assertThat(url.queryParameterValue(0)).isNull(); + assertThat(url.queryParameterValue(1)).isNull(); + assertThat(url.queryParameterValue(2)).isNull(); + assertThat(url.queryParameterValues("foo")).isEqualTo(singletonList((String) null)); + assertThat(url.queryParameterValues("bar")).isEqualTo(singletonList((String) null)); + assertThat(url.queryParameterValues("baz")).isEqualTo(singletonList((String) null)); } @Test public void queryParametersWithEmptyValues() throws Exception { HttpUrl url = parse("http://host/?foo=&bar=&baz="); - assertEquals(3, url.querySize()); - assertEquals(new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz")), - url.queryParameterNames()); - assertEquals("", url.queryParameterValue(0)); - assertEquals("", url.queryParameterValue(1)); - assertEquals("", url.queryParameterValue(2)); - assertEquals(singletonList(""), url.queryParameterValues("foo")); - assertEquals(singletonList(""), url.queryParameterValues("bar")); - assertEquals(singletonList(""), url.queryParameterValues("baz")); + assertThat(url.querySize()).isEqualTo(3); + assertThat(url.queryParameterNames()).isEqualTo( + new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz"))); + assertThat(url.queryParameterValue(0)).isEqualTo(""); + assertThat(url.queryParameterValue(1)).isEqualTo(""); + assertThat(url.queryParameterValue(2)).isEqualTo(""); + assertThat(url.queryParameterValues("foo")).isEqualTo(singletonList("")); + assertThat(url.queryParameterValues("bar")).isEqualTo(singletonList("")); + assertThat(url.queryParameterValues("baz")).isEqualTo(singletonList("")); } @Test public void queryParametersWithRepeatedName() throws Exception { HttpUrl url = parse("http://host/?foo[]=1&foo[]=2&foo[]=3"); - assertEquals(3, url.querySize()); - assertEquals(Collections.singleton("foo[]"), url.queryParameterNames()); - assertEquals("1", url.queryParameterValue(0)); - assertEquals("2", url.queryParameterValue(1)); - assertEquals("3", url.queryParameterValue(2)); - assertEquals(Arrays.asList("1", "2", "3"), url.queryParameterValues("foo[]")); + assertThat(url.querySize()).isEqualTo(3); + assertThat(url.queryParameterNames()).isEqualTo(Collections.singleton("foo[]")); + assertThat(url.queryParameterValue(0)).isEqualTo("1"); + assertThat(url.queryParameterValue(1)).isEqualTo("2"); + assertThat(url.queryParameterValue(2)).isEqualTo("3"); + assertThat(url.queryParameterValues("foo[]")).isEqualTo(Arrays.asList("1", "2", "3")); } @Test public void queryParameterLookupWithNonCanonicalEncoding() throws Exception { HttpUrl url = parse("http://host/?%6d=m&+=%20"); - assertEquals("m", url.queryParameterName(0)); - assertEquals(" ", url.queryParameterName(1)); - assertEquals("m", url.queryParameter("m")); - assertEquals(" ", url.queryParameter(" ")); + assertThat(url.queryParameterName(0)).isEqualTo("m"); + assertThat(url.queryParameterName(1)).isEqualTo(" "); + assertThat(url.queryParameter("m")).isEqualTo("m"); + assertThat(url.queryParameter(" ")).isEqualTo(" "); } @Test public void parsedQueryDoesntIncludeFragment() { HttpUrl url = parse("http://host/?#fragment"); - assertEquals("fragment", url.fragment()); - assertEquals("", url.query()); - assertEquals("", url.encodedQuery()); + assertThat(url.fragment()).isEqualTo("fragment"); + assertThat(url.query()).isEqualTo(""); + assertThat(url.encodedQuery()).isEqualTo(""); } @Test public void roundTripBuilder() throws Exception { @@ -1556,9 +1665,10 @@ public final class HttpUrlTest { .query("%") .fragment("%") .build(); - assertEquals("http://%25:%25@host/%25?%25#%25", url.toString()); - assertEquals("http://%25:%25@host/%25?%25#%25", url.newBuilder().build().toString()); - assertEquals("http://%25:%25@host/%25?%25", url.resolve("").toString()); + assertThat(url.toString()).isEqualTo("http://%25:%25@host/%25?%25#%25"); + assertThat(url.newBuilder().build().toString()).isEqualTo( + "http://%25:%25@host/%25?%25#%25"); + assertThat(url.resolve("").toString()).isEqualTo("http://%25:%25@host/%25?%25"); } /** @@ -1568,15 +1678,16 @@ public final class HttpUrlTest { @Test public void rawEncodingRetained() throws Exception { String urlString = "http://%6d%6D:%6d%6D@host/%6d%6D?%6d%6D#%6d%6D"; HttpUrl url = parse(urlString); - assertEquals("%6d%6D", url.encodedUsername()); - assertEquals("%6d%6D", url.encodedPassword()); - assertEquals("/%6d%6D", url.encodedPath()); - assertEquals(Arrays.asList("%6d%6D"), url.encodedPathSegments()); - assertEquals("%6d%6D", url.encodedQuery()); - assertEquals("%6d%6D", url.encodedFragment()); - assertEquals(urlString, url.toString()); - assertEquals(urlString, url.newBuilder().build().toString()); - assertEquals("http://%6d%6D:%6d%6D@host/%6d%6D?%6d%6D", url.resolve("").toString()); + assertThat(url.encodedUsername()).isEqualTo("%6d%6D"); + assertThat(url.encodedPassword()).isEqualTo("%6d%6D"); + assertThat(url.encodedPath()).isEqualTo("/%6d%6D"); + assertThat(url.encodedPathSegments()).isEqualTo(Arrays.asList("%6d%6D")); + assertThat(url.encodedQuery()).isEqualTo("%6d%6D"); + assertThat(url.encodedFragment()).isEqualTo("%6d%6D"); + assertThat(url.toString()).isEqualTo(urlString); + assertThat(url.newBuilder().build().toString()).isEqualTo(urlString); + assertThat(url.resolve("").toString()).isEqualTo( + "http://%6d%6D:%6d%6D@host/%6d%6D?%6d%6D"); } @Test public void clearFragment() throws Exception { @@ -1584,9 +1695,9 @@ public final class HttpUrlTest { .newBuilder() .fragment(null) .build(); - assertEquals("http://host/", url.toString()); - assertNull(url.fragment()); - assertNull(url.encodedFragment()); + assertThat(url.toString()).isEqualTo("http://host/"); + assertThat(url.fragment()).isNull(); + assertThat(url.encodedFragment()).isNull(); } @Test public void clearEncodedFragment() throws Exception { @@ -1594,24 +1705,26 @@ public final class HttpUrlTest { .newBuilder() .encodedFragment(null) .build(); - assertEquals("http://host/", url.toString()); - assertNull(url.fragment()); - assertNull(url.encodedFragment()); + assertThat(url.toString()).isEqualTo("http://host/"); + assertThat(url.fragment()).isNull(); + assertThat(url.encodedFragment()).isNull(); } @Test public void topPrivateDomain() { - assertEquals("google.com", parse("https://google.com").topPrivateDomain()); - assertEquals("google.co.uk", parse("https://adwords.google.co.uk").topPrivateDomain()); - assertEquals("xn--ewv.xn--4pvxs.jp", parse("https://栃.栃木.jp").topPrivateDomain()); - assertEquals("xn--ewv.xn--4pvxs.jp", - parse("https://xn--ewv.xn--4pvxs.jp").topPrivateDomain()); + assertThat(parse("https://google.com").topPrivateDomain()).isEqualTo("google.com"); + assertThat(parse("https://adwords.google.co.uk").topPrivateDomain()).isEqualTo( + "google.co.uk"); + assertThat(parse("https://栃.栃木.jp").topPrivateDomain()).isEqualTo( + "xn--ewv.xn--4pvxs.jp"); + assertThat(parse("https://xn--ewv.xn--4pvxs.jp").topPrivateDomain()).isEqualTo( + "xn--ewv.xn--4pvxs.jp"); - assertNull(parse("https://co.uk").topPrivateDomain()); - assertNull(parse("https://square").topPrivateDomain()); - assertNull(parse("https://栃木.jp").topPrivateDomain()); - assertNull(parse("https://xn--4pvxs.jp").topPrivateDomain()); - assertNull(parse("https://localhost").topPrivateDomain()); - assertNull(parse("https://127.0.0.1").topPrivateDomain()); + assertThat(parse("https://co.uk").topPrivateDomain()).isNull(); + assertThat(parse("https://square").topPrivateDomain()).isNull(); + assertThat(parse("https://栃木.jp").topPrivateDomain()).isNull(); + assertThat(parse("https://xn--4pvxs.jp").topPrivateDomain()).isNull(); + assertThat(parse("https://localhost").topPrivateDomain()).isNull(); + assertThat(parse("https://127.0.0.1").topPrivateDomain()).isNull(); } private void assertInvalid(String string, String exceptionMessage) { @@ -1620,10 +1733,10 @@ public final class HttpUrlTest { 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(); } } } diff --git a/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java b/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java index 89242dcf2..92b580959 100644 --- a/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java +++ b/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java @@ -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) { diff --git a/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java b/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java index 1520bcaf8..ac4c608f1 100644 --- a/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java +++ b/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java @@ -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(); } } } diff --git a/okhttp-tests/src/test/java/okhttp3/MultipartBodyTest.java b/okhttp-tests/src/test/java/okhttp3/MultipartBodyTest.java index 7696ed997..00ae7bbdf 100644 --- a/okhttp-tests/src/test/java/okhttp3/MultipartBodyTest.java +++ b/okhttp-tests/src/test/java/okhttp3/MultipartBodyTest.java @@ -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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java b/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java index caf43a52d..b999eb285 100644 --- a/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java +++ b/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java @@ -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 { diff --git a/okhttp-tests/src/test/java/okhttp3/ProtocolTest.java b/okhttp-tests/src/test/java/okhttp3/ProtocolTest.java index 78b408093..ffced6eac 100644 --- a/okhttp-tests/src/test/java/okhttp3/ProtocolTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ProtocolTest.java @@ -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"); } } diff --git a/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java b/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java index 715cbda38..8d502a088 100644 --- a/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java +++ b/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java @@ -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) { diff --git a/okhttp-tests/src/test/java/okhttp3/RecordingEventListener.java b/okhttp-tests/src/test/java/okhttp3/RecordingEventListener.java index 5dde53d6b..f3ed94acd 100644 --- a/okhttp-tests/src/test/java/okhttp3/RecordingEventListener.java +++ b/okhttp-tests/src/test/java/okhttp3/RecordingEventListener.java @@ -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 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); diff --git a/okhttp-tests/src/test/java/okhttp3/RequestTest.java b/okhttp-tests/src/test/java/okhttp3/RequestTest.java index a335abc2d..c16c44139 100644 --- a/okhttp-tests/src/test/java/okhttp3/RequestTest.java +++ b/okhttp-tests/src/test/java/okhttp3/RequestTest.java @@ -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.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 { diff --git a/okhttp-tests/src/test/java/okhttp3/ResponseBodyTest.java b/okhttp-tests/src/test/java/okhttp3/ResponseBodyTest.java index a64ac17d5..cced85f93 100644 --- a/okhttp-tests/src/test/java/okhttp3/ResponseBodyTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ResponseBodyTest.java @@ -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(); } diff --git a/okhttp-tests/src/test/java/okhttp3/ResponseTest.java b/okhttp-tests/src/test/java/okhttp3/ResponseTest.java index 5d77a02a2..162d2d9a3 100644 --- a/okhttp-tests/src/test/java/okhttp3/ResponseTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ResponseTest.java @@ -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"); } /** diff --git a/okhttp-tests/src/test/java/okhttp3/SocksProxyTest.java b/okhttp-tests/src/test/java/okhttp3/SocksProxyTest.java index 83a6617b9..c0e884e72 100644 --- a/okhttp-tests/src/test/java/okhttp3/SocksProxyTest.java +++ b/okhttp-tests/src/test/java/okhttp3/SocksProxyTest.java @@ -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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java b/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java index f1f070efd..e44ab7736 100644 --- a/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java +++ b/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java @@ -76,6 +76,7 @@ import okio.BufferedSource; import okio.GzipSink; import okio.Okio; import okio.Utf8; +import org.assertj.core.api.Assertions; import org.junit.After; import org.junit.AssumptionViolatedException; import org.junit.Before; @@ -100,11 +101,7 @@ import static okhttp3.mockwebserver.SocketPolicy.UPGRADE_TO_SSL_AT_END; import static okhttp3.tls.internal.TlsUtil.localhost; 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.assertNull; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; @@ -144,11 +141,13 @@ public final class URLConnectionTest { .addHeader("D", "e") .addHeader("D", "f") .build(); - assertEquals("f", request.header("D")); - assertEquals("f", request.header("d")); + Assertions.assertThat(request.header("D")).isEqualTo("f"); + Assertions.assertThat(request.header("d")).isEqualTo("f"); Headers requestHeaders = request.headers(); - assertEquals(newSet("e", "f"), new LinkedHashSet<>(requestHeaders.values("D"))); - assertEquals(newSet("e", "f"), new LinkedHashSet<>(requestHeaders.values("d"))); + Assertions.assertThat(new LinkedHashSet<>(requestHeaders.values("D"))).isEqualTo( + newSet("e", "f")); + Assertions.assertThat(new LinkedHashSet<>(requestHeaders.values("d"))).isEqualTo( + newSet("e", "f")); try { new Request.Builder() .header(null, "j"); @@ -178,9 +177,10 @@ public final class URLConnectionTest { response.close(); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals(Arrays.asList("e", "f"), recordedRequest.getHeaders().values("D")); - assertNull(recordedRequest.getHeader("G")); - assertNull(recordedRequest.getHeader("null")); + Assertions.assertThat(recordedRequest.getHeaders().values("D")).isEqualTo( + Arrays.asList("e", "f")); + Assertions.assertThat(recordedRequest.getHeader("G")).isNull(); + Assertions.assertThat(recordedRequest.getHeader("null")).isNull(); } @Test public void getRequestPropertyReturnsLastValue() { @@ -189,7 +189,7 @@ public final class URLConnectionTest { .addHeader("A", "value1") .addHeader("A", "value2") .build(); - assertEquals("value2", request.header("A")); + Assertions.assertThat(request.header("A")).isEqualTo("value2"); } @Test public void responseHeaders() throws Exception { @@ -202,22 +202,24 @@ public final class URLConnectionTest { Request request = newRequest("/"); Response response = getResponse(request); - assertEquals(200, response.code()); - assertEquals("Fantastic", response.message()); + Assertions.assertThat(response.code()).isEqualTo(200); + Assertions.assertThat(response.message()).isEqualTo("Fantastic"); try { response.header(null); fail(); } catch (NullPointerException expected) { } Headers responseHeaders = response.headers(); - assertEquals(newSet("c", "e"), new LinkedHashSet<>(responseHeaders.values("A"))); - assertEquals(newSet("c", "e"), new LinkedHashSet<>(responseHeaders.values("a"))); - assertEquals("A", responseHeaders.name(0)); - assertEquals("c", responseHeaders.value(0)); - assertEquals("B", responseHeaders.name(1)); - assertEquals("d", responseHeaders.value(1)); - assertEquals("A", responseHeaders.name(2)); - assertEquals("e", responseHeaders.value(2)); + Assertions.assertThat(new LinkedHashSet<>(responseHeaders.values("A"))).isEqualTo( + newSet("c", "e")); + Assertions.assertThat(new LinkedHashSet<>(responseHeaders.values("a"))).isEqualTo( + newSet("c", "e")); + Assertions.assertThat(responseHeaders.name(0)).isEqualTo("A"); + Assertions.assertThat(responseHeaders.value(0)).isEqualTo("c"); + Assertions.assertThat(responseHeaders.name(1)).isEqualTo("B"); + Assertions.assertThat(responseHeaders.value(1)).isEqualTo("d"); + Assertions.assertThat(responseHeaders.name(2)).isEqualTo("A"); + Assertions.assertThat(responseHeaders.value(2)).isEqualTo("e"); response.body().close(); } @@ -305,7 +307,7 @@ public final class URLConnectionTest { Response response = getResponse(request); assertContent("abc", response); - assertEquals("body", server.takeRequest().getBody().readUtf8()); + Assertions.assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("body"); } // Check that if we don't read to the end of a response, the next request on the @@ -337,11 +339,11 @@ public final class URLConnectionTest { server.enqueue(response); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/foo"))); - assertEquals(0, server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/bar?baz=quux"))); - assertEquals(1, server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/z"))); - assertEquals(2, server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void chunkedConnectionsArePooled() throws Exception { @@ -353,11 +355,11 @@ public final class URLConnectionTest { server.enqueue(response); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/foo"))); - assertEquals(0, server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/bar?baz=quux"))); - assertEquals(1, server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/z"))); - assertEquals(2, server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void serverClosesSocket() throws Exception { @@ -398,7 +400,7 @@ public final class URLConnectionTest { Response response1 = getResponse(newRequest("/a")); response1.body().source().timeout().timeout(100, MILLISECONDS); assertContent("This connection won't pool properly", response1); - assertEquals(0, server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // Give the server time to enact the socket policy if it's one that could happen after the // client has received the response. @@ -414,9 +416,8 @@ public final class URLConnectionTest { // creating a fresh connection, the server may have recorded 2 requests at this point. The order // of recording is non-deterministic. RecordedRequest requestAfter = server.takeRequest(); - assertTrue( - requestAfter.getSequenceNumber() == 0 - || server.getRequestCount() == 3 && server.takeRequest().getSequenceNumber() == 0); + Assertions.assertThat(requestAfter.getSequenceNumber() == 0 + || server.getRequestCount() == 3 && server.takeRequest().getSequenceNumber() == 0).isTrue(); } enum WriteKind {BYTE_BY_BYTE, SMALL_BUFFERS, LARGE_BUFFERS} @@ -478,13 +479,13 @@ public final class URLConnectionTest { .url(server.url("/")) .post(requestBody) .build()); - assertEquals(200, response.code()); + Assertions.assertThat(response.code()).isEqualTo(200); RecordedRequest request = server.takeRequest(); - assertEquals(n, request.getBodySize()); + Assertions.assertThat(request.getBodySize()).isEqualTo(n); if (uploadKind == TransferKind.CHUNKED) { - assertTrue(request.getChunkSizes().size() > 0); + Assertions.assertThat(request.getChunkSizes().size() > 0).isTrue(); } else { - assertTrue(request.getChunkSizes().isEmpty()); + Assertions.assertThat(request.getChunkSizes().isEmpty()).isTrue(); } } @@ -503,7 +504,7 @@ public final class URLConnectionTest { assertContent("this response comes via HTTPS", response); RecordedRequest request = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", request.getRequestLine()); + Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); } @Test public void connectViaHttpsReusingConnections() throws Exception { @@ -551,8 +552,8 @@ public final class URLConnectionTest { Response response2 = getResponse(newRequest("/")); assertContent("another response via HTTPS", response2); - 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 connectViaHttpsReusingConnectionsDifferentFactories() throws Exception { @@ -611,10 +612,10 @@ public final class URLConnectionTest { assertContent("this response comes via SSL", response); RecordedRequest failHandshakeRequest = server.takeRequest(); - assertNull(failHandshakeRequest.getRequestLine()); + Assertions.assertThat(failHandshakeRequest.getRequestLine()).isNull(); RecordedRequest fallbackRequest = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", fallbackRequest.getRequestLine()); + Assertions.assertThat(fallbackRequest.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); assertThat(fallbackRequest.getTlsVersion(), either(equalTo(TlsVersion.TLS_1_2)).or(equalTo(TlsVersion.TLS_1_3))); } @@ -637,7 +638,7 @@ public final class URLConnectionTest { getResponse(newRequest("/foo")); fail(); } catch (IOException expected) { - assertEquals(1, expected.getSuppressed().length); + Assertions.assertThat(expected.getSuppressed().length).isEqualTo(1); } } @@ -673,10 +674,10 @@ public final class URLConnectionTest { TlsVersion.TLS_1_3); // v1.2 on OpenJDK 8. RecordedRequest request1 = server.takeRequest(); - assertTrue(tlsVersions.contains(request1.getTlsVersion())); + Assertions.assertThat(tlsVersions.contains(request1.getTlsVersion())).isTrue(); RecordedRequest request2 = server.takeRequest(); - assertTrue(tlsVersions.contains(request2.getTlsVersion())); + Assertions.assertThat(tlsVersions.contains(request2.getTlsVersion())).isTrue(); } /** @@ -692,9 +693,10 @@ public final class URLConnectionTest { getResponse(newRequest("/foo")); fail(); } catch (SSLHandshakeException expected) { - assertTrue(expected.getCause() instanceof CertificateException); + boolean condition = expected.getCause() instanceof CertificateException; + Assertions.assertThat(condition).isTrue(); } - assertEquals(0, server.getRequestCount()); + Assertions.assertThat(server.getRequestCount()).isEqualTo(0); } @Test public void connectViaProxyUsingProxyArg() throws Exception { @@ -719,8 +721,9 @@ public final class URLConnectionTest { assertContent("this response comes via a proxy", response); RecordedRequest request = server.takeRequest(); - assertEquals("GET http://android.com/foo HTTP/1.1", request.getRequestLine()); - assertEquals("android.com", request.getHeader("Host")); + Assertions.assertThat(request.getRequestLine()).isEqualTo( + "GET http://android.com/foo HTTP/1.1"); + Assertions.assertThat(request.getHeader("Host")).isEqualTo("android.com"); } @Test public void contentDisagreesWithContentLengthHeaderBodyTooLong() throws IOException { @@ -793,7 +796,7 @@ public final class URLConnectionTest { .socketFactory(SocketFactory.getDefault()) .build(); Response response = getResponse(newRequest("/")); - assertEquals(200, response.code()); + Assertions.assertThat(response.code()).isEqualTo(200); } @Test public void connectHttpViaSocketFactory() throws Exception { @@ -866,7 +869,7 @@ public final class URLConnectionTest { assertContent("this response comes via HTTPS", call.execute()); RecordedRequest request = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", request.getRequestLine()); + Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); } @Test public void connectViaHttpProxyToHttpsUsingProxyArg() throws Exception { @@ -910,14 +913,15 @@ public final class URLConnectionTest { assertContent("this response comes via a secure proxy", call.execute()); RecordedRequest connect = server.takeRequest(); - assertEquals("Connect line failure on proxy", "CONNECT android.com:443 HTTP/1.1", - connect.getRequestLine()); - assertEquals("android.com:443", connect.getHeader("Host")); + Assertions.assertThat(connect.getRequestLine()).overridingErrorMessage( + "Connect line failure on proxy").isEqualTo("CONNECT android.com:443 HTTP/1.1"); + Assertions.assertThat(connect.getHeader("Host")).isEqualTo("android.com:443"); RecordedRequest get = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", get.getRequestLine()); - assertEquals("android.com", get.getHeader("Host")); - assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls); + Assertions.assertThat(get.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + Assertions.assertThat(get.getHeader("Host")).isEqualTo("android.com"); + Assertions.assertThat(hostnameVerifier.calls).isEqualTo( + Arrays.asList("verify android.com")); } /** Tolerate bad https proxy response when using HttpResponseCache. Android bug 6754912. */ @@ -949,8 +953,9 @@ public final class URLConnectionTest { assertContent("response", response); RecordedRequest connect = server.takeRequest(); - assertEquals("CONNECT android.com:443 HTTP/1.1", connect.getRequestLine()); - assertEquals("android.com:443", connect.getHeader("Host")); + Assertions.assertThat(connect.getRequestLine()).isEqualTo( + "CONNECT android.com:443 HTTP/1.1"); + Assertions.assertThat(connect.getHeader("Host")).isEqualTo("android.com:443"); } private void initResponseCache() { @@ -987,15 +992,16 @@ public final class URLConnectionTest { assertContent("encrypted response from the origin server", response); RecordedRequest connect = server.takeRequest(); - assertNull(connect.getHeader("Private")); - assertNull(connect.getHeader("Proxy-Authorization")); - assertEquals(Version.userAgent(), connect.getHeader("User-Agent")); - assertEquals("android.com:443", connect.getHeader("Host")); - assertEquals("Keep-Alive", connect.getHeader("Proxy-Connection")); + Assertions.assertThat(connect.getHeader("Private")).isNull(); + Assertions.assertThat(connect.getHeader("Proxy-Authorization")).isNull(); + Assertions.assertThat(connect.getHeader("User-Agent")).isEqualTo(Version.userAgent()); + Assertions.assertThat(connect.getHeader("Host")).isEqualTo("android.com:443"); + Assertions.assertThat(connect.getHeader("Proxy-Connection")).isEqualTo("Keep-Alive"); RecordedRequest get = server.takeRequest(); - assertEquals("Secret", get.getHeader("Private")); - assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls); + Assertions.assertThat(get.getHeader("Private")).isEqualTo("Secret"); + Assertions.assertThat(hostnameVerifier.calls).isEqualTo( + Arrays.asList("verify android.com")); } @Test public void proxyAuthenticateOnConnect() throws Exception { @@ -1024,17 +1030,19 @@ public final class URLConnectionTest { assertContent("A", response); RecordedRequest connect1 = server.takeRequest(); - assertEquals("CONNECT android.com:443 HTTP/1.1", connect1.getRequestLine()); - assertNull(connect1.getHeader("Proxy-Authorization")); + Assertions.assertThat(connect1.getRequestLine()).isEqualTo( + "CONNECT android.com:443 HTTP/1.1"); + Assertions.assertThat(connect1.getHeader("Proxy-Authorization")).isNull(); RecordedRequest connect2 = server.takeRequest(); - assertEquals("CONNECT android.com:443 HTTP/1.1", connect2.getRequestLine()); - assertEquals("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS, - connect2.getHeader("Proxy-Authorization")); + Assertions.assertThat(connect2.getRequestLine()).isEqualTo( + "CONNECT android.com:443 HTTP/1.1"); + Assertions.assertThat(connect2.getHeader("Proxy-Authorization")).isEqualTo( + ("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS)); RecordedRequest get = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", get.getRequestLine()); - assertNull(get.getHeader("Proxy-Authorization")); + Assertions.assertThat(get.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + Assertions.assertThat(get.getHeader("Proxy-Authorization")).isNull(); } // Don't disconnect after building a tunnel with CONNECT @@ -1103,7 +1111,7 @@ public final class URLConnectionTest { }).build(); HttpUrl url = HttpUrl.get("http://android.com/foo"); assertContent("response 1", getResponse(newRequest(url))); - assertEquals(407, getResponse(newRequest(url)).code()); + Assertions.assertThat(getResponse(newRequest(url)).code()).isEqualTo(407); } @Test public void disconnectedConnection() throws IOException { @@ -1114,7 +1122,7 @@ public final class URLConnectionTest { Call call = client.newCall(newRequest("/")); Response response = call.execute(); InputStream in = response.body().byteStream(); - assertEquals('A', (char) in.read()); + Assertions.assertThat((char) in.read()).isEqualTo('A'); call.cancel(); try { // Reading 'B' may succeed if it's buffered. @@ -1150,7 +1158,7 @@ public final class URLConnectionTest { call.execute(); fail("Connection should not be established"); } catch (IOException expected) { - assertEquals("Canceled", expected.getMessage()); + Assertions.assertThat(expected.getMessage()).isEqualTo("Canceled"); } } @@ -1169,7 +1177,8 @@ public final class URLConnectionTest { @SuppressWarnings("deprecation") @Test public void defaultRequestProperty() { URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A"); - assertNull(URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty")); + Assertions.assertThat( + (Object) URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty")).isNull(); } /** @@ -1208,15 +1217,17 @@ public final class URLConnectionTest { server.enqueue(response); InputStream in = getResponse(newRequest("/")).body().byteStream(); - assertFalse("This implementation claims to support mark().", in.markSupported()); + Assertions.assertThat(in.markSupported()).overridingErrorMessage( + "This implementation claims to support mark().").isFalse(); in.mark(5); - assertEquals("ABCDE", readAscii(in, 5)); + Assertions.assertThat(readAscii(in, 5)).isEqualTo("ABCDE"); try { in.reset(); fail(); } catch (IOException expected) { } - assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(in, Integer.MAX_VALUE)).isEqualTo( + "FGHIJKLMNOPQRSTUVWXYZ"); in.close(); assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", getResponse(newRequest("/"))); } @@ -1236,10 +1247,10 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); - assertEquals(401, response.code()); - assertEquals(401, response.code()); - assertEquals(401, response.code()); - assertEquals(1, server.getRequestCount()); + Assertions.assertThat(response.code()).isEqualTo(401); + Assertions.assertThat(response.code()).isEqualTo(401); + Assertions.assertThat(response.code()).isEqualTo(401); + Assertions.assertThat(server.getRequestCount()).isEqualTo(1); response.body().close(); } @@ -1304,12 +1315,13 @@ public final class URLConnectionTest { .addHeader("Content-Encoding: gzip")); Response response = getResponse(newRequest("/")); - assertEquals("ABCABCABC", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); - assertNull(response.header("Content-Encoding")); - assertEquals(-1L, response.body().contentLength()); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "ABCABCABC"); + Assertions.assertThat(response.header("Content-Encoding")).isNull(); + Assertions.assertThat(response.body().contentLength()).isEqualTo(-1L); RecordedRequest request = server.takeRequest(); - assertEquals("gzip", request.getHeader("Accept-Encoding")); + Assertions.assertThat(request.getHeader("Accept-Encoding")).isEqualTo("gzip"); } @Test public void clientConfiguredGzipContentEncoding() throws Exception { @@ -1323,11 +1335,12 @@ public final class URLConnectionTest { .header("Accept-Encoding", "gzip") .build()); InputStream gunzippedIn = new GZIPInputStream(response.body().byteStream()); - assertEquals("ABCDEFGHIJKLMNOPQRSTUVWXYZ", readAscii(gunzippedIn, Integer.MAX_VALUE)); - assertEquals(bodyBytes.size(), response.body().contentLength()); + Assertions.assertThat(readAscii(gunzippedIn, Integer.MAX_VALUE)).isEqualTo( + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + Assertions.assertThat(response.body().contentLength()).isEqualTo(bodyBytes.size()); RecordedRequest request = server.takeRequest(); - assertEquals("gzip", request.getHeader("Accept-Encoding")); + Assertions.assertThat(request.getHeader("Accept-Encoding")).isEqualTo("gzip"); } @Test public void gzipAndConnectionReuseWithFixedLength() throws Exception { @@ -1355,10 +1368,11 @@ public final class URLConnectionTest { .url(server.url("/")) .header("Accept-Encoding", "custom") .build()); - assertEquals("ABCDE", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "ABCDE"); RecordedRequest request = server.takeRequest(); - assertEquals("custom", request.getHeader("Accept-Encoding")); + Assertions.assertThat(request.getHeader("Accept-Encoding")).isEqualTo("custom"); } /** @@ -1391,14 +1405,16 @@ public final class URLConnectionTest { .url(server.url("/")) .build()); InputStream gunzippedIn = new GZIPInputStream(response1.body().byteStream()); - assertEquals("one (gzipped)", readAscii(gunzippedIn, Integer.MAX_VALUE)); - assertEquals(0, server.takeRequest().getSequenceNumber()); + Assertions.assertThat(readAscii(gunzippedIn, Integer.MAX_VALUE)).isEqualTo( + "one (gzipped)"); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); Response response2 = getResponse(new Request.Builder() .url(server.url("/")) .build()); - assertEquals("two (identity)", readAscii(response2.body().byteStream(), Integer.MAX_VALUE)); - assertEquals(1, server.takeRequest().getSequenceNumber()); + Assertions.assertThat(readAscii(response2.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "two (identity)"); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void transparentGzipWorksAfterExceptionRecovery() throws Exception { @@ -1418,8 +1434,9 @@ public final class URLConnectionTest { // This connection will need to be recovered. When it is, transparent gzip should still work! assertContent("b", getResponse(newRequest("/"))); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals(0, server.takeRequest().getSequenceNumber()); // Connection is not pooled. + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + // Connection is not pooled. + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } @Test public void endOfStreamResponseIsNotPooled() throws Exception { @@ -1431,7 +1448,7 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); assertContent("{}", response); - assertEquals(0, client.connectionPool().idleConnectionCount()); + Assertions.assertThat(client.connectionPool().idleConnectionCount()).isEqualTo(0); } @Test public void earlyDisconnectDoesntHarmPoolingWithChunkedEncoding() throws Exception { @@ -1454,19 +1471,20 @@ public final class URLConnectionTest { Call call1 = client.newCall(newRequest("/")); Response response1 = call1.execute(); InputStream in1 = response1.body().byteStream(); - assertEquals("ABCDE", readAscii(in1, 5)); + Assertions.assertThat(readAscii(in1, 5)).isEqualTo("ABCDE"); in1.close(); call1.cancel(); Call call2 = client.newCall(newRequest("/")); Response response2 = call2.execute(); InputStream in2 = response2.body().byteStream(); - assertEquals("LMNOP", readAscii(in2, 5)); + Assertions.assertThat(readAscii(in2, 5)).isEqualTo("LMNOP"); in2.close(); call2.cancel(); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection is pooled! + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + // Connection is pooled! + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void streamDiscardingIsTimely() throws Exception { @@ -1487,13 +1505,15 @@ public final class URLConnectionTest { // If we're working correctly, this should be greater than 100ms, but less than double that. // Previously we had a bug where we would download the entire response body as long as no // individual read took longer than 100ms. - assertTrue(Util.format("Time to close: %sms", elapsedMillis), elapsedMillis < 500); + Assertions.assertThat(elapsedMillis < 500).overridingErrorMessage( + Util.format("Time to close: %sms", elapsedMillis)).isTrue(); // Do another request to confirm that the discarded connection was not pooled. assertContent("A", getResponse(newRequest("/"))); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals(0, server.takeRequest().getSequenceNumber()); // Connection is not pooled. + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + // Connection is not pooled. + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } @Test public void setChunkedStreamingMode() throws Exception { @@ -1503,11 +1523,12 @@ public final class URLConnectionTest { .url(server.url("/")) .post(TransferKind.CHUNKED.newRequestBody("ABCDEFGHIJKLMNOPQ")) .build()); - assertEquals(200, response.code()); + Assertions.assertThat(response.code()).isEqualTo(200); RecordedRequest request = server.takeRequest(); - assertEquals("ABCDEFGHIJKLMNOPQ", request.getBody().readUtf8()); - assertEquals(Arrays.asList("ABCDEFGHIJKLMNOPQ".length()), request.getChunkSizes()); + Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("ABCDEFGHIJKLMNOPQ"); + Assertions.assertThat(request.getChunkSizes()).isEqualTo( + Arrays.asList("ABCDEFGHIJKLMNOPQ".length())); } @Test public void authenticateWithFixedLengthStreaming() throws Exception { @@ -1535,13 +1556,13 @@ public final class URLConnectionTest { .post(streamingMode.newRequestBody("ABCD")) .build(); Response response = getResponse(request); - assertEquals(200, response.code()); + Assertions.assertThat(response.code()).isEqualTo(200); assertContent("Authenticated!", response); // No authorization header for the request... RecordedRequest recordedRequest = server.takeRequest(); - assertNull(recordedRequest.getHeader("Authorization")); - assertEquals("ABCD", recordedRequest.getBody().readUtf8()); + Assertions.assertThat(recordedRequest.getHeader("Authorization")).isNull(); + Assertions.assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("ABCD"); } @Test public void postBodyRetransmittedAfterAuthorizationFail() throws Exception { @@ -1577,28 +1598,29 @@ public final class URLConnectionTest { .url(server.url("/")) .post(RequestBody.create(null, body)) .build()); - assertEquals(200, response.code()); + Assertions.assertThat(response.code()).isEqualTo(200); response.body().byteStream().close(); RecordedRequest recordedRequest1 = server.takeRequest(); - assertEquals("POST", recordedRequest1.getMethod()); - assertEquals(body, recordedRequest1.getBody().readUtf8()); - assertNull(recordedRequest1.getHeader("Authorization")); + Assertions.assertThat(recordedRequest1.getMethod()).isEqualTo("POST"); + Assertions.assertThat(recordedRequest1.getBody().readUtf8()).isEqualTo(body); + Assertions.assertThat(recordedRequest1.getHeader("Authorization")).isNull(); RecordedRequest recordedRequest2 = server.takeRequest(); - assertEquals("POST", recordedRequest2.getMethod()); - assertEquals(body, recordedRequest2.getBody().readUtf8()); - assertEquals(credential, recordedRequest2.getHeader("Authorization")); + Assertions.assertThat(recordedRequest2.getMethod()).isEqualTo("POST"); + Assertions.assertThat(recordedRequest2.getBody().readUtf8()).isEqualTo(body); + Assertions.assertThat(recordedRequest2.getHeader("Authorization")).isEqualTo( + credential); } @Test public void nonStandardAuthenticationScheme() throws Exception { List calls = authCallsForHeader("WWW-Authenticate: Foo"); - assertEquals(Collections.emptyList(), calls); + Assertions.assertThat(calls).isEqualTo(Collections.emptyList()); } @Test public void nonStandardAuthenticationSchemeWithRealm() throws Exception { List calls = authCallsForHeader("WWW-Authenticate: Foo realm=\"Bar\""); - assertEquals(0, calls.size()); + Assertions.assertThat(calls.size()).isEqualTo(0); } // Digest auth is currently unsupported. Test that digest requests should fail reasonably. @@ -1608,37 +1630,43 @@ public final class URLConnectionTest { + "realm=\"testrealm@host.com\", qop=\"auth,auth-int\", " + "nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\", " + "opaque=\"5ccc069c403ebaf9f0171e9517f40e41\""); - assertEquals(0, calls.size()); + Assertions.assertThat(calls.size()).isEqualTo(0); } @Test public void allAttributesSetInServerAuthenticationCallbacks() throws Exception { List calls = authCallsForHeader("WWW-Authenticate: Basic realm=\"Bar\""); - assertEquals(1, calls.size()); + Assertions.assertThat(calls.size()).isEqualTo(1); URL url = server.url("/").url(); String call = calls.get(0); - assertTrue(call, call.contains("host=" + url.getHost())); - assertTrue(call, call.contains("port=" + url.getPort())); - assertTrue(call, call.contains("site=" + url.getHost())); - assertTrue(call, call.contains("url=" + url)); - assertTrue(call, call.contains("type=" + Authenticator.RequestorType.SERVER)); - assertTrue(call, call.contains("prompt=Bar")); - assertTrue(call, call.contains("protocol=http")); - assertTrue(call, call.toLowerCase(US).contains("scheme=basic")); // lowercase for the RI. + Assertions.assertThat(call.contains("host=" + url.getHost())).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("port=" + url.getPort())).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("site=" + url.getHost())).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("url=" + url)).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("type=" + Authenticator.RequestorType.SERVER)).overridingErrorMessage( + call).isTrue(); + Assertions.assertThat(call.contains("prompt=Bar")).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("protocol=http")).overridingErrorMessage(call).isTrue(); + // lowercase for the RI. + Assertions.assertThat(call.toLowerCase(US).contains("scheme=basic")).overridingErrorMessage( + call).isTrue(); } @Test public void allAttributesSetInProxyAuthenticationCallbacks() throws Exception { List calls = authCallsForHeader("Proxy-Authenticate: Basic realm=\"Bar\""); - assertEquals(1, calls.size()); + Assertions.assertThat(calls.size()).isEqualTo(1); URL url = server.url("/").url(); String call = calls.get(0); - assertTrue(call, call.contains("host=" + url.getHost())); - assertTrue(call, call.contains("port=" + url.getPort())); - assertTrue(call, call.contains("site=" + url.getHost())); - assertTrue(call, call.contains("url=http://android.com")); - assertTrue(call, call.contains("type=" + Authenticator.RequestorType.PROXY)); - assertTrue(call, call.contains("prompt=Bar")); - assertTrue(call, call.contains("protocol=http")); - assertTrue(call, call.toLowerCase(US).contains("scheme=basic")); // lowercase for the RI. + Assertions.assertThat(call.contains("host=" + url.getHost())).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("port=" + url.getPort())).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("site=" + url.getHost())).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("url=http://android.com")).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("type=" + Authenticator.RequestorType.PROXY)).overridingErrorMessage( + call).isTrue(); + Assertions.assertThat(call.contains("prompt=Bar")).overridingErrorMessage(call).isTrue(); + Assertions.assertThat(call.contains("protocol=http")).overridingErrorMessage(call).isTrue(); + // lowercase for the RI. + Assertions.assertThat(call.toLowerCase(US).contains("scheme=basic")).overridingErrorMessage( + call).isTrue(); } private List authCallsForHeader(String authHeader) throws IOException { @@ -1664,7 +1692,7 @@ public final class URLConnectionTest { .build(); response = getResponse(newRequest("/")); } - assertEquals(responseCode, response.code()); + Assertions.assertThat(response.code()).isEqualTo(responseCode); response.body().byteStream().close(); return authenticator.calls; } @@ -1694,7 +1722,7 @@ public final class URLConnectionTest { .url(server.url("/")) .method(requestMethod, RequestBody.create(null, "abc")) .build(); - assertEquals(requestMethod, request.method()); + Assertions.assertThat(request.method()).isEqualTo(requestMethod); } private void assertMethodForbidsRequestBody(String requestMethod) { @@ -1712,7 +1740,7 @@ public final class URLConnectionTest { .url(server.url("/")) .method(requestMethod, null) .build(); - assertEquals(requestMethod, request.method()); + Assertions.assertThat(request.method()).isEqualTo(requestMethod); } private void assertMethodForbidsNoRequestBody(String requestMethod) { @@ -1739,9 +1767,9 @@ public final class URLConnectionTest { .url(server.url("/")) .method(requestMethod, null) .build()); - assertEquals(200, response.code()); + Assertions.assertThat(response.code()).isEqualTo(200); RecordedRequest recordedRequest = server.takeRequest(); - assertEquals(requestMethod, recordedRequest.getMethod()); + Assertions.assertThat(recordedRequest.getMethod()).isEqualTo(requestMethod); } @Test public void shoutcast() throws Exception { @@ -1764,8 +1792,8 @@ public final class URLConnectionTest { .addHeader("icy-metaint:16000") .setBody("mp3 data")); Response response = getResponse(newRequest("/")); - assertEquals(200, response.code()); - assertEquals("OK", response.message()); + Assertions.assertThat(response.code()).isEqualTo(200); + Assertions.assertThat(response.message()).isEqualTo("OK"); assertContent("mp3 data", response); } @@ -1795,16 +1823,18 @@ public final class URLConnectionTest { .url(server.url("/")) .post(streamingMode.newRequestBody("ABCD")) .build()); - assertEquals("Success!", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Success!"); RecordedRequest request = server.takeRequest(); - assertEquals("POST / HTTP/1.1", request.getRequestLine()); + Assertions.assertThat(request.getRequestLine()).isEqualTo("POST / HTTP/1.1"); if (streamingMode == TransferKind.FIXED_LENGTH) { - assertEquals(Collections.emptyList(), request.getChunkSizes()); + Assertions.assertThat(request.getChunkSizes()).isEqualTo( + Collections.emptyList()); } else if (streamingMode == TransferKind.CHUNKED) { - assertEquals(Arrays.asList(4), request.getChunkSizes()); + Assertions.assertThat(request.getChunkSizes()).isEqualTo(Arrays.asList(4)); } - assertEquals("ABCD", request.getBody().readUtf8()); + Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("ABCD"); } @Test public void authenticateWithPost() throws Exception { @@ -1828,19 +1858,20 @@ public final class URLConnectionTest { .url(server.url("/")) .post(RequestBody.create(null, "ABCD")) .build()); - assertEquals("Successful auth!", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Successful auth!"); // No authorization header for the first request... RecordedRequest request = server.takeRequest(); - assertNull(request.getHeader("Authorization")); + Assertions.assertThat(request.getHeader("Authorization")).isNull(); // ...but the three requests that follow include an authorization header. for (int i = 0; i < 3; i++) { request = server.takeRequest(); - assertEquals("POST / HTTP/1.1", request.getRequestLine()); - assertEquals("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS, - request.getHeader("Authorization")); - assertEquals("ABCD", request.getBody().readUtf8()); + Assertions.assertThat(request.getRequestLine()).isEqualTo("POST / HTTP/1.1"); + Assertions.assertThat(request.getHeader("Authorization")).isEqualTo( + ("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS)); + Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("ABCD"); } } @@ -1862,18 +1893,19 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - assertEquals("Successful auth!", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Successful auth!"); // No authorization header for the first request... RecordedRequest request = server.takeRequest(); - assertNull(request.getHeader("Authorization")); + Assertions.assertThat(request.getHeader("Authorization")).isNull(); // ...but the three requests that follow requests include an authorization header. for (int i = 0; i < 3; i++) { request = server.takeRequest(); - assertEquals("GET / HTTP/1.1", request.getRequestLine()); - assertEquals("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS, - request.getHeader("Authorization")); + Assertions.assertThat(request.getRequestLine()).isEqualTo("GET / HTTP/1.1"); + Assertions.assertThat(request.getHeader("Authorization")).isEqualTo( + ("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS)); } } @@ -1895,19 +1927,22 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - assertEquals("Successful auth!", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Successful auth!"); // No authorization header for the first request... RecordedRequest request1 = server.takeRequest(); - assertNull(request1.getHeader("Authorization")); + Assertions.assertThat(request1.getHeader("Authorization")).isNull(); // UTF-8 encoding for the first credential. RecordedRequest request2 = server.takeRequest(); - assertEquals("Basic dXNlcm5hbWU6bcO2dG9yaGVhZA==", request2.getHeader("Authorization")); + Assertions.assertThat(request2.getHeader("Authorization")).isEqualTo( + "Basic dXNlcm5hbWU6bcO2dG9yaGVhZA=="); // ISO-8859-1 encoding for the second credential. RecordedRequest request3 = server.takeRequest(); - assertEquals("Basic dXNlcm5hbWU6bfZ0b3JoZWFk", request3.getHeader("Authorization")); + Assertions.assertThat(request3.getHeader("Authorization")).isEqualTo( + "Basic dXNlcm5hbWU6bfZ0b3JoZWFk"); } /** https://code.google.com/p/android/issues/detail?id=74026 */ @@ -1931,18 +1966,19 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - assertEquals("Successful auth!", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Successful auth!"); // no authorization header for the first request... RecordedRequest request = server.takeRequest(); - assertNull(request.getHeader("Authorization")); + Assertions.assertThat(request.getHeader("Authorization")).isNull(); // ...but the three requests that follow requests include an authorization header for (int i = 0; i < 3; i++) { request = server.takeRequest(); - assertEquals("GET / HTTP/1.1", request.getRequestLine()); - assertEquals("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS, - request.getHeader("Authorization")); + Assertions.assertThat(request.getRequestLine()).isEqualTo("GET / HTTP/1.1"); + Assertions.assertThat(request.getHeader("Authorization")).isEqualTo( + ("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS)); } } @@ -1960,7 +1996,8 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - assertEquals("Successful auth!", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Successful auth!"); } @Test public void redirectedWithChunkedEncoding() throws Exception { @@ -1985,15 +2022,16 @@ public final class URLConnectionTest { .setBody("This is the new location!")); Response response = getResponse(newRequest("/")); - assertEquals("This is the new location!", - readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "This is the new location!"); RecordedRequest first = server.takeRequest(); - assertEquals("GET / HTTP/1.1", first.getRequestLine()); + Assertions.assertThat(first.getRequestLine()).isEqualTo("GET / HTTP/1.1"); RecordedRequest retry = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", retry.getRequestLine()); + Assertions.assertThat(retry.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); if (reuse) { - assertEquals("Expected connection reuse", 1, retry.getSequenceNumber()); + Assertions.assertThat(retry.getSequenceNumber()).overridingErrorMessage( + "Expected connection reuse").isEqualTo(1); } } @@ -2012,14 +2050,15 @@ public final class URLConnectionTest { .hostnameVerifier(new RecordingHostnameVerifier()) .build(); Response response = getResponse(newRequest("/")); - assertEquals("This is the new location!", - readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "This is the new location!"); RecordedRequest first = server.takeRequest(); - assertEquals("GET / HTTP/1.1", first.getRequestLine()); + Assertions.assertThat(first.getRequestLine()).isEqualTo("GET / HTTP/1.1"); RecordedRequest retry = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", retry.getRequestLine()); - assertEquals("Expected connection reuse", 1, retry.getSequenceNumber()); + Assertions.assertThat(retry.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + Assertions.assertThat(retry.getSequenceNumber()).overridingErrorMessage( + "Expected connection reuse").isEqualTo(1); } @Test public void notRedirectedFromHttpsToHttp() throws Exception { @@ -2036,8 +2075,8 @@ public final class URLConnectionTest { .hostnameVerifier(new RecordingHostnameVerifier()) .build(); Response response = getResponse(newRequest("/")); - assertEquals("This page has moved!", - readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "This page has moved!"); } @Test public void notRedirectedFromHttpToHttps() throws Exception { @@ -2050,8 +2089,8 @@ public final class URLConnectionTest { .followSslRedirects(false) .build(); Response response = getResponse(newRequest("/")); - assertEquals("This page has moved!", - readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "This page has moved!"); } @Test public void redirectedFromHttpsToHttpFollowingProtocolRedirects() throws Exception { @@ -2072,7 +2111,7 @@ public final class URLConnectionTest { .build(); Response response = getResponse(newRequest("/")); assertContent("This is insecure HTTP!", response); - assertNull(response.handshake()); + Assertions.assertThat(response.handshake()).isNull(); } @Test public void redirectedFromHttpToHttpsFollowingProtocolRedirects() throws Exception { @@ -2129,7 +2168,7 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); assertContent("This is the 2nd server!", response); - assertEquals(server2.url("/"), response.request().url()); + Assertions.assertThat(response.request().url()).isEqualTo(server2.url("/")); // make sure the first server was careful to recycle the connection assertContent("This is the first server again!", getResponse(newRequest(server.url("/")))); @@ -2137,10 +2176,12 @@ public final class URLConnectionTest { String server1Host = server.getHostName() + ":" + server.getPort(); String server2Host = server2.getHostName() + ":" + server2.getPort(); - assertEquals(server1Host, server.takeRequest().getHeader("Host")); - assertEquals(server2Host, server2.takeRequest().getHeader("Host")); - assertEquals("Expected connection reuse", 1, server.takeRequest().getSequenceNumber()); - assertEquals("Expected connection reuse", 1, server2.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getHeader("Host")).isEqualTo(server1Host); + Assertions.assertThat(server2.takeRequest().getHeader("Host")).isEqualTo(server2Host); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( + "Expected connection reuse").isEqualTo(1); + Assertions.assertThat(server2.takeRequest().getSequenceNumber()).overridingErrorMessage( + "Expected connection reuse").isEqualTo(1); } @Test public void redirectWithProxySelector() throws Exception { @@ -2171,8 +2212,8 @@ public final class URLConnectionTest { assertContent("This is the 2nd server!", getResponse(newRequest("/a"))); - assertEquals(Arrays.asList(server.url("/").url().toURI(), server2.url("/").url().toURI()), - proxySelectionRequests); + Assertions.assertThat(proxySelectionRequests).isEqualTo( + Arrays.asList(server.url("/").url().toURI(), server2.url("/").url().toURI())); } @Test public void redirectWithAuthentication() throws Exception { @@ -2191,8 +2232,8 @@ public final class URLConnectionTest { assertContent("Page 2", getResponse(newRequest("/a"))); RecordedRequest redirectRequest = server2.takeRequest(); - assertNull(redirectRequest.getHeader("Authorization")); - assertEquals("/b", redirectRequest.getPath()); + Assertions.assertThat(redirectRequest.getHeader("Authorization")).isNull(); + Assertions.assertThat(redirectRequest.getPath()).isEqualTo("/b"); } @Test public void response300MultipleChoiceWithPost() throws Exception { @@ -2233,14 +2274,15 @@ public final class URLConnectionTest { .url(server.url("/page1")) .post(transferKind.newRequestBody("ABCD")) .build()); - assertEquals("Page 2", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Page 2"); RecordedRequest page1 = server.takeRequest(); - assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine()); - assertEquals("ABCD", page1.getBody().readUtf8()); + Assertions.assertThat(page1.getRequestLine()).isEqualTo("POST /page1 HTTP/1.1"); + Assertions.assertThat(page1.getBody().readUtf8()).isEqualTo("ABCD"); RecordedRequest page2 = server.takeRequest(); - assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine()); + Assertions.assertThat(page2.getRequestLine()).isEqualTo("GET /page2 HTTP/1.1"); } @Test public void redirectedPostStripsRequestBodyHeaders() throws Exception { @@ -2255,15 +2297,17 @@ public final class URLConnectionTest { .post(RequestBody.create(MediaType.get("text/plain; charset=utf-8"), "ABCD")) .header("Transfer-Encoding", "identity") .build()); - assertEquals("Page 2", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Page 2"); - assertEquals("POST /page1 HTTP/1.1", server.takeRequest().getRequestLine()); + Assertions.assertThat(server.takeRequest().getRequestLine()).isEqualTo( + "POST /page1 HTTP/1.1"); RecordedRequest page2 = server.takeRequest(); - assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine()); - assertNull(page2.getHeader("Content-Length")); - assertNull(page2.getHeader("Content-Type")); - assertNull(page2.getHeader("Transfer-Encoding")); + Assertions.assertThat(page2.getRequestLine()).isEqualTo("GET /page2 HTTP/1.1"); + Assertions.assertThat(page2.getHeader("Content-Length")).isNull(); + Assertions.assertThat(page2.getHeader("Content-Type")).isNull(); + Assertions.assertThat(page2.getHeader("Transfer-Encoding")).isNull(); } @Test public void response305UseProxy() throws Exception { @@ -2276,12 +2320,12 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/foo")); // Fails on the RI, which gets "Proxy Response". - assertEquals("This page has moved!", - readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "This page has moved!"); RecordedRequest page1 = server.takeRequest(); - assertEquals("GET /foo HTTP/1.1", page1.getRequestLine()); - assertEquals(1, server.getRequestCount()); + Assertions.assertThat(page1.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + Assertions.assertThat(server.getRequestCount()).isEqualTo(1); } @Test public void response307WithGet() throws Exception { @@ -2339,26 +2383,26 @@ public final class URLConnectionTest { String responseString = readAscii(response.body().byteStream(), Integer.MAX_VALUE); RecordedRequest page1 = server.takeRequest(); - assertEquals(method + " /page1 HTTP/1.1", page1.getRequestLine()); + Assertions.assertThat(page1.getRequestLine()).isEqualTo((method + " /page1 HTTP/1.1")); if (method.equals("GET")) { - assertEquals("Page 2", responseString); + Assertions.assertThat(responseString).isEqualTo("Page 2"); } else if (method.equals("HEAD")) { - assertEquals("", responseString); + Assertions.assertThat(responseString).isEqualTo(""); } else { // Methods other than GET/HEAD shouldn't follow the redirect. if (method.equals("POST")) { - assertEquals("ABCD", page1.getBody().readUtf8()); + Assertions.assertThat(page1.getBody().readUtf8()).isEqualTo("ABCD"); } - assertEquals(1, server.getRequestCount()); - assertEquals("This page has moved!", responseString); + Assertions.assertThat(server.getRequestCount()).isEqualTo(1); + Assertions.assertThat(responseString).isEqualTo("This page has moved!"); return; } // GET/HEAD requests should have followed the redirect with the same method. - assertEquals(2, server.getRequestCount()); + Assertions.assertThat(server.getRequestCount()).isEqualTo(2); RecordedRequest page2 = server.takeRequest(); - assertEquals(method + " /page2 HTTP/1.1", page2.getRequestLine()); + Assertions.assertThat(page2.getRequestLine()).isEqualTo((method + " /page2 HTTP/1.1")); } @Test public void follow20Redirects() throws Exception { @@ -2373,7 +2417,7 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/0")); assertContent("Success!", response); - assertEquals(server.url("/20"), response.request().url()); + Assertions.assertThat(response.request().url()).isEqualTo(server.url("/20")); } @Test public void doesNotFollow21Redirects() throws Exception { @@ -2388,7 +2432,8 @@ public final class URLConnectionTest { getResponse(newRequest("/0")); fail(); } catch (ProtocolException expected) { - assertEquals("Too many follow-up requests: 21", expected.getMessage()); + Assertions.assertThat(expected.getMessage()).isEqualTo( + "Too many follow-up requests: 21"); } } @@ -2415,8 +2460,10 @@ public final class URLConnectionTest { assertContent("DEF", getResponse(newRequest("/"))); assertContent("GHI", getResponse(newRequest("/"))); - assertEquals(Arrays.asList("verify " + server.getHostName()), hostnameVerifier.calls); - assertEquals(Arrays.asList("checkServerTrusted [CN=localhost 1]"), trustManager.calls); + Assertions.assertThat(hostnameVerifier.calls).isEqualTo( + Arrays.asList("verify " + server.getHostName())); + Assertions.assertThat(trustManager.calls).isEqualTo( + Arrays.asList("checkServerTrusted [CN=localhost 1]")); } @Test public void getClientRequestTimeout() throws Exception { @@ -2424,8 +2471,9 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); - assertEquals(200, response.code()); - assertEquals("Body", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(response.code()).isEqualTo(200); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Body"); } private void enqueueClientRequestTimeoutResponses() { @@ -2446,14 +2494,15 @@ public final class URLConnectionTest { .post(RequestBody.create(null, "Hello")) .build()); - assertEquals(200, response.code()); - assertEquals("Body", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(response.code()).isEqualTo(200); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "Body"); RecordedRequest request1 = server.takeRequest(); - assertEquals("Hello", request1.getBody().readUtf8()); + Assertions.assertThat(request1.getBody().readUtf8()).isEqualTo("Hello"); RecordedRequest request2 = server.takeRequest(); - assertEquals("Hello", request2.getBody().readUtf8()); + Assertions.assertThat(request2.getBody().readUtf8()).isEqualTo("Hello"); } @Test public void streamedBodyWithClientRequestTimeout() throws Exception { @@ -2464,10 +2513,10 @@ public final class URLConnectionTest { .post(TransferKind.CHUNKED.newRequestBody("Hello")) .build()); - assertEquals(200, response.code()); + Assertions.assertThat(response.code()).isEqualTo(200); assertContent("Body", response); response.close(); - assertEquals(2, server.getRequestCount()); + Assertions.assertThat(server.getRequestCount()).isEqualTo(2); } @Test public void readTimeouts() throws IOException { @@ -2484,9 +2533,9 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); BufferedSource in = response.body().source(); in.timeout().timeout(1000, MILLISECONDS); - assertEquals('A', in.readByte()); - assertEquals('B', in.readByte()); - assertEquals('C', in.readByte()); + Assertions.assertThat(in.readByte()).isEqualTo((byte) 'A'); + Assertions.assertThat(in.readByte()).isEqualTo((byte) 'B'); + Assertions.assertThat(in.readByte()).isEqualTo((byte) 'C'); try { in.readByte(); // If Content-Length was accurate, this would return -1 immediately. fail(); @@ -2553,10 +2602,10 @@ public final class URLConnectionTest { .header("Transfer-encoding", "chunked") .post(TransferKind.CHUNKED.newRequestBody("ABC")) .build()); - assertEquals(200, response.code()); + Assertions.assertThat(response.code()).isEqualTo(200); RecordedRequest request = server.takeRequest(); - assertEquals("ABC", request.getBody().readUtf8()); + Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("ABC"); } @Test public void connectionCloseInRequest() throws Exception { @@ -2567,14 +2616,15 @@ public final class URLConnectionTest { .url(server.url("/")) .header("Connection", "close") .build()); - assertEquals(200, a.code()); + Assertions.assertThat(a.code()).isEqualTo(200); Response b = getResponse(newRequest("/")); - assertEquals(200, b.code()); + Assertions.assertThat(b.code()).isEqualTo(200); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals("When connection: close is used, each request should get its own connection", 0, - server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( + "When connection: close is used, each request should get its own connection").isEqualTo( + (long) 0); } @Test public void connectionCloseInResponse() throws Exception { @@ -2583,14 +2633,15 @@ public final class URLConnectionTest { server.enqueue(new MockResponse()); Response a = getResponse(newRequest("/")); - assertEquals(200, a.code()); + Assertions.assertThat(a.code()).isEqualTo(200); Response b = getResponse(newRequest("/")); - assertEquals(200, b.code()); + Assertions.assertThat(b.code()).isEqualTo(200); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals("When connection: close is used, each request should get its own connection", 0, - server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( + "When connection: close is used, each request should get its own connection").isEqualTo( + (long) 0); } @Test public void connectionCloseWithRedirect() throws Exception { @@ -2602,12 +2653,13 @@ public final class URLConnectionTest { .setBody("This is the new location!")); Response response = getResponse(newRequest("/")); - assertEquals("This is the new location!", - readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "This is the new location!"); - assertEquals(0, server.takeRequest().getSequenceNumber()); - assertEquals("When connection: close is used, each request should get its own connection", 0, - server.takeRequest().getSequenceNumber()); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + Assertions.assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( + "When connection: close is used, each request should get its own connection").isEqualTo( + (long) 0); } /** @@ -2624,8 +2676,8 @@ public final class URLConnectionTest { assertContent("This is the new page!", getResponse(newRequest("/"))); - 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 responseCodeDisagreesWithHeaders() { @@ -2637,7 +2689,8 @@ public final class URLConnectionTest { getResponse(newRequest("/")); fail(); } catch (IOException expected) { - assertEquals("HTTP 204 had non-zero Content-Length: 25", expected.getMessage()); + Assertions.assertThat(expected.getMessage()).isEqualTo( + "HTTP 204 had non-zero Content-Length: 25"); } } @@ -2649,9 +2702,9 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); InputStream in = response.body().byteStream(); - assertEquals(254, in.read()); - assertEquals(255, in.read()); - assertEquals(-1, in.read()); + Assertions.assertThat(in.read()).isEqualTo(254); + Assertions.assertThat(in.read()).isEqualTo(255); + Assertions.assertThat(in.read()).isEqualTo(-1); } @Test public void flushAfterStreamTransmittedWithChunkedEncoding() throws IOException { @@ -2686,7 +2739,8 @@ public final class URLConnectionTest { }) .build()); - assertEquals("abc", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "abc"); try { sinkReference.get().flush(); @@ -2737,7 +2791,8 @@ public final class URLConnectionTest { Response connection1 = getResponse(newRequest("/")); BufferedSource source1 = connection1.body().source(); source1.timeout().timeout(100, TimeUnit.MILLISECONDS); - assertEquals("ABC", readAscii(source1.inputStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(source1.inputStream(), Integer.MAX_VALUE)).isEqualTo( + "ABC"); server.shutdown(); try { getResponse(newRequest("/")); @@ -2756,9 +2811,10 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); InputStream in = response.body().byteStream(); - assertEquals("ABC", readAscii(in, 3)); - assertEquals(-1, in.read()); - assertEquals(-1, in.read()); // throws IOException in Gingerbread. + Assertions.assertThat(readAscii(in, 3)).isEqualTo("ABC"); + Assertions.assertThat(in.read()).isEqualTo(-1); + // throws IOException in Gingerbread. + Assertions.assertThat(in.read()).isEqualTo(-1); } @Test public void getOutputStreamOnGetFails() { @@ -2779,9 +2835,10 @@ public final class URLConnectionTest { .url(server.url("/")) .post(RequestBody.create(null, "ABC")) .build()); - assertEquals("A", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "A"); RecordedRequest request = server.takeRequest(); - assertEquals("3", request.getHeader("Content-Length")); + Assertions.assertThat(request.getHeader("Content-Length")).isEqualTo("3"); response.body().close(); } @@ -2789,7 +2846,7 @@ public final class URLConnectionTest { server.enqueue(new MockResponse() .setBody("ABC")); Response response = getResponse(newRequest("/")); - assertEquals(3L, response.body().contentLength()); + Assertions.assertThat(response.body().contentLength()).isEqualTo(3L); response.body().close(); } @@ -2798,7 +2855,8 @@ public final class URLConnectionTest { .addHeader("Content-Type: text/plain") .setBody("ABC")); Response response = getResponse(newRequest("/")); - assertEquals(MediaType.get("text/plain"), response.body().contentType()); + Assertions.assertThat(response.body().contentType()).isEqualTo( + MediaType.get("text/plain")); response.body().close(); } @@ -2807,7 +2865,7 @@ public final class URLConnectionTest { .addHeader("Content-Encoding: identity") .setBody("ABC")); Response response = getResponse(newRequest("/")); - assertEquals("identity", response.header("Content-Encoding")); + Assertions.assertThat(response.header("Content-Encoding")).isEqualTo("identity"); response.body().close(); } @@ -2817,9 +2875,10 @@ public final class URLConnectionTest { HttpUrl url = server.url("?query"); Response response = getResponse(newRequest(url)); - assertEquals("A", readAscii(response.body().byteStream(), Integer.MAX_VALUE)); + Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + "A"); RecordedRequest request = server.takeRequest(); - assertEquals("GET /?query HTTP/1.1", request.getRequestLine()); + Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /?query HTTP/1.1"); } @Test public void doOutputForMethodThatDoesntSupportOutput() { @@ -2854,11 +2913,11 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); InputStream in = response.body().byteStream(); for (int i = 0; i < body.length(); i++) { - assertTrue(in.available() >= 0); - assertEquals(body.charAt(i), in.read()); + Assertions.assertThat(in.available() >= 0).isTrue(); + Assertions.assertThat(in.read()).isEqualTo(body.charAt(i)); } - assertEquals(0, in.available()); - assertEquals(-1, in.read()); + Assertions.assertThat(in.available()).isEqualTo(0); + Assertions.assertThat(in.read()).isEqualTo(-1); } @Test public void postFailsWithBufferedRequestForSmallRequest() throws Exception { @@ -2915,17 +2974,17 @@ public final class URLConnectionTest { break; } catch (IOException socketException) { // If there's a socket exception, this must have a streamed request body. - assertEquals(0, j); - assertTrue(transferKind == TransferKind.CHUNKED - || transferKind == TransferKind.FIXED_LENGTH); + Assertions.assertThat(j).isEqualTo(0); + Assertions.assertThat(transferKind == TransferKind.CHUNKED + || transferKind == TransferKind.FIXED_LENGTH).isTrue(); } } RecordedRequest requestA = server.takeRequest(); - assertEquals("/a", requestA.getPath()); + Assertions.assertThat(requestA.getPath()).isEqualTo("/a"); RecordedRequest requestB = server.takeRequest(); - assertEquals("/b", requestB.getPath()); - assertEquals(requestBody, requestB.getBody().readUtf8()); + Assertions.assertThat(requestB.getPath()).isEqualTo("/b"); + Assertions.assertThat(requestB.getBody().readUtf8()).isEqualTo(requestBody); } @Test public void postBodyRetransmittedOnFailureRecovery() throws Exception { @@ -2946,15 +3005,15 @@ public final class URLConnectionTest { assertContent("def", post); RecordedRequest get = server.takeRequest(); - assertEquals(0, get.getSequenceNumber()); + Assertions.assertThat(get.getSequenceNumber()).isEqualTo(0); RecordedRequest post1 = server.takeRequest(); - assertEquals("body!", post1.getBody().readUtf8()); - assertEquals(1, post1.getSequenceNumber()); + Assertions.assertThat(post1.getBody().readUtf8()).isEqualTo("body!"); + Assertions.assertThat(post1.getSequenceNumber()).isEqualTo(1); RecordedRequest post2 = server.takeRequest(); - assertEquals("body!", post2.getBody().readUtf8()); - assertEquals(0, post2.getSequenceNumber()); + Assertions.assertThat(post2.getBody().readUtf8()).isEqualTo("body!"); + Assertions.assertThat(post2.getSequenceNumber()).isEqualTo(0); } @Test public void fullyBufferedPostIsTooShort() { @@ -3033,7 +3092,7 @@ public final class URLConnectionTest { .header("B", "") .build()); assertContent("body", response); - assertEquals("", response.request().header("B")); + Assertions.assertThat(response.request().header("B")).isEqualTo(""); } @Test public void emptyResponseHeaderValueIsAllowed() throws Exception { @@ -3042,7 +3101,7 @@ public final class URLConnectionTest { .setBody("body")); Response response = getResponse(newRequest("/")); assertContent("body", response); - assertEquals("", response.header("A")); + Assertions.assertThat(response.header("A")).isEqualTo(""); } @Test public void emptyRequestHeaderNameIsStrict() { @@ -3063,8 +3122,8 @@ public final class URLConnectionTest { .setHeaders(headers.build()) .setBody("body")); Response response = getResponse(newRequest("/")); - assertEquals(200, response.code()); - assertEquals("A", response.header("")); + Assertions.assertThat(response.code()).isEqualTo(200); + Assertions.assertThat(response.header("")).isEqualTo("A"); response.body().close(); } @@ -3112,10 +3171,10 @@ public final class URLConnectionTest { .setHeaders(headers)); Response response = getResponse(newRequest("/")); - assertEquals(200, response.code()); - assertEquals("c\u007fd", response.header("a\tb")); - assertEquals("\u2615\ufe0f", response.header("\ud83c\udf69")); - assertEquals("ef", response.header("")); + Assertions.assertThat(response.code()).isEqualTo(200); + Assertions.assertThat(response.header("a\tb")).isEqualTo("c\u007fd"); + Assertions.assertThat(response.header("\ud83c\udf69")).isEqualTo("\u2615\ufe0f"); + Assertions.assertThat(response.header("")).isEqualTo("ef"); } @Test @Ignore public void deflateCompression() { @@ -3145,13 +3204,15 @@ public final class URLConnectionTest { .build(); assertContent("A", getResponse(newRequest("/private"))); - assertNull(server.takeRequest().getHeader("Authorization")); - assertEquals(credential, server.takeRequest().getHeader("Authorization")); + Assertions.assertThat(server.takeRequest().getHeader("Authorization")).isNull(); + Assertions.assertThat(server.takeRequest().getHeader("Authorization")).isEqualTo( + credential); - assertEquals(Proxy.NO_PROXY, authenticator.onlyRoute().proxy()); + Assertions.assertThat(authenticator.onlyRoute().proxy()).isEqualTo(Proxy.NO_PROXY); Response response = authenticator.onlyResponse(); - assertEquals("/private", response.request().url().url().getPath()); - assertEquals(Arrays.asList(new Challenge("Basic", "protected area")), response.challenges()); + Assertions.assertThat(response.request().url().url().getPath()).isEqualTo("/private"); + Assertions.assertThat(response.challenges()).isEqualTo( + Arrays.asList(new Challenge("Basic", "protected area"))); } @Test public void customTokenAuthenticator() throws Exception { @@ -3169,12 +3230,14 @@ public final class URLConnectionTest { .build(); assertContent("A", getResponse(newRequest("/private"))); - assertNull(server.takeRequest().getHeader("Authorization")); - assertEquals("oauthed abc123", server.takeRequest().getHeader("Authorization")); + Assertions.assertThat(server.takeRequest().getHeader("Authorization")).isNull(); + Assertions.assertThat(server.takeRequest().getHeader("Authorization")).isEqualTo( + "oauthed abc123"); Response response = authenticator.onlyResponse(); - assertEquals("/private", response.request().url().url().getPath()); - assertEquals(Arrays.asList(new Challenge("Bearer", "oauthed")), response.challenges()); + Assertions.assertThat(response.request().url().url().getPath()).isEqualTo("/private"); + Assertions.assertThat(response.challenges()).isEqualTo( + Arrays.asList(new Challenge("Bearer", "oauthed"))); } @Test public void authenticateCallsTrackedAsRedirects() throws Exception { @@ -3195,10 +3258,11 @@ public final class URLConnectionTest { assertContent("c", getResponse(newRequest("/a"))); Response challengeResponse = authenticator.responses.get(0); - assertEquals("/b", challengeResponse.request().url().url().getPath()); + Assertions.assertThat(challengeResponse.request().url().url().getPath()).isEqualTo( + "/b"); Response redirectedBy = challengeResponse.priorResponse(); - assertEquals("/a", redirectedBy.request().url().url().getPath()); + Assertions.assertThat(redirectedBy.request().url().url().getPath()).isEqualTo("/a"); } @Test public void attemptAuthorization20Times() throws Exception { @@ -3233,7 +3297,8 @@ public final class URLConnectionTest { getResponse(newRequest("/")); fail(); } catch (ProtocolException expected) { - assertEquals("Too many follow-up requests: 21", expected.getMessage()); + Assertions.assertThat(expected.getMessage()).isEqualTo( + "Too many follow-up requests: 21"); } } @@ -3249,7 +3314,7 @@ public final class URLConnectionTest { .protocols(Arrays.asList(protocol, Protocol.HTTP_1_1)) .build(); Response response = getResponse(newRequest("/")); - assertEquals(protocol, response.protocol()); + Assertions.assertThat(response.protocol()).isEqualTo(protocol); assertContent("A", response); } @@ -3257,14 +3322,14 @@ public final class URLConnectionTest { server.enqueue(new MockResponse() .setStatus("HTTP/1.0 200 OK")); Response response = getResponse(newRequest("/")); - assertEquals(Protocol.HTTP_1_0, response.protocol()); + Assertions.assertThat(response.protocol()).isEqualTo(Protocol.HTTP_1_0); } @Test public void http11SelectedProtocol() throws IOException { server.enqueue(new MockResponse() .setStatus("HTTP/1.1 200 OK")); Response response = getResponse(newRequest("/")); - assertEquals(Protocol.HTTP_1_1, response.protocol()); + Assertions.assertThat(response.protocol()).isEqualTo(Protocol.HTTP_1_1); } /** For example, empty Protobuf RPC messages end up as a zero-length POST. */ @@ -3296,9 +3361,9 @@ public final class URLConnectionTest { .build()); assertContent("", response); RecordedRequest zeroLengthPayload = server.takeRequest(); - assertEquals(method, zeroLengthPayload.getMethod()); - assertEquals("0", zeroLengthPayload.getHeader("content-length")); - assertEquals(0L, zeroLengthPayload.getBodySize()); + Assertions.assertThat(zeroLengthPayload.getMethod()).isEqualTo(method); + Assertions.assertThat(zeroLengthPayload.getHeader("content-length")).isEqualTo("0"); + Assertions.assertThat(zeroLengthPayload.getBodySize()).isEqualTo(0L); } @Test public void setProtocols() throws Exception { @@ -3358,7 +3423,8 @@ public final class URLConnectionTest { assertContent("", response); RecordedRequest request = server.takeRequest(); - assertEquals(Long.toString(contentLength), request.getHeader("Content-Length")); + Assertions.assertThat(request.getHeader("Content-Length")).isEqualTo( + Long.toString(contentLength)); } @Test public void testNoSslFallback() throws Exception { @@ -3401,18 +3467,19 @@ public final class URLConnectionTest { .setBody("b")); Response response1 = getResponse(newRequest("/")); - assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, response1.code()); + Assertions.assertThat(response1.code()).isEqualTo( + (long) HttpURLConnection.HTTP_NOT_MODIFIED); assertContent("", response1); Response response2 = getResponse(newRequest("/")); - assertEquals(HttpURLConnection.HTTP_OK, response2.code()); + Assertions.assertThat(response2.code()).isEqualTo(HttpURLConnection.HTTP_OK); assertContent("b", response2); RecordedRequest requestA = server.takeRequest(); - assertEquals(0, requestA.getSequenceNumber()); + Assertions.assertThat(requestA.getSequenceNumber()).isEqualTo(0); RecordedRequest requestB = server.takeRequest(); - assertEquals(1, requestB.getSequenceNumber()); + Assertions.assertThat(requestB.getSequenceNumber()).isEqualTo(1); } @Test public void nullSSLSocketFactory_throws() { @@ -3440,10 +3507,10 @@ public final class URLConnectionTest { assertContent("This is the new page!", response); RecordedRequest requestA = server.takeRequest(); - assertEquals(0, requestA.getSequenceNumber()); + Assertions.assertThat(requestA.getSequenceNumber()).isEqualTo(0); RecordedRequest requestB = server.takeRequest(); - assertEquals(1, requestB.getSequenceNumber()); + Assertions.assertThat(requestB.getSequenceNumber()).isEqualTo(1); } /** @@ -3457,11 +3524,11 @@ public final class URLConnectionTest { .url(server.url("/")) .delete(RequestBody.create(null, "BODY")) .build()); - assertEquals(200, response.code()); + Assertions.assertThat(response.code()).isEqualTo(200); RecordedRequest request = server.takeRequest(); - assertEquals("DELETE", request.getMethod()); - assertEquals("BODY", request.getBody().readUtf8()); + Assertions.assertThat(request.getMethod()).isEqualTo("DELETE"); + Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("BODY"); } @Test public void userAgentDefaultsToOkHttpVersion() throws Exception { @@ -3471,7 +3538,7 @@ public final class URLConnectionTest { assertContent("abc", getResponse(newRequest("/"))); RecordedRequest request = server.takeRequest(); - assertEquals(Version.userAgent(), request.getHeader("User-Agent")); + Assertions.assertThat(request.getHeader("User-Agent")).isEqualTo(Version.userAgent()); } @Test public void urlWithSpaceInHost() { @@ -3505,8 +3572,8 @@ public final class URLConnectionTest { .addHeaderLenient("Location", redirectUrl)); Response response = getResponse(newRequest("/")); - assertEquals(302, response.code()); - assertEquals(redirectUrl, response.header("Location")); + Assertions.assertThat(response.code()).isEqualTo(302); + Assertions.assertThat(response.header("Location")).isEqualTo(redirectUrl); } @Test public void urlWithBadAsciiHost() { @@ -3542,7 +3609,7 @@ public final class URLConnectionTest { getResponse(newRequest("/")); fail(); } catch (RuntimeException expected) { - assertEquals("boom!", expected.getMessage()); + Assertions.assertThat(expected.getMessage()).isEqualTo("boom!"); } } @@ -3567,11 +3634,11 @@ public final class URLConnectionTest { .build())); RecordedRequest request1 = server.takeRequest(); - assertEquals(0, request1.getSequenceNumber()); + Assertions.assertThat(request1.getSequenceNumber()).isEqualTo(0); RecordedRequest request2 = server.takeRequest(); - assertEquals("123", request2.getBody().readUtf8()); - assertEquals(0, request2.getSequenceNumber()); + Assertions.assertThat(request2.getBody().readUtf8()).isEqualTo("123"); + Assertions.assertThat(request2.getSequenceNumber()).isEqualTo(0); } @Test public void authenticateNoConnection() throws Exception { @@ -3585,7 +3652,7 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - assertEquals(401, response.code()); + Assertions.assertThat(response.code()).isEqualTo(401); } private Request newRequest(String s) { @@ -3613,7 +3680,8 @@ public final class URLConnectionTest { private void assertContent(String expected, Response response, int limit) throws IOException { - assertEquals(expected, readAscii(response.body().byteStream(), limit)); + Assertions.assertThat(readAscii(response.body().byteStream(), limit)).isEqualTo( + expected); } private void assertContent(String expected, Response response) throws IOException { diff --git a/okhttp-tests/src/test/java/okhttp3/WebPlatformUrlTest.java b/okhttp-tests/src/test/java/okhttp3/WebPlatformUrlTest.java index d9b3d442f..c12c6a417 100644 --- a/okhttp-tests/src/test/java/okhttp3/WebPlatformUrlTest.java +++ b/okhttp-tests/src/test/java/okhttp3/WebPlatformUrlTest.java @@ -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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/WholeOperationTimeoutTest.java b/okhttp-tests/src/test/java/okhttp3/WholeOperationTimeoutTest.java index 7847332f5..6d9dcef39 100644 --- a/okhttp-tests/src/test/java/okhttp3/WholeOperationTimeoutTest.java +++ b/okhttp-tests/src/test/java/okhttp3/WholeOperationTimeoutTest.java @@ -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) { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/UtilTest.java b/okhttp-tests/src/test/java/okhttp3/internal/UtilTest.java index dacf8ddaf..cac32a992 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/UtilTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/UtilTest.java @@ -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 map = new LinkedHashMap<>(); map.put("a", "A"); Map 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(); diff --git a/okhttp-tests/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.java b/okhttp-tests/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.java index 1d5bf3073..9e8f2a989 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.java @@ -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 Issue #2 */ @@ -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 Issue #2 */ @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 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 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 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 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 { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/cache2/FileOperatorTest.java b/okhttp-tests/src/test/java/okhttp3/internal/cache2/FileOperatorTest.java index 21bbd4935..cca27974f 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/cache2/FileOperatorTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/cache2/FileOperatorTest.java @@ -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 { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/cache2/RelayTest.java b/okhttp-tests/src/test/java/okhttp3/internal/cache2/RelayTest.java index 8ed0c911f..5e3911899 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/cache2/RelayTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/cache2/RelayTest.java @@ -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(); } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionPoolTest.java b/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionPoolTest.java index af85106bf..3224f9fa2 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionPoolTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionPoolTest.java @@ -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. */ diff --git a/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionSpecSelectorTest.java b/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionSpecSelectorTest.java index 25e6b86a4..f0c47d76d 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionSpecSelectorTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionSpecSelectorTest.java @@ -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 actual = new LinkedHashSet<>(Arrays.asList(socket.getEnabledProtocols())); Set expected = new LinkedHashSet<>(Arrays.asList(javaNames(required))); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } private static String[] javaNames(TlsVersion... tlsVersions) { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/connection/RouteExceptionTest.java b/okhttp-tests/src/test/java/okhttp3/internal/connection/RouteExceptionTest.java index 44e939aae..bce264a61 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/connection/RouteExceptionTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/connection/RouteExceptionTest.java @@ -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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/connection/RouteSelectorTest.java b/okhttp-tests/src/test/java/okhttp3/internal/connection/RouteSelectorTest.java index 6c4a0d2d9..e1c870da1 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/connection/RouteSelectorTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/connection/RouteSelectorTest.java @@ -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 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 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. */ diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/HttpDateTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/HttpDateTest.java index 0a22eb0f8..3d9860da6 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/HttpDateTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/HttpDateTest.java @@ -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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/RecordingProxySelector.java b/okhttp-tests/src/test/java/okhttp3/internal/http/RecordingProxySelector.java index fb37e7e49..dafaae89f 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/RecordingProxySelector.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/RecordingProxySelector.java @@ -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 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(); } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/StatusLineTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/StatusLineTest.java index 6eb1aa8b1..08e002de7 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/StatusLineTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/StatusLineTest.java @@ -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 { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http2/FrameLogTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http2/FrameLogTest.java index 94e5e8358..ee21f46c8 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/FrameLogTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/FrameLogTest.java @@ -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 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); + )); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http2/HpackTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http2/HpackTest.java index f8bd93128..69dd07923 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/HpackTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/HpackTest.java @@ -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) { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.java index 2344249cb..fd1703404 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.java @@ -56,10 +56,9 @@ import static okhttp3.internal.http2.Settings.HEADER_TABLE_SIZE; import static okhttp3.internal.http2.Settings.INITIAL_WINDOW_SIZE; import static okhttp3.internal.http2.Settings.MAX_CONCURRENT_STREAMS; import static okhttp3.internal.http2.Settings.MAX_FRAME_SIZE; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public final class Http2ConnectionTest { @@ -88,11 +87,11 @@ public final class Http2ConnectionTest { // verify the peer received what was expected InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); - assertEquals(0, ping.streamId); - assertEquals(2, ping.payload1); - assertEquals(3, ping.payload2); - assertTrue(ping.ack); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); + assertThat(ping.streamId).isEqualTo(0); + assertThat(ping.payload1).isEqualTo(2); + assertThat(ping.payload2).isEqualTo(3); + assertThat(ping.ack).isTrue(); } @Test public void peerHttp2ServerLowersInitialWindowSize() throws Exception { @@ -112,16 +111,16 @@ public final class Http2ConnectionTest { // Verify the peer received the second ACK. InFrame ackFrame = peer.takeFrame(); - assertEquals(Http2.TYPE_SETTINGS, ackFrame.type); - assertEquals(0, ackFrame.streamId); - assertTrue(ackFrame.ack); + assertThat(ackFrame.type).isEqualTo(Http2.TYPE_SETTINGS); + assertThat(ackFrame.streamId).isEqualTo(0); + assertThat(ackFrame.ack).isTrue(); // This stream was created *after* the connection settings were adjusted. Http2Stream stream = connection.newStream(headerEntries("a", "android"), false); - assertEquals(3368, connection.peerSettings.getInitialWindowSize()); + assertThat(connection.peerSettings.getInitialWindowSize()).isEqualTo(3368); // New Stream is has the most recent initial window size. - assertEquals(3368, stream.bytesLeftInWriteWindow); + assertThat(stream.bytesLeftInWriteWindow).isEqualTo(3368); } @Test public void peerHttp2ServerZerosCompressionTable() throws Exception { @@ -132,10 +131,10 @@ public final class Http2ConnectionTest { Http2Connection connection = connectWithSettings(client, settings); // Verify the peer's settings were read and applied. - assertEquals(0, connection.peerSettings.getHeaderTableSize()); + assertThat(connection.peerSettings.getHeaderTableSize()).isEqualTo(0); Http2Writer writer = connection.writer; - assertEquals(0, writer.hpackWriter.dynamicTableByteCount); - assertEquals(0, writer.hpackWriter.headerTableSizeSetting); + assertThat(writer.hpackWriter.dynamicTableByteCount).isEqualTo(0); + assertThat(writer.hpackWriter.headerTableSizeSetting).isEqualTo(0); } @Test public void peerHttp2ClientDisablesPush() throws Exception { @@ -146,7 +145,7 @@ public final class Http2ConnectionTest { Http2Connection connection = connectWithSettings(client, settings); // verify the peer's settings were read and applied. - assertFalse(connection.peerSettings.getEnablePush(true)); + assertThat(connection.peerSettings.getEnablePush(true)).isFalse(); } @Test public void peerIncreasesMaxFrameSize() throws Exception { @@ -157,8 +156,8 @@ public final class Http2ConnectionTest { Http2Connection connection = connectWithSettings(true, settings); // verify the peer's settings were read and applied. - assertEquals(newMaxFrameSize, connection.peerSettings.getMaxFrameSize(-1)); - assertEquals(newMaxFrameSize, connection.writer.maxDataLength()); + assertThat(connection.peerSettings.getMaxFrameSize(-1)).isEqualTo(newMaxFrameSize); + assertThat(connection.writer.maxDataLength()).isEqualTo(newMaxFrameSize); } /** @@ -193,14 +192,14 @@ public final class Http2ConnectionTest { // Verify the peer received what was expected. peer.takeFrame(); // PING InFrame headers = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, headers.type); + assertThat(headers.type).isEqualTo(Http2.TYPE_HEADERS); InFrame data1 = peer.takeFrame(); - assertEquals(Http2.TYPE_DATA, data1.type); - assertEquals(3, data1.streamId); + assertThat(data1.type).isEqualTo(Http2.TYPE_DATA); + assertThat(data1.streamId).isEqualTo(3); assertArrayEquals("abcde".getBytes(UTF_8), data1.data); InFrame data2 = peer.takeFrame(); - assertEquals(Http2.TYPE_DATA, data2.type); - assertEquals(3, data2.streamId); + assertThat(data2.type).isEqualTo(Http2.TYPE_DATA); + assertThat(data2.streamId).isEqualTo(3); assertArrayEquals("fghi".getBytes(UTF_8), data2.data); } @@ -228,13 +227,13 @@ public final class Http2ConnectionTest { stream1.close(ErrorCode.CANCEL, null); InFrame frame1 = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, frame1.type); + assertThat(frame1.type).isEqualTo(Http2.TYPE_HEADERS); InFrame frame2 = peer.takeFrame(); - assertEquals(Http2.TYPE_RST_STREAM, frame2.type); + assertThat(frame2.type).isEqualTo(Http2.TYPE_RST_STREAM); InFrame frame3 = peer.takeFrame(); - assertEquals(Http2.TYPE_RST_STREAM, frame3.type); + assertThat(frame3.type).isEqualTo(Http2.TYPE_RST_STREAM); - assertEquals(2048, connection.unacknowledgedBytesRead); + assertThat(connection.unacknowledgedBytesRead).isEqualTo(2048); } @Test public void receiveGoAwayHttp2() throws Exception { @@ -262,7 +261,7 @@ public final class Http2ConnectionTest { sink2.flush(); fail(); } catch (IOException expected) { - assertEquals("stream was reset: REFUSED_STREAM", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("stream was reset: REFUSED_STREAM"); } sink1.writeUtf8("def"); sink1.close(); @@ -271,20 +270,20 @@ public final class Http2ConnectionTest { fail(); } catch (ConnectionShutdownException expected) { } - assertTrue(stream1.isOpen()); - assertFalse(stream2.isOpen()); - assertEquals(1, connection.openStreamCount()); + assertThat(stream1.isOpen()).isTrue(); + assertThat(stream2.isOpen()).isFalse(); + assertThat(connection.openStreamCount()).isEqualTo(1); // verify the peer received what was expected InFrame synStream1 = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream1.type); + assertThat(synStream1.type).isEqualTo(Http2.TYPE_HEADERS); InFrame synStream2 = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream2.type); + assertThat(synStream2.type).isEqualTo(Http2.TYPE_HEADERS); InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); InFrame data1 = peer.takeFrame(); - assertEquals(Http2.TYPE_DATA, data1.type); - assertEquals(3, data1.streamId); + assertThat(data1.type).isEqualTo(Http2.TYPE_DATA); + assertThat(data1.streamId).isEqualTo(3); assertArrayEquals("abcdef".getBytes(UTF_8), data1.data); } @@ -312,26 +311,28 @@ public final class Http2ConnectionTest { Http2Connection connection = connect(peer); connection.okHttpSettings.set(INITIAL_WINDOW_SIZE, windowSize); Http2Stream stream = connection.newStream(headerEntries("b", "banana"), false); - assertEquals(0, stream.unacknowledgedBytesRead); - assertEquals(Headers.of("a", "android"), stream.takeHeaders()); + assertThat(stream.unacknowledgedBytesRead).isEqualTo(0); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("a", "android")); Source in = stream.getSource(); Buffer buffer = new Buffer(); buffer.writeAll(in); - assertEquals(-1, in.read(buffer, 1)); - assertEquals(150, buffer.size()); + assertThat(in.read(buffer, 1)).isEqualTo(-1); + assertThat(buffer.size()).isEqualTo(150); InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); for (int i = 0; i < 3; i++) { List windowUpdateStreamIds = new ArrayList<>(2); for (int j = 0; j < 2; j++) { InFrame windowUpdate = peer.takeFrame(); - assertEquals(Http2.TYPE_WINDOW_UPDATE, windowUpdate.type); + assertThat(windowUpdate.type).isEqualTo(Http2.TYPE_WINDOW_UPDATE); windowUpdateStreamIds.add(windowUpdate.streamId); - assertEquals(windowUpdateThreshold, windowUpdate.windowSizeIncrement); + assertThat(windowUpdate.windowSizeIncrement).isEqualTo(windowUpdateThreshold); } - assertTrue(windowUpdateStreamIds.contains(0)); // connection - assertTrue(windowUpdateStreamIds.contains(3)); // stream + // connection + assertThat(windowUpdateStreamIds.contains(0)).isTrue(); + // stream + assertThat(windowUpdateStreamIds.contains(3)).isTrue(); } } @@ -347,12 +348,12 @@ public final class Http2ConnectionTest { // Play it back. Http2Connection connection = connect(peer); Http2Stream client = connection.newStream(headerEntries("b", "banana"), false); - assertEquals(-1, client.getSource().read(new Buffer(), 1)); + assertThat(client.getSource().read(new Buffer(), 1)).isEqualTo(-1); // Verify the peer received what was expected. InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertEquals(5, peer.frameCount()); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.frameCount()).isEqualTo(5); } @Test public void clientSendsEmptyDataServerDoesntSendWindowUpdateHttp2() throws Exception { @@ -373,9 +374,9 @@ public final class Http2ConnectionTest { out.close(); // Verify the peer received what was expected. - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); - assertEquals(Http2.TYPE_DATA, peer.takeFrame().type); - assertEquals(5, peer.frameCount()); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_DATA); + assertThat(peer.frameCount()).isEqualTo(5); } @Test public void maxFrameSizeHonored() throws Exception { @@ -400,11 +401,11 @@ public final class Http2ConnectionTest { out.close(); InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); InFrame data = peer.takeFrame(); - assertEquals(peer.maxOutboundDataLength(), data.data.length); + assertThat(data.data.length).isEqualTo(peer.maxOutboundDataLength()); data = peer.takeFrame(); - assertEquals(1, data.data.length); + assertThat(data.data.length).isEqualTo(1); } @Test public void pushPromiseStream() throws Exception { @@ -432,13 +433,13 @@ public final class Http2ConnectionTest { // play it back Http2Connection connection = connect(peer, observer, REFUSE_INCOMING_STREAMS); Http2Stream client = connection.newStream(headerEntries("b", "banana"), false); - assertEquals(-1, client.getSource().read(new Buffer(), 1)); + assertThat(client.getSource().read(new Buffer(), 1)).isEqualTo(-1); // verify the peer received what was expected - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); - assertEquals(expectedRequestHeaders, observer.takeEvent()); - assertEquals(expectedResponseHeaders, observer.takeEvent()); + assertThat(observer.takeEvent()).isEqualTo(expectedRequestHeaders); + assertThat(observer.takeEvent()).isEqualTo(expectedResponseHeaders); } @Test public void doublePushPromise() throws Exception { @@ -456,8 +457,8 @@ public final class Http2ConnectionTest { connection.newStream(headerEntries("b", "banana"), false); // verify the peer received what was expected - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); - assertEquals(ErrorCode.PROTOCOL_ERROR, peer.takeFrame().errorCode); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.takeFrame().errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR); } @Test public void pushPromiseStreamsAutomaticallyCancel() throws Exception { @@ -481,9 +482,9 @@ public final class Http2ConnectionTest { // verify the peer received what was expected InFrame rstStream = peer.takeFrame(); - assertEquals(Http2.TYPE_RST_STREAM, rstStream.type); - assertEquals(2, rstStream.streamId); - assertEquals(ErrorCode.CANCEL, rstStream.errorCode); + assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM); + assertThat(rstStream.streamId).isEqualTo(2); + assertThat(rstStream.errorCode).isEqualTo(ErrorCode.CANCEL); } /** @@ -535,18 +536,18 @@ public final class Http2ConnectionTest { BufferedSink out = Okio.buffer(stream.getSink()); out.writeUtf8("c3po"); out.close(); - assertEquals(Headers.of("a", "android"), stream.takeHeaders()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("a", "android")); assertStreamData("robot", stream.getSource()); connection.writePingAndAwaitPong(); - assertEquals(0, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertFalse(synStream.outFinished); - assertEquals(3, synStream.streamId); - assertEquals(-1, synStream.associatedStreamId); - assertEquals(headerEntries("b", "banana"), synStream.headerBlock); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(synStream.outFinished).isFalse(); + assertThat(synStream.streamId).isEqualTo(3); + assertThat(synStream.associatedStreamId).isEqualTo(-1); + assertThat(synStream.headerBlock).isEqualTo(headerEntries("b", "banana")); InFrame requestData = peer.takeFrame(); assertArrayEquals("c3po".getBytes(UTF_8), requestData.data); } @@ -565,17 +566,17 @@ public final class Http2ConnectionTest { Http2Connection connection = connect(peer); Http2Stream stream = connection.newStream(headerEntries("a", "artichaut"), false); connection.writePingAndAwaitPong(); - assertEquals(Headers.of("headers", "bam"), stream.takeHeaders()); - assertEquals(EMPTY_HEADERS, stream.trailers()); - assertEquals(0, connection.openStreamCount()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("headers", "bam")); + assertThat(stream.trailers()).isEqualTo(EMPTY_HEADERS); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertFalse(synStream.outFinished); - assertEquals(3, synStream.streamId); - assertEquals(-1, synStream.associatedStreamId); - assertEquals(headerEntries("a", "artichaut"), synStream.headerBlock); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(synStream.outFinished).isFalse(); + assertThat(synStream.streamId).isEqualTo(3); + assertThat(synStream.associatedStreamId).isEqualTo(-1); + assertThat(synStream.headerBlock).isEqualTo(headerEntries("a", "artichaut")); } @Test public void serverWritesTrailersAndClientReadsTrailers() throws Exception { @@ -592,18 +593,18 @@ public final class Http2ConnectionTest { // play it back Http2Connection connection = connect(peer); Http2Stream stream = connection.newStream(headerEntries("a", "artichaut"), false); - assertEquals(Headers.of("headers", "bam"), stream.takeHeaders()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("headers", "bam")); connection.writePingAndAwaitPong(); - assertEquals(Headers.of("trailers", "boom"), stream.trailers()); - assertEquals(0, connection.openStreamCount()); + assertThat(stream.trailers()).isEqualTo(Headers.of("trailers", "boom")); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertFalse(synStream.outFinished); - assertEquals(3, synStream.streamId); - assertEquals(-1, synStream.associatedStreamId); - assertEquals(headerEntries("a", "artichaut"), synStream.headerBlock); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(synStream.outFinished).isFalse(); + assertThat(synStream.streamId).isEqualTo(3); + assertThat(synStream.associatedStreamId).isEqualTo(-1); + assertThat(synStream.headerBlock).isEqualTo(headerEntries("a", "artichaut")); } @Test public void serverWritesTrailersWithData() throws Exception { @@ -632,15 +633,15 @@ public final class Http2ConnectionTest { // Verify the peer received what was expected. InFrame headers1 = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, headers1.type); + assertThat(headers1.type).isEqualTo(Http2.TYPE_HEADERS); InFrame data1 = peer.takeFrame(); - assertEquals(Http2.TYPE_DATA, data1.type); - assertEquals(3, data1.streamId); + assertThat(data1.type).isEqualTo(Http2.TYPE_DATA); + assertThat(data1.streamId).isEqualTo(3); assertArrayEquals("abcdefghi".getBytes(UTF_8), data1.data); - assertFalse(data1.inFinished); + assertThat(data1.inFinished).isFalse(); InFrame headers2 = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, headers2.type); - assertTrue(headers2.inFinished); + assertThat(headers2.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(headers2.inFinished).isTrue(); } @Test public void clientCannotReadTrailersWithoutExhaustingStream() throws Exception { @@ -723,18 +724,18 @@ public final class Http2ConnectionTest { Http2Stream stream = connection.newStream(headerEntries("a", "artichaut"), false); BufferedSource source = Okio.buffer(stream.getSource()); connection.writePingAndAwaitPong(); - assertEquals(Headers.of("headers", "bam"), stream.takeHeaders()); - assertEquals("robot", source.readUtf8(5)); - assertEquals(EMPTY_HEADERS, stream.trailers()); - assertEquals(0, connection.openStreamCount()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("headers", "bam")); + assertThat(source.readUtf8(5)).isEqualTo("robot"); + assertThat(stream.trailers()).isEqualTo(EMPTY_HEADERS); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertFalse(synStream.outFinished); - assertEquals(3, synStream.streamId); - assertEquals(-1, synStream.associatedStreamId); - assertEquals(headerEntries("a", "artichaut"), synStream.headerBlock); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(synStream.outFinished).isFalse(); + assertThat(synStream.streamId).isEqualTo(3); + assertThat(synStream.associatedStreamId).isEqualTo(-1); + assertThat(synStream.headerBlock).isEqualTo(headerEntries("a", "artichaut")); } @Test public void serverReadsHeadersDataHeaders() throws Exception { @@ -757,20 +758,20 @@ public final class Http2ConnectionTest { out.close(); stream.writeHeaders(headerEntries("e", "elephant"), false, false); connection.writePingAndAwaitPong(); - assertEquals(0, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertFalse(synStream.outFinished); - assertEquals(3, synStream.streamId); - assertEquals(-1, synStream.associatedStreamId); - assertEquals(headerEntries("b", "banana"), synStream.headerBlock); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(synStream.outFinished).isFalse(); + assertThat(synStream.streamId).isEqualTo(3); + assertThat(synStream.associatedStreamId).isEqualTo(-1); + assertThat(synStream.headerBlock).isEqualTo(headerEntries("b", "banana")); InFrame requestData = peer.takeFrame(); assertArrayEquals("c3po".getBytes(UTF_8), requestData.data); InFrame nextFrame = peer.takeFrame(); - assertEquals(headerEntries("e", "elephant"), nextFrame.headerBlock); + assertThat(nextFrame.headerBlock).isEqualTo(headerEntries("e", "elephant")); } @Test public void clientCreatesStreamAndServerRepliesWithFin() throws Exception { @@ -786,15 +787,15 @@ public final class Http2ConnectionTest { // play it back Http2Connection connection = connect(peer); connection.newStream(headerEntries("b", "banana"), false); - assertEquals(1, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(1); connection.writePingAndAwaitPong(); // Ensure that the SYN_REPLY has been received. - assertEquals(0, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); } @Test public void serverPingsClient() throws Exception { @@ -810,10 +811,10 @@ public final class Http2ConnectionTest { // verify the peer received what was expected InFrame ping = peer.takeFrame(); - assertEquals(0, ping.streamId); - assertEquals(2, ping.payload1); - assertEquals(0, ping.payload2); - assertTrue(ping.ack); + assertThat(ping.streamId).isEqualTo(0); + assertThat(ping.payload1).isEqualTo(2); + assertThat(ping.payload2).isEqualTo(0); + assertThat(ping.ack).isTrue(); } @Test public void clientPingsServer() throws Exception { @@ -829,16 +830,18 @@ public final class Http2ConnectionTest { long pingAtNanos = System.nanoTime(); connection.writePingAndAwaitPong(); long elapsedNanos = System.nanoTime() - pingAtNanos; - assertTrue(elapsedNanos > 0); - assertTrue(elapsedNanos < TimeUnit.SECONDS.toNanos(1)); + assertThat(elapsedNanos > 0).isTrue(); + assertThat(elapsedNanos < TimeUnit.SECONDS.toNanos(1)).isTrue(); // verify the peer received what was expected InFrame pingFrame = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, pingFrame.type); - assertEquals(0, pingFrame.streamId); - assertEquals(0x4f4b6f6b, pingFrame.payload1); // OkOk - assertEquals(0xf09f8da9, pingFrame.payload2); // donut - assertFalse(pingFrame.ack); + assertThat(pingFrame.type).isEqualTo(Http2.TYPE_PING); + assertThat(pingFrame.streamId).isEqualTo(0); + // OkOk + assertThat(pingFrame.payload1).isEqualTo(0x4f4b6f6b); + // donut + assertThat(pingFrame.payload2).isEqualTo(0xf09f8da9); + assertThat(pingFrame.ack).isFalse(); } @Test public void unexpectedPingIsNotReturned() throws Exception { @@ -857,9 +860,9 @@ public final class Http2ConnectionTest { // verify the peer received what was expected InFrame ping2 = peer.takeFrame(); - assertEquals(2, ping2.payload1); + assertThat(ping2.payload1).isEqualTo(2); InFrame ping4 = peer.takeFrame(); - assertEquals(4, ping4.payload1); + assertThat(ping4.payload1).isEqualTo(4); } @Test public void serverSendsSettingsToClient() throws Exception { @@ -888,10 +891,10 @@ public final class Http2ConnectionTest { Http2Connection connection = connect(peer, IGNORE, listener); synchronized (connection) { - assertEquals(10, connection.peerSettings.getMaxConcurrentStreams(-1)); + assertThat(connection.peerSettings.getMaxConcurrentStreams(-1)).isEqualTo(10); } maxConcurrentStreamsUpdated.await(); - assertEquals(10, maxConcurrentStreams.get()); + assertThat(maxConcurrentStreams.get()).isEqualTo(10); } @Test public void multipleSettingsFramesAreMerged() throws Exception { @@ -915,13 +918,13 @@ public final class Http2ConnectionTest { // play it back Http2Connection connection = connect(peer); - assertEquals(Http2.TYPE_SETTINGS, peer.takeFrame().type); - assertEquals(Http2.TYPE_PING, peer.takeFrame().type); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_SETTINGS); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_PING); synchronized (connection) { - assertEquals(10000, connection.peerSettings.getHeaderTableSize()); - assertEquals(40000, connection.peerSettings.getInitialWindowSize()); - assertEquals(50000, connection.peerSettings.getMaxFrameSize(-1)); - assertEquals(60000, connection.peerSettings.getMaxConcurrentStreams(-1)); + assertThat(connection.peerSettings.getHeaderTableSize()).isEqualTo(10000); + assertThat(connection.peerSettings.getInitialWindowSize()).isEqualTo(40000); + assertThat(connection.peerSettings.getMaxFrameSize(-1)).isEqualTo(50000); + assertThat(connection.peerSettings.getMaxConcurrentStreams(-1)).isEqualTo(60000); } } @@ -946,10 +949,11 @@ public final class Http2ConnectionTest { connection.readerRunnable.settings(true, settings2); synchronized (connection) { - assertEquals(-1, connection.peerSettings.getHeaderTableSize()); - assertEquals(DEFAULT_INITIAL_WINDOW_SIZE, connection.peerSettings.getInitialWindowSize()); - assertEquals(-1, connection.peerSettings.getMaxFrameSize(-1)); - assertEquals(60000, connection.peerSettings.getMaxConcurrentStreams(-1)); + assertThat(connection.peerSettings.getHeaderTableSize()).isEqualTo(-1); + assertThat(connection.peerSettings.getInitialWindowSize()).isEqualTo( + (long) DEFAULT_INITIAL_WINDOW_SIZE); + assertThat(connection.peerSettings.getMaxFrameSize(-1)).isEqualTo(-1); + assertThat(connection.peerSettings.getMaxConcurrentStreams(-1)).isEqualTo(60000); } } @@ -968,11 +972,11 @@ public final class Http2ConnectionTest { // verify the peer received what was expected InFrame rstStream = peer.takeFrame(); - assertEquals(Http2.TYPE_RST_STREAM, rstStream.type); - assertEquals(41, rstStream.streamId); - assertEquals(ErrorCode.PROTOCOL_ERROR, rstStream.errorCode); + assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM); + assertThat(rstStream.streamId).isEqualTo(41); + assertThat(rstStream.errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR); InFrame ping = peer.takeFrame(); - assertEquals(2, ping.payload1); + assertThat(ping.payload1).isEqualTo(2); } @Test public void bogusReplySilentlyIgnored() throws Exception { @@ -989,7 +993,7 @@ public final class Http2ConnectionTest { // verify the peer received what was expected InFrame ping = peer.takeFrame(); - assertEquals(2, ping.payload1); + assertThat(ping.payload1).isEqualTo(2); } @Test public void serverClosesClientOutputStream() throws Exception { @@ -1012,7 +1016,7 @@ public final class Http2ConnectionTest { out.flush(); fail(); } catch (IOException expected) { - assertEquals("stream was reset: CANCEL", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("stream was reset: CANCEL"); } try { out.close(); @@ -1020,15 +1024,15 @@ public final class Http2ConnectionTest { } catch (IOException expected) { // Close throws because buffered data wasn't flushed. } - assertEquals(0, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertFalse(synStream.inFinished); - assertFalse(synStream.outFinished); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(synStream.inFinished).isFalse(); + assertThat(synStream.outFinished).isFalse(); InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); } /** @@ -1052,25 +1056,25 @@ public final class Http2ConnectionTest { in.read(new Buffer(), 1); fail(); } catch (IOException expected) { - assertEquals("stream closed", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("stream closed"); } try { out.writeUtf8("a"); out.flush(); fail(); } catch (IOException expected) { - assertEquals("stream finished", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("stream finished"); } - assertEquals(0, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertTrue(synStream.inFinished); - assertFalse(synStream.outFinished); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(synStream.inFinished).isTrue(); + assertThat(synStream.outFinished).isFalse(); InFrame rstStream = peer.takeFrame(); - assertEquals(Http2.TYPE_RST_STREAM, rstStream.type); - assertEquals(ErrorCode.CANCEL, rstStream.errorCode); + assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM); + assertThat(rstStream.errorCode).isEqualTo(ErrorCode.CANCEL); } /** @@ -1096,28 +1100,28 @@ public final class Http2ConnectionTest { source.read(new Buffer(), 1); fail(); } catch (IOException expected) { - assertEquals("stream closed", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("stream closed"); } out.writeUtf8("square"); out.flush(); out.close(); - assertEquals(0, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertFalse(synStream.inFinished); - assertFalse(synStream.outFinished); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(synStream.inFinished).isFalse(); + assertThat(synStream.outFinished).isFalse(); InFrame data = peer.takeFrame(); - assertEquals(Http2.TYPE_DATA, data.type); + assertThat(data.type).isEqualTo(Http2.TYPE_DATA); assertArrayEquals("square".getBytes(UTF_8), data.data); InFrame fin = peer.takeFrame(); - assertEquals(Http2.TYPE_DATA, fin.type); - assertTrue(fin.inFinished); - assertFalse(fin.outFinished); + assertThat(fin.type).isEqualTo(Http2.TYPE_DATA); + assertThat(fin.inFinished).isTrue(); + assertThat(fin.outFinished).isFalse(); InFrame rstStream = peer.takeFrame(); - assertEquals(Http2.TYPE_RST_STREAM, rstStream.type); - assertEquals(ErrorCode.CANCEL, rstStream.errorCode); + assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM); + assertThat(rstStream.errorCode).isEqualTo(ErrorCode.CANCEL); } @Test public void serverClosesClientInputStream() throws Exception { @@ -1137,13 +1141,13 @@ public final class Http2ConnectionTest { Source source = stream.getSource(); assertStreamData("square", source); connection.writePingAndAwaitPong(); // Ensure that inFinished has been received. - assertEquals(0, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertTrue(synStream.inFinished); - assertFalse(synStream.outFinished); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(synStream.inFinished).isTrue(); + assertThat(synStream.outFinished).isFalse(); } @Test public void remoteDoubleSynReply() throws Exception { @@ -1160,14 +1164,14 @@ public final class Http2ConnectionTest { // play it back Http2Connection connection = connect(peer); Http2Stream stream = connection.newStream(headerEntries("c", "cola"), false); - assertEquals(Headers.of("a", "android"), stream.takeHeaders()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("a", "android")); connection.writePingAndAwaitPong(); // Ensure that the 2nd SYN REPLY has been received. // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); } @Test public void remoteSendsDataAfterInFinished() throws Exception { @@ -1186,18 +1190,18 @@ public final class Http2ConnectionTest { // play it back Http2Connection connection = connect(peer); Http2Stream stream = connection.newStream(headerEntries("b", "banana"), false); - assertEquals(Headers.of("a", "android"), stream.takeHeaders()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("a", "android")); assertStreamData("robot", stream.getSource()); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); InFrame rstStream = peer.takeFrame(); - assertEquals(Http2.TYPE_RST_STREAM, rstStream.type); - assertEquals(3, rstStream.streamId); + assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM); + assertThat(rstStream.streamId).isEqualTo(3); InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); - assertEquals(2, ping.payload1); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); + assertThat(ping.payload1).isEqualTo(2); } @Test public void clientDoesNotLimitFlowControl() throws Exception { @@ -1219,14 +1223,14 @@ public final class Http2ConnectionTest { // play it back Http2Connection connection = connect(peer); Http2Stream stream = connection.newStream(headerEntries("a", "android"), false); - assertEquals(Headers.of("b", "banana"), stream.takeHeaders()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("b", "banana")); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); - assertEquals(2, ping.payload1); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); + assertThat(ping.payload1).isEqualTo(2); } @Test public void remoteSendsRefusedStreamBeforeReplyHeaders() throws Exception { @@ -1246,16 +1250,16 @@ public final class Http2ConnectionTest { stream.takeHeaders(); fail(); } catch (IOException expected) { - assertEquals("stream was reset: REFUSED_STREAM", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("stream was reset: REFUSED_STREAM"); } - assertEquals(0, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); - assertEquals(2, ping.payload1); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); + assertThat(ping.payload1).isEqualTo(2); } @Test public void receiveGoAway() throws Exception { @@ -1283,7 +1287,7 @@ public final class Http2ConnectionTest { sink2.flush(); fail(); } catch (IOException expected) { - assertEquals("stream was reset: REFUSED_STREAM", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("stream was reset: REFUSED_STREAM"); } sink1.writeUtf8("def"); sink1.close(); @@ -1292,20 +1296,20 @@ public final class Http2ConnectionTest { fail(); } catch (ConnectionShutdownException expected) { } - assertTrue(stream1.isOpen()); - assertFalse(stream2.isOpen()); - assertEquals(1, connection.openStreamCount()); + assertThat(stream1.isOpen()).isTrue(); + assertThat(stream2.isOpen()).isFalse(); + assertThat(connection.openStreamCount()).isEqualTo(1); // verify the peer received what was expected InFrame synStream1 = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream1.type); + assertThat(synStream1.type).isEqualTo(Http2.TYPE_HEADERS); InFrame synStream2 = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream2.type); + assertThat(synStream2.type).isEqualTo(Http2.TYPE_HEADERS); InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); InFrame data1 = peer.takeFrame(); - assertEquals(Http2.TYPE_DATA, data1.type); - assertEquals(3, data1.streamId); + assertThat(data1.type).isEqualTo(Http2.TYPE_DATA); + assertThat(data1.streamId).isEqualTo(3); assertArrayEquals("abcdef".getBytes(UTF_8), data1.data); } @@ -1330,18 +1334,18 @@ public final class Http2ConnectionTest { } connection.writePing(false, 0x01, 0x02); connection.shutdown(ErrorCode.PROTOCOL_ERROR); - assertEquals(1, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(1); connection.awaitPong(); // Prevent the peer from exiting prematurely. // verify the peer received what was expected InFrame synStream1 = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream1.type); + assertThat(synStream1.type).isEqualTo(Http2.TYPE_HEADERS); InFrame pingFrame = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, pingFrame.type); + assertThat(pingFrame.type).isEqualTo(Http2.TYPE_PING); InFrame goaway = peer.takeFrame(); - assertEquals(Http2.TYPE_GOAWAY, goaway.type); - assertEquals(0, goaway.streamId); - assertEquals(ErrorCode.PROTOCOL_ERROR, goaway.errorCode); + assertThat(goaway.type).isEqualTo(Http2.TYPE_GOAWAY); + assertThat(goaway.streamId).isEqualTo(0); + assertThat(goaway.errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR); } @Test public void close() throws Exception { @@ -1356,9 +1360,9 @@ public final class Http2ConnectionTest { // play it back Http2Connection connection = connect(peer); Http2Stream stream = connection.newStream(headerEntries("a", "android"), false); - assertEquals(1, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(1); connection.close(); - assertEquals(0, connection.openStreamCount()); + assertThat(connection.openStreamCount()).isEqualTo(0); try { connection.newStream(headerEntries("b", "banana"), false); fail(); @@ -1370,23 +1374,23 @@ public final class Http2ConnectionTest { sink.flush(); fail(); } catch (IOException expected) { - assertEquals("stream finished", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("stream finished"); } try { stream.getSource().read(new Buffer(), 1); fail(); } catch (IOException expected) { - assertEquals("stream was reset: CANCEL", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("stream was reset: CANCEL"); } // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); InFrame goaway = peer.takeFrame(); - assertEquals(Http2.TYPE_GOAWAY, goaway.type); + assertThat(goaway.type).isEqualTo(Http2.TYPE_GOAWAY); InFrame rstStream = peer.takeFrame(); - assertEquals(Http2.TYPE_RST_STREAM, rstStream.type); - assertEquals(3, rstStream.streamId); + assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM); + assertThat(rstStream.streamId).isEqualTo(3); } @Test public void getResponseHeadersTimesOut() throws Exception { @@ -1409,12 +1413,13 @@ public final class Http2ConnectionTest { } long elapsedNanos = System.nanoTime() - startNanos; awaitWatchdogIdle(); - assertEquals(500d, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), 200d /* 200ms delta */); - assertEquals(0, connection.openStreamCount()); + /* 200ms delta */ + assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedNanos)).isCloseTo(500d, offset(200d)); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); - assertEquals(Http2.TYPE_RST_STREAM, peer.takeFrame().type); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_RST_STREAM); } @Test public void readTimesOut() throws Exception { @@ -1439,12 +1444,13 @@ public final class Http2ConnectionTest { } long elapsedNanos = System.nanoTime() - startNanos; awaitWatchdogIdle(); - assertEquals(500d, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), 200d /* 200ms delta */); - assertEquals(0, connection.openStreamCount()); + /* 200ms delta */ + assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedNanos)).isCloseTo(500d, offset(200d)); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); - assertEquals(Http2.TYPE_RST_STREAM, peer.takeFrame().type); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_RST_STREAM); } @Test public void writeTimesOutAwaitingStreamWindow() throws Exception { @@ -1478,14 +1484,15 @@ public final class Http2ConnectionTest { } long elapsedNanos = System.nanoTime() - startNanos; awaitWatchdogIdle(); - assertEquals(500d, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), 200d /* 200ms delta */); - assertEquals(0, connection.openStreamCount()); + /* 200ms delta */ + assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedNanos)).isCloseTo(500d, offset(200d)); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected - assertEquals(Http2.TYPE_PING, peer.takeFrame().type); - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); - assertEquals(Http2.TYPE_DATA, peer.takeFrame().type); - assertEquals(Http2.TYPE_RST_STREAM, peer.takeFrame().type); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_PING); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_DATA); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_RST_STREAM); } @Test public void writeTimesOutAwaitingConnectionWindow() throws Exception { @@ -1522,15 +1529,16 @@ public final class Http2ConnectionTest { } long elapsedNanos = System.nanoTime() - startNanos; awaitWatchdogIdle(); - assertEquals(500d, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), 200d /* 200ms delta */); - assertEquals(0, connection.openStreamCount()); + /* 200ms delta */ + assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedNanos)).isCloseTo(500d, offset(200d)); + assertThat(connection.openStreamCount()).isEqualTo(0); // verify the peer received what was expected - assertEquals(Http2.TYPE_PING, peer.takeFrame().type); - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); - assertEquals(Http2.TYPE_PING, peer.takeFrame().type); - assertEquals(Http2.TYPE_DATA, peer.takeFrame().type); - assertEquals(Http2.TYPE_RST_STREAM, peer.takeFrame().type); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_PING); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_PING); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_DATA); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_RST_STREAM); } @Test public void outgoingWritesAreBatched() throws Exception { @@ -1553,11 +1561,11 @@ public final class Http2ConnectionTest { sink.close(); // verify the peer received one incoming frame - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); InFrame data = peer.takeFrame(); - assertEquals(Http2.TYPE_DATA, data.type); + assertThat(data.type).isEqualTo(Http2.TYPE_DATA); assertArrayEquals("abcdefghij".getBytes(UTF_8), data.data); - assertTrue(data.inFinished); + assertThat(data.inFinished).isTrue(); } @Test public void headers() throws Exception { @@ -1575,14 +1583,14 @@ public final class Http2ConnectionTest { Http2Connection connection = connect(peer); Http2Stream stream = connection.newStream(headerEntries("b", "banana"), true); connection.writePingAndAwaitPong(); // Ensure that the HEADERS has been received. - assertEquals(Headers.of("a", "android"), stream.takeHeaders()); - assertEquals(Headers.of("c", "c3po"), stream.takeHeaders()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("a", "android")); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("c", "c3po")); // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); InFrame ping = peer.takeFrame(); - assertEquals(Http2.TYPE_PING, ping.type); + assertThat(ping.type).isEqualTo(Http2.TYPE_PING); } @Test public void readMultipleSetsOfResponseHeaders() throws Exception { @@ -1600,13 +1608,13 @@ public final class Http2ConnectionTest { Http2Connection connection = connect(peer); Http2Stream stream = connection.newStream(headerEntries("b", "banana"), true); stream.getConnection().flush(); - assertEquals(Headers.of("a", "android"), stream.takeHeaders()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("a", "android")); connection.writePingAndAwaitPong(); - assertEquals(Headers.of("c", "cola"), stream.trailers()); + assertThat(stream.trailers()).isEqualTo(Headers.of("c", "cola")); // verify the peer received what was expected - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); - assertEquals(Http2.TYPE_PING, peer.takeFrame().type); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_PING); } @Test public void readSendsWindowUpdate() throws Exception { @@ -1633,26 +1641,28 @@ public final class Http2ConnectionTest { Http2Connection connection = connect(peer); connection.okHttpSettings.set(INITIAL_WINDOW_SIZE, windowSize); Http2Stream stream = connection.newStream(headerEntries("b", "banana"), false); - assertEquals(0, stream.unacknowledgedBytesRead); - assertEquals(Headers.of("a", "android"), stream.takeHeaders()); + assertThat(stream.unacknowledgedBytesRead).isEqualTo(0); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("a", "android")); Source in = stream.getSource(); Buffer buffer = new Buffer(); buffer.writeAll(in); - assertEquals(-1, in.read(buffer, 1)); - assertEquals(150, buffer.size()); + assertThat(in.read(buffer, 1)).isEqualTo(-1); + assertThat(buffer.size()).isEqualTo(150); InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); for (int i = 0; i < 3; i++) { List windowUpdateStreamIds = new ArrayList<>(2); for (int j = 0; j < 2; j++) { InFrame windowUpdate = peer.takeFrame(); - assertEquals(Http2.TYPE_WINDOW_UPDATE, windowUpdate.type); + assertThat(windowUpdate.type).isEqualTo(Http2.TYPE_WINDOW_UPDATE); windowUpdateStreamIds.add(windowUpdate.streamId); - assertEquals(windowUpdateThreshold, windowUpdate.windowSizeIncrement); + assertThat(windowUpdate.windowSizeIncrement).isEqualTo(windowUpdateThreshold); } - assertTrue(windowUpdateStreamIds.contains(0)); // connection - assertTrue(windowUpdateStreamIds.contains(3)); // stream + // connection + assertThat(windowUpdateStreamIds.contains(0)).isTrue(); + // stream + assertThat(windowUpdateStreamIds.contains(3)).isTrue(); } } @@ -1668,12 +1678,12 @@ public final class Http2ConnectionTest { // Play it back. Http2Connection connection = connect(peer); Http2Stream client = connection.newStream(headerEntries("b", "banana"), false); - assertEquals(-1, client.getSource().read(new Buffer(), 1)); + assertThat(client.getSource().read(new Buffer(), 1)).isEqualTo(-1); // Verify the peer received what was expected. InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); - assertEquals(5, peer.frameCount()); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.frameCount()).isEqualTo(5); } @Test public void clientSendsEmptyDataServerDoesntSendWindowUpdate() throws Exception { @@ -1694,9 +1704,9 @@ public final class Http2ConnectionTest { out.close(); // Verify the peer received what was expected. - assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); - assertEquals(Http2.TYPE_DATA, peer.takeFrame().type); - assertEquals(5, peer.frameCount()); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS); + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_DATA); + assertThat(peer.frameCount()).isEqualTo(5); } @Test public void testTruncatedDataFrame() throws Exception { @@ -1712,7 +1722,7 @@ public final class Http2ConnectionTest { // play it back Http2Connection connection = connect(peer); Http2Stream stream = connection.newStream(headerEntries("b", "banana"), false); - assertEquals(Headers.of("a", "android"), stream.takeHeaders()); + assertThat(stream.takeHeaders()).isEqualTo(Headers.of("a", "android")); Source in = stream.getSource(); try { Okio.buffer(in).readByteString(101); @@ -1743,14 +1753,14 @@ public final class Http2ConnectionTest { out1.flush(); // Check that we've filled the window for both the stream and also the connection. - assertEquals(0, connection.bytesLeftInWriteWindow); - assertEquals(0, connection.getStream(3).bytesLeftInWriteWindow); + assertThat(connection.bytesLeftInWriteWindow).isEqualTo(0); + assertThat(connection.getStream(3).bytesLeftInWriteWindow).isEqualTo(0); // receiving a window update on the connection will unblock new streams. connection.readerRunnable.windowUpdate(0, 3); - assertEquals(3, connection.bytesLeftInWriteWindow); - assertEquals(0, connection.getStream(3).bytesLeftInWriteWindow); + assertThat(connection.bytesLeftInWriteWindow).isEqualTo(3); + assertThat(connection.getStream(3).bytesLeftInWriteWindow).isEqualTo(0); // Another stream should be able to send data even though 1 is blocked. Http2Stream stream2 = connection.newStream(headerEntries("b", "banana"), true); @@ -1758,9 +1768,10 @@ public final class Http2ConnectionTest { out2.writeUtf8("foo"); out2.flush(); - assertEquals(0, connection.bytesLeftInWriteWindow); - assertEquals(0, connection.getStream(3).bytesLeftInWriteWindow); - assertEquals(DEFAULT_INITIAL_WINDOW_SIZE - 3, connection.getStream(5).bytesLeftInWriteWindow); + assertThat(connection.bytesLeftInWriteWindow).isEqualTo(0); + assertThat(connection.getStream(3).bytesLeftInWriteWindow).isEqualTo(0); + assertThat(connection.getStream(5).bytesLeftInWriteWindow).isEqualTo( + (long) (DEFAULT_INITIAL_WINDOW_SIZE - 3)); } @Test public void remoteOmitsInitialSettings() throws Exception { @@ -1780,15 +1791,15 @@ public final class Http2ConnectionTest { stream.takeHeaders(); fail(); } catch (IOException expected) { - assertEquals("Expected a SETTINGS frame but was 1", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("Expected a SETTINGS frame but was 1"); } // verify the peer received what was expected InFrame synStream = peer.takeFrame(); - assertEquals(Http2.TYPE_HEADERS, synStream.type); + assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS); InFrame goaway = peer.takeFrame(); - assertEquals(Http2.TYPE_GOAWAY, goaway.type); - assertEquals(ErrorCode.PROTOCOL_ERROR, goaway.errorCode); + assertThat(goaway.type).isEqualTo(Http2.TYPE_GOAWAY); + assertThat(goaway.errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR); } private Buffer data(int byteCount) { @@ -1797,12 +1808,12 @@ public final class Http2ConnectionTest { private void assertStreamData(String expected, Source source) throws IOException { String actual = Okio.buffer(source).readUtf8(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } /** Reads {@code prefix} from {@code source}. */ private void assertStreamPrefix(String prefix, BufferedSource source) throws IOException { - assertEquals(prefix, source.readUtf8(Utf8.size(prefix))); + assertThat(source.readUtf8(Utf8.size(prefix))).isEqualTo(prefix); } /** @@ -1850,9 +1861,9 @@ public final class Http2ConnectionTest { // verify the peer received the ACK InFrame ackFrame = peer.takeFrame(); - assertEquals(Http2.TYPE_SETTINGS, ackFrame.type); - assertEquals(0, ackFrame.streamId); - assertTrue(ackFrame.ack); + assertThat(ackFrame.type).isEqualTo(Http2.TYPE_SETTINGS); + assertThat(ackFrame.streamId).isEqualTo(0); + assertThat(ackFrame.ack).isTrue(); return connection; } @@ -1888,7 +1899,7 @@ public final class Http2ConnectionTest { } @Override public synchronized boolean onRequest(int streamId, List
requestHeaders) { - assertEquals(2, streamId); + assertThat(streamId).isEqualTo(2); events.add(requestHeaders); notifyAll(); return false; @@ -1896,8 +1907,8 @@ public final class Http2ConnectionTest { @Override public synchronized boolean onHeaders( int streamId, List
responseHeaders, boolean last) { - assertEquals(2, streamId); - assertTrue(last); + assertThat(streamId).isEqualTo(2); + assertThat(last).isTrue(); events.add(responseHeaders); notifyAll(); return false; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2Test.java b/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2Test.java index 684d22269..0854370aa 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2Test.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2Test.java @@ -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
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
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
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
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
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
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); } } }; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.java b/okhttp-tests/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.java index 198bbea22..6656a0eeb 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.java @@ -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 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 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 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 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 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); diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http2/HuffmanTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http2/HuffmanTest.java index e92445f26..b84d2de09 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/HuffmanTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/HuffmanTest.java @@ -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); diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http2/SettingsTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http2/SettingsTest.java index 46ec0a82a..8e2aa424b 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/SettingsTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/SettingsTest.java @@ -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); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/platform/Jdk8WithJettyBootPlatformTest.java b/okhttp-tests/src/test/java/okhttp3/internal/platform/Jdk8WithJettyBootPlatformTest.java index bc981e9a3..3d9cd3cea 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/platform/Jdk8WithJettyBootPlatformTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/platform/Jdk8WithJettyBootPlatformTest.java @@ -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(); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/platform/Jdk9PlatformTest.java b/okhttp-tests/src/test/java/okhttp3/internal/platform/Jdk9PlatformTest.java index 2889911d5..2881fe0e1 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/platform/Jdk9PlatformTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/platform/Jdk9PlatformTest.java @@ -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"); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/platform/PlatformTest.java b/okhttp-tests/src/test/java/okhttp3/internal/platform/PlatformTest.java index 087d5047e..a192b8c5e 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/platform/PlatformTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/platform/PlatformTest.java @@ -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"); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.java b/okhttp-tests/src/test/java/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.java index e99989099..70d44bbe2 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.java @@ -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)); } } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/tls/CertificatePinnerChainValidationTest.java b/okhttp-tests/src/test/java/okhttp3/internal/tls/CertificatePinnerChainValidationTest.java index a7b1802b5..f707064cd 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/tls/CertificatePinnerChainValidationTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/tls/CertificatePinnerChainValidationTest.java @@ -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!"); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/tls/ClientAuthTest.java b/okhttp-tests/src/test/java/okhttp3/internal/tls/ClientAuthTest.java index f12154336..252333bba 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/tls/ClientAuthTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/tls/ClientAuthTest.java @@ -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"); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/tls/DistinguishedNameParserTest.java b/okhttp-tests/src/test/java/okhttp3/internal/tls/DistinguishedNameParserTest.java index 09c22b859..099b8982b 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/tls/DistinguishedNameParserTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/tls/DistinguishedNameParserTest.java @@ -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) { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java b/okhttp-tests/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java index 81f41b044..9a878f1c4 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java @@ -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 { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/ws/RealWebSocketTest.java b/okhttp-tests/src/test/java/okhttp3/internal/ws/RealWebSocketTest.java index 38b2762e6..044643cd4 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/ws/RealWebSocketTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/ws/RealWebSocketTest.java @@ -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. */ diff --git a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.java b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.java index 3a560f179..270357969 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.java @@ -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) { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java index 9fa5d1d9d..401f50926 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java @@ -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) { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketRecorder.java b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketRecorder.java index e8d435382..d46205c5f 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketRecorder.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketRecorder.java @@ -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 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. */ diff --git a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketWriterTest.java b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketWriterTest.java index 48684f553..175df0ea7 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketWriterTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketWriterTest.java @@ -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()); } } diff --git a/okhttp-tls/pom.xml b/okhttp-tls/pom.xml index ca9a11717..36ebc369f 100644 --- a/okhttp-tls/pom.xml +++ b/okhttp-tls/pom.xml @@ -39,6 +39,11 @@ junit test + + org.assertj + assertj-core + test + diff --git a/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.java b/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.java index 6892e14f0..ac5bc6a53 100644 --- a/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.java +++ b/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.java @@ -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 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())); } } diff --git a/okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.java b/okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.java index ffec150f3..4335d67f2 100644 --- a/okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.java +++ b/okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.java @@ -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> 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"); } } diff --git a/okhttp-urlconnection/pom.xml b/okhttp-urlconnection/pom.xml index 0c68595b7..f9e8ac9cb 100644 --- a/okhttp-urlconnection/pom.xml +++ b/okhttp-urlconnection/pom.xml @@ -53,6 +53,11 @@ ${project.version} test + + org.assertj + assertj-core + test + diff --git a/pom.xml b/pom.xml index dec764dfd..acb68500e 100644 --- a/pom.xml +++ b/pom.xml @@ -26,6 +26,7 @@ okhttp-testing-support okhttp-tls okhttp-urlconnection + okhttp-hpacktests okhttp-logging-interceptor @@ -53,6 +54,7 @@ 4.12 + 3.11.0 platform @@ -130,6 +132,11 @@ conscrypt-openjdk-uber ${conscrypt.version} + + org.assertj + assertj-core + ${assertj.version} +